@gjermundgaraba/effect-actions 0.30.0 → 0.32.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 (111) hide show
  1. package/README.md +4 -3
  2. package/dist/Action.d.mts +6 -6
  3. package/dist/Action.mjs +12 -14
  4. package/dist/ActionEntity.d.mts +237 -0
  5. package/dist/ActionEntity.mjs +211 -0
  6. package/dist/ActionHttp.d.mts +5 -5
  7. package/dist/ActionHttp.mjs +24 -28
  8. package/dist/ActionMcp.d.mts +2 -3
  9. package/dist/ActionMcp.mjs +7 -10
  10. package/dist/ActionRpc.d.mts +25 -57
  11. package/dist/ActionRpc.mjs +45 -274
  12. package/dist/ActionToolkit.mjs +4 -3
  13. package/dist/Authentication.d.mts +8 -9
  14. package/dist/Authentication.mjs +49 -51
  15. package/dist/Event.d.mts +26 -6
  16. package/dist/Event.mjs +2 -2
  17. package/dist/Stored.d.mts +49 -0
  18. package/dist/Stored.mjs +78 -0
  19. package/dist/Webhook.d.mts +5 -4
  20. package/dist/Webhook.mjs +11 -4
  21. package/dist/authentication/provider.d.mts +2 -2
  22. package/dist/authentication/refusal.mjs +11 -4
  23. package/dist/cli/commands.mjs +8 -8
  24. package/dist/contract/call.mjs +6 -2
  25. package/dist/contract/callback.mjs +6 -1
  26. package/dist/contract/caller.d.mts +2 -6
  27. package/dist/contract/caller.mjs +3 -3
  28. package/dist/contract/digest.mjs +3 -2
  29. package/dist/contract/event-tables.mjs +90 -0
  30. package/dist/contract/feed.d.mts +15 -3
  31. package/dist/contract/feed.mjs +27 -16
  32. package/dist/contract/hub.d.mts +4 -57
  33. package/dist/contract/hub.mjs +12 -15
  34. package/dist/contract/idempotency.d.mts +6 -18
  35. package/dist/contract/idempotency.mjs +6 -14
  36. package/dist/contract/implementation.mjs +10 -21
  37. package/dist/contract/log.d.mts +0 -26
  38. package/dist/contract/log.mjs +16 -8
  39. package/dist/contract/pages.d.mts +30 -2
  40. package/dist/contract/pages.mjs +27 -3
  41. package/dist/contract/push.mjs +3 -5
  42. package/dist/contract/recent.mjs +3 -2
  43. package/dist/contract/serving.mjs +17 -17
  44. package/dist/contract/stream.d.mts +1 -1
  45. package/dist/contract/stream.mjs +14 -2
  46. package/dist/contract/subscribe.mjs +7 -2
  47. package/dist/contract/wake.mjs +9 -0
  48. package/dist/contract/watch.mjs +24 -22
  49. package/dist/contract/webhooks.d.mts +8 -4
  50. package/dist/contract/webhooks.mjs +50 -28
  51. package/dist/entity/forwarded.d.mts +11 -0
  52. package/dist/entity/forwarded.mjs +32 -0
  53. package/dist/entity/wakes.mjs +39 -0
  54. package/dist/http/client.mjs +8 -6
  55. package/dist/http/events.d.mts +1 -12
  56. package/dist/http/events.mjs +5 -25
  57. package/dist/http/redacted.mjs +9 -0
  58. package/dist/http/streamed.d.mts +1 -0
  59. package/dist/http/streamed.mjs +10 -5
  60. package/dist/mcp/bridge.mjs +14 -24
  61. package/dist/mcp/client.mjs +3 -12
  62. package/dist/mcp/events.mjs +1 -1
  63. package/dist/mcp/progress.mjs +11 -1
  64. package/dist/rpc/erased.d.mts +62 -0
  65. package/dist/rpc/erased.mjs +356 -0
  66. package/dist/rpc/watch.mjs +12 -13
  67. package/dist/webhook/health.mjs +25 -28
  68. package/dist/webhook/receiver.mjs +4 -7
  69. package/dist/webhook/stored.mjs +6 -4
  70. package/dist/webhook/subscriptions.mjs +65 -48
  71. package/docs/Action-streams.md +2 -2
  72. package/docs/Action.md +3 -3
  73. package/docs/ActionEntity-failures.md +10 -0
  74. package/docs/ActionEntity.md +165 -0
  75. package/docs/ActionHttp.md +0 -4
  76. package/docs/ActionMcp.md +2 -2
  77. package/docs/ActionRpc-events.md +2 -2
  78. package/docs/ActionRpc.md +1 -1
  79. package/docs/Authentication-failures.md +1 -0
  80. package/docs/Authentication.md +4 -2
  81. package/docs/Event.md +5 -5
  82. package/docs/README.md +5 -2
  83. package/docs/Webhook.md +1 -1
  84. package/docs/setup-failures.md +1 -1
  85. package/docs/setup.md +6 -5
  86. package/examples/README.md +1 -1
  87. package/examples/kitchen-sink/src/admin/Admin.ts +1 -0
  88. package/examples/kitchen-sink/src/identity/Identity.ts +5 -1
  89. package/examples/live-rpc/src/identity/Identity.ts +3 -1
  90. package/examples/notes-service/src/identity/Identity.ts +3 -1
  91. package/examples/shopping-carts/README.md +46 -0
  92. package/examples/shopping-carts/src/Api.ts +9 -0
  93. package/examples/shopping-carts/src/Rpc.ts +6 -0
  94. package/examples/shopping-carts/src/cart/Cart.ts +47 -0
  95. package/examples/shopping-carts/src/cart/handlers.ts +42 -0
  96. package/examples/shopping-carts/src/cart/held.ts +5 -0
  97. package/examples/shopping-carts/src/cart/store.ts +10 -0
  98. package/examples/shopping-carts/src/entities.ts +7 -0
  99. package/examples/shopping-carts/src/identity/Identity.ts +16 -0
  100. package/examples/shopping-carts/src/identity/shoppers.ts +6 -0
  101. package/examples/shopping-carts/src/identity/verifier.ts +21 -0
  102. package/examples/shopping-carts/src/platform/cluster.ts +7 -0
  103. package/examples/shopping-carts/src/platform/sql-carts.ts +30 -0
  104. package/examples/shopping-carts/src/routes.ts +23 -0
  105. package/examples/shopping-carts/src/server.ts +23 -0
  106. package/examples/shopping-carts/test/routes.test.ts +69 -0
  107. package/package.json +12 -9
  108. package/dist/contract/input-check.d.mts +0 -15
  109. package/dist/contract/input-check.mjs +0 -15
  110. package/dist/http/placed.d.mts +0 -34
  111. package/dist/http/placed.mjs +0 -71
