@gjermundgaraba/effect-actions 0.35.0 → 0.37.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.
Files changed (48) hide show
  1. package/README.md +7 -7
  2. package/dist/Action.d.mts +2 -2
  3. package/dist/Action.mjs +1 -1
  4. package/dist/ActionEntity.d.mts +162 -75
  5. package/dist/ActionEntity.mjs +74 -55
  6. package/dist/ActionHttp.d.mts +7 -4
  7. package/dist/ActionRpc.d.mts +69 -17
  8. package/dist/ActionRpc.mjs +29 -11
  9. package/dist/Event.d.mts +62 -8
  10. package/dist/Event.mjs +49 -2
  11. package/dist/RequestPolicy.d.mts +3 -9
  12. package/dist/RequestPolicy.mjs +18 -6
  13. package/dist/authentication/provider.d.mts +0 -22
  14. package/dist/authentication/refusal.mjs +0 -4
  15. package/dist/contract/authorizer.d.mts +0 -4
  16. package/dist/contract/call.mjs +0 -4
  17. package/dist/contract/caller.mjs +0 -1
  18. package/dist/contract/declared.d.mts +0 -1
  19. package/dist/contract/feed.d.mts +0 -3
  20. package/dist/contract/feed.mjs +41 -24
  21. package/dist/contract/hub.mjs +0 -10
  22. package/dist/contract/implementation.d.mts +4 -27
  23. package/dist/contract/implementation.mjs +0 -9
  24. package/dist/contract/progress.d.mts +0 -1
  25. package/dist/contract/serving.mjs +15 -9
  26. package/dist/contract/subscribe.mjs +0 -1
  27. package/dist/contract/wake.d.mts +14 -0
  28. package/dist/contract/wake.mjs +4 -3
  29. package/dist/contract/webhooks.mjs +0 -13
  30. package/dist/entity/wakes.mjs +29 -22
  31. package/dist/http/client.mjs +8 -2
  32. package/dist/http/streamed.d.mts +6 -5
  33. package/dist/http/streamed.mjs +17 -3
  34. package/dist/rpc/erased.d.mts +0 -11
  35. package/dist/rpc/erased.mjs +7 -8
  36. package/dist/rpc/watch.mjs +4 -2
  37. package/docs/ActionEntity-failures.md +0 -1
  38. package/docs/ActionEntity.md +17 -9
  39. package/docs/ActionHttp.md +1 -1
  40. package/docs/ActionRpc.md +21 -1
  41. package/docs/Authentication-failures.md +1 -1
  42. package/docs/Event.md +3 -1
  43. package/docs/setup.md +2 -2
  44. package/examples/kitchen-sink/src/browser.ts +9 -21
  45. package/examples/shopping-carts/README.md +1 -1
  46. package/examples/shopping-carts/src/entities.ts +4 -2
  47. package/package.json +12 -12
  48. package/examples/shopping-carts/src/Rpc.ts +0 -6
@@ -3,68 +3,95 @@ 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)),
75
+ remoteParentSpan: void 0,
64
76
  headers: request.headers,
65
77
  rpc
66
78
  });
67
- function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options } = {}) {
79
+ const ClusterFailures = Schema.Union([
80
+ ClusterError.MailboxFull,
81
+ ClusterError.PersistenceError,
82
+ ClusterError.AlreadyProcessingMessage,
83
+ ClusterError.EntityNotAssignedToRunner
84
+ ]);
85
+ /**
86
+ * Whether a failure is one of those Effect's entity client fails with when the entity could not
87
+ * be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
88
+ * `EntityNotAssignedToRunner`, which `client`, `nativeClient` and `reaching` answer as
89
+ * `Action.Unavailable`: a server forwarding calls into an entity, as the Cloudflare package's
90
+ * socket host does, makes them a defect, and a Worker calling Effect's `Entity.client` itself
91
+ * answers them, as the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
92
+ */
93
+ const isClusterFailure = Schema.is(ClusterFailures);
94
+ function layer(entity, served, { services = Layer.empty, rpcs = {}, onWake, ...options } = {}) {
68
95
  const { binding } = entity;
69
96
  const named = namedBy(entity.key);
70
97
  const { apps, events, authentication } = servingOf("ActionEntity binding", binding, served, { actions: [...binding.actions, ...binding.events] });
@@ -72,10 +99,14 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
72
99
  const build = Effect.gen(function* () {
73
100
  const address = yield* Entity.CurrentAddress;
74
101
  const sharding = yield* Effect.context();
75
- const { wake, woke } = yield* makeWake((payload) => Effect.flatMap(entity.client, (clientFor) => {
102
+ const outsideTransactions = Effect.gen(function* () {
103
+ const clients = [yield* Effect.serviceOption(SqlClient.SqlClient), Context.getOption(sharding, SqlClient.SqlClient)].flatMap(Option.toArray);
104
+ 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)`));
105
+ });
106
+ const { wake, woke } = yield* makeWake((payload) => Effect.andThen(outsideTransactions, Effect.flatMap(entity.client, (clientFor) => {
76
107
  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));
108
+ }).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))));
109
+ 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
110
  const check = (contract, input) => {
80
111
  const entityId = named(input);
81
112
  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 +121,10 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
90
121
  }
91
122
  }), built);
92
123
  const natives = yield* Effect.provideContext(Effect.isEffect(rpcs) ? rpcs : Effect.succeed(rpcs), built);
124
+ const woken = (at) => onWake === void 0 ? Effect.void : Effect.provideContext(Effect.catchCauseIf(onWake(DateTime.makeUnsafe(at)), (cause) => !Cause.hasInterruptsOnly(cause), reported), built);
93
125
  const answering = (handler) => (request) => Rpc.wrapMap(handler(request), (answer) => Effect.isEffect(answer) ? Effect.provideContext(answer, built) : Stream.provideContext(answer, built));
94
126
  return Object.fromEntries([...nativeOf(entity.protocol).requests.values()].map((rpc) => {
95
- if (rpc._tag === "effect-actions/wake") return [rpc._tag, woke];
127
+ if (rpc._tag === "effect-actions/wake") return [rpc._tag, ({ payload }) => Rpc.fork(Effect.andThen(woke(payload.at), () => woken(payload.at)))];
96
128
  const handler = handlers[rpc._tag];
97
129
  if (handler !== void 0) return [rpc._tag, (request) => {
98
130
  const answer = handler(request.payload, callOf(request, rpc));
@@ -108,21 +140,6 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
108
140
  disableFatalDefects: true
109
141
  });
110
142
  }
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
143
  const defaultTimeout = Duration.seconds(20);
127
144
  const sendingWithin = (type, options) => {
128
145
  const timeout = Duration.fromInputUnsafe(options.timeout ?? defaultTimeout);
@@ -190,7 +207,8 @@ function nativeClient(entity, options = {}) {
190
207
  }
191
208
  /**
192
209
  * 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
210
+ * own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`, one for every action the
211
+ * entity lists, those no surface's binding lists included: each call sent through
194
212
  * `Entity.client` to the entity its contract's key names for its input, with the caller's
195
213
  * headers, and its answer, declared errors and progress passed back; each event followed through
196
214
  * the entity's poll rpc. A call the entity could not be reached for, or that did not answer
@@ -199,6 +217,7 @@ function nativeClient(entity, options = {}) {
199
217
  *
200
218
  * **Gotchas**
201
219
  *
220
+ * - 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
221
  * - 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
222
  * - 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
223
  * - 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 +230,7 @@ function nativeClient(entity, options = {}) {
211
230
  * - 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
231
  * - 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
232
  * - 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.
233
+ * - 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
234
  */
216
235
  const reaching = (entity, options = {}) => {
217
236
  const { binding } = entity;
@@ -246,4 +265,4 @@ const reaching = (entity, options = {}) => {
246
265
  };
247
266
  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
267
  };
249
- export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, nativeClient, reaching };
268
+ 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
@@ -159,7 +162,7 @@ export declare function make<const Contracts extends ReadonlyArray<Any$1 | Any$2
159
162
  * **Gotchas**
160
163
  *
161
164
  * - A success is its JSON as the body; an action without `success` answers an empty 200, no body and no content type, so a hand-written client must not parse it, or an empty 204 where it declares `progress`. One without `input` still takes the body `{}` typed as JSON: no body is a 400.
162
- * - An action declaring `progress` answers a request whose `Accept` names `text/event-stream`, whatever else it names, with an SSE stream, listed in OpenAPI: a `progress` event for each value, its data the value's JSON, then one `final` event holding the answer's JSON, `null` for none; without that `Accept` it answers as any action, its progress dropped.
165
+ * - An action declaring `progress` answers a request whose `Accept` explicitly allows `text/event-stream` at nonzero quality with an SSE stream, listed in OpenAPI: a `progress` event for each value, its data the value's JSON, then one `final` event holding the answer's JSON, `null` for none; without that `Accept` it answers as any action, its progress dropped.
163
166
  * - An action answering a stream, `Action.Stream`, answers an SSE stream alone, whatever `Accept` says: an `element` event for each element, its data the element's JSON, and a `progress` event for each value where it declares `progress`; a stream of none answers a 200 with no event. A failure before the first event answers its status; one after ends the stream as Effect's stream failure event, a defect as `Internal server error`.
164
167
  * - The stream starts with the call's first event, so a failure before it, a refusal included, answers as it would without the stream; a declared failure after it ends the stream with Effect's `effect/http-api/stream/failure` event, reported as `Info` as without the stream, and a defect or an answer that does not encode with one saying `Internal server error`, its cause logged and reported.
165
168
  * - An action's SSE stream writes a `: keepalive` comment every 15 seconds from its first event until it ends, events or not, which SSE clients skip, so a proxy closing a silent response keeps it open through a slow step; before the first event no response has started, so a proxy timing out a response's start still ends a call silent that long.
@@ -194,7 +197,7 @@ export declare function layer<const H extends AnyHttp, const Apps extends Served
194
197
  * - `watch(event, input, options)` holds the event's SSE stream open, or polls its pages with `mode: "poll"`, as `Action.client`'s; a watch of an event the server does not serve, its route a 404, fails with `Event.SubscriptionError`, reason `NotServed`.
195
198
  * - A watch reconnects after the transport fails, a status such as 502, `Action.Unavailable`, or 60 seconds without an answer or a frame, a second later and doubling to 30 seconds, each reconnect logged as a warning; another declared error, a refusal included, ends it.
196
199
  * - A watch's stream ends at an SSE `retry:` field, which `ActionHttp.layer` never sends, as Effect's client decodes it, and the watch connects again: a server or proxy sending one as each stream starts delivers nothing.
197
- * - A call of an action declaring `progress` reads the route's event stream, as every request accepts it, and its answer from the `final` event; the server sends the values whether or not the call gave `onProgress`, and without one they are dropped.
200
+ * - A call of an action declaring `progress` reads the route's `text/event-stream` response and its answer from the `final` event; the server sends the values whether or not the call gave `onProgress`, and without one they are dropped.
198
201
  * - A call of an action answering a stream returns a `Stream` of its elements, failing as the route's stream fails, with `Sse.SseError` or `Sse.Retry` too; its `onProgress` gets each `progress` event, which the server sends whether or not the call gave one.
199
202
  */
200
203
  export declare function client<const H extends AnyHttp>(binding: H, options?: Options): Effect.Effect<Client<H>, never, HttpClient.HttpClient>;
@@ -4,7 +4,7 @@ import { Call } from "./contract/call.mjs";
4
4
  import { Anyone } from "./contract/caller.mjs";
5
5
  import { Codec } from "./contract/codec.mjs";
6
6
  import { Certain, ErrorsOf } from "./contract/declared.mjs";
7
- import { BuiltIn, BuiltIns, Unauthenticated } from "./contract/errors.mjs";
7
+ import { BuiltIn, BuiltIns, Forbidden, Unauthenticated } from "./contract/errors.mjs";
8
8
  import { Any as Any$3, Received, SubscriptionError } from "./Event.mjs";
9
9
  import { EventBuildError, EventBuildServices, EventServedRequest, HoldingEvents, ServingEvents } from "./contract/feed.mjs";
10
10
  import { BuildError, Holding, Known, Member, MiddlewareOf, Selected, SelectedEvents, Served } from "./contract/implementation.mjs";
@@ -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", {
@@ -27,7 +28,7 @@ type ElementedOf<Element extends Schema.Constraint, P> = Schema.Union<readonly [
27
28
  type RpcOf<A extends Any$2, E extends Errors, D> = A extends Any$2 ? A["success"] extends StreamOf<infer Element> ? Rpc.Rpc<A["name"], A["input"], RpcSchema.Stream<ElementedOf<Element, A["progress"]>, ErrorOf<A, E, D>>> : A["progress"] extends Codec ? Rpc.Rpc<A["name"], A["input"], RpcSchema.Stream<ReturnType<typeof ProgressedOf<A["progress"], A["success"]>>, ErrorOf<A, E, D>>> : Rpc.Rpc<A["name"], A["input"], A["success"], ErrorOf<A, E, D>> : never;
28
29
  type EventRpcOf<V extends Any$3, E extends Errors, D> = V extends Any$3 ? Rpc.Rpc<V["name"], ReturnType<typeof SubscriptionOf<V>>, RpcSchema.Stream<ReturnType<typeof PushedOf<V>>, Schema.Union<ReadonlyArray<E[number] | VerifierError<V, D> | BuiltIns>>>> : never;
29
30
  declare const authenticatedKey = "effect-actions/ActionRpc/Authenticated";
30
- type RefusalOf<E extends Errors> = Schema.Union<ReadonlyArray<typeof Unauthenticated | E[number]>>;
31
+ type RefusalOf<E extends Errors> = Schema.Union<ReadonlyArray<typeof Unauthenticated | typeof Forbidden | E[number]>>;
31
32
  declare const authenticatedBrand: unique symbol;
32
33
  interface Authenticated<I, E extends Errors = Errors> {
33
34
  readonly [authenticatedBrand]: typeof authenticatedBrand;
@@ -100,8 +101,8 @@ export interface Options<E extends Errors = Errors> {
100
101
  /**
101
102
  * Native rpcs the binding serves beside its actions and event types, with their own schemas
102
103
  * and handlers: `RpcGroup.make(Upload)`. Under an `authentication`, each of their messages
103
- * authenticates as a protected action's does: its handler reads the identity, and a refusal
104
- * fails the call with `Unauthenticated`.
104
+ * authenticates as a protected action's does: its handler reads the identity, and the client
105
+ * receives the verifier's `Unauthenticated`, `Forbidden` (including any `scopes`), or declared error.
105
106
  *
106
107
  * **Gotchas**
107
108
  *
@@ -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 };
@@ -1,17 +1,22 @@
1
1
  import { bindingErrors, bindingOf, eventErrors } from "./contract/declared.mjs";
2
- import { Unauthenticated } from "./contract/errors.mjs";
2
+ import { Forbidden, Unauthenticated } from "./contract/errors.mjs";
3
3
  import { listed } from "./contract/listed.mjs";
4
4
  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
- const authenticatedOf = (authentication) => RpcMiddleware.Service()(authenticatedKey, { error: Schema.Union([Unauthenticated, ...authentication.error]) });
15
+ const authenticatedOf = (authentication) => RpcMiddleware.Service()(authenticatedKey, { error: Schema.Union([
16
+ Unauthenticated,
17
+ Forbidden,
18
+ ...authentication.error
19
+ ]) });
15
20
  const authenticatedIn = (rpc) => [...rpc.middlewares].find(({ key }) => key === authenticatedKey);
16
21
  function make(contracts, options = {}) {
17
22
  const { actions, events } = listed(contracts);
@@ -67,8 +72,7 @@ function layer(binding, served, options = {}) {
67
72
  const servedActions = jsonGroup.toLayer(byName);
68
73
  const authenticated = natives.map(authenticatedIn).find(Predicate.isNotUndefined);
69
74
  if (authenticated === void 0 || authenticating === void 0) return servedActions;
70
- const authenticate = authenticating(verifyingNative);
71
- return Layer.merge(servedActions, Layer.succeed(authenticated)(authenticate));
75
+ return Layer.merge(servedActions, Layer.succeed(authenticated)(authenticating(verifyingNative)));
72
76
  })).pipe(provideServed(selected.apps, selected.events));
73
77
  return RpcServer.layer(jsonGroup.merge(binding.rpcs), { disableFatalDefects: true }).pipe(Layer.provide(handlers));
74
78
  }
@@ -77,27 +81,41 @@ function layer(binding, served, options = {}) {
77
81
  * from the same cursor and interrupts the first.
78
82
  */
79
83
  const pollResentAfter = Duration.minutes(4);
80
- function client(binding, options = {}) {
84
+ function client(binding, { watchMode, ...options } = {}) {
81
85
  return Effect.map(Effect.all([RpcClient.make(erasedOf(binding.actions, binding.events, "ActionRpc.layer").merge(nativeOf(binding.rpcs)), {
82
86
  ...options,
83
87
  flatten: true
84
88
  }), Effect.map(Effect.service(RpcClient.Protocol), ({ supportsAck }) => !supportsAck)]), ([call, silenceEnds]) => ({
85
- ...methodsOf(binding, streamedTransport(silenceEnds, polledTransport(isRpcTransient, pollResentAfter)))(Function.constant(Effect.succeed(erasedCallOf(call)))),
89
+ ...methodsOf(binding, streamedTransport(silenceEnds, polledTransport(isRpcTransient, pollResentAfter)), watchMode)(Function.constant(Effect.succeed(erasedCallOf(call)))),
86
90
  ...Object.fromEntries([...nativeOf(binding.rpcs).requests.keys()].map((tag) => [tag, (payload, callOptions) => call(tag, payload, callOptions)]))
87
91
  }));
88
92
  }
93
+ 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
94
  /**
90
95
  * A socket client's `retryPolicy`, for `RpcClient.layerProtocolSocket`, that stops connecting
91
96
  * again once the server closes the socket with one of `codes`, such as a refusal of its upgrade:
92
97
  * until then it is Effect's own default, `Schedule.min([Schedule.exponential(500, 1.5),
93
98
  * Schedule.spaced(5000)])`, which Effect does not export. A page refused with its code stops, its
94
99
  * calls and streams failing with an `RpcClientError` whose `reason` is that `SocketCloseError`,
95
- * its `code` the one it closed with.
100
+ * its `code` the one it closed with. `socketClient` stops at every application code already.
96
101
  *
97
102
  * **Gotchas**
98
103
  *
99
104
  * - A client without it connects again after a refusal as after any close, every five seconds for good.
100
105
  * - Any other socket error, a drop included, is retried as Effect's default retries it.
106
+ * - 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
107
  */
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 };
108
+ const reconnectUntil = (...codes) => reconnectingUnless((code) => codes.includes(code));
109
+ function socketClient(binding, options) {
110
+ const { hooks, url: _url, webSocket: _webSocket, socket: _socket, serialization = RpcSerialization.json, ...clientOptions } = options;
111
+ 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);
112
+ return Effect.flatMap(Layer.build(RpcClient.layerProtocolSocket({ retryPolicy: reconnectingUnless(isApplicationCode) }).pipe(Layer.provide([
113
+ connection,
114
+ Layer.succeed(RpcSerialization.RpcSerialization)(serialization),
115
+ Layer.succeed(RpcClient.ConnectionHooks)({
116
+ onConnect: hooks?.onConnect ?? Effect.void,
117
+ onDisconnect: hooks?.onDisconnect ?? Effect.void
118
+ })
119
+ ]))), (protocol) => Effect.provideContext(client(binding, clientOptions), protocol));
120
+ }
121
+ export { AnyPage as Page, Poll, client, layer, make, pollResentAfter, pollTag, reconnectUntil, socketClient };
package/dist/Event.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Options as Options$1 } from "./Action.mjs";
2
- import { Authorizer, Deferred as Deferred$1 } from "./contract/authorizer.mjs";
2
+ import { Deferred as Deferred$1 } from "./contract/authorizer.mjs";
3
3
  import { Codec, CodecOf, Fields, NoInput } from "./contract/codec.mjs";
4
4
  import { Refusal } from "./contract/errors.mjs";
5
5
  import { AnyEventImplementation, EventImplementation } from "./contract/feed.mjs";
@@ -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
  }
@@ -361,7 +415,7 @@ type Implemented<T extends Target, RequestServices, R, EX, RX, RA, EAX, RAX> = E
361
415
  export declare function implement<const T extends Target, RequestServices extends (T extends readonly Any[] ? { readonly [K in NamesOf<T>]: unknown; } : never), R = never, EX = never, RX = never, RA = never, EAX = never, RAX = never>(events: T, sources: SourcesOf<T, R, RequestServices> | Effect.Effect<SourcesOf<T, R, RequestServices>, EX, RX>, options: [Protected<EventsOf<T>>] extends [never] ? {
362
416
  readonly authorize?: "A public-only target takes no authorize";
363
417
  } | undefined : {
364
- readonly authorize: Authorizer<Protected<EventsOf<T>>, RA, EAX, RAX>;
418
+ readonly authorize: ((contract: Protected<EventsOf<T>>) => Effect.Effect<void, Refusal, RA>) | Effect.Effect<(contract: Protected<EventsOf<T>>) => Effect.Effect<void, Refusal, RA>, EAX, RAX>;
365
419
  }): Implemented<T, RequestServices, R, EX, RX, RA, EAX, RAX>;
366
420
  export declare function implement<const T extends Target, RequestServices extends (T extends readonly Any[] ? { readonly [K in NamesOf<T>]: unknown; } : never), R = never, EX = never, RX = never>(events: T & TakesNoAuthorize<T>, sources: SourcesOf<T, R, RequestServices> | Effect.Effect<SourcesOf<T, R, RequestServices>, EX, RX>): Implemented<T, RequestServices, R, EX, RX, never, never, never>;
367
421
  export { type AnyEventImplementation as AnyImplementation, Events, Gap, type EventImplementation as Implementation, type KeyOptions, type Listed, layerMemory };