@rotorsoft/act-http
v2.1.7
Published
HTTP integrations for act apps — webhooks, SSE, and tRPC, Hono and OpenAPI APIs generated from the registry
Maintainers
Readme
@rotorsoft/act-http
HTTP integrations for @rotorsoft/act — outbound webhooks and incremental state broadcast over Server-Sent Events.
Note. The
/ssesubpath is the home of the surface once published as@rotorsoft/act-sse. That package's status is in the deprecation policy.
Why this package
Most Act apps reach beyond their own process eventually — POSTing committed events to a downstream service, broadcasting state to a live UI, or both. The patterns are different (outbound HTTP vs long-lived text/event-stream), but they share a transport (HTTP) and an integration mental model ("Act over the wire"). Combining them under one umbrella with subpath exports gives you one install + one mental model, without conflating two implementations.
webhook() is sugar on top of .do(handler, { backoff }) — the same fetch wrapper most teams end up writing (timeout, idempotency key, status-classified errors, JSON serialization). The SSE surface is the verbatim continuation of @rotorsoft/act-sse. Nothing in webhook depends on sse or vice versa — pay only for what you import.
Installation
pnpm add @rotorsoft/act-httpThree independent subpath exports:
| Import path | What you get |
|---|---|
| @rotorsoft/act-http/webhook | webhook() — reaction handler that POSTs committed events with timeout, auto Idempotency-Key, and status-classified errors. |
| @rotorsoft/act-http/sse | BroadcastChannel, PresenceTracker, StateCache, applyPatchMessage — server-side broadcast + client-side patch applicator for incremental state sync. |
| @rotorsoft/act-http/receiver | receiver() builder (high-level Hono-backed runtime) + extractIdempotencyKey + verifyWebhook + checkWebhook (framework-agnostic core composing both with IdempotencyStore.claim). |
| @rotorsoft/act-http/receiver/trpc | webhookMiddleware — tRPC middleware adapter. |
| @rotorsoft/act-http/receiver/express | webhookMiddleware — Express middleware adapter. |
| @rotorsoft/act-http/receiver/fastify | webhookMiddleware — Fastify preHandler adapter. |
| @rotorsoft/act-http/receiver/hono | webhookMiddleware — Hono middleware adapter. |
| @rotorsoft/act-http/api | ActorExtractor type, ApiError + ERROR_MAP + toApiError envelope mapping, withIdempotency wrapper. Shared utilities for the auto-generated API surfaces (/trpc, /hono, /openapi subpaths, landing under issues #843/#844/#845). |
Quick start
webhook — outbound POST from a reaction
import { webhook } from "@rotorsoft/act-http/webhook";
.on("OrderConfirmed")
.do(
webhook({
url: "https://api.example.com/webhooks/orders",
headers: (event) => ({ Authorization: "Bearer " + token }),
body: (event) => ({ orderId: event.stream, total: event.data.total }),
timeoutMs: 2_000,
}),
{
maxRetries: 5,
backoff: { strategy: "exponential", baseMs: 200, maxMs: 30_000, jitter: true },
}
)
.to(resolver)receiver — high-level builder (the canonical path)
The receiver builder from @rotorsoft/act-http/receiver is Hono-backed and runs on every fetch-shaped runtime — long-running Node (via .listen()), AWS Lambda, Cloudflare Workers, Vercel Edge, Bun, Deno (all via .fetch()). Declare typed handlers with Zod schemas, call .build(), and the runtime handles signature verification, dedup, raw-body capture, schema validation, and HTTP server lifecycle:
import { receiver } from "@rotorsoft/act-http/receiver";
import { InMemoryIdempotencyStore } from "@rotorsoft/act-ops/idempotency";
import { z } from "zod";
const escalations = receiver({
port: 4001,
store: new InMemoryIdempotencyStore(),
secret: process.env.WEBHOOK_SECRET,
})
.on("OrderConfirmed", z.object({ orderId: z.string(), total: z.number() }),
async (event, ctx) => { await processOrder(event.orderId, event.total); })
.build();
await escalations.listen(); // Node
// export default { fetch: escalations.fetch }; // Cloudflare / Vercel / Bun / DenoNaming convention: type Receiver (PascalCase), factory receiver (lowercase) — matches Act's existing act / state / slice / projection builder analogs.
receiver/<framework> — low-level middleware
When the receiver needs to compose with an existing HTTP stack (auth middleware, route-level rate limiting, an app already serving other routes), reach for the per-framework webhookMiddleware factories. They compose extractIdempotencyKey + verifyWebhook + IdempotencyStore.claim (a tentative claim — see the two-phase note below) and translate the result into the framework's idiomatic 400/401 response:
// tRPC
import { webhookMiddleware } from "@rotorsoft/act-http/receiver/trpc";
import { InMemoryIdempotencyStore } from "@rotorsoft/act-ops/idempotency";
const dedup = new InMemoryIdempotencyStore();
const idempotent = t.procedure.use(
webhookMiddleware({ store: dedup, secret: process.env.WEBHOOK_SECRET })
);
const router = t.router({
webhook: idempotent.input(Schema).mutation(({ input, ctx }) => {
const { key, deduped } = ctx.idempotency;
if (deduped) return { status: "dedup-skipped", key };
return { status: "processed", key };
}),
});Each adapter follows the same shape:
import { webhookMiddleware } from "@rotorsoft/act-http/receiver/express";
app.post("/webhook", webhookMiddleware({ store, secret }), async (req, res) => {
const { key, deduped, commit, release } = (req as any).idempotency;
if (deduped) return res.status(204).end();
try {
// … process the event …
await commit(); // success — later retries dedup
res.status(204).end();
} catch (err) {
await release(); // transient — the sender's retry re-processes
res.status(500).json({ error: "handler-failed" });
}
});import { webhookMiddleware } from "@rotorsoft/act-http/receiver/fastify";
app.post("/webhook", { preHandler: webhookMiddleware({ store, secret }) }, async (req, reply) => {
const { key, deduped, commit, release } = (req as any).idempotency;
if (deduped) return reply.status(204).send();
try {
// … process the event …
await commit();
return reply.status(204).send();
} catch (err) {
await release();
return reply.status(500).send({ error: "handler-failed" });
}
});import { webhookMiddleware } from "@rotorsoft/act-http/receiver/hono";
app.post("/webhook", webhookMiddleware({ store, secret }), (c) => {
const { key, deduped } = c.get("idempotency");
// Hono auto-finalizes off the response: a 2xx/3xx commits, any 4xx/5xx (or a
// thrown handler) releases so a corrected same-key retry re-processes (#1364).
// …
return c.body(null, 204);
});On failure: the adapter responds with the framework's idiomatic 400 (missing-key) or 401 (one of five verification reasons — missing-signature, missing-timestamp, stale, future, bad-signature) and short-circuits the handler. On success: { key, deduped, commit, release } is injected into the request context.
Two-phase dedup. The claim a middleware makes is tentative: it dedups a concurrent duplicate mid-flight but is not durable until confirmed, so a transient handler failure never claims-then-loses the delivery. Hono and tRPC wrap the downstream chain and finalize automatically (2xx / resolved → commit; 5xx / thrown / { ok: false } → release). Express and Fastify middleware complete before the route handler, so the handler must call commit() on success or release() on a transient failure — skipping both leaves the claim tentative (dedups concurrent duplicates, expires on TTL, never permanently lost). deduped: true means another delivery holds the key, not that it succeeded. If your route answers a duplicate with 2xx while the original may still fail, a sender that stops on 2xx can lose that delivery. The receiver() builder avoids this by answering an in-flight duplicate with a retryable 503.
receiver primitives — when neither builder nor middleware fits
The framework-agnostic core (checkWebhook) and the underlying primitives (extractIdempotencyKey, verifyWebhook) are exported from @rotorsoft/act-http/receiver for receivers whose framework isn't in the adapter list (Koa, raw Node http, gRPC-over-HTTP, …) or for receivers with custom policy (e.g. "missing key falls back to body-derived dedup"). Use the receiver builder when you can; fall back to the framework webhookMiddleware, then the primitives.
trpc, hono, openapi — APIs generated from the registry
Each generator walks app.registry.actions and emits one route per action, so adding an action to the app adds it to every transport:
import { hono } from "@rotorsoft/act-http/hono";
import { openapi } from "@rotorsoft/act-http/openapi";
import { trpc } from "@rotorsoft/act-http/trpc";
type Ctx = { user: { id: string; name: string }; tenant: string };
const router = trpc<Ctx, typeof app>(app, {
actor: (ctx) => ({ id: ctx.user.id, name: ctx.user.name }),
stream: (action, input, ctx) => `tenant-${ctx.tenant}`,
});
const api = hono(app, {
actor: (c) => resolveActorFromJwt(c),
stream: (action, input, c) => `tenant-${c.req.header("x-tenant")}`,
}); // POST /api/actions/<action>
api.get("/openapi.json", (c) =>
c.json(openapi(app, { info: { title: "My API", version: "1.0.0" } }))
);Both are typed from the app: a tRPC client and Hono's hc<typeof api> see each action's payload and the snapshots it returns, with no casts. Framework errors share one envelope ({ error, detail?, code? }) and one status table. Optimistic concurrency (expectedVersion), Idempotency-Key handling, SSE subscriptions (sse: { channel }), auth composition and deployment recipes are in the auto-generated API guide.
sse — live state broadcast
import { BroadcastChannel, applyPatchMessage } from "@rotorsoft/act-http/sse";
// Server: after every app.do(), publish the state and its patches.
// Building both, including the empty patch a `.snap` needs, is in the
// real-time guide's "Broadcasting a commit".
broadcast.publish(streamId, state, patches);
// Client: in your SSE onData handler
onData: (msg) => {
const cached = utils.getState.getData({ streamId });
const result = applyPatchMessage(msg, cached);
if (result.ok) utils.getState.setData({ streamId }, result.state);
else if (result.reason === "behind") utils.getState.invalidate({ streamId });
};How to build state and patches from app.do()'s snapshots: Broadcasting a commit.
API
/webhook subpath
webhook(config)— reaction-handler factory. Returns a function compatible with.do(handler, opts).tryOk(response, { url, label? })— collapses the classify-and-throw block to one line for custom HTTP-like reactions (gRPC bridges, SDK-based deliveries). Returns void on 2xx; throwsRetryableHttpErroron 5xx; throwsNonRetryableHttpErroron 3xx/4xx. Captures the response body (best-effort) onto the thrown error.classifyHttpResponse(response)— the underlying"ok" | "retry" | "block"classifier. Reach for it directly when you need custom error classes; otherwisetryOkwraps it.RetryableHttpError— generic retryable delivery error. ExtendsError. Thrown bytryOkon 5xx.WebhookErrorextends it.NonRetryableHttpError— generic non-retryable delivery error. ExtendsNonRetryableErrorfrom@rotorsoft/act, so the drain finalizer blocks the stream on first failed attempt. Thrown bytryOkon 3xx/4xx.NonRetryableWebhookErrorextends it.WebhookError— webhook-specific subclass ofRetryableHttpError, thrown by thewebhookhelper. Existinginstanceof WebhookErrorchecks continue to work; new code targeting any HTTP integration can catchRetryableHttpErrorto handle both webhook + custom-integration errors uniformly.NonRetryableWebhookError— webhook-specific subclass ofNonRetryableHttpError, thrown bywebhookon 3xx/4xx. Same backward-compat story asWebhookError.WebhookConfig— TypeScript type for the helper options.HttpDisposition— the"ok" | "retry" | "block"discriminator returned byclassifyHttpResponse.HttpDeliveryErrorInit— common{ status, url, responseBody? }shape passed to every HTTP error class.TryOkOptions—{ url, label? }shape passed totryOk.
/receiver subpath
checkWebhook(headers, body, options)— framework-agnostic core. ComposesverifyWebhook(whenoptions.secretis set; an emptysecretthrows, here and whenwebhook(...)or awebhookMiddlewareis built, because the sender would read it as unsigned and the receiver as signed; aNaNor negativeverify.maxAgeSecondsthrows when a middleware is built too) +extractIdempotencyKey+options.store.claim(a tentative claim). Returns{ ok: false; status: 400|401; reason }on failure or{ ok: true; key; deduped }on success. The caller owns finalization:options.store.commit(key)on handler success,options.store.release(key)on a transient failure. The per-framework adapters wrap this and translate the outcome into the framework's idiomatic response.extractIdempotencyKey(headers)— case-insensitiveIdempotency-Keyheader parser. Returnsundefinedwhen the header carries no usable key: missing, array-valued (ambiguous), or empty string. Validation beyond "is there a usable key?" (length, format) is intentionally out of scope.verifyWebhook(headers, body, secret, opts?)— HMAC-SHA256 signature + timestamp window verifier. Returns{ ok: true }or{ ok: false; reason }where reason is one ofmissing-signature/missing-timestamp/stale/future/bad-signature. Default timestamp window is ±300 seconds; override viaopts.maxAgeSeconds. Usescrypto.timingSafeEqualto avoid timing attacks. Pair withwebhook({ secret })on the sender side.- Types:
CheckResult,CheckWebhookOptions,CheckFailureReason,VerifyResult,VerifyOptions.
/receiver/<framework> subpaths
Each framework adapter exports a single function webhookMiddleware(options) that returns the framework's native middleware shape. Options are { store, secret?, verify? } — the same CheckWebhookOptions as the core. Failure → 400/401 with { error: <reason> }; success → { key, deduped, commit, release } is injected. Hono and tRPC auto-finalize off the downstream outcome; Express and Fastify require the route handler to call commit() / release() (see the two-phase note above):
| Subpath | Injection site | Failure response |
|---|---|---|
| /receiver/trpc | ctx.idempotency | throws TRPCError({ code, message: reason }) |
| /receiver/express | req.idempotency | res.status(...).json({ error: reason }) |
| /receiver/fastify | request.idempotency | reply.status(...).send({ error: reason }) |
| /receiver/hono | c.get("idempotency") (typed via Variables) | c.json({ error: reason }, status) |
/api, /trpc, /hono, /openapi subpaths
/api— what every transport shares:ActorExtractor, theApiErrorenvelope,ERROR_MAPandtoApiError(err),withIdempotency(store, key, handler), and the SSE wiring (SseOptions,runSseSubscription). Bad SSE options throwZodErrorwhen the transport is built./trpc—trpc(app, options), theauthenticated(extractor)middleware, andTrpcOptions./hono—hono(app, options), theauthenticated(extractor)middleware,HonoOptionsandActMiddlewareVariables. A body that fails its action's schema returns422with theApiErrorenvelope./openapi—openapi(app, options), which returns an OpenAPI 3.1 document describing thehonoroutes, plusOpenAPIOptionsand the document types.
Every option is described in the auto-generated API guide.
/sse subpath
BroadcastChannel<S>— server-side broadcast manager with per-stream subscriber sets and an LRU state cache.PresenceTracker— ref-counted online-status tracker for multi-tab clients.StateCache<S>— the generic LRU used internally byBroadcastChannel.applyPatchMessage(msg, cached)— client-side patch applicator. Returns{ ok: true, state }or{ ok: false, reason: "stale" | "behind" }.patch(original, patches)— browser-safe deep-merge utility (re-exported from@rotorsoft/act-patch).- Types:
BroadcastState,PatchMessage<S>,Subscriber<S>.
Configuration
webhook options
| Option | Type | Default |
|---|---|---|
| url | string or (event) => string | required |
| method | "POST" | "PUT" | "PATCH" | "DELETE" | "POST" |
| headers | Record<string, string> or (event) => … | {} |
| body | unknown or (event) => unknown | the committed event (JSON-serialized) |
| timeoutMs | number | 5000 |
| idempotencyKey | (event) => string | null | String(event.id) |
| secret | string | unset (unsigned) |
| fetch | typeof fetch | globalThis.fetch |
Strings as body are sent as-is; anything else is JSON.stringify'd and Content-Type: application/json is set automatically (unless the caller supplies it).
A caller-supplied Idempotency-Key header (case-insensitive) always wins; the auto-derived event.id is only applied when the header is absent. event.id is the framework's immutable, per-event monotonic integer — well-suited to downstream dedup.
When secret is set, the helper signs each request with HMAC-SHA256 over ${timestamp}.${body} (the final serialized body) and attaches X-Webhook-Signature: sha256=<hex> + X-Webhook-Timestamp: <unix-seconds>. Caller-supplied versions of either header (case-insensitive) win, the same way the Idempotency-Key and Content-Type defaults yield to caller intent. Pair with verifyWebhook from @rotorsoft/act-http/receiver on the receiving side — the protocol matches Stripe / GitHub / Slack conventions modulo the X-Webhook-* prefix.
Common patterns
Retry & block semantics
The drain pipeline retries on WebhookError per maxRetries and paces with backoff. It blocks immediately on NonRetryableWebhookError (when blockOnError is true) — no retry budget consumed.
| Shape | Config |
|---|---|
| Be patient with the receiver (recommended) | { maxRetries: 5, backoff: { strategy: "exponential", baseMs: 200, maxMs: 30_000, jitter: true } } |
| Never give up | { blockOnError: false, backoff: {…} } — for sinks that must eventually succeed: the stream never blocks, so maxRetries stops nothing. 4xx falls back to the same loop. |
| Strict — block on any failure | { maxRetries: 0 } — useful for endpoints with strong idempotency where any failed POST warrants operator review. |
In catch blocks, distinguish retryable from non-retryable via the two classes (or the shared status field):
try {
await deliver();
} catch (err) {
if (err instanceof NonRetryableWebhookError) {
// 4xx — caller bug or permanent state; log and move on
} else if (err instanceof WebhookError) {
// retryable — drain will handle
}
}Generic catch sites that don't care about HTTP specifics can match on the base NonRetryableError from @rotorsoft/act.
Recovering a blocked stream
When webhook blocks a stream (on a 4xx, or after exhausting retries), recover with app.unblock(...), which resumes from where the stream stopped. Never app.reset() it: that replays from event 0 and re-fires every historical webhook. See Blocked streams.
SSE wire format
Version-keyed domain patches; keys are the state version after the patch applies:
{
"5": { territories: { brazil: { armies: 3 } } },
"6": { currentPlayerIndex: 2, phase: "reinforce" }
}Multi-event commits produce multiple entries in one message. Version gaps trigger full state refetch on the client (applyPatchMessage returns { ok: false, reason: "behind" }).
When webhook is the right tool — and when it isn't
webhook is built for fire-and-forget delivery to a cooperative receiver: timeouts shorter than the drain lease, retries paced by backoff, idempotent endpoints.
Keep timeoutMs below leaseMillis. The drain lease stops competing workers from re-dispatching while your handler is in flight. The default lease is 10 seconds; the default timeoutMs is 5000. If timeoutMs approaches or exceeds the lease, a slow receiver can hold the lease through expiry, another worker claims the stream, and the same event POSTs twice. The downstream Idempotency-Key then becomes load-bearing — if your receiver doesn't dedup, you'll deliver twice. Rule: timeoutMs ≤ leaseMillis - safety_margin.
For heavy or long-running delivery, don't use webhook directly. Drain leases aren't free, and holding one for tens of seconds while a slow API churns is the wrong shape. The Act-native pattern is outbox-style fan-out: emit a "needs delivery" event from your reaction (a cheap, local operation), and let a separate consumer — a downstream worker, a Kafka/SQS pipeline, an external scheduler — do the long work at its own pace.
| Shape of work | Right tool |
|---|---|
| 1–2s POST to a fast, idempotent API | webhook directly |
| Webhook to a flaky-but-fast third party | webhook + aggressive backoff |
| Multi-second / multi-minute API call | Emit a "needs delivery" event; bus worker calls the API |
| Bulk fan-out (10k+ receivers) | Emit a "fanout" event; dedicated consumer enumerates receivers |
| Streaming / long-poll / large file transfer | Not webhook — write a dedicated worker |
For the recommended receiver-side idempotency contract that pairs with webhook, see the external integration guide.
Compatibility
- Node: >=22.23.4
- Peer:
@rotorsoft/act(workspace version) - Runtime deps:
@rotorsoft/act-patch(used by the SSE subpath for state merging) - Module formats: ESM + CJS, dual subpath exports
- Browser: the
/sseclient-side helpers (applyPatchMessage,patch, types) are browser-safe and have no Node-specific dependencies
Stability
Public API governed by the Act Stability Charter. Both subpaths (@rotorsoft/act-http/webhook and @rotorsoft/act-http/sse) are covered by the charter. Charter is in effect as of 1.0.0; the milestone tracker is milestone 1.0.
Related packages
- @rotorsoft/act — core framework.
webhookcomposes with.do(handler, { backoff });BroadcastChannelpublishes fromapp.do()snapshots. - @rotorsoft/act-sse — predecessor of the
/ssesubpath here; its status is in the deprecation policy. - @rotorsoft/act-patch — the immutable patch utility that powers the SSE state merge.
- @rotorsoft/act-pg / @rotorsoft/act-sqlite — store adapters.
webhookreactions persist their watermarks through whichever store you've wired.
Documentation
- Auto-generated API surfaces — narrative walkthrough of the
/trpc,/hono,/openapisubpaths plus the shared utilities at/api. Authentication seam, idempotency, optimistic concurrency, deployment recipes (Node, Lambda, Cloudflare, Next.js), and migrating from a hand-written router. - External integration patterns — inline
webhookvs forwarded bus, receiver-side idempotency contract, the recovery loop. - Real-time with SSE — concept guide for the
/ssesurface. - Error handling — backoff,
NonRetryableError, blocked streams,unblockrecovery.
License
MIT
