@gjermundgaraba/effect-actions 0.31.0 → 0.33.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 (94) hide show
  1. package/README.md +4 -3
  2. package/dist/Action.d.mts +6 -6
  3. package/dist/Action.mjs +3 -4
  4. package/dist/ActionEntity.d.mts +237 -0
  5. package/dist/ActionEntity.mjs +211 -0
  6. package/dist/ActionHttp.d.mts +4 -5
  7. package/dist/ActionHttp.mjs +12 -12
  8. package/dist/ActionMcp.d.mts +2 -3
  9. package/dist/ActionMcp.mjs +1 -1
  10. package/dist/ActionRpc.d.mts +25 -58
  11. package/dist/ActionRpc.mjs +34 -249
  12. package/dist/Authentication.d.mts +8 -9
  13. package/dist/Authentication.mjs +6 -6
  14. package/dist/Event.d.mts +26 -6
  15. package/dist/Event.mjs +2 -2
  16. package/dist/Stored.d.mts +64 -0
  17. package/dist/Stored.mjs +102 -0
  18. package/dist/Webhook.d.mts +5 -4
  19. package/dist/Webhook.mjs +11 -4
  20. package/dist/authentication/provider.d.mts +2 -2
  21. package/dist/contract/call.mjs +6 -2
  22. package/dist/contract/caller.d.mts +2 -6
  23. package/dist/contract/caller.mjs +3 -3
  24. package/dist/contract/event-tables.mjs +90 -0
  25. package/dist/contract/feed.d.mts +15 -3
  26. package/dist/contract/feed.mjs +20 -11
  27. package/dist/contract/hub.d.mts +4 -57
  28. package/dist/contract/hub.mjs +12 -15
  29. package/dist/contract/idempotency.d.mts +6 -18
  30. package/dist/contract/idempotency.mjs +6 -14
  31. package/dist/contract/implementation.mjs +3 -4
  32. package/dist/contract/log.d.mts +0 -26
  33. package/dist/contract/log.mjs +16 -8
  34. package/dist/contract/pages.d.mts +30 -2
  35. package/dist/contract/pages.mjs +27 -3
  36. package/dist/contract/wake.mjs +9 -0
  37. package/dist/contract/watch.mjs +20 -15
  38. package/dist/contract/webhooks.d.mts +8 -4
  39. package/dist/contract/webhooks.mjs +42 -31
  40. package/dist/entity/forwarded.d.mts +11 -0
  41. package/dist/entity/forwarded.mjs +32 -0
  42. package/dist/entity/wakes.mjs +39 -0
  43. package/dist/http/client.mjs +2 -2
  44. package/dist/http/events.d.mts +1 -12
  45. package/dist/http/events.mjs +2 -24
  46. package/dist/http/redacted.mjs +9 -0
  47. package/dist/mcp/bridge.mjs +5 -6
  48. package/dist/mcp/client.mjs +2 -2
  49. package/dist/rpc/erased.d.mts +62 -0
  50. package/dist/rpc/erased.mjs +356 -0
  51. package/dist/rpc/watch.mjs +10 -9
  52. package/dist/webhook/stored.mjs +6 -4
  53. package/dist/webhook/subscriptions.mjs +58 -40
  54. package/docs/Action-streams.md +2 -2
  55. package/docs/Action.md +3 -3
  56. package/docs/ActionEntity-failures.md +10 -0
  57. package/docs/ActionEntity.md +165 -0
  58. package/docs/ActionHttp.md +0 -4
  59. package/docs/ActionMcp.md +2 -2
  60. package/docs/ActionRpc-events.md +2 -2
  61. package/docs/ActionRpc.md +1 -1
  62. package/docs/Authentication-failures.md +1 -0
  63. package/docs/Authentication.md +4 -2
  64. package/docs/Event.md +5 -5
  65. package/docs/README.md +5 -2
  66. package/docs/Webhook.md +1 -1
  67. package/docs/setup-failures.md +1 -1
  68. package/docs/setup.md +6 -5
  69. package/examples/README.md +1 -1
  70. package/examples/kitchen-sink/src/admin/Admin.ts +1 -0
  71. package/examples/kitchen-sink/src/identity/Identity.ts +5 -1
  72. package/examples/live-rpc/src/identity/Identity.ts +3 -1
  73. package/examples/notes-service/src/identity/Identity.ts +3 -1
  74. package/examples/shopping-carts/README.md +46 -0
  75. package/examples/shopping-carts/src/Api.ts +9 -0
  76. package/examples/shopping-carts/src/Rpc.ts +6 -0
  77. package/examples/shopping-carts/src/cart/Cart.ts +47 -0
  78. package/examples/shopping-carts/src/cart/handlers.ts +42 -0
  79. package/examples/shopping-carts/src/cart/held.ts +5 -0
  80. package/examples/shopping-carts/src/cart/store.ts +10 -0
  81. package/examples/shopping-carts/src/entities.ts +7 -0
  82. package/examples/shopping-carts/src/identity/Identity.ts +16 -0
  83. package/examples/shopping-carts/src/identity/shoppers.ts +6 -0
  84. package/examples/shopping-carts/src/identity/verifier.ts +21 -0
  85. package/examples/shopping-carts/src/platform/cluster.ts +7 -0
  86. package/examples/shopping-carts/src/platform/sql-carts.ts +30 -0
  87. package/examples/shopping-carts/src/routes.ts +23 -0
  88. package/examples/shopping-carts/src/server.ts +23 -0
  89. package/examples/shopping-carts/test/routes.test.ts +69 -0
  90. package/package.json +9 -6
  91. package/dist/contract/input-check.d.mts +0 -15
  92. package/dist/contract/input-check.mjs +0 -15
  93. package/dist/http/placed.d.mts +0 -34
  94. package/dist/http/placed.mjs +0 -71