@@ -1,5 +1,6 @@
1
- import { NotServed, SubscriptionError, Unsupported } from "../Event.mjs";
1
+ import { NotServed, SubscriptionError } from "../Event.mjs";
2
2
  import { readOn } from "../contract/push.mjs";
3
+ import { deliveryUnsupported } from "../contract/subscribe.mjs";
3
4
  import { isTransientReason, receivedFrom } from "../contract/transient.mjs";
4
5
  import { Cause, Effect, Match, Predicate, Schema, Stream } from "effect";
5
6
  import { HttpClientError } from "effect/http";
@@ -17,17 +18,15 @@ const isUnknownTag = (tag) => {
17
18
  const message = `Unknown request tag: ${tag}`;
18
19
  return (cause) => cause.reasons.some((reason) => Cause.isDieReason(reason) && (Predicate.hasProperty(reason.defect, "message") ? reason.defect.message === message : reason.defect === message));
19
20
  };
20
- const transportOf = (event, stream, silenceEnds) => {
21
- 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"));
22
23
  const unknownTag = isUnknownTag(event.name);
23
- return {
24
- name: event.name,
25
- poll: () => Effect.fail(SubscriptionError.of(event.name, new Unsupported({
26
- feature: "deliveryMode",
27
- value: "poll"
28
- }))),
29
- stream: (cursor) => stream(cursor).pipe(Stream.catchCauseIf(unknownTag, () => notServed), silenceEnds ? receivedFrom("RPC", event.name) : readOn("RPC", event.name)),
30
- transient: isRpcTransient
31
- };
24
+ return (cursor) => stream(cursor).pipe(Stream.catchCauseIf(unknownTag, () => unserved), silenceEnds ? receivedFrom("RPC", event.name) : readOn("RPC", event.name));
32
25
  };
33
- 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 };
@@ -1,14 +1,19 @@
1
1
  import { DateTime, Option } from "effect";
2
2
  // src/webhook/health.ts
3
- const deliveryHealth = (retryForMs) => {
3
+ const delivering = {
4
+ _tag: "Delivering",
5
+ lastDeliveryAt: null,
6
+ lastError: null
7
+ };
8
+ const healthTransition = (retryForMs) => {
4
9
  const spent = (failedSince, at) => at - failedSince >= retryForMs;
5
- const transition = (health, event) => {
10
+ return (health, event) => {
6
11
  const { lastDeliveryAt } = health;
7
- switch (health.value) {
12
+ switch (health._tag) {
8
13
  case "Delivering":
9
- if (event.type === "Refreshed") return health;
10
- if (event.type === "Delivered") return {
11
- value: "Delivering",
14
+ if (event._tag === "Refreshed") return health;
15
+ if (event._tag === "Delivered") return {
16
+ _tag: "Delivering",
12
17
  lastDeliveryAt: event.at,
13
18
  lastError: null
14
19
  };
@@ -17,47 +22,39 @@ const deliveryHealth = (retryForMs) => {
17
22
  lastError: event.category
18
23
  };
19
24
  return {
20
- value: spent(event.at, event.at) ? "Suspended" : "Failing",
25
+ _tag: spent(event.at, event.at) ? "Suspended" : "Failing",
21
26
  lastDeliveryAt,
22
27
  lastError: event.category,
23
28
  failedSince: event.at
24
29
  };
25
30
  case "Failing":
26
- if (event.type === "Refreshed") return health;
27
- if (event.type === "Delivered") return {
28
- value: "Delivering",
31
+ if (event._tag === "Refreshed") return health;
32
+ if (event._tag === "Delivered") return {
33
+ _tag: "Delivering",
29
34
  lastDeliveryAt: event.at,
30
35
  lastError: null
31
36
  };
32
37
  if (event.final) return {
33
- value: "Delivering",
38
+ _tag: "Delivering",
34
39
  lastDeliveryAt,
35
40
  lastError: event.category
36
41
  };
37
42
  if (spent(health.failedSince, event.at)) return {
38
43
  ...health,
39
- value: "Suspended",
44
+ _tag: "Suspended",
40
45
  lastError: event.category
41
46
  };
42
47
  return event.category === health.lastError ? health : {
43
48
  ...health,
44
49
  lastError: event.category
45
50
  };
46
- case "Suspended": return event.type === "Refreshed" ? {
47
- value: "Delivering",
51
+ case "Suspended": return event._tag === "Refreshed" ? {
52
+ _tag: "Delivering",
48
53
  lastDeliveryAt,
49
54
  lastError: health.lastError
50
55
  } : health;
51
56
  }
52
57
  };
53
- return {
54
- initialState: {
55
- value: "Delivering",
56
- lastDeliveryAt: null,
57
- lastError: null
58
- },
59
- transition
60
- };
61
58
  };
62
59
  const iso = (millis) => DateTime.formatIso(DateTime.makeUnsafe(millis));
63
60
  const millisOf = (text) => {
@@ -66,13 +63,13 @@ const millisOf = (text) => {
66
63
  };
67
64
  const statusOf = (health) => {
68
65
  const lastDeliveryAt = health.lastDeliveryAt === null ? null : iso(health.lastDeliveryAt);
69
- if (health.value === "Delivering") return {
66
+ if (health._tag === "Delivering") return {
70
67
  active: true,
71
68
  lastDeliveryAt,
72
69
  lastError: health.lastError
73
70
  };
74
71
  return {
75
- active: health.value === "Failing",
72
+ active: health._tag === "Failing",
76
73
  lastDeliveryAt,
77
74
  lastError: health.lastError,
78
75
  failedSince: iso(health.failedSince)
@@ -83,17 +80,17 @@ const healthOf = (status) => Option.gen(function* () {
83
80
  if (status.failedSince === void 0) {
84
81
  if (!status.active) return yield* Option.none();
85
82
  return {
86
- value: "Delivering",
83
+ _tag: "Delivering",
87
84
  lastDeliveryAt,
88
85
  lastError: status.lastError
89
86
  };
90
87
  }
91
88
  return {
92
- value: status.active ? "Failing" : "Suspended",
89
+ _tag: status.active ? "Failing" : "Suspended",
93
90
  lastDeliveryAt,
94
91
  lastError: yield* Option.fromNullOr(status.lastError),
95
92
  failedSince: yield* millisOf(status.failedSince)
96
93
  };
97
94
  });
98
- const failingForMs = (health, now) => health.value === "Failing" ? now - health.failedSince : 0;
99
- export { deliveryHealth, failingForMs, healthOf, statusOf };
95
+ const failingForMs = (health, now) => health._tag === "Failing" ? now - health.failedSince : 0;
96
+ export { delivering, failingForMs, healthOf, healthTransition, iso, statusOf };
@@ -1,12 +1,12 @@
1
+ import { signingSecretOf } from "../contract/callback.mjs";
1
2
  import { watchParameter } from "../contract/receiving.mjs";
2
3
  import { makeRecent } from "../contract/recent.mjs";
3
4
  import { constantTimeEqual, standardWebhooksSignature } from "./signing.mjs";
4
5
  import { Clock, Effect, Option, Predicate, Schema } from "effect";
5
6
  import { HttpServerRequest, HttpServerResponse } from "effect/http";
6
- import { Base64, Base64Url } from "effect/encoding";
7
+ import { Base64Url } from "effect/encoding";
7
8
  // src/webhook/receiver.ts
8
9
  const timestampToleranceSeconds = 300;
9
- const dedupeWindow = 1e3;
10
10
  const Body = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json));
11
11
  const decodeBody = Schema.decodeUnknownOption(Body);
12
12
  const gone = HttpServerResponse.empty({ status: 410 });
@@ -19,14 +19,11 @@ const makeReceiver = (path) => Effect.sync(() => {
19
19
  places.set(id, {
20
20
  key,
21
21
  deliver,
22
- seen: makeRecent(dedupeWindow)
22
+ seen: makeRecent()
23
23
  });
24
24
  return {
25
25
  id,
26
- secret: {
27
- text: `whsec_${Base64.encode(key)}`,
28
- key
29
- }
26
+ secret: signingSecretOf(key)
30
27
  };
31
28
  }), ({ id }) => Effect.sync(() => places.delete(id)));
32
29
  const handler = Effect.gen(function* () {
@@ -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 };
@@ -6,9 +6,9 @@ import { pushed, refusalIn } from "../contract/push.mjs";
6
6
  import { reported } from "../contract/reported.mjs";
7
7
  import { checkedHost } from "./address.mjs";
8
8
  import { attempt, challenged } from "./attempt.mjs";
9
- import { deliveryHealth, failingForMs, healthOf, statusOf } from "./health.mjs";
9
+ import { delivering, failingForMs, healthOf, healthTransition, iso, statusOf } from "./health.mjs";
10
10
  import { randomToken, subscriptionId } from "./signing.mjs";
11
- import { Cause, Clock, Context, DateTime, Deferred, Duration, Effect, Exit, Fiber, FiberMap, Match, Option, RcMap, Schedule, Schema, Scope, Semaphore, Stream } from "effect";
11
+ import { Cause, Clock, Context, Deferred, Duration, Effect, Exit, Fiber, FiberMap, Match, Option, RcMap, Schedule, Schema, Scope, Semaphore, Stream } from "effect";
12
12
  import { HttpRouter, HttpServerRequest } from "effect/http";
13
13
  // src/webhook/subscriptions.ts
14
14
  const minTtl = Duration.minutes(1);
@@ -16,13 +16,13 @@ const rotationGrace = Duration.minutes(5);
16
16
  const maxBody = 262144;
17
17
  const encoder = new TextEncoder();
18
18
  const terminatedEnvelopeRetries = Schedule.exponential(Duration.seconds(1)).pipe(Schedule.upTo({ times: 3 }));
19
- const iso = (millis) => DateTime.formatIso(DateTime.makeUnsafe(millis));
20
19
  const grantOf = (ttlMs, policy) => Duration.clamp(ttlMs === null || ttlMs === void 0 ? policy.maxTtl : Duration.millis(ttlMs), {
21
20
  minimum: minTtl,
22
21
  maximum: policy.maxTtl
23
22
  });
24
23
  const trusted = (url, prefixes) => prefixes.some(({ origin, pathname }) => url.origin === origin && (url.pathname === pathname || url.pathname.startsWith(pathname.endsWith("/") ? pathname : `${pathname}/`)));
25
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))));
26
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)"));
27
27
  const confirmedAt = (cursor) => Effect.tap(Deferred.make(), (confirmation) => Deferred.succeed(confirmation, {
28
28
  cursor,
@@ -46,27 +46,28 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
46
46
  secret: subscription.secret,
47
47
  expiresAt: subscription.expiresAt,
48
48
  watermark: subscription.watermark,
49
- status: statusOf(subscription.health)
49
+ status: statusOf(subscription.health),
50
+ retryingAt: subscription.retryingAt
50
51
  });
51
52
  });
52
53
  const dropped = (id) => Effect.sync(() => storage?.mark(id, void 0));
53
54
  const verified = /* @__PURE__ */ new Map();
54
55
  const locks = yield* RcMap.make({ lookup: (_id) => Semaphore.make(1) });
55
- const health = deliveryHealth(Duration.toMillis(policy.retryFor));
56
+ const transition = healthTransition(Duration.toMillis(policy.retryFor));
56
57
  const transitioned = (subscription, event) => Effect.suspend(() => {
57
- const next = health.transition(subscription.health, event);
58
+ const next = transition(subscription.health, event);
58
59
  if (next === subscription.health) return Effect.void;
59
60
  subscription.health = next;
60
61
  return kept(subscription);
61
62
  });
62
- 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)), {
63
68
  minimum: Duration.seconds(1),
64
69
  maximum: Duration.minutes(5)
65
- })));
66
- const retrying = (subscription) => ({
67
- schedule: waitingAsLongAsFailing(subscription),
68
- while: () => subscription.health.value === "Failing"
69
- });
70
+ }));
70
71
  const locked = (id) => (effect) => Effect.scoped(Effect.flatMap(RcMap.get(locks, id), (lock) => lock.withPermits(1)(effect)));
71
72
  const asSubscriber = (subscription, effect) => Effect.updateContext(effect, () => subscription.context);
72
73
  const post = (subscription, webhookId, body) => Effect.flatMap(Clock.currentTimeMillis, (now) => Effect.provideContext(attempt({
@@ -76,23 +77,35 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
76
77
  body,
77
78
  keys: subscription.previous !== void 0 && now < subscription.previous.until ? [subscription.secret.key, subscription.previous.key] : [subscription.secret.key]
78
79
  }, trusted(subscription.url, policy.allowedCallbacks) ? Effect.void : checkedHost(subscription.url, policy.dns)), built));
79
- const delivered = (subscription, webhookId, body) => post(subscription, webhookId, body).pipe(Effect.tapError(({ category, final }) => Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
80
- type: "AttemptFailed",
81
- category,
82
- final,
83
- at
84
- }))), Effect.retry(retrying(subscription)), Effect.matchEffect({
85
- onSuccess: () => Effect.as(Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
86
- type: "Delivered",
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,
87
90
  at
88
- })), true),
89
- onFailure: () => subscription.health.value === "Suspended" ? Effect.never : Effect.succeed(false)
90
- }));
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, {
99
+ _tag: "Delivered",
100
+ at
101
+ })), true);
102
+ return subscription.health._tag === "Suspended" ? Effect.never : Effect.succeed(false);
103
+ });
91
104
  const gapped = (subscription, cursor) => Effect.flatMap(randomToken, (token) => delivered(subscription, `msg_gap_${token}`, JSON.stringify({
92
105
  type: "gap",
93
106
  cursor
94
107
  })));
95
- const deliverTo = (subscription, input, confirmation) => {
108
+ const deliverTo = (subscription, confirmation) => {
96
109
  const encode = encodeUntaggedOf(subscription.feed.event);
97
110
  const moved = (cursor) => cursor === null || cursor === subscription.watermark ? Effect.void : Effect.andThen(Effect.sync(() => {
98
111
  subscription.watermark = cursor;
@@ -106,7 +119,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
106
119
  Checked: ({ cursor }) => Deferred.isDoneUnsafe(confirmation) ? moved(cursor) : confirmed(cursor, false),
107
120
  Gap: ({ cursor }) => Deferred.isDoneUnsafe(confirmation) ? skipped(cursor) : confirmed(cursor, true),
108
121
  Occurrence: (occurrence) => Effect.gen(function* () {
109
- 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)));
110
123
  if (encoder.encode(body).length > maxBody) {
111
124
  yield* Effect.logWarning(`Webhook delivery of ${occurrence.eventId} abandoned: its body is over 256 KiB`);
112
125
  return yield* skipped(occurrence.cursor);
@@ -117,7 +130,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
117
130
  Failed: () => Effect.void
118
131
  });
119
132
  };
120
- 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);
121
134
  const terminated = (subscription, cause) => {
122
135
  const refusal = refusalIn(cause);
123
136
  if (refusal === void 0) return Cause.hasInterruptsOnly(cause) ? Effect.void : reported(cause);
@@ -136,10 +149,10 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
136
149
  if (holds(subscription)) held.delete(subscription.id);
137
150
  });
138
151
  const finished = (subscription) => Effect.suspend(() => holds(subscription) ? Effect.andThen(ended(subscription), dropped(subscription.id)) : Effect.void);
139
- 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), {
140
153
  positions: "watermark",
141
154
  resumesUnconfirmed: Deferred.isDoneUnsafe(confirmation)
142
- }), 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) => {
143
156
  if (Deferred.isDoneUnsafe(confirmation)) return Exit.isFailure(exit) ? terminated(subscription, exit.cause) : Effect.void;
144
157
  return Exit.isFailure(exit) ? Deferred.failCause(confirmation, exit.cause) : Deferred.succeed(confirmation, {
145
158
  cursor,
@@ -184,7 +197,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
184
197
  key: subscription.secret.key,
185
198
  until: now + Duration.toMillis(rotationGrace)
186
199
  } },
187
- health: health.transition(before, { type: "Refreshed" })
200
+ health: transition(before, { _tag: "Refreshed" })
188
201
  };
189
202
  const confirmation = yield* confirmedAt(watermark);
190
203
  yield* swapHeldWorker(renewed.id, renewed, workerOf(renewed, input, watermark, confirmation));
@@ -201,7 +214,8 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
201
214
  const heldOf = (fields) => ({
202
215
  ...fields,
203
216
  verifiedAs: `${fields.principal}\u0000${fields.url.href}`,
204
- previous: void 0
217
+ previous: void 0,
218
+ retryingAt: void 0
205
219
  });
206
220
  const keptOf = ({ feed, keyed, input }) => Effect.gen(function* () {
207
221
  const { schema } = keyed;
@@ -237,23 +251,26 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
237
251
  });
238
252
  if (current !== id) yield* dropped(id);
239
253
  if (held.has(current)) return;
240
- const subscription = heldOf({
241
- id: current,
242
- url,
243
- feed,
244
- principal,
245
- kept: {
246
- input: record.input,
247
- identity: record.identity
248
- },
249
- secret,
250
- context: Context.add(built, feed.event.caller, identity),
251
- expiresAt,
252
- health: restoredHealth,
253
- watermark: record.watermark
254
- });
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
+ };
255
272
  const confirmation = yield* confirmedAt(record.watermark);
256
- yield* swapHeldWorker(current, subscription, restoredHealth.value === "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));
257
274
  if (current !== id) yield* kept(subscription);
258
275
  }).pipe(Effect.catchCause(reported));
259
276
  const serve = (feeds, keyed) => Effect.gen(function* () {
@@ -282,7 +299,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
282
299
  const { feed, principal, input, delivery: { url, secret }, cursor, ttlMs } = subscribing;
283
300
  const id = yield* idOf(subscribing);
284
301
  return yield* locked(id)(Effect.gen(function* () {
285
- yield* Effect.catchCause(feed.admit(input), (cause) => terminatedOnRefusal(id, cause));
302
+ yield* Effect.catchCause(feed.admit, (cause) => terminatedOnRefusal(id, cause));
286
303
  const now = yield* Clock.currentTimeMillis;
287
304
  const granted = {
288
305
  secret,
@@ -298,7 +315,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
298
315
  url,
299
316
  feed,
300
317
  principal,
301
- health: health.initialState,
318
+ health: delivering,
302
319
  watermark: cursor
303
320
  });
304
321
  yield* verify(subscription, now);
@@ -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.
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`.
@@ -0,0 +1,10 @@
1
+ # ActionEntity failure modes
2
+
3
+ What you see when something is wrong, and the fix. Search for a fragment of the message. The tasks are in [ActionEntity.md](ActionEntity.md).
4
+
5
+ - `"An entity's binding holds no native rpcs"` in a type error on `ActionEntity.make`: the binding was made with `ActionRpc.make`'s `rpcs`. Make the binding of the actions and event types alone, and give the native rpcs to `ActionEntity.make`'s `rpcs`.
6
+ - `An entity provides no service per call` in a type error on `ActionEntity.layer`: a handler, an authorizer or an event source reads per call a service other than its caller and `services`' output, named in the diagnostic. Yield it in the implementation's builder, where the layer requires it at startup, or build it in the layer's `services`. Where `services` already outputs it, and is written inline as a `Layer.merge` or another generic combinator's result, TypeScript infers its output too late: assign the layer to a `const` first.
7
+ - `Service not found: effect/http/HttpRouter`, a defect as `ActionEntity.layer` builds, before any call: its authentication provider publishes a `protectedResource`, on a router an entity lacks. Give the provider serving the entity no `protectedResource`.
8
+ - `Defect building entity handlers`, logged again and again while calls wait: an implementation's builder fails or dies, or reads a service the layer was not given. Fix the builder, or provide the service to `ActionEntity.layer`.
9
+ - `A test is using time, but is not advancing the test clock`, Effect's warning, then `Test timed out`: a test of an entity on `TestRunner.layer` under `it.effect`, whose cluster waits on a clock that `TestClock` holds still. Run it with `it.live`.
10
+ - `Entity.makeTestClient: <type> was not registered by layer`, Effect's own error: the layer given registers another entity. Give it `ActionEntity.layer` of the same entity.