@gjermundgaraba/effect-actions 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,68 +3,94 @@ import { allowAll } from "./Action.mjs";
3
3
  import { allowAll as allowAll$1 } from "./Event.mjs";
4
4
  import { EventImplementation } from "./contract/feed.mjs";
5
5
  import { Implementation, memoized } from "./contract/implementation.mjs";
6
+ import { reported } from "./contract/reported.mjs";
6
7
  import { buildersOf, servingOf } from "./contract/serving.mjs";
7
8
  import { Wake } from "./contract/wake.mjs";
8
9
  import { polling } from "./contract/watch.mjs";
9
10
  import { offersWebhook } from "./contract/webhooks.mjs";
11
+ import { make as make$1 } from "./ActionRpc.mjs";
10
12
  import { actionMethodOf, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollOf, polledTransport, watchedOf, webhookCallsOf, webhookRpcsOf } from "./rpc/erased.mjs";
11
13
  import { forwarded, forwardedHeaders } from "./entity/forwarded.mjs";
12
14
  import { WakeRpc, makeWake, wakeTag } from "./entity/wakes.mjs";
13
- import { Duration, Effect, Function, Layer, Predicate, Schema, Stream } from "effect";
15
+ import { Cause, Context, DateTime, Duration, Effect, Function, Layer, Option, Predicate, Schema, Stream } from "effect";
14
16
  import { ClusterError, Entity } from "effect/cluster";
15
17
  import { Rpc, RpcGroup, RpcMessage } from "effect/rpc";
18
+ import { SqlClient } from "effect/sql";
16
19
  // src/entity/ActionEntity.ts
17
20
  const namedBy = (key) => (input) => {
18
21
  const named = key(input);
19
22
  return Predicate.isString(named) ? named : void 0;
20
23
  };
24
+ const bindingOf = make$1;
21
25
  const libraryRpcsOf = (binding) => erasedOf(binding.actions, binding.events, "ActionEntity.layer").merge(webhookRpcsOf(binding.events)).add(WakeRpc);