@@ -0,0 +1,356 @@
1
+ import { providerOf } from "../authentication/provider.mjs";
2
+ import { checked, checkedStream, decodeInput, sendingJson, sentInput } from "../contract/call.mjs";
3
+ import { Anyone, principalOf } from "../contract/caller.mjs";
4
+ import { bindingErrors, eventErrors } from "../contract/declared.mjs";
5
+ import { SubscriptionError } from "../Event.mjs";
6
+ import { acquireFeeds } from "../contract/feed.mjs";
7
+ import { acquire, answered, elementsOf } from "../contract/implementation.mjs";
8
+ import { pageOf, rpcPageOf } from "../contract/pages.mjs";
9
+ import { answerFrom, elementsFrom } from "../contract/progress.mjs";
10
+ import { PushedOf, SubscriptionOf, queuedPush } from "../contract/push.mjs";
11
+ import { concealed } from "../contract/reported.mjs";
12
+ import { Answering, answeringOf, elementOf } from "../contract/stream.mjs";
13
+ import { Subscribed, WebhookCancellationOf, WebhookSubscriptionOf, deliveryUnsupported } from "../contract/subscribe.mjs";
14
+ import { watching } from "../contract/watch.mjs";
15
+ import { offersWebhook, servingFeeds, webhookAnswers } from "../contract/webhooks.mjs";
16
+ import { isUnknownTag, polledTransportOf, streamingOf } from "./watch.mjs";
17
+ import { Cause, Effect, ErrorReporter, Option, Predicate, Queue, Result, Schema, SchemaTransformation, Stream } from "effect";
18
+ import { HttpClientRequest, HttpServerRequest } from "effect/http";
19
+ import { Rpc, RpcGroup } from "effect/rpc";
20
+ import { HttpApiBuilder } from "effect/http-api";
21
+ // src/rpc/erased.ts
22
+ const streams = (action) => !Answering.$is("Value")(answeringOf(action));
23
+ const withSyntheticRequestFromHeaders = (headers) => (effect) => effect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromClientRequest(HttpClientRequest.get("/", { headers }))), Effect.provideService(HttpServerRequest.ParsedSearchParams, {}));
24
+ const throughSteps = (steps, call, options) => {
25
+ let wrapped = call;
26
+ for (const step of steps) {
27
+ const inner = wrapped;
28
+ wrapped = Effect.suspend(() => step(inner, options));
29
+ }
30
+ return wrapped;
31
+ };
32
+ const authenticatingOf = (authentication) => Effect.map(providerOf(authentication), (provider) => {
33
+ const verify = Effect.flatMap(HttpApiBuilder.securityDecode(authentication.security), provider.authenticate);
34
+ return (verifying) => (effect, options) => Effect.flatMap(verifying(verify, options), (actor) => Effect.provideService(effect, authentication.identity, actor));
35
+ });
36
+ var DeclaredFailure = class {
37
+ [ErrorReporter.ignore] = true;
38
+ json;
39
+ constructor(json) {
40
+ this.json = json;
41
+ }
42
+ toString() {
43
+ return Predicate.isString(this.json) ? this.json : JSON.stringify(this.json);
44
+ }
45
+ };
46
+ const asJson = () => Schema.link()(Schema.Json, SchemaTransformation.transform({
47
+ decode: (json) => new DeclaredFailure(json),
48
+ encode: (failure) => failure.json
49
+ }));
50
+ const Declared = Schema.instanceOf(DeclaredFailure, {
51
+ toCodecJson: asJson,
52
+ toCodecIso: asJson
53
+ });
54
+ const streamOf = (name) => Rpc.make(name, {
55
+ payload: Schema.Json,
56
+ success: Schema.Json,
57
+ error: Declared,
58
+ stream: true
59
+ });
60
+ const unaryOf = (name) => Rpc.make(name, {
61
+ payload: Schema.Json,
62
+ success: Schema.Json,
63
+ error: Declared
64
+ });
65
+ const streamsEvents = (server) => server === "ActionRpc.layer";
66
+ /**
67
+ * The tag of the unary rpc polling the event type `name`, `<name>/poll`, taking `Poll` beside
68
+ * its `input` and answering a `Page`, which `ActionRpc.layer` and an `ActionEntity` serve and
69
+ * `ActionRpc.client`'s polling watch calls.
70
+ */
71
+ const pollTag = (name) => `${name}/poll`;
72
+ const subscribeTag = (name) => `${name}/subscribe`;
73
+ const unsubscribeTag = (name) => `${name}/unsubscribe`;
74
+ const webhookRpcsOf = (events) => RpcGroup.make(...events.filter(offersWebhook).flatMap((event) => [unaryOf(subscribeTag(event.name)), unaryOf(unsubscribeTag(event.name))]));
75
+ const webhookErrors = (event, binding) => Schema.Union([...eventErrors(event, binding), SubscriptionError]);
76
+ /** The rpcs `server` serves for `actions` and `events`, and its clients call. */
77
+ const erasedOf = (actions, events, server) => RpcGroup.make(...actions.map((action) => streams(action) ? streamOf(action.name) : unaryOf(action.name)), ...events.flatMap((event) => [...streamsEvents(server) ? [streamOf(event.name)] : [], unaryOf(pollTag(event.name))]));
78
+ const Watch = Schema.String.check(Schema.isUUID());
79
+ /**
80
+ * The payload of an event type's poll rpc, `<event>/poll`, past its `input`, as a client sends
81
+ * it: the `cursor` to read after, `null` reading from now, at most `maxEvents` occurrences, and
82
+ * the `watch`, a UUID one watch sends with each of its polls, which tells a page's watches apart
83
+ * on a socket and holds nothing on the server: a poll's subscription hook is its caller's.
84
+ */
85
+ const Poll = Schema.Struct({
86
+ cursor: Schema.NullOr(Schema.String),
87
+ maxEvents: Schema.optionalKey(Schema.Finite),
88
+ watch: Schema.optionalKey(Watch)
89
+ });
90
+ const PollOf = (event) => Schema.Struct({
91
+ ...Poll.fields,
92
+ ...SubscriptionOf(event).fields
93
+ });
94
+ const erasedCallOf = (send) => ({
95
+ unary: (tag, payload) => {
96
+ const answer = send(tag, payload);
97
+ return Effect.isEffect(answer) ? answer : Effect.die(/* @__PURE__ */ new Error(`The rpc ${tag} streams, called as unary`));
98
+ },
99
+ stream: (tag, payload) => {
100
+ const answer = send(tag, payload);
101
+ return Stream.isStream(answer) ? answer : Stream.die(/* @__PURE__ */ new Error(`The rpc ${tag} is unary, called as a stream`));
102
+ }
103
+ });
104
+ const ProgressedOf = (progress, success) => Schema.Union([Schema.TaggedStruct("Progress", { value: progress }), Schema.TaggedStruct("Final", { value: success })]);
105
+ const elementedOf = (element, progress) => Schema.Union([Schema.TaggedStruct("Element", { value: element }), ...progress === void 0 ? [] : [Schema.TaggedStruct("Progress", { value: progress })]]);
106
+ const streamedOf = (action) => Answering.$match(answeringOf(action), {
107
+ Value: () => void 0,
108
+ Progressed: ({ success, progress }) => ProgressedOf(progress, success),
109
+ Elements: ({ element, progress }) => elementedOf(element, progress)
110
+ });
111
+ const nativeOf = (group) => group;
112
+ const isDeclared = (failure) => failure instanceof DeclaredFailure;
113
+ const failedOf = (error) => {
114
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(error));
115
+ return (failure) => Effect.flatMap(Effect.orDie(decode(failure.json)), Effect.fail);
116
+ };
117
+ const calledMethodOf = (action, binding) => {
118
+ const failed = failedOf(Schema.Union(bindingErrors(action, binding)));
119
+ const streamed = streamedOf(action);
120
+ const encode = sendingJson(action);
121
+ const sending = () => encode;
122
+ if (streamed === void 0) {
123
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(action.success));
124
+ return (call) => checked(action, sending, (json) => call.unary(action.name, json).pipe(Effect.catchIf(isDeclared, failed), Effect.flatMap((sent) => Effect.orDie(decode(sent)))));
125
+ }
126
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(streamed));
127
+ const progressed = (call, json) => call.stream(action.name, json).pipe(Stream.catchIf(isDeclared, (failure) => Stream.fromEffect(failed(failure))), Stream.mapEffect((sent) => Effect.orDie(decode(sent))));
128
+ return elementOf(action.success) === void 0 ? (call) => checked(action, sending, (json, onProgress) => answerFrom(progressed(call, json), onProgress)) : (call) => checkedStream(action, sending, (json, onProgress) => elementsFrom(progressed(call, json), onProgress));
129
+ };
130
+ const streamedTransport = (silenceEnds, polled) => (event, binding) => {
131
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(PushedOf(event)));
132
+ const failed = failedOf(Schema.Union(eventErrors(event, binding)));
133
+ const polledThrough = polled(event, binding);
134
+ return (call) => {
135
+ const polling = polledThrough(call);
136
+ return (input, streamOnly) => ({
137
+ ...polling(input, streamOnly),
138
+ stream: streamingOf(event, (cursor) => call.stream(event.name, {
139
+ input,
140
+ cursor
141
+ }).pipe(Stream.catchIf(isDeclared, (failure) => Stream.fromEffect(failed(failure))), Stream.mapEffect((json) => Effect.orDie(decode(json)))), silenceEnds, streamOnly)
142
+ });
143
+ };
144
+ };
145
+ const pollOf = (event, binding) => {
146
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(pageOf(event)));
147
+ const failed = failedOf(Schema.Union(eventErrors(event, binding)));
148
+ return (call) => (payload) => call.unary(pollTag(event.name), payload).pipe(Effect.catchIf(isDeclared, failed), Effect.flatMap((json) => Effect.orDie(decode(json))));
149
+ };
150
+ const watchedOf = (event, binding) => {
151
+ const pollThrough = pollOf(event, binding);
152
+ return (call) => {
153
+ const poll = pollThrough(call);
154
+ return (input) => ({ poll: (cursor, watch) => poll({
155
+ input,
156
+ cursor,
157
+ ...watch === void 0 ? {} : { watch }
158
+ }) });
159
+ };
160
+ };
161
+ const webhookCallsOf = (event, binding) => {
162
+ const failed = failedOf(webhookErrors(event, binding));
163
+ const encodeSubscription = Schema.encodeUnknownEffect(Schema.toCodecJson(WebhookSubscriptionOf(event)));
164
+ const encodeCancellation = Schema.encodeUnknownEffect(Schema.toCodecJson(WebhookCancellationOf(event)));
165
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(Subscribed));
166
+ return (call) => ({
167
+ subscribe: ({ input, delivery, cursor, ttlMs }) => Effect.orDie(encodeSubscription({
168
+ input,
169
+ delivery,
170
+ cursor,
171
+ ttlMs
172
+ })).pipe(Effect.flatMap((json) => call.unary(subscribeTag(event.name), json)), Effect.catchIf(isDeclared, failed), Effect.flatMap((json) => Effect.orDie(decode(json)))),
173
+ unsubscribe: ({ input, delivery: { url } }) => Effect.orDie(encodeCancellation({
174
+ input,
175
+ delivery: { url }
176
+ })).pipe(Effect.flatMap((json) => call.unary(unsubscribeTag(event.name), json)), Effect.catchIf(isDeclared, failed), Effect.asVoid)
177
+ });
178
+ };
179
+ const resending = (poll, after) => (cursor, watch) => Effect.timeoutOrElse(poll(cursor, watch), {
180
+ duration: after,
181
+ orElse: () => resending(poll, after)(cursor, watch)
182
+ });
183
+ const polledTransport = (transient, resendAfter) => (event, binding) => {
184
+ const watchedThrough = watchedOf(event, binding);
185
+ const pollUnserved = isUnknownTag(pollTag(event.name));
186
+ return (call) => {
187
+ const watched = watchedThrough(call);
188
+ return (input) => {
189
+ const { poll } = watched(input);
190
+ return polledTransportOf(event, { poll: resendAfter === void 0 ? poll : resending(poll, resendAfter) }, transient, pollUnserved);
191
+ };
192
+ };
193
+ };
194
+ /**
195
+ * An action's client method over `reach`: its call goes where its input, decoded as the server
196
+ * will decode it, a decoding default included, says.
197
+ */
198
+ const actionMethodOf = (action, binding) => {
199
+ const method = calledMethodOf(action, binding);
200
+ const answer = (reach, [input, ...rest]) => Effect.flatMap(sentInput(action, input), ({ value }) => Effect.map(reach(action, value), (call) => method(call)(value, ...rest)));
201
+ return elementOf(action.success) === void 0 ? (reach) => (...args) => Effect.flatMap(answer(reach, args), answered) : (reach) => (...args) => elementsOf(answer(reach, args));
202
+ };
203
+ const methodsOf = (binding, transport) => {
204
+ const actions = binding.actions.map((action) => [action.name, actionMethodOf(action, binding)]);
205
+ const transports = new Map(binding.events.map((event) => [event.name, transport(event, binding)]));
206
+ return (reach) => {
207
+ const methods = Object.fromEntries(actions.map(([name, method]) => [name, method(reach)]));
208
+ if (transports.size === 0) return methods;
209
+ const watch = (event, input, watchOptions) => {
210
+ const feed = transports.get(event.name);
211
+ if (feed === void 0) return Stream.die(/* @__PURE__ */ new Error(`ActionRpc.client: the binding holds no event type ${event.name} (watch one the binding ActionRpc.make returned lists)`));
212
+ return Stream.unwrap(Effect.flatMap(sentInput(event, input), ({ json, value }) => Effect.map(reach(event, value), (call) => watching(feed(call)(json, watchOptions?.mode === "stream"), watchOptions))));
213
+ };
214
+ return {
215
+ ...methods,
216
+ watch
217
+ };
218
+ };
219
+ };
220
+ const callBoundaryOf = (error) => {
221
+ const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(error));
222
+ return (effect) => Effect.catchCause(effect, (cause) => {
223
+ if (Cause.hasDies(cause)) return concealed(cause);
224
+ const failure = Cause.findFail(cause);
225
+ return Result.isSuccess(failure) ? encode(failure.success.error).pipe(Effect.matchCauseEffect({
226
+ onFailure: (unencoded) => concealed(Cause.combine(cause, unencoded)),
227
+ onSuccess: (encoded) => Effect.fail(new DeclaredFailure(encoded))
228
+ })) : Effect.failCause(failure.failure);
229
+ });
230
+ };
231
+ const servedCall = (steps, boundary, call) => (payload, options) => boundary(throughSteps(steps, call(payload, options), {
232
+ ...options,
233
+ payload
234
+ }));
235
+ const handlerOf = (action, run, steps, error) => {
236
+ const decode = decodeInput(action);
237
+ const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(action.success));
238
+ return servedCall(steps, callBoundaryOf(error), (payload) => Effect.suspend(() => decode(payload)).pipe(Effect.flatMap(run), Effect.flatMap(encode)));
239
+ };
240
+ const streamingHandlerOf = (action, sending, steps, error) => {
241
+ const decode = decodeInput(action);
242
+ const boundary = callBoundaryOf(error);
243
+ const encodeProgress = Schema.encodeUnknownEffect(Schema.toCodecJson(action.progress ?? Schema.Never));
244
+ return servedCall(steps, boundary, (payload) => Effect.gen(function* () {
245
+ const input = yield* decode(payload);
246
+ const sent = yield* Queue.bounded(1);
247
+ const send = (each) => Effect.asVoid(Queue.offer(sent, each));
248
+ yield* sending(input, { progress: (value) => Effect.flatMap(Effect.orDie(encodeProgress(value)), (json) => send({
249
+ _tag: "Progress",
250
+ value: json
251
+ })) }, send).pipe(boundary, Queue.into(sent), Effect.forkScoped({ startImmediately: true }));
252
+ return sent;
253
+ }));
254
+ };
255
+ const sendingAnswer = (success, run) => {
256
+ const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(success));
257
+ return (input, reporting, send) => run(input, reporting).pipe(Effect.flatMap(encode), Effect.flatMap((value) => send({
258
+ _tag: "Final",
259
+ value
260
+ })));
261
+ };
262
+ const sendingElements = (element, run) => {
263
+ const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(element));
264
+ return (input, reporting, send) => Stream.runForEach(elementsOf(run(input, reporting)), (each) => Effect.flatMap(encode(each), (value) => send({
265
+ _tag: "Element",
266
+ value
267
+ })));
268
+ };
269
+ const subscriptionHandlerOf = (feed, steps, error) => {
270
+ const decode = decodeInput({ input: SubscriptionOf(feed.event) });
271
+ const encode = Schema.encodeEffect(Schema.toCodecJson(PushedOf(feed.event)));
272
+ const boundary = callBoundaryOf(error);
273
+ return servedCall(steps, boundary, (payload) => Effect.gen(function* () {
274
+ const { input, cursor } = yield* decode(payload);
275
+ const open = yield* feed.stream(input);
276
+ return yield* queuedPush(open, cursor, encode, {
277
+ ending: boundary,
278
+ positions: "heartbeat"
279
+ });
280
+ }));
281
+ };
282
+ const pollHandlerOf = (feed, steps, error, authentication, check) => {
283
+ const decode = decodeInput({ input: PollOf(feed.event) });
284
+ const encode = Schema.encodeEffect(Schema.toCodecJson(rpcPageOf(feed.event)));
285
+ return servedCall(steps, callBoundaryOf(error), (payload) => Effect.gen(function* () {
286
+ const { input, cursor, maxEvents } = yield* decode(payload);
287
+ yield* check(input);
288
+ const subscriber = yield* principalOf(feed.event, authentication);
289
+ const page = yield* feed.poll(input, cursor, {
290
+ subscriber,
291
+ maxEvents
292
+ });
293
+ return yield* encode({
294
+ ...page,
295
+ notified: !feed.polls
296
+ });
297
+ }));
298
+ };
299
+ const pollingRefused = ({ event }) => Effect.logWarning(`An entity refused a webhook subscription to "${event.name}", whose check source is not notified: its timer would be cut by Effect's entity reaper and keep a Durable Object awake (mark the source notified, notifying after each write, or serve the event's webhooks from a surface outside the entity)`);
300
+ const webhookHandlersOf = (feed, steps, error, answers, check) => {
301
+ const subscribing = decodeInput({ input: WebhookSubscriptionOf(feed.event) });
302
+ const cancelling = decodeInput({ input: WebhookCancellationOf(feed.event) });
303
+ const encode = Schema.encodeEffect(Schema.toCodecJson(Subscribed));
304
+ const boundary = callBoundaryOf(error);
305
+ return [[subscribeTag(feed.event.name), servedCall(steps, boundary, (payload) => Effect.suspend(() => subscribing(payload)).pipe(Effect.tap(({ input }) => check(input)), Effect.flatMap(answers.subscribe), Effect.flatMap(encode)))], [unsubscribeTag(feed.event.name), servedCall(steps, boundary, (payload) => Effect.suspend(() => cancelling(payload)).pipe(Effect.tap(({ input }) => check(input)), Effect.flatMap(answers.unsubscribe), Effect.as(null)))]];
306
+ };
307
+ const verifyingNative = (verify, { headers }) => withSyntheticRequestFromHeaders(headers)(verify).pipe(Effect.catchCauseIf(Cause.hasDies, concealed));
308
+ const requested = (effect, { headers }) => withSyntheticRequestFromHeaders(headers)(effect);
309
+ const handlersOf = Effect.fnUntraced(function* (binding, { apps, events, authentication, server }) {
310
+ const holdsWebhooks = server._tag === "ActionEntity.layer";
311
+ const check = server._tag === "ActionEntity.layer" ? server.check : () => Effect.void;
312
+ const listedMiddleware = server._tag === "ActionRpc.layer" ? yield* Effect.forEach(server.middleware, (key) => Effect.service(key)) : [];
313
+ const authenticating = authentication === void 0 ? void 0 : yield* authenticatingOf(authentication);
314
+ const bound = yield* acquire(apps, authentication);
315
+ const { feeds, webhooks } = holdsWebhooks ? yield* servingFeeds(events, authentication, ({ polls }) => !polls) : {
316
+ feeds: yield* acquireFeeds(events),
317
+ webhooks: Option.none()
318
+ };
319
+ const heldAnswers = (feed) => {
320
+ const answers = webhookAnswers(feed, authentication, webhooks);
321
+ if (!feed.polls || Option.isNone(webhooks)) return answers;
322
+ return {
323
+ ...answers,
324
+ subscribe: () => Effect.andThen(pollingRefused(feed), Effect.fail(deliveryUnsupported(feed.event.name, "webhook")))
325
+ };
326
+ };
327
+ const stepsOf = (caller) => caller === Anyone || authenticating === void 0 ? [...listedMiddleware, requested] : [
328
+ ...listedMiddleware,
329
+ authenticating((verify) => verify),
330
+ requested
331
+ ];
332
+ const handlerFor = (action, unchecked, steps, error) => {
333
+ const run = (input, reporting) => Effect.andThen(check(action, input), () => unchecked(input, reporting));
334
+ const streaming = (sending) => streamingHandlerOf(action, sending, steps, error);
335
+ return Answering.$match(answeringOf(action), {
336
+ Value: () => handlerOf(action, run, steps, error),
337
+ Progressed: ({ success }) => streaming(sendingAnswer(success, run)),
338
+ Elements: ({ element }) => streaming(sendingElements(element, run))
339
+ });
340
+ };
341
+ return {
342
+ handlers: {
343
+ ...Object.fromEntries(bound.map(([action, run]) => [action.name, handlerFor(action, run, stepsOf(action.caller), Schema.Union(bindingErrors(action, binding)))])),
344
+ ...Object.fromEntries(streamsEvents(server._tag) ? feeds.map((feed) => [feed.event.name, subscriptionHandlerOf(feed, stepsOf(feed.event.caller), Schema.Union(eventErrors(feed.event, binding)))]) : []),
345
+ ...Object.fromEntries(feeds.flatMap((feed) => {
346
+ const steps = stepsOf(feed.event.caller);
347
+ const error = Schema.Union(eventErrors(feed.event, binding));
348
+ const checking = (input) => check(feed.event, input);
349
+ return [[pollTag(feed.event.name), pollHandlerOf(feed, steps, error, authentication, checking)]];
350
+ })),
351
+ ...Object.fromEntries(holdsWebhooks ? feeds.filter(({ event }) => offersWebhook(event)).flatMap((feed) => webhookHandlersOf(feed, stepsOf(feed.event.caller), webhookErrors(feed.event, binding), heldAnswers(feed), (input) => check(feed.event, input))) : [])
352
+ },
353
+ authenticating
354
+ };
355
+ });
356
+ export { DeclaredFailure, Poll, ProgressedOf, actionMethodOf, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollOf, pollTag, polledTransport, streamedOf, streamedTransport, verifyingNative, watchedOf, webhookCallsOf, webhookRpcsOf };
@@ -18,14 +18,15 @@ const isUnknownTag = (tag) => {
18
18
  const message = `Unknown request tag: ${tag}`;
19
19
  return (cause) => cause.reasons.some((reason) => Cause.isDieReason(reason) && (Predicate.hasProperty(reason.defect, "message") ? reason.defect.message === message : reason.defect === message));
20
20
  };
21
- const transportOf = (event, stream, silenceEnds) => {
22
- const notServed = Stream.fail(SubscriptionError.of(event.name, new NotServed()));
21
+ const streamingOf = (event, stream, silenceEnds, streamOnly) => {
22
+ const unserved = Stream.fail(streamOnly ? SubscriptionError.of(event.name, new NotServed()) : deliveryUnsupported(event.name, "push"));
23
23
  const unknownTag = isUnknownTag(event.name);
24
- return {
25
- name: event.name,
26
- poll: () => Effect.fail(deliveryUnsupported(event.name, "poll")),
27
- stream: (cursor) => stream(cursor).pipe(Stream.catchCauseIf(unknownTag, () => notServed), silenceEnds ? receivedFrom("RPC", event.name) : readOn("RPC", event.name)),
28
- transient: isRpcTransient
29
- };
24
+ return (cursor) => stream(cursor).pipe(Stream.catchCauseIf(unknownTag, () => unserved), silenceEnds ? receivedFrom("RPC", event.name) : readOn("RPC", event.name));
30
25
  };
31
- export { isRpcTransient, transportOf };
26
+ const polledTransportOf = (event, { poll }, transient, unserved) => ({
27
+ name: event.name,
28
+ poll: (cursor, watch) => poll(cursor, watch).pipe(Effect.catchCauseIf(unserved, () => Effect.fail(SubscriptionError.of(event.name, new NotServed())))),
29
+ stream: () => Stream.fail(deliveryUnsupported(event.name, "push")),
30
+ transient
31
+ });
32
+ export { isRpcTransient, isUnknownTag, polledTransportOf, streamingOf };
@@ -12,9 +12,11 @@ const Stored = Schema.Struct({
12
12
  secret: WebhookSecret,
13
13
  expiresAt: Schema.Finite,
14
14
  watermark: Schema.NullOr(Schema.String),
15
- status: DeliveryStatus
15
+ status: DeliveryStatus,
16
+ retryingAt: Schema.optional(Schema.Finite)
16
17
  });
17
- const prefix = "effect-actions/webhook/";
18
+ const storePrefix = "effect-actions/webhook/";
19
+ const entityStorePrefix = (entityType, entityId) => `effect-actions/entity-webhook/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}/`;
18
20
  const flushTimeout = Duration.seconds(5);
19
21
  var UnfinishedWrites = class UnfinishedWrites extends Schema.TaggedError()("UnfinishedWrites", {
20
22
  ids: Schema.Array(Schema.String),
@@ -27,7 +29,7 @@ var UnfinishedWrites = class UnfinishedWrites extends Schema.TaggedError()("Unfi
27
29
  });
28
30
  }
29
31
  };
30
- const makeWriteBehindStorage = (store) => Effect.gen(function* () {
32
+ const makeWriteBehindStorage = (store, prefix = storePrefix) => Effect.gen(function* () {
31
33
  const records = KeyValueStore.toSchemaStore(KeyValueStore.prefix(store, prefix), Stored);
32
34
  const kept = new Set(yield* Effect.orDie(records.keys));
33
35
  const pending = /* @__PURE__ */ new Map();
@@ -55,4 +57,4 @@ const makeWriteBehindStorage = (store) => Effect.gen(function* () {
55
57
  get: (id) => pending.has(id) ? Effect.succeed(Option.fromUndefinedOr(pending.get(id))) : records.get(id)
56
58
  };
57
59
  });
58
- export { Stored, makeWriteBehindStorage };
60
+ export { Stored, entityStorePrefix, makeWriteBehindStorage, storePrefix };
@@ -22,6 +22,7 @@ const grantOf = (ttlMs, policy) => Duration.clamp(ttlMs === null || ttlMs === vo
22
22
  });
23
23
  const trusted = (url, prefixes) => prefixes.some(({ origin, pathname }) => url.origin === origin && (url.pathname === pathname || url.pathname.startsWith(pathname.endsWith("/") ? pathname : `${pathname}/`)));
24
24
  const snapshotOf = Context.omit(Scope.Scope, HttpServerRequest.HttpServerRequest, HttpServerRequest.ParsedSearchParams, HttpRouter.RouteContext);
25
+ const slept = (at) => Effect.flatMap(Clock.currentTimeMillis, (now) => Effect.sleep(Duration.millis(Math.max(at - now, 0))));
25
26
  const unencoded = Effect.die(/* @__PURE__ */ new Error("A webhook subscriber's identity did not encode by its authentication's schema (give Authentication.make a schema that encodes every identity its verifier provides)"));
26
27
  const confirmedAt = (cursor) => Effect.tap(Deferred.make(), (confirmation) => Deferred.succeed(confirmation, {
27
28
  cursor,
@@ -45,7 +46,8 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
45
46
  secret: subscription.secret,
46
47
  expiresAt: subscription.expiresAt,
47
48
  watermark: subscription.watermark,
48
- status: statusOf(subscription.health)
49
+ status: statusOf(subscription.health),
50
+ retryingAt: subscription.retryingAt
49
51
  });
50
52
  });
51
53
  const dropped = (id) => Effect.sync(() => storage?.mark(id, void 0));
@@ -58,14 +60,14 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
58
60
  subscription.health = next;
59
61
  return kept(subscription);
60
62
  });
61
- const waitingAsLongAsFailing = (subscription) => Schedule.modifyDelay(Schedule.forever, () => Effect.map(Clock.currentTimeMillis, (now) => Duration.clamp(Duration.millis(failingForMs(subscription.health, now)), {
63
+ const waitedUntil = (at) => Option.match(policy.wake, {
64
+ onNone: () => slept(at),
65
+ onSome: ({ until }) => until(at)
66
+ });
67
+ const retryAt = (subscription, failedAt) => failedAt + Duration.toMillis(Duration.clamp(Duration.millis(failingForMs(subscription.health, failedAt)), {
62
68
  minimum: Duration.seconds(1),
63
69
  maximum: Duration.minutes(5)
64
- })));
65
- const retrying = (subscription) => ({
66
- schedule: waitingAsLongAsFailing(subscription),
67
- while: () => subscription.health._tag === "Failing"
68
- });
70
+ }));
69
71
  const locked = (id) => (effect) => Effect.scoped(Effect.flatMap(RcMap.get(locks, id), (lock) => lock.withPermits(1)(effect)));
70
72
  const asSubscriber = (subscription, effect) => Effect.updateContext(effect, () => subscription.context);
71
73
  const post = (subscription, webhookId, body) => Effect.flatMap(Clock.currentTimeMillis, (now) => Effect.provideContext(attempt({
@@ -75,23 +77,35 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
75
77
  body,
76
78
  keys: subscription.previous !== void 0 && now < subscription.previous.until ? [subscription.secret.key, subscription.previous.key] : [subscription.secret.key]
77
79
  }, trusted(subscription.url, policy.allowedCallbacks) ? Effect.void : checkedHost(subscription.url, policy.dns)), built));
78
- const delivered = (subscription, webhookId, body) => post(subscription, webhookId, body).pipe(Effect.tapError(({ category, final }) => Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
79
- _tag: "AttemptFailed",
80
- category,
81
- final,
82
- at
83
- }))), Effect.retry(retrying(subscription)), Effect.matchEffect({
84
- onSuccess: () => Effect.as(Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
80
+ const unexpired = (subscription) => Effect.flatMap(Clock.currentTimeMillis, (now) => now < subscription.expiresAt ? Effect.void : Effect.interrupt);
81
+ const retried = (subscription) => Effect.flatMap(Clock.currentTimeMillis, (now) => Effect.andThen(subscription.retryingAt === void 0 || subscription.retryingAt <= now ? Effect.void : waitedUntil(subscription.retryingAt), Effect.sync(() => {
82
+ subscription.retryingAt = void 0;
83
+ })));
84
+ const attempted = (subscription, webhookId, body) => retried(subscription).pipe(Effect.andThen(unexpired(subscription)), Effect.andThen(post(subscription, webhookId, body)), Effect.as(true), Effect.catch(({ category, final }) => Effect.gen(function* () {
85
+ const at = yield* Clock.currentTimeMillis;
86
+ yield* transitioned(subscription, {
87
+ _tag: "AttemptFailed",
88
+ category,
89
+ final,
90
+ at
91
+ });
92
+ if (subscription.health._tag !== "Failing") return false;
93
+ subscription.retryingAt = retryAt(subscription, at);
94
+ yield* kept(subscription);
95
+ return yield* attempted(subscription, webhookId, body);
96
+ })));
97
+ const delivered = (subscription, webhookId, body) => Effect.flatMap(attempted(subscription, webhookId, body), (accepted) => {
98
+ if (accepted) return Effect.as(Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
85
99
  _tag: "Delivered",
86
100
  at
87
- })), true),
88
- onFailure: () => subscription.health._tag === "Suspended" ? Effect.never : Effect.succeed(false)
89
- }));
101
+ })), true);
102
+ return subscription.health._tag === "Suspended" ? Effect.never : Effect.succeed(false);
103
+ });
90
104
  const gapped = (subscription, cursor) => Effect.flatMap(randomToken, (token) => delivered(subscription, `msg_gap_${token}`, JSON.stringify({
91
105
  type: "gap",
92
106
  cursor
93
107
  })));
94
- const deliverTo = (subscription, input, confirmation) => {
108
+ const deliverTo = (subscription, confirmation) => {
95
109
  const encode = encodeUntaggedOf(subscription.feed.event);
96
110
  const moved = (cursor) => cursor === null || cursor === subscription.watermark ? Effect.void : Effect.andThen(Effect.sync(() => {
97
111
  subscription.watermark = cursor;
@@ -105,7 +119,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
105
119
  Checked: ({ cursor }) => Deferred.isDoneUnsafe(confirmation) ? moved(cursor) : confirmed(cursor, false),
106
120
  Gap: ({ cursor }) => Deferred.isDoneUnsafe(confirmation) ? skipped(cursor) : confirmed(cursor, true),
107
121
  Occurrence: (occurrence) => Effect.gen(function* () {
108
- const body = yield* asSubscriber(subscription, subscription.feed.admit(input)).pipe(Effect.andThen(Effect.map(encode(occurrence), JSON.stringify)));
122
+ const body = yield* asSubscriber(subscription, subscription.feed.admit).pipe(Effect.andThen(Effect.map(encode(occurrence), JSON.stringify)));
109
123
  if (encoder.encode(body).length > maxBody) {
110
124
  yield* Effect.logWarning(`Webhook delivery of ${occurrence.eventId} abandoned: its body is over 256 KiB`);
111
125
  return yield* skipped(occurrence.cursor);
@@ -116,7 +130,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
116
130
  Failed: () => Effect.void
117
131
  });
118
132
  };
119
- const expired = ({ expiresAt }) => Effect.flatMap(Clock.currentTimeMillis, (now) => Effect.sleep(Duration.millis(Math.max(expiresAt - now, 0))));
133
+ const expiryTimer = ({ expiresAt }) => Option.isSome(policy.wake) ? Effect.never : slept(expiresAt);
120
134
  const terminated = (subscription, cause) => {
121
135
  const refusal = refusalIn(cause);
122
136
  if (refusal === void 0) return Cause.hasInterruptsOnly(cause) ? Effect.void : reported(cause);
@@ -135,10 +149,10 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
135
149
  if (holds(subscription)) held.delete(subscription.id);
136
150
  });
137
151
  const finished = (subscription) => Effect.suspend(() => holds(subscription) ? Effect.andThen(ended(subscription), dropped(subscription.id)) : Effect.void);
138
- const workerOf = (subscription, input, cursor, confirmation) => Effect.raceFirst(pushed((from) => Stream.unwrap(Effect.map(subscription.feed.stream(input), (read) => read(from))), cursor, deliverTo(subscription, input, confirmation), {
152
+ const workerOf = (subscription, input, cursor, confirmation) => Effect.raceFirst(pushed((from) => Stream.unwrap(Effect.map(subscription.feed.stream(input), (read) => read(from))), cursor, deliverTo(subscription, confirmation), {
139
153
  positions: "watermark",
140
154
  resumesUnconfirmed: Deferred.isDoneUnsafe(confirmation)
141
- }), expired(subscription)).pipe(Effect.exit, Effect.tap(() => finished(subscription)), Effect.flatMap((exit) => {
155
+ }), expiryTimer(subscription)).pipe(Effect.exit, Effect.tap(() => finished(subscription)), Effect.flatMap((exit) => {
142
156
  if (Deferred.isDoneUnsafe(confirmation)) return Exit.isFailure(exit) ? terminated(subscription, exit.cause) : Effect.void;
143
157
  return Exit.isFailure(exit) ? Deferred.failCause(confirmation, exit.cause) : Deferred.succeed(confirmation, {
144
158
  cursor,
@@ -200,7 +214,8 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
200
214
  const heldOf = (fields) => ({
201
215
  ...fields,
202
216
  verifiedAs: `${fields.principal}\u0000${fields.url.href}`,
203
- previous: void 0
217
+ previous: void 0,
218
+ retryingAt: void 0
204
219
  });
205
220
  const keptOf = ({ feed, keyed, input }) => Effect.gen(function* () {
206
221
  const { schema } = keyed;
@@ -236,23 +251,26 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
236
251
  });
237
252
  if (current !== id) yield* dropped(id);
238
253
  if (held.has(current)) return;
239
- const subscription = heldOf({
240
- id: current,
241
- url,
242
- feed,
243
- principal,
244
- kept: {
245
- input: record.input,
246
- identity: record.identity
247
- },
248
- secret,
249
- context: Context.add(built, feed.event.caller, identity),
250
- expiresAt,
251
- health: restoredHealth,
252
- watermark: record.watermark
253
- });
254
+ const subscription = {
255
+ ...heldOf({
256
+ id: current,
257
+ url,
258
+ feed,
259
+ principal,
260
+ kept: {
261
+ input: record.input,
262
+ identity: record.identity
263
+ },
264
+ secret,
265
+ context: Context.add(Context.merge(built, snapshotOf(yield* Effect.context())), feed.event.caller, identity),
266
+ expiresAt,
267
+ health: restoredHealth,
268
+ watermark: record.watermark
269
+ }),
270
+ retryingAt: record.retryingAt
271
+ };
254
272
  const confirmation = yield* confirmedAt(record.watermark);
255
- yield* swapHeldWorker(current, subscription, restoredHealth._tag === "Suspended" ? Effect.andThen(expired(subscription), finished(subscription)) : workerOf(subscription, input, record.watermark, confirmation));
273
+ yield* swapHeldWorker(current, subscription, restoredHealth._tag === "Suspended" ? Effect.andThen(expiryTimer(subscription), finished(subscription)) : workerOf(subscription, input, record.watermark, confirmation));
256
274
  if (current !== id) yield* kept(subscription);
257
275
  }).pipe(Effect.catchCause(reported));
258
276
  const serve = (feeds, keyed) => Effect.gen(function* () {
@@ -281,7 +299,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
281
299
  const { feed, principal, input, delivery: { url, secret }, cursor, ttlMs } = subscribing;
282
300
  const id = yield* idOf(subscribing);
283
301
  return yield* locked(id)(Effect.gen(function* () {
284
- yield* Effect.catchCause(feed.admit(input), (cause) => terminatedOnRefusal(id, cause));
302
+ yield* Effect.catchCause(feed.admit, (cause) => terminatedOnRefusal(id, cause));
285
303
  const now = yield* Clock.currentTimeMillis;
286
304
  const granted = {
287
305
  secret,
@@ -63,7 +63,7 @@ export const builds = Action.implement(
63
63
  );
64
64
  ```
65
65
 
66
- The rules are on `Action.Options.progress`; how each surface carries the values, on `ActionHttp.layer`, `ActionRpc.make`, `ActionMcp.layerHttp`, `ActionToolkit.make` and `ActionCli.command`.
66
+ The rules are on `Action.Options.progress`; how each surface carries the values, on `ActionHttp.layer`, `ActionRpc.make`, `ActionEntity.make`, `ActionMcp.layerHttp`, `ActionToolkit.make` and `ActionCli.command`.
67
67
 
68
68
  - **Report a snapshot to show, never an event to count.** A caller falling behind loses the oldest values, never the answer: what a caller must receive each time is the answer, or an [event](Event.md).
69
69
 
@@ -98,6 +98,6 @@ export const logs = Action.implement(
98
98
  );
99
99
  ```
100
100
 
101
- How each surface carries it is on `ActionHttp.layer`, `ActionRpc.make`, `ActionMcp.layerHttp`, `ActionToolkit.make` and `ActionCli.command`.
101
+ How each surface carries it is on `ActionHttp.layer`, `ActionRpc.make`, `ActionEntity.make`, `ActionMcp.layerHttp`, `ActionToolkit.make` and `ActionCli.command`.
102
102
 
103
103
  - **A tool collects it whole.** A tool answers one result, so an MCP endpoint and a toolkit answer the elements as one array once the stream ends, and `ActionMcp.client`'s method streams that array again: a stream that never ends never answers a tool, and a long one fills a model's context, so [kitchen-sink/src/Actions.ts](../examples/kitchen-sink/src/Actions.ts) leaves `exportIssues` out of its tools.
package/docs/Action.md CHANGED
@@ -23,7 +23,7 @@ export const Greet = Action.make("greet", {
23
23
 
24
24
  [notes-service/src/notes/Notes.ts](../examples/notes-service/src/notes/Notes.ts) adds declared errors with their statuses, described fields and the list; [kitchen-sink/src/issues/Issues.ts](../examples/kitchen-sink/src/issues/Issues.ts) uses every option. The rules of each option, `input`'s optional fields and `error`'s tags included, are on `Action.Options`; where an action must be listed to be served, and matching by object identity, are on `Action.make`. The list each surface takes lives in one file beside the contracts ([kitchen-sink/src/Actions.ts](../examples/kitchen-sink/src/Actions.ts)).
25
25
 
26
- - **List an action as a tool only where a model may hold what it takes and returns.** A tool call passes both through the model's context, and `ActionToolkit`, through Effect's toolkit, records its arguments on the current span, a `Schema.Redacted` value included: always before effect 4.1.3, and from it where `Toolkit.RecordToolArguments` is `true`, which also records an MCP tool call's arguments on its request span.
26
+ - **List an action as a tool only where a model may hold what it takes and returns.** A tool call passes both through the model's context, and `ActionToolkit`, through Effect's toolkit, records its arguments on the current span, a `Schema.Redacted` value included, where `Toolkit.RecordToolArguments` is `true`, which also records an MCP tool call's arguments on its request span.
27
27
 
28
28
  ## Say who may call an action
29
29
 
@@ -128,7 +128,7 @@ A handler fails with the errors its action lists in `error`, and with the three
128
128
 
129
129
  ## Answer a retried call once
130
130
 
131
- A write a caller may send again, after a dropped connection or a timeout, names a string field of its input as its `idempotencyKey`. The caller makes the key at random for the call and sends it again on each retry: a repeat with the same input is answered as the first call was, its handler run once, on every surface, since the key travels with the input. An implementation of such an action requires `Action.Idempotency` at startup, where the answers are kept: provide `Action.layerIdempotency` around the surfaces, as `Event.layerMemory` is provided; in a Durable Object, the Cloudflare package's `ActionDurableObject.make` provides it. What is kept, whose a key is, and what a repeat with another input answers, are on the option.
131
+ A write a caller may send again, after a dropped connection or a timeout, names a string field of its input as its `idempotencyKey`. The caller makes the key at random for the call and sends it again on each retry: a repeat with the same input is answered as the first call was, its handler run once, on every surface, since the key travels with the input. An implementation of such an action requires `Action.Idempotency` at startup, where the answers are kept: provide `Action.layerIdempotency` around the surfaces, as `Event.layerMemory` is provided, or `Stored.layerIdempotency` over the `SqlClient` `Stored.layerEvents` uses, to keep answers across restarts, such as in a cluster entity's `services`. What is kept, whose a key is, and what a repeat with another input answers, are on the option; why a crash after the handler's write runs a repeat again is on `Action.Idempotency`.
132
132
 
133
133
  ## Call actions in process
134
134
 
@@ -139,5 +139,5 @@ A write a caller may send again, after a dropped connection or a timeout, names
139
139
  Inside one `HttpRouter.serve` or one `Testing.layer`, a builder runs once, however many surfaces serve it, a toolkit's `layer` provided to the routes included. Each `HttpRouter.serve` is a layer graph of its own, the layers Effect builds together, each once, which shares nothing it builds with another graph: a builder's run, a built authorizer, or an in-memory store of yours.
140
140
 
141
141
  - **With one server, put everything the process runs inside the layer it serves**, a job or an agent beside the routes included; why a job merged beside `HttpRouter.serve` is not enough is on `Action.layer`.
142
- - **Otherwise, provide `Action.layer(implementations)` and the services they share above the server and its siblings**: a second server, a program beside it, several `Testing.layer`s. [kitchen-sink/src/server.ts](../examples/kitchen-sink/src/server.ts) does it for two ports with the `builders` layer of [kitchen-sink/src/routes.ts](../examples/kitchen-sink/src/routes.ts), and [kitchen-sink/test/routes.test.ts](../examples/kitchen-sink/test/routes.test.ts) with two `Testing.layer`s, asserting one run of a builder both ports serve.
142
+ - **Otherwise, provide `Action.layer(implementations)` and the services they share above the server and its siblings**: a second server, a program beside it, several `Testing.layer`s. [kitchen-sink/src/server.ts](../examples/kitchen-sink/src/server.ts) does it for two ports with the `builders` layer of [kitchen-sink/src/routes.ts](../examples/kitchen-sink/src/routes.ts), and [kitchen-sink/test/routes.test.ts](../examples/kitchen-sink/test/routes.test.ts) with two `Testing.layer`s, asserting one run of a builder both ports serve. An entity is the exception: each entity id builds for itself, as `ActionEntity.layer` says.
143
143
  - **Inside one layer graph, a builder runs with the services of whichever surface builds it first**, and services provided around one surface reach the others: provide startup services once, for every surface. Where two must differ is on `Action.layer`.