Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Each major version of spring-services targets one Spring Boot line:
| 2.x | 4.1 | 25 |

Upgrading from 1.x? See [`docs/releases/upgrade-to-2.0.md`](docs/releases/upgrade-to-2.0.md).
Upgrading from 2.0? See [`docs/releases/upgrade-to-2.1.md`](docs/releases/upgrade-to-2.1.md).

## Installation

Expand Down Expand Up @@ -260,8 +261,10 @@ management, never from committed configuration.
configuration that lives in the database rather than in `application.yml`.
- **Webhooks** — Outbound webhook subscriptions. Data lifecycle events trigger a webhook dispatch
*after the originating transaction commits*; HTTP POST is performed asynchronously via Spring
`RestClient` (10 s connect/read timeout) and the last response status is persisted on the
webhook row. A `ping` operation is exposed for testing a subscription on demand.
`RestClient` (10 s connect/read timeout) on the `webhookTaskExecutor` (one virtual thread per
call), and the last response status is persisted on the webhook row without publishing a
lifecycle event. A `ping` operation is exposed for testing a subscription on demand; it runs on
the calling thread.
- **Multi-Tenancy** — Row-level isolation in a shared schema. Tenant id is taken from the
authenticated principal; a JPA pre-persist guard fails fast if a row would be written without
one. Tenant-aware base classes mirror the non-tenant data abstractions and make cross-tenant
Expand Down
111 changes: 111 additions & 0 deletions docs/releases/upgrade-to-2.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# Upgrade prompt: spring-services 2.0.0 → 2.1.0

`spring-services` 2.1.0 brings the changes below. Every section stands on its own — apply only the
ones that affect you:

| Change | Spec | Nature |
| --- | --- | --- |
| **Webhooks are delivered asynchronously** on a dedicated executor | — | behaviour change; **source break** only if you construct `WebhookSender` yourself |
| No database migration | — | — |

This file is a self-contained prompt for an agent (Claude Code, etc.) to run inside a consumer repo.

---

## Asynchronous webhook delivery

Up to 2.0.0, `WebhookSender` was documented as asynchronous, but its `@Async` never took effect: the
annotated method was called through `this`, bypassing the Spring proxy, and the library never enabled
`@Async`. Every webhook call therefore ran sequentially on the thread that saved the data. With a
10 s connect and a 10 s read timeout per webhook, a slow or unreachable receiver blocked `save(...)`
and `delete(...)` of **every** data service — and with it the HTTP request that triggered them.

2.1.0 fixes this:

- Data events (`OnObjectCreate` / `OnObjectUpdate` / `OnObjectDelete`) are still dispatched after the
originating transaction commits, but each webhook call now runs on the new executor bean
`webhookTaskExecutor` (`WebhookConfig.EXECUTOR_BEAN_NAME`), one virtual thread per call.
`save(...)` and `delete(...)` no longer wait for webhook receivers.
- `WebhookSender.ping(id)` still runs on the calling thread, so the recorded status is available as
soon as it returns.
- The result of a call (`lastStatus`, `lastCalledAt`) is written through the new
`WebhookDataService.recordCall(id, status, calledAt)`. It changes only these two columns and
publishes **no** `OnObjectUpdate<WebhookDto>`. Before, a delivery saved the whole `WebhookDto`,
which could overwrite a concurrent change of `url` or `active` with a stale value.
- `webhookTaskExecutor` is registered with `defaultCandidate = false`. It is never injected into an
`Executor` injection point of your application, and Spring Boot's `applicationTaskExecutor` stays in
place.

> **No wire change.** Receivers get the same payload as with 2.0.0 — only sooner from the point of
> view of the caller, and possibly in a different order when several webhooks are registered.

## Prompt

You are working inside a Spring Boot service that depends on `spring-services` 2.0.0 and moves to
2.1.0.

### 1. Adapt code that constructs `WebhookSender`

Search the codebase for `new WebhookSender(` and for subclasses of `WebhookSender`. Most
applications have neither — the library wires the bean itself — and can skip this step.

The public constructor takes a third argument, the executor that delivers data events:

```java
// 2.0.0
new WebhookSender(restClient, webhookDataService);

// 2.1.0
new WebhookSender(restClient, webhookDataService, executor);
```

In a Spring context, inject the library's executor by name:

```java
@Qualifier(WebhookConfig.EXECUTOR_BEAN_NAME) Executor executor
```

In a plain unit test, `Runnable::run` delivers on the calling thread, which keeps the test
synchronous.

The former `protected void sendAndTrack(WebhookDto, WebhookEventPayload)` is now private. A subclass
that overrode it to change delivery must be rewritten; the public `sendAndTrack(WebhookDataEventPayload)`
and `ping(UUID)` are unchanged.

### 2. Check code that relied on synchronous delivery

Search for code that reads `lastStatus` or `lastCalledAt` of a webhook right after a `save(...)` or
`delete(...)` of another entity — typically in tests. After such a call the webhook may not have been
called yet. Wait for the value instead, for example with Awaitility:

```java
await().atMost(Duration.ofSeconds(10))
.untilAsserted(() ->
assertThat(webhookDataService.findById(id).orElseThrow().lastStatus()).isEqualTo(200));
```

Code that reads the status after `ping(id)` needs no change.

### 3. Check listeners on `OnObjectUpdate<WebhookDto>`

Search for listeners on `OnObjectUpdate` that handle `WebhookDto`. A webhook delivery no longer
publishes such an event; only changes made through `WebhookDataService.save(...)` (for example
editing the URL or the `active` flag) still do. If a listener used the delivery events to track call
results, read `lastStatus` / `lastCalledAt` from `WebhookDataService` instead.

### 4. Verify

- The application starts; `webhookTaskExecutor` and — if you rely on it — `applicationTaskExecutor`
are both present.
- Saving an entity with an unreachable webhook registered returns immediately instead of after the
connect timeout.
- The webhook's `lastStatus` / `lastCalledAt` are updated shortly after a delivery.

### Guard rails / Don't do this

- **Do not declare your own bean named `webhookTaskExecutor`.** The library does not back off from
it, and Spring Boot refuses a second bean definition with the same name at startup.
- **Do not add `@EnableAsync` to "make webhooks async".** Delivery no longer depends on it.
- **Webhooks are not retried and not persisted before delivery.** A call that is still running on
the executor when the application shuts down can be lost. If a receiver must get every event, it
has to reconcile on its own, for example by reading the current state through the REST API.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestClient;

Expand All @@ -12,6 +13,9 @@
@ComponentScan(basePackageClasses = WebhookConfig.class)
public class WebhookConfig {

/** Bean name of the executor that delivers webhook calls. */
public static final String EXECUTOR_BEAN_NAME = "webhookTaskExecutor";

private static final Duration TIMEOUT = Duration.ofSeconds(10);

/** Creates the configuration; webhook beans are declared via the annotated factory methods. */
Expand All @@ -24,4 +28,18 @@ RestClient webhookRestClient() {
factory.setReadTimeout(TIMEOUT);
return RestClient.builder().requestFactory(factory).build();
}

/**
* Delivers webhook calls, one virtual thread per call. No default candidate, so that it never
* competes with an {@link java.util.concurrent.Executor} of the application and never makes
* Spring Boot's {@code applicationTaskExecutor} back off.
*
* @return the executor
*/
@Bean(name = EXECUTOR_BEAN_NAME, defaultCandidate = false)
SimpleAsyncTaskExecutor webhookTaskExecutor() {
final SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor("webhook-");
executor.setVirtualThreads(true);
return executor;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,23 @@
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;

/**
* Sends webhook HTTP POST calls asynchronously and persists the response status. Each call runs in
* its own Spring-managed async thread with transactional context.
* Sends webhook HTTP POST calls and records the response status. Data events are delivered on the
* {@linkplain WebhookConfig#EXECUTOR_BEAN_NAME webhook executor}, so that a slow or unreachable
* receiver never blocks the operation that caused the event; a ping is delivered on the calling
* thread.
*/
@Component
public class WebhookSender {
Expand All @@ -33,28 +36,34 @@ public class WebhookSender {

private final WebhookDataService webhookDataService;

private final Executor executor;

/**
* Creates a new webhook sender.
*
* @param webhookRestClient the pre-configured {@link RestClient} used to deliver webhook calls
* @param webhookDataService the service used to look up webhooks and record delivery results
* @param webhookTaskExecutor the executor that delivers data events
*/
public WebhookSender(
final RestClient webhookRestClient, final WebhookDataService webhookDataService) {
final RestClient webhookRestClient,
final WebhookDataService webhookDataService,
@Qualifier(WebhookConfig.EXECUTOR_BEAN_NAME) final Executor webhookTaskExecutor) {
this.restClient =
Objects.requireNonNull(webhookRestClient, "webhookRestClient must not be null");
this.webhookDataService =
Objects.requireNonNull(webhookDataService, "webhookDataService must not be null");
this.executor =
Objects.requireNonNull(webhookTaskExecutor, "webhookTaskExecutor must not be null");
}

/**
* Delivers a payload to a single webhook and records the resulting HTTP status asynchronously.
* Delivers a payload to a single webhook and records the resulting HTTP status.
*
* @param webhook the target webhook
* @param payload the payload to deliver
*/
@Async
protected void sendAndTrack(final WebhookDto webhook, final WebhookEventPayload payload) {
private void sendAndTrack(final WebhookDto webhook, final WebhookEventPayload payload) {
int status;
try {
final ResponseEntity<Void> response =
Expand Down Expand Up @@ -82,26 +91,37 @@ protected void sendAndTrack(final WebhookDto webhook, final WebhookEventPayload
status = 0;
LOG.warn("Webhook call failed for URL {}: {}", webhook.url(), e.getMessage());
}
final WebhookDto updated =
new WebhookDto(webhook.id(), webhook.url(), webhook.active(), status, Instant.now());
webhookDataService.save(updated);
webhookDataService.recordCall(webhook.id(), status, Instant.now());
}

private boolean isTimeout(final ResourceAccessException e) {
return e.getCause() instanceof SocketTimeoutException;
}

/**
* Delivers a data-event payload to every currently active webhook.
* Delivers a data-event payload to every currently active webhook. Returns as soon as the calls
* are handed to the webhook executor; each call runs on its own.
*
* @param payload the payload to deliver
*/
public void sendAndTrack(WebhookDataEventPayload payload) {
webhookDataService.findAllActive().forEach(webhook -> sendAndTrack(webhook, payload));
public void sendAndTrack(final WebhookDataEventPayload payload) {
Objects.requireNonNull(payload, "payload must not be null");
webhookDataService
.findAllActive()
.forEach(webhook -> executor.execute(() -> sendAndTrackLogged(webhook, payload)));
}

private void sendAndTrackLogged(final WebhookDto webhook, final WebhookEventPayload payload) {
try {
sendAndTrack(webhook, payload);
} catch (final RuntimeException e) {
LOG.error("Failed to record the call of webhook {}", webhook.id(), e);
}
}

/**
* Sends a ping payload to a single webhook to verify that its endpoint is reachable.
* Sends a ping payload to a single webhook to verify that its endpoint is reachable. Runs on the
* calling thread, so the recorded status is available as soon as this method returns.
*
* @param id the id of the webhook to ping
* @throws IllegalArgumentException if no webhook with that id exists
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
package com.openelements.spring.base.services.webhook.data;

import com.openelements.spring.base.data.AbstractDbBackedDataService;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

/** Service handling webhook CRUD operations. */
@Service
public class WebhookDataService extends AbstractDbBackedDataService<WebhookEntity, WebhookDto> {

private static final Logger LOG = LoggerFactory.getLogger(WebhookDataService.class);

private final WebhookRepository webhookRepository;

/**
Expand Down Expand Up @@ -61,4 +67,28 @@ protected WebhookDto toData(WebhookEntity entity) {
public List<WebhookDto> findAllActive() {
return getRepository().findAllByActiveTrue().stream().map(this::toData).toList();
}

/**
* Records the result of a call to a webhook. Only the status and the call time are written, and
* no lifecycle event is published: the result of a delivery is bookkeeping, not a change of the
* registration, and an event would trigger a webhook call for every webhook call. A webhook that
* was deleted in the meantime is ignored.
*
* @param id the id of the called webhook
* @param status the HTTP status of the response, {@code 0} for a failed call or {@code -1} for a
* timeout
* @param calledAt when the webhook was called
*/
public void recordCall(final UUID id, final int status, final Instant calledAt) {
Objects.requireNonNull(id, "id must not be null");
Objects.requireNonNull(calledAt, "calledAt must not be null");
webhookRepository
.findById(id)
.ifPresentOrElse(
entity -> {
entity.setLastStatus(status);
entity.setLastCalledAt(calledAt);
},
() -> LOG.debug("Webhook {} was deleted before its call could be recorded", id));
}
}
Loading