22
- /**
23
- * The cluster entity of type `type` serving the actions and event types of `binding`, an
24
- * `ActionRpc` binding, each call and subscription in the entity its contract's `key` names for
25
- * its input. Each event type is a unary rpc named `<event>/poll`, `ActionRpc.pollTag`, taking
26
- * `{ input, cursor, maxEvents, watch }` and answering a page,
27
- * `{ events, cursor, truncated, hasMore, nextPollMs, notified }`, an HTTP poll's page and
28
- * `notified`, `ActionRpc.Page`, as `ActionRpc.layer` serves it too, its subscription hook held
29
- * for the caller's principal. A protected event type has two more, `<event>/subscribe` and
30
- * `<event>/unsubscribe`, taking a webhook subscription and its cancellation, and the entity has
31
- * its wake, `effect-actions/wake`, a persisted tell it sends itself to end a webhook delivery's
32
- * retry wait. Guide: `docs/ActionEntity.md` in this package.
33
- *
34
- * **Gotchas**
35
- *
36
- * - The rpcs of its actions, event types and webhook subscriptions are volatile, as `ClusterSchema.Persisted` defaults, and its wake alone is persisted: annotated persisted, each envelope, its caller's headers and credential included, would be stored and replayed with them, on Effect's SQL runners until a `MessageRetention` layer deletes it, and on the Cloudflare runtime, which never prunes `cluster_messages`, for good, its credential headers redacted. `rpcs`' natives are persisted as their own annotations say.
37
- * - A binding with native rpcs throws: give the entity's own rpcs to `make`'s `rpcs`.
38
- * - A streaming action, one declaring `progress` or answering `Action.Stream`, is a stream rpc, its frames those `ActionRpc.make` states, `client`'s method handing each progress value to `onProgress` before it answers, and returning a `Stream` of the elements of an `Action.Stream` answer; it holds a slot of the entity's `concurrency`, by default its only one, until its stream ends, but on the Cloudflare runtime, which frees the slot while a frame waits for its client's acknowledgement.
39
- * - `annotate` and its kin return a plain `Entity`, without `binding` and `key`, which `layer` and `client` do not take.
40
- */
41
- const make = (type, binding, options) => {
42
- const natives = [...nativeOf(binding.rpcs).requests.keys()];
43
- if (natives.length > 0) throw new Error(`ActionEntity.make: the binding of ${type} holds native rpcs, ${natives.join(", ")} (give them to ActionEntity.make's rpcs, unauthenticated)`);
44
- const erased = libraryRpcsOf(binding);
45
- const rpcs = options.rpcs ?? RpcGroup.make();
46
- const taken = [...rpcs.requests.keys()].filter((tag) => erased.requests.has(tag) || binding.events.some(({ name }) => name === tag));
47
- if (taken.length > 0) throw new Error(`ActionEntity.make: the native rpcs of ${type}, ${taken.join(", ")}, are named after an action, an event type, an event's poll, subscribe or unsubscribe, or the entity's wake, ${wakeTag} (rename them)`);
48
- const protocol = erased.merge(rpcs);
26
+ const entityOf = (type, binding, key, library, natives) => {
27
+ const rebuilt = (annotated) => entityOf(type, binding, key, library, annotated);
28
+ const protocol = library.merge(natives);
49
29
  return Object.assign(Entity.fromRpcGroup(type, protocol), {
50
30
  binding,
51
- key: options.key
31
+ key,
32
+ of: (handlers) => handlers,
33
+ annotate: (tag, value) => rebuilt(natives.annotate(tag, value)),
34
+ annotateMerge: (annotations) => rebuilt(natives.annotateMerge(annotations)),
35
+ annotateRpcs: (tag, value) => rebuilt(natives.annotateRpcs(tag, value)),
36
+ annotateRpcsMerge: (annotations) => rebuilt(natives.annotateRpcsMerge(annotations))
52
37
  });
53
38
  };
39
+ function make(type, contracts, options) {
40
+ const { key, authentication } = options;
41
+ const rpcs = nativeOf(options.rpcs ?? RpcGroup.make());
42
+ const binding = bindingOf(contracts, authentication === void 0 ? {} : { authentication });
43
+ const erased = libraryRpcsOf(binding);
44
+ const taken = [...rpcs.requests.keys()].filter((tag) => erased.requests.has(tag) || binding.events.some(({ name }) => name === tag));
45
+ if (taken.length > 0) throw new Error(`ActionEntity.make: the native rpcs of ${type}, ${taken.join(", ")}, are named after an action, an event type, an event's poll, subscribe or unsubscribe, or the entity's wake, ${wakeTag} (rename them)`);
46
+ return entityOf(type, binding, key, erased, nativeOf(rpcs));
47
+ }
54
48
  /**
55
49
  * The rpcs of `entity`'s binding, as its `protocol` holds them without its native rpcs: one per
56
- * action, and per event type its poll. What a surface outside the
57
- * cluster may forward to the entity, as the Cloudflare package's socket host does, which
58
- * `ActionRpc.client`'s watch polls, finding no stream rpc.
50
+ * action, the entity's internal actions included, and per event type its poll. A surface outside
51
+ * the cluster forwards to the entity those of them its own binding lists alone, as the Cloudflare
52
+ * package's socket host forwards its `actions`, which `ActionRpc.client`'s watch polls, finding
53
+ * no stream rpc.
59
54
  */
60
55
  const bindingRpcs = (entity) => erasedOf(entity.binding.actions, entity.binding.events, "ActionEntity.layer");
56
+ /**
57
+ * Wake the entity at `at`: a persisted tell it sends itself, delivered then to `layer`'s
58
+ * `onWake`, through eviction, a restart and a deploy, in whichever activation is current, built
59
+ * again for it where the entity had stopped. It succeeds once the runtime stored the tell, and
60
+ * fails with `Action.Unavailable` where it could not, so a caller knows the wake is scheduled
61
+ * before it starts what the wake guards. Read it in the entity: `services`, a builder or a handler.
62
+ *
63
+ * **Gotchas**
64
+ *
65
+ * - The wake keeps the earliest time: a time no earlier than one this activation scheduled and has not seen fire sends nothing, as that wake's `onWake` asks for it again; a tell cannot be taken back, so a time moved later or dropped still fires.
66
+ * - Each wake is a row of the runtime's messages, kept once processed, on Effect's SQL runners until a `MessageRetention` layer deletes it, and on the Cloudflare runtime for good.
67
+ * - It holds nothing awake: work already running keeps its activation with `Entity.keepAlive` and its Durable Object event with `waitUntil`, beside the wake that resumes it later.
68
+ * - Asked for inside a transaction of the entity's or the runner's `SqlClient`, it dies, as the wake would be stored in that transaction and dropped by its rollback while the activation counted it pending: call it after the transaction commits.
69
+ * - A time between milliseconds is rounded up to the next one, as the runtime stores whole milliseconds.
70
+ */
71
+ const wakeAt = (at) => Effect.flatMap(Wake, (wake) => wake.wakeAt(Math.ceil(DateTime.toEpochMillis(at))));
61
72
  const callOf = (request, rpc) => ({
62
73
  client: new Rpc.ServerClient(0),
63
74
  requestId: RpcMessage.RequestId(String(request.requestId)),
64
75
  headers: request.headers,
65
76
  rpc
66
77
  });
67
- function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options } = {}) {
78
+ const ClusterFailures = Schema.Union([
79
+ ClusterError.MailboxFull,
80
+ ClusterError.PersistenceError,
81
+ ClusterError.AlreadyProcessingMessage,
82
+ ClusterError.EntityNotAssignedToRunner
83
+ ]);
84
+ /**
85
+ * Whether a failure is one of those Effect's entity client fails with when the entity could not
86
+ * be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
87
+ * `EntityNotAssignedToRunner`, which `client`, `nativeClient` and `reaching` answer as
88
+ * `Action.Unavailable`: a server forwarding calls into an entity, as the Cloudflare package's
89
+ * socket host does, makes them a defect, and a Worker calling Effect's `Entity.client` itself
90
+ * answers them, as the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
91
+ */
92
+ const isClusterFailure = Schema.is(ClusterFailures);
93
+ function layer(entity, served, { services = Layer.empty, rpcs = {}, onWake, ...options } = {}) {
68
94
  const { binding } = entity;
69
95
  const named = namedBy(entity.key);
70
96
  const { apps, events, authentication } = servingOf("ActionEntity binding", binding, served, { actions: [...binding.actions, ...binding.events] });
@@ -72,10 +98,14 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
72
98
  const build = Effect.gen(function* () {
73
99
  const address = yield* Entity.CurrentAddress;
74
100
  const sharding = yield* Effect.context();
75
- const { wake, woke } = yield* makeWake((payload) => Effect.flatMap(entity.client, (clientFor) => {
101
+ const outsideTransactions = Effect.gen(function* () {
102
+ const clients = [yield* Effect.serviceOption(SqlClient.SqlClient), Context.getOption(sharding, SqlClient.SqlClient)].flatMap(Option.toArray);
103
+ for (const sql of clients) if (Option.isSome(yield* Effect.serviceOption(sql.transactionService))) return yield* Effect.die(/* @__PURE__ */ new Error(`ActionEntity.wakeAt: the wake of ${address.entityType}/${address.entityId} was asked for inside a SQL transaction, whose rollback would drop it unseen (call wakeAt after the transaction commits)`));
104
+ });
105
+ const { wake, woke } = yield* makeWake((payload) => Effect.andThen(outsideTransactions, Effect.flatMap(entity.client, (clientFor) => {
76
106
  return clientFor(address.entityId)[wakeTag](payload, { discard: true });
77
- }).pipe(Effect.provideContext(sharding)));
78
- const built = yield* Layer.buildWithMemoMap(first === void 0 ? services : Layer.provideMerge(Layer.mergeAll(first, ...rest), services), Layer.makeMemoMapUnsafe(), yield* Effect.scope).pipe(Effect.provideService(Wake, wake));
107
+ }).pipe(Effect.catchIf(isClusterFailure, ({ _tag }) => Effect.fail(new Unavailable({ message: `The wake of ${address.entityType}/${address.entityId} could not be scheduled (${_tag})` }))), Effect.provideContext(sharding))));
108
+ const built = yield* Layer.buildWithMemoMap(Layer.provideMerge(first === void 0 ? services : Layer.provideMerge(Layer.mergeAll(first, ...rest), services), Layer.succeed(Wake, wake)), Layer.makeMemoMapUnsafe(), yield* Effect.scope);
79
109
  const check = (contract, input) => {
80
110
  const entityId = named(input);
81
111
  return entityId === address.entityId ? Effect.void : Effect.fail(new Forbidden({ message: `This entity is ${address.entityType}/${address.entityId}, and the input of ${contract.name} names ${entityId ?? "none"}` }));
@@ -90,9 +120,10 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
90
120
  }
91
121
  }), built);
92
122
  const natives = yield* Effect.provideContext(Effect.isEffect(rpcs) ? rpcs : Effect.succeed(rpcs), built);
123
+ const woken = (at) => onWake === void 0 ? Effect.void : Effect.provideContext(Effect.catchCauseIf(onWake(DateTime.makeUnsafe(at)), (cause) => !Cause.hasInterruptsOnly(cause), reported), built);
93
124
  const answering = (handler) => (request) => Rpc.wrapMap(handler(request), (answer) => Effect.isEffect(answer) ? Effect.provideContext(answer, built) : Stream.provideContext(answer, built));
94
125
  return Object.fromEntries([...nativeOf(entity.protocol).requests.values()].map((rpc) => {
95
- if (rpc._tag === "effect-actions/wake") return [rpc._tag, woke];
126
+ if (rpc._tag === "effect-actions/wake") return [rpc._tag, ({ payload }) => Rpc.fork(Effect.andThen(woke(payload.at), () => woken(payload.at)))];
96
127
  const handler = handlers[rpc._tag];
97
128
  if (handler !== void 0) return [rpc._tag, (request) => {
98
129
  const answer = handler(request.payload, callOf(request, rpc));
@@ -108,21 +139,6 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
108
139
  disableFatalDefects: true
109
140
  });
110
141
  }
111
- const ClusterFailures = Schema.Union([
112
- ClusterError.MailboxFull,
113
- ClusterError.PersistenceError,
114
- ClusterError.AlreadyProcessingMessage,
115
- ClusterError.EntityNotAssignedToRunner
116
- ]);
117
- /**
118
- * Whether a failure is one of those Effect's entity client fails with when the entity could not
119
- * be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
120
- * `EntityNotAssignedToRunner`, which `client`, `nativeClient` and `reaching` answer as
121
- * `Action.Unavailable`: a server forwarding calls into an entity, as the Cloudflare package's
122
- * socket host does, makes them a defect, and a Worker calling Effect's `Entity.client` itself
123
- * answers them, as the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
124
- */
125
- const isClusterFailure = Schema.is(ClusterFailures);
126
142
  const defaultTimeout = Duration.seconds(20);
127
143
  const sendingWithin = (type, options) => {
128
144
  const timeout = Duration.fromInputUnsafe(options.timeout ?? defaultTimeout);
@@ -190,7 +206,8 @@ function nativeClient(entity, options = {}) {
190
206
  }
191
207
  /**
192
208
  * The implementations of `entity`'s actions and event types that any surface serves beside its
193
- * own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
209
+ * own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`, one for every action the
210
+ * entity lists, those no surface's binding lists included: each call sent through
194
211
  * `Entity.client` to the entity its contract's key names for its input, with the caller's
195
212
  * headers, and its answer, declared errors and progress passed back; each event followed through
196
213
  * the entity's poll rpc. A call the entity could not be reached for, or that did not answer
@@ -199,6 +216,7 @@ function nativeClient(entity, options = {}) {
199
216
  *
200
217
  * **Gotchas**
201
218
  *
219
+ * - A surface that serves every implementation it is given serves the entity's internal actions to its callers too: `ActionMcp.layerHttp` without `actions`, and `ActionRpc.layer` or `ActionHttp.layer` on `entity.binding`, so give MCP its `actions` and the others a binding of the public contracts.
202
220
  * - The caller's credential is verified by the surface serving these and again by the entity reached, so both are given the verifier: a call the surface refuses reaches no entity.
203
221
  * - A refusal by the entity, a credential expired since the surface verified it included, ends a stream after it answered 200, where the surface's own refusal would have answered its 401 or 403.
204
222
  * - The caller's request's headers are sent on as `forwardedHeaders` keeps them: its connection's, its body's, what it accepts and an MCP request's routing headers are not.
@@ -211,7 +229,7 @@ function nativeClient(entity, options = {}) {
211
229
  * - HTTP's `text/event-stream` whose polling ended on a failure other than a refusal sends `Failed` and opens it again 5 seconds later, from where it reached; MCP's `events/stream` does what `ActionMcp.layerHttp` says of an upstream's failure, a `-32603` before `active`.
212
230
  * - A stream's polls, and a poll, MCP's `events/poll` included, hold the subscriber's subscription hook in the entity until its source's `lease` lapses after the last, as on any surface.
213
231
  * - A protected event's webhook subscription is held by the entity its input's key names, the subscribe and unsubscribe sent there with the caller's headers, and delivered by the `Webhook.layer` in that entity's `services`, never the serving surface's: an entity without one fails the subscribe with `Event.SubscriptionError`, reason `Unsupported`, a 409 over HTTP, before any callback is sent.
214
- * - An error the entity declares beyond the action's own and the built-in ones, its binding's `error` or its verifier's, is undeclared where the serving surface's binding does not declare it too.
232
+ * - An error the entity declares beyond the action's own and the built-in ones, its verifier's, is undeclared where the serving surface's binding does not declare it too.
215
233
  */
216
234
  const reaching = (entity, options = {}) => {
217
235
  const { binding } = entity;
@@ -246,4 +264,4 @@ const reaching = (entity, options = {}) => {
246
264
  };
247
265
  return [...binding.actions.length === 0 ? [] : [new Implementation(binding.actions, memoized(Effect.map(reaches, (reach) => binding.actions.map((action) => [action, handlerOf(action, reach)]))), memoized(Effect.succeed(allowAll)))], ...binding.events.length === 0 ? [] : [new EventImplementation(binding.events, binding.events.map((event) => [event, memoized(Effect.map(reaches, (reach) => runOf(event, reach)))]), memoized(Effect.succeed(allowAll$1)))]];
248
266
  };
249
- export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, nativeClient, reaching };
267
+ export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, nativeClient, reaching, wakeAt };
@@ -145,8 +145,11 @@ export declare function make<const Contracts extends ReadonlyArray<Any$1 | Any$2
145
145
  * Serve the binding's actions and event types among `implementations` in one layer, or those its
146
146
  * `actions` lists, authenticating a protected action's request before decoding it, then running
147
147
  * its implementation's `authorize` before each handler. An implementation's actions the binding
148
- * leaves out have no route here, one holding none of those served is not built, and a non-empty
149
- * list holding none of the binding's actions is refused when `layer` is called. Several layers
148
+ * leaves out have no route here, and one holding none of those served is not built. Where the
149
+ * binding has no event types, implementations' event types are ignored, so
150
+ * `ActionEntity.reaching` serves a binding of the entity's actions alone, and the same holds for
151
+ * actions; otherwise implementations holding none of the binding's actions, or none of its event
152
+ * types, are refused when `layer` is called. Several layers
150
153
  * may serve one binding, each with its own `actions` and `middleware` covering its routes only.
151
154
  * The layer fails as the builders do, needs at startup what they need, and per request what the
152
155
  * authorization and handlers of the actions it serves need, until its `middleware` or middleware
@@ -16,7 +16,8 @@ import { Poll, ProgressedOf, pollTag } from "./rpc/erased.mjs";
16
16
  import { AnyPage } from "./contract/pages.mjs";
17
17
  import { Context, Duration, Effect, Layer, Schedule, Schema, Scope, Stream, Types } from "effect";
18
18
  import { HttpRouter, HttpServerRequest } from "effect/http";
19
- import { Rpc, RpcClient, RpcClientError, RpcGroup, RpcMiddleware, RpcSchema, RpcServer } from "effect/rpc";
19
+ import { Rpc, RpcClient, RpcClientError, RpcGroup, RpcMiddleware, RpcSchema, RpcSerialization, RpcServer } from "effect/rpc";
20
+ import { Socket } from "effect/socket";
20
21
  type BindingError = Errors[number];
21
22
  type ErrorOf<A extends Any$2, E extends Errors, D> = Schema.Union<ReadonlyArray<A["error"][number] | E[number] | VerifierError<A, D> | BuiltIns>>;
22
23
  type ElementedOf<Element extends Schema.Constraint, P> = Schema.Union<readonly [Schema.TaggedStruct<"Element", {
@@ -235,10 +236,17 @@ type Watching<B extends Any> = [B["events"][number]] extends [never] ? unknown :
235
236
  export type Client<B extends Any> = { readonly [A in B["actions"][number] as A["name"]]: Method<A, B["error"][number] | VerifierError<A, B["authentication"]>>; } & Watching<B> & RpcClient.RpcClient<RpcGroup.Rpcs<B["rpcs"]>, RpcClientError.RpcClientError>;
236
237
  /**
237
238
  * `client`'s options: the native `RpcClient.make` options, `spanPrefix`, `spanAttributes`,
238
- * `generateRequestId` and `disableTracing`. `flatten` changes the client's shape, which the
239
- * method types cannot follow.
239
+ * `generateRequestId` and `disableTracing`, and `watchMode`. `flatten` changes the client's
240
+ * shape, which the method types cannot follow.
240
241
  */
241
- export type ClientOptions = Omit<NonNullable<Parameters<typeof RpcClient.make>[1]>, "flatten">;
242
+ export interface ClientOptions extends Omit<NonNullable<Parameters<typeof RpcClient.make>[1]>, "flatten"> {
243
+ /**
244
+ * The `mode` of a watch that gives none: `"poll"` reads its pages from the first, as a server
245
+ * serving events by poll alone, such as the Cloudflare package's socket host, needs, without the
246
+ * round trip a watch otherwise spends finding that out. A watch's own `mode` wins.
247
+ */
248
+ readonly watchMode?: "stream" | "poll" | undefined;
249
+ }
242
250
  /**
243
251
  * How long a polling watch waits for a poll's answer, 4 minutes, before it sends the poll again
244
252
  * from the same cursor and interrupts the first.
@@ -264,25 +272,69 @@ export declare const pollResentAfter: Duration.Duration;
264
272
  * - A native rpc of the binding's `rpcs` is the native client's method: a stream rpc's is a `Stream`, its headers given as its options' `headers`, since `RpcClient.withHeaders` wraps an Effect.
265
273
  */
266
274
  export declare function client<const B extends Any>(binding: B, options?: ClientOptions): Effect.Effect<Client<B>, never, RpcClient.Protocol | Scope.Scope | Rpc.MiddlewareClient<RpcGroup.Rpcs<B["rpcs"]>>>;
267
- /**
268
- * What `reconnectUntil`'s schedule reads of each failure to connect: the `reason` of the
269
- * `Socket.SocketError` Effect's socket protocol retries after.
270
- */
271
- export interface ReconnectReason {
272
- readonly reason: unknown;
273
- }
274
275
  /**
275
276
  * A socket client's `retryPolicy`, for `RpcClient.layerProtocolSocket`, that stops connecting
276
277
  * again once the server closes the socket with one of `codes`, such as a refusal of its upgrade:
277
278
  * until then it is Effect's own default, `Schedule.min([Schedule.exponential(500, 1.5),
278
279
  * Schedule.spaced(5000)])`, which Effect does not export. A page refused with its code stops, its
279
280
  * calls and streams failing with an `RpcClientError` whose `reason` is that `SocketCloseError`,
280
- * its `code` the one it closed with.
281
+ * its `code` the one it closed with. `socketClient` stops at every application code already.
281
282
  *
282
283
  * **Gotchas**
283
284
  *
284
285
  * - A client without it connects again after a refusal as after any close, every five seconds for good.
285
286
  * - Any other socket error, a drop included, is retried as Effect's default retries it.
287
+ * - A watch through `client` connects again after a close below 4000 whatever the protocol stopped at, failing each time: stop at codes from 4000 to 4999, which a watch ends at.
288
+ */
289
+ export declare const reconnectUntil: (...codes: readonly number[]) => Schedule.Schedule<Duration.Duration, Socket.SocketError, never, never>;
290
+ /** Where `socketClient` connects: a URL, or a socket made elsewhere, never both. */
291
+ export type SocketTarget = {
292
+ /** The `ws:` or `wss:` URL the client dials, again after each drop. */
293
+ readonly url: string;
294
+ /**
295
+ * What makes each WebSocket. Omitted: the global `WebSocket`, looked up on every
296
+ * connection, as a browser has it. Node's `ws` package, `(url) => new WebSocket(url, {
297
+ * headers })`, sends headers on the upgrade, which a browser cannot.
298
+ */
299
+ readonly webSocket?: Socket.WebSocketConstructor["Service"] | undefined;
300
+ readonly socket?: never;
301
+ } | {
302
+ /**
303
+ * A `Socket` made elsewhere, such as `Socket.fromWebSocket` over a socket a Worker's
304
+ * `fetch` returned: its acquisition runs again for each connection.
305
+ */
306
+ readonly socket: Socket.Socket;
307
+ readonly url?: never;
308
+ readonly webSocket?: never;
309
+ };
310
+ /** What `socketClient` takes: where it connects, its connection hooks, and `client`'s options. */
311
+ export type SocketClientOptions = SocketTarget & ClientOptions & {
312
+ /**
313
+ * Effects run as each connection opens and as it ends, Effect's `RpcClient.ConnectionHooks`:
314
+ * a page showing that it is connected.
315
+ */
316
+ readonly hooks?: Partial<RpcClient.ConnectionHooks["Service"]> | undefined;
317
+ /**
318
+ * How messages are written on the socket: `RpcSerialization.json` by default, which the
319
+ * Cloudflare package's socket host reads; the server's own, such as `RpcSerialization.ndjson`,
320
+ * for an `ActionRpc.layer` served under another.
321
+ */
322
+ readonly serialization?: RpcSerialization.RpcSerialization["Service"] | undefined;
323
+ };
324
+ /**
325
+ * `client` over one WebSocket the client holds, for as long as the `Scope` it is built in:
326
+ * Effect's socket protocol, under JSON serialization unless `serialization` says otherwise, its
327
+ * calls and watches sharing the socket, which connects again after a drop as Effect's own socket client
328
+ * does. A close with an application code, 4000 to 4999, such as a server's refusal, stops it:
329
+ * every call and watch under way, and each later one, fails with an `RpcClientError` whose
330
+ * `reason` is that `SocketCloseError`. Guide: `docs/ActionRpc.md#call-the-rpcs`.
331
+ *
332
+ * **Gotchas**
333
+ *
334
+ * - The socket closes with the `Scope` the client was built in, not with each call's: a call or a watch run after that scope ends is interrupted.
335
+ * - Once stopped by a close it never connects again: build a new client, in a new `Scope`, such as after a page's reload.
336
+ * - It stops only at a close the socket delivers: a WebSocket firing `error` before a refusal's `close`, as Node's may, is read by Effect's `Socket.fromWebSocket` as a drop and connected again.
337
+ * - A protocol of your own takes `client` under `RpcClient.layerProtocolSocket`, its `retryPolicy` `reconnectUntil(code)`: a watch over it still connects again after a code below 4000.
286
338
  */
287
- export declare const reconnectUntil: (...codes: readonly number[]) => Schedule.Schedule<Duration.Duration, ReconnectReason, never, never>;
339
+ export declare function socketClient<const B extends Any>(binding: B, options: SocketClientOptions): Effect.Effect<Client<B>, never, Scope.Scope | Rpc.MiddlewareClient<RpcGroup.Rpcs<B["rpcs"]>>>;
288
340
  export { AnyPage as Page, Poll, pollTag };
@@ -5,10 +5,11 @@ import { reservedList, reservedNames } from "./contract/names.mjs";
5
5
  import { PushedOf, SubscriptionOf } from "./contract/push.mjs";
6
6
  import { provideServed, servingOf } from "./contract/serving.mjs";
7
7
  import { Poll, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollTag, polledTransport, streamedOf, streamedTransport, verifyingNative } from "./rpc/erased.mjs";
8
- import { isRpcTransient } from "./rpc/watch.mjs";
8
+ import { isApplicationCode, isRpcTransient } from "./rpc/watch.mjs";
9
9
  import { AnyPage } from "./contract/pages.mjs";
10
10
  import { Duration, Effect, Function, Layer, Predicate, Schedule, Schema } from "effect";
11
- import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcServer } from "effect/rpc";
11
+ import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcSerialization, RpcServer } from "effect/rpc";
12
+ import { Socket } from "effect/socket";
12
13
  // src/rpc/ActionRpc.ts
13
14
  const authenticatedKey = "effect-actions/ActionRpc/Authenticated";
14
15
  const authenticatedOf = (authentication) => RpcMiddleware.Service()(authenticatedKey, { error: Schema.Union([Unauthenticated, ...authentication.error]) });
@@ -77,27 +78,41 @@ function layer(binding, served, options = {}) {
77
78
  * from the same cursor and interrupts the first.
78
79
  */
79
80
  const pollResentAfter = Duration.minutes(4);
80
- function client(binding, options = {}) {
81
+ function client(binding, { watchMode, ...options } = {}) {
81
82
  return Effect.map(Effect.all([RpcClient.make(erasedOf(binding.actions, binding.events, "ActionRpc.layer").merge(nativeOf(binding.rpcs)), {
82
83
  ...options,
83
84
  flatten: true
84
85
  }), Effect.map(Effect.service(RpcClient.Protocol), ({ supportsAck }) => !supportsAck)]), ([call, silenceEnds]) => ({
85
- ...methodsOf(binding, streamedTransport(silenceEnds, polledTransport(isRpcTransient, pollResentAfter)))(Function.constant(Effect.succeed(erasedCallOf(call)))),
86
+ ...methodsOf(binding, streamedTransport(silenceEnds, polledTransport(isRpcTransient, pollResentAfter)), watchMode)(Function.constant(Effect.succeed(erasedCallOf(call)))),
86
87
  ...Object.fromEntries([...nativeOf(binding.rpcs).requests.keys()].map((tag) => [tag, (payload, callOptions) => call(tag, payload, callOptions)]))
87
88
  }));
88
89
  }
90
+ const reconnectingUnless = (stops) => Schedule.min([Schedule.exponential(500, 1.5), Schedule.spaced(5e3)]).pipe(Schedule.setInputType(), Schedule.while(({ input: { reason } }) => !(reason._tag === "SocketCloseError" && stops(reason.code))));
89
91
  /**
90
92
  * A socket client's `retryPolicy`, for `RpcClient.layerProtocolSocket`, that stops connecting
91
93
  * again once the server closes the socket with one of `codes`, such as a refusal of its upgrade:
92
94
  * until then it is Effect's own default, `Schedule.min([Schedule.exponential(500, 1.5),
93
95
  * Schedule.spaced(5000)])`, which Effect does not export. A page refused with its code stops, its
94
96
  * calls and streams failing with an `RpcClientError` whose `reason` is that `SocketCloseError`,
95
- * its `code` the one it closed with.
97
+ * its `code` the one it closed with. `socketClient` stops at every application code already.
96
98
  *
97
99
  * **Gotchas**
98
100
  *
99
101
  * - A client without it connects again after a refusal as after any close, every five seconds for good.
100
102
  * - Any other socket error, a drop included, is retried as Effect's default retries it.
103
+ * - A watch through `client` connects again after a close below 4000 whatever the protocol stopped at, failing each time: stop at codes from 4000 to 4999, which a watch ends at.
101
104
  */
102
- const reconnectUntil = (...codes) => Schedule.min([Schedule.exponential(500, 1.5), Schedule.spaced(5e3)]).pipe(Schedule.setInputType(), Schedule.while(({ input: { reason } }) => !(Predicate.isTagged(reason, "SocketCloseError") && Predicate.hasProperty(reason, "code") && codes.some((code) => code === reason.code))));
103
- export { AnyPage as Page, Poll, client, layer, make, pollResentAfter, pollTag, reconnectUntil };
105
+ const reconnectUntil = (...codes) => reconnectingUnless((code) => codes.includes(code));
106
+ function socketClient(binding, options) {
107
+ const { hooks, url: _url, webSocket: _webSocket, socket: _socket, serialization = RpcSerialization.json, ...clientOptions } = options;
108
+ const connection = options.socket === void 0 ? Socket.layerWebSocket(options.url).pipe(Layer.provide(options.webSocket === void 0 ? Socket.layerWebSocketConstructorGlobal : Layer.succeed(Socket.WebSocketConstructor)(options.webSocket))) : Layer.succeed(Socket.Socket)(options.socket);
109
+ return Effect.flatMap(Layer.build(RpcClient.layerProtocolSocket({ retryPolicy: reconnectingUnless(isApplicationCode) }).pipe(Layer.provide([
110
+ connection,
111
+ Layer.succeed(RpcSerialization.RpcSerialization)(serialization),
112
+ Layer.succeed(RpcClient.ConnectionHooks)({
113
+ onConnect: hooks?.onConnect ?? Effect.void,
114
+ onDisconnect: hooks?.onDisconnect ?? Effect.void
115
+ })
116
+ ]))), (protocol) => Effect.provideContext(client(binding, clientOptions), protocol));
117
+ }
118
+ export { AnyPage as Page, Poll, client, layer, make, pollResentAfter, pollTag, reconnectUntil, socketClient };
package/dist/Event.d.mts CHANGED
@@ -144,22 +144,76 @@ export interface Check<E extends Any, R = never> extends Hooked<E, R> {
144
144
  readonly log?: never;
145
145
  readonly current?: never;
146
146
  }
147
+ /** What `appended` reads after a position: the entries past it, oldest first. */
148
+ export interface Appended<E extends Any> {
149
+ /** The occurrences' data, oldest first: none where every entry read was skipped. */
150
+ readonly items: ReadonlyArray<E["payload"]["Type"]>;
151
+ /**
152
+ * The id of the last entry read, where it is not the last item's, as where entries read are
153
+ * skipped: the next read goes on after it.
154
+ *
155
+ * **Gotchas**
156
+ *
157
+ * - One below the last item's id is read as the last item's, so no item is sent twice.
158
+ * - One past `newest` makes the next read answer `truncated: true` and the newest id, a gap the subscriber never had.
159
+ */
160
+ readonly through?: number | undefined;
161
+ /**
162
+ * More entries are ready past `through`: the subscriber reads again without waiting. Ignored on a
163
+ * read that moved the cursor nowhere, which would read the same entries again at once forever.
164
+ */
165
+ readonly hasMore?: boolean | undefined;
166
+ }
167
+ /** What `appended` needs to page a store appending entries under increasing integer ids. */
168
+ export interface AppendedOptions<E extends Any, RN = never, RA = never, RK = never, RS = never> extends Pick<Check<E>, "notified" | "lease"> {
169
+ /** The id of the newest entry, `0` while there is none, run as the subscriber. */
170
+ readonly newest: (input: E["input"]["Type"]) => Effect.Effect<number, Refusal, RN>;
171
+ /** The entries after `id`, oldest first, as many as one read takes, run as the subscriber. */
172
+ readonly after: (input: E["input"]["Type"], id: number) => Effect.Effect<Appended<E>, Refusal, RA>;
173
+ /** The id of the entry an occurrence's data was read from: its `eventId`, and a cursor. */
174
+ readonly id: (data: E["payload"]["Type"]) => number;
175
+ /** Each page's `nextPoll`; defaults to 5 seconds. */
176
+ readonly nextPoll?: Duration.Input | undefined;
177
+ readonly key?: Hooked<E, RK>["key"];
178
+ readonly subscription?: Hooked<E, RS>["subscription"];
179
+ }
180
+ /**
181
+ * A check source for a store that appends entries under increasing integer ids, such as a table's
182
+ * `INTEGER PRIMARY KEY`: its cursor is the id of the last entry a subscriber read, and an
183
+ * occurrence's `eventId` its entry's id. A new subscriber starts after the newest entry. `event`
184
+ * types the options alone, as `Event.appended(MessagePosted, { … })` in `implement`'s builder.
185
+ *
186
+ * **Gotchas**
187
+ *
188
+ * - A cursor that is not an id up to `newest`'s as the check spells one, digits without a sign, exponent or leading zero, such as another store's or one past a store emptied since, is answered with `truncated: true` and the newest id: the subscriber goes on from there.
189
+ * - A store deleting its oldest entries sends no gap for those a subscriber resuming before them missed: a cursor is stale only past `newest`.
190
+ * - Ids that start again, as a store kept in memory restarts them, make an old cursor read entries it never saw as the ones after it: such a store's cursor carries its epoch in a `check` of its own.
191
+ */
192
+ export declare const appended: <E extends Any, RN = never, RA = never, RK = never, RS = never>(_event: E, { newest, after, id, nextPoll, ...source }: AppendedOptions<E, RN, RA, RK, RS>) => Check<E, RN | RA | RK | RS>;
147
193
  /**
148
194
  * An event type whose occurrence is the whole value, such as a status or a list small enough to
149
195
  * send whole: a subscriber receives the value as it is first, then again after each
150
- * `Events.notify` that reaches it, never a change it missed one by one. The library keeps a
151
- * revision per key, which each such notify moves, as the cursor and each occurrence's id. Its
152
- * streams and webhook deliveries read it again only when notified, on no timer, so an idle
153
- * Cloudflare Durable Object holding them hibernates; a polling client polls every 5 seconds.
196
+ * `Events.notify` that reaches it and changes it, never a change it missed one by one. The
197
+ * library keeps a revision per key, which each such notify moves; the revision and a digest of
198
+ * the subscription's input, its key and the value sent make the cursor and each occurrence's id.
199
+ * Its streams and webhook deliveries read it again only when notified, on no timer, so an idle
200
+ * Cloudflare Durable Object holding them hibernates; a polling client polls at `nextPoll`.
154
201
  *
155
202
  * **Gotchas**
156
203
  *
157
- * - A notify without a change sends the value again, under a new id: notify after a write that changed it.
158
- * - The revision is read before `current`, so a value written between them is sent again at the next read, never missed: write the value, then notify.
204
+ * - A notify reads the value again for each subscriber it reaches, though a value equal to the one its cursor saw, for the same input and key, is not sent: notify after a write that may change it, not on a timer.
205
+ * - The revision is read before `current`, so a value written between them is read again at the next read, never missed: write the value, then notify.
206
+ * - A cursor is its subscription's own: one taken to another input of the same key, at a revision it already holds, is answered with nothing until the next notify.
159
207
  */
160
208
  export interface Current<E extends Any, R = never> extends Hooked<E, R> {
161
209
  /** The value as it is, as the subscriber's `input` selects it, run as the subscriber. */
162
210
  readonly current: (input: E["input"]["Type"]) => Effect.Effect<E["payload"]["Type"], Refusal, R>;
211
+ /**
212
+ * How long a polling client waits before it asks again, read in the bounds of `Page`'s
213
+ * `nextPoll`; defaults to 5 seconds. Streams and webhook deliveries never wait on it: they read
214
+ * when notified.
215
+ */
216
+ readonly nextPoll?: Duration.Input | undefined;
163
217
  readonly check?: never;
164
218
  readonly log?: never;
165
219
  }
package/dist/Event.mjs CHANGED
@@ -5,7 +5,7 @@ import { EventImplementation, sourcesOf } from "./contract/feed.mjs";
5
5
  import { assertEventName, assertOnce } from "./contract/names.mjs";
6
6
  import { Events, layerMemory } from "./contract/hub.mjs";
7
7
  import { Gap } from "./contract/occurrence.mjs";
8
- import { Array as Array$1, Data, Effect, Match, Predicate, Schema } from "effect";
8
+ import { Array as Array$1, Data, Effect, Match, Option, Predicate, Schema } from "effect";
9
9
  // src/contract/Event.ts
10
10
  const TypeId = "~@gjermundgaraba/effect-actions/Event";
11
11
  /** Whether `u` is an event type `make` defined: a binding's list tells events from actions by it. */
@@ -24,6 +24,53 @@ function make(name, options) {
24
24
  payload: codecOf(options.payload)
25
25
  };
26
26
  }
27
+ const appendedId = (cursor) => {
28
+ const id = Number(cursor);
29
+ return cursor !== null && Number.isSafeInteger(id) && id >= 0 && String(id) === cursor ? Option.some(id) : Option.none();
30
+ };
31
+ /**
32
+ * A check source for a store that appends entries under increasing integer ids, such as a table's
33
+ * `INTEGER PRIMARY KEY`: its cursor is the id of the last entry a subscriber read, and an
34
+ * occurrence's `eventId` its entry's id. A new subscriber starts after the newest entry. `event`
35
+ * types the options alone, as `Event.appended(MessagePosted, { … })` in `implement`'s builder.
36
+ *
37
+ * **Gotchas**
38
+ *
39
+ * - A cursor that is not an id up to `newest`'s as the check spells one, digits without a sign, exponent or leading zero, such as another store's or one past a store emptied since, is answered with `truncated: true` and the newest id: the subscriber goes on from there.
40
+ * - A store deleting its oldest entries sends no gap for those a subscriber resuming before them missed: a cursor is stale only past `newest`.
41
+ * - Ids that start again, as a store kept in memory restarts them, make an old cursor read entries it never saw as the ones after it: such a store's cursor carries its epoch in a `check` of its own.
42
+ */
43
+ const appended = (_event, { newest, after, id, nextPoll, ...source }) => ({
44
+ ...source,
45
+ check: (input, cursor) => Effect.gen(function* () {
46
+ const last = yield* newest(input);
47
+ const from = Option.filter(appendedId(cursor), (at) => at <= last);
48
+ if (Option.isNone(from)) return {
49
+ events: [],
50
+ cursor: String(last),
51
+ truncated: cursor !== null,
52
+ nextPoll
53
+ };
54
+ if (from.value === last) return {
55
+ events: [],
56
+ cursor: String(last),
57
+ nextPoll
58
+ };
59
+ const read = yield* after(input, from.value);
60
+ const lastItem = read.items.at(-1);
61
+ const reached = lastItem === void 0 ? from.value : id(lastItem);
62
+ const through = Math.max(read.through ?? reached, reached);
63
+ return {
64
+ events: read.items.map((data) => ({
65
+ eventId: String(id(data)),
66
+ data
67
+ })),
68
+ cursor: String(through),
69
+ hasMore: read.hasMore === true && through > from.value,
70
+ nextPoll
71
+ };
72
+ })
73
+ });
27
74
  /** The server serves no event type of that name, or no longer does. */
28
75
  var NotServed = class extends Schema.TaggedError()("NotServed", {}) {};
29
76
  /**
@@ -100,4 +147,4 @@ function implement(events, sources, options) {
100
147
  }, listed.some((event) => event.caller !== Anyone), options?.authorize);
101
148
  return new EventImplementation(listed, sourcesOf(listed, !Array.isArray(events), sources), authorizer);
102
149
  }
103
- export { CallbackCategory, CallbackFailed, Events, Gap, NotServed, NotSubscribed, SubscriptionError, Unsupported, WebhookDelivery, allowAll, implement, isEvent, layerMemory, make };
150
+ export { CallbackCategory, CallbackFailed, Events, Gap, NotServed, NotSubscribed, SubscriptionError, Unsupported, WebhookDelivery, allowAll, appended, implement, isEvent, layerMemory, make };
@@ -13,22 +13,16 @@ export interface Options {
13
13
  */
14
14
  readonly allowedOrigins?: readonly string[];
15
15
  }
16
- /** One request, as a Node `upgrade` handler or a router middleware sees it. */
17
- export interface Request {
18
- /** The request target: `/a?b` or an absolute URL. Only its path is read. */
19
- readonly target: string;
20
- readonly host: string | undefined;
21
- readonly origin: string | undefined;
22
- }
23
16
  /**
24
- * Build a Host/Origin policy once at startup. `allows` takes no services, so a
25
- * raw request or Node upgrade handler applies the same rule as the router.
17
+ * Build a Host/Origin policy once at startup. `allows` takes a web `Request` and no
18
+ * services, so a Worker's `fetch` or a raw web handler applies the same rule as the router.
26
19
  * The middleware answers refused requests with status 403 and text `Forbidden`.
27
20
  *
28
21
  * **Gotchas**
29
22
  * - `/healthz` is unchecked, including its query and fragment; do not serve application data there.
30
23
  * - Provide `middleware.layer` to every route layer to protect; it is not global middleware.
31
24
  * - This checks browser request headers, not caller identity; access control belongs to the application or its network.
25
+ * - A request sending no Host header is judged by its absolute target's host, as a Worker's in-process `fetch` sends one; a Node server's path-only target has none, and is refused.
32
26
  */
33
27
  export declare const make: (options: Options) => {
34
28
  allows: (request: Request) => boolean;