@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
@@ -4,12 +4,12 @@ import { canonicalInput } from "./canonical.mjs";
4
4
  import { Unauthenticated } from "./errors.mjs";
5
5
  import { Events, attachmentsOf, reaches } from "./hub.mjs";
6
6
  import { builderLayer, memoized, notMadeHere } from "./implementation.mjs";
7
- import { checkInput } from "./input-check.mjs";
8
7
  import { makeLeases } from "./lease.mjs";
9
8
  import { assertKnown } from "./names.mjs";
10
9
  import { AnyOccurrence, Gap } from "./occurrence.mjs";
11
10
  import { fedOf, pagedFrom } from "./pages.mjs";
12
11
  import { reported } from "./reported.mjs";
12
+ import { Wake } from "./wake.mjs";
13
13
  import { Array, DateTime, Duration, Effect, Layer, Option, Predicate, Stream } from "effect";
14
14
  // src/contract/feed.ts
15
15
  const defaultNextPoll = Duration.seconds(5);
@@ -30,7 +30,7 @@ const occurrencesOf = (event) => {
30
30
  });
31
31
  };
32
32
  const isOccurrence = (fed) => Predicate.isTagged(fed, "Occurrence");
33
- const pageOf = (items, { truncated, ...page }) => {
33
+ const pageFrom = (items, { truncated, ...page }) => {
34
34
  const events = items.filter(isOccurrence);
35
35
  return {
36
36
  ...page,
@@ -41,19 +41,21 @@ const pageOf = (items, { truncated, ...page }) => {
41
41
  const lifted = (value) => Effect.isEffect(value) ? value : Effect.succeed(value);
42
42
  const keyOf = (source, input) => source.key === void 0 ? Effect.undefined : lifted(source.key(input));
43
43
  const leaseKey = (event, subscriber, input) => Effect.map(canonicalInput(event.input, input), (encoded) => `${subscriber ?? ""}\u0000${encoded}`);
44
- const answeredPage = ({ answered, items }) => pageOf(items, {
44
+ const answeredPage = ({ answered, items }) => pageFrom(items, {
45
45
  cursor: answered.cursor,
46
46
  truncated: answered.truncated === true,
47
47
  hasMore: answered.hasMore === true,
48
48
  nextPoll: Duration.min(Duration.fromInputUnsafe(answered.nextPoll ?? defaultNextPoll), longestNextPoll)
49
49
  });
50
- const checkRun = (event, source, { wakes, polls }) => {
50
+ const checkRun = (event, source, { wakes }) => {
51
51
  const occurrenceOf = occurrencesOf(event);
52
+ const polls = source.notified !== true;
52
53
  const read = (input, cursor) => Effect.flatMap(source.check(input, cursor), (answered) => Effect.map(Effect.forEach(answered.events, (emitted, index) => occurrenceOf(emitted, index === answered.events.length - 1 ? answered.cursor : cursor)), (items) => ({
53
54
  answered,
54
55
  items
55
56
  })));
56
57
  return {
58
+ polls,
57
59
  poll: (input, cursor) => Effect.map(read(input, cursor), answeredPage),
58
60
  stream: (input, cursor) => Stream.unwrap(Effect.map(Effect.flatMap(keyOf(source, input), wakes), (woken) => pagedFrom((at) => Effect.map(read(input, at), (delivered) => ({
59
61
  ...answeredPage(delivered),
@@ -68,6 +70,7 @@ const checkRun = (event, source, { wakes, polls }) => {
68
70
  };
69
71
  const currentRun = (event, source, checking) => checkRun(event, {
70
72
  key: source.key,
73
+ notified: true,
71
74
  check: (input, cursor) => Effect.gen(function* () {
72
75
  const at = yield* checking.revision(yield* keyOf(source, input));
73
76
  if (cursor === at) return {
@@ -102,7 +105,8 @@ const logRun = (event, source, log) => {
102
105
  });
103
106
  const received = (input, key, read) => Effect.map(Effect.forEach(read.entries, (entry) => delivered(input, key, entry)), (items) => items.filter(Predicate.isNotUndefined));
104
107
  return {
105
- poll: (input, cursor, { maxEvents = logPageSize }) => Effect.flatMap(Effect.all([keyOf(source, input), log.read(cursor, pageLimit(maxEvents))]), ([key, read]) => Effect.map(received(input, key, read), (items) => pageOf(items, {
108
+ polls: false,
109
+ poll: (input, cursor, { maxEvents = logPageSize }) => Effect.flatMap(Effect.all([keyOf(source, input), log.read(cursor, pageLimit(maxEvents))]), ([key, read]) => Effect.map(received(input, key, read), (items) => pageFrom(items, {
106
110
  cursor: read.cursor,
107
111
  truncated: read.truncated,
108
112
  hasMore: read.hasMore,
@@ -127,9 +131,12 @@ const isCurrent = (source) => Predicate.isFunction(source.current);
127
131
  const runOf = (event, source) => Effect.gen(function* () {
128
132
  const attach = yield* Effect.flatMap(Events, attachmentsOf);
129
133
  let run;
130
- if (isCheck(source)) run = checkRun(event, source, yield* attach.check(event, false));
131
- else if (isCurrent(source)) run = currentRun(event, source, yield* attach.check(event, true));
132
- else run = logRun(event, source, yield* attach.log(event, source.log, source.log.emit));
134
+ if (isCheck(source)) run = checkRun(event, source, yield* attach.check(event));
135
+ else if (isCurrent(source)) run = currentRun(event, source, yield* attach.check(event));
136
+ else {
137
+ if (source.log.emit !== void 0 && Option.isSome(yield* Effect.serviceOption(Wake))) return yield* Effect.die(/* @__PURE__ */ new Error(`Event "${event.name}": a cluster entity runs no log source's emit stream, as Effect's entity reaper stops the entity while it runs and what it sends meanwhile is lost (append with Events.publish from a handler, or serve the event from a surface outside the entity)`));
138
+ run = logRun(event, source, yield* attach.log(event, source.log, source.log.emit));
139
+ }
133
140
  if (source.subscription === void 0) return run;
134
141
  return hooked(event, run, source.subscription, yield* makeLeases(source.subscription, source.lease));
135
142
  });
@@ -166,13 +173,15 @@ const sourcesOf = (events, single, sources) => {
166
173
  };
167
174
  const guarded = (event, run, before) => {
168
175
  const attributes = { "event.name": event.name };
169
- const admit = (input) => event.caller === Anyone ? checkInput(event, input) : Effect.flatMap(Effect.serviceOption(event.caller), (subscriber) => Option.isSome(subscriber) ? Effect.andThen(checkInput(event, input), Effect.suspend(() => before(event))) : Effect.fail(new Unauthenticated()));
176
+ const admit = event.caller === Anyone ? Effect.void : Effect.flatMap(Effect.serviceOption(event.caller), (subscriber) => Option.isSome(subscriber) ? Effect.suspend(() => before(event)) : Effect.fail(new Unauthenticated()));
170
177
  return {
171
178
  event,
179
+ polls: run.polls,
172
180
  release: run.release,
181
+ webhook: run.webhook,
173
182
  admit,
174
- poll: (input, cursor, options) => Effect.andThen(admit(input), () => run.poll(input, cursor, options)).pipe(Effect.annotateLogs(attributes), Effect.withSpan(event.name, { attributes }, { captureStackTrace: false })),
175
- stream: (input) => Effect.as(admit(input), (cursor) => run.stream(input, cursor).pipe(Stream.withSpan(event.name, { attributes })))
183
+ poll: (input, cursor, options) => Effect.andThen(admit, () => run.poll(input, cursor, options)).pipe(Effect.annotateLogs(attributes), Effect.withSpan(event.name, { attributes }, { captureStackTrace: false })),
184
+ stream: (input) => Effect.as(admit, (cursor) => run.stream(input, cursor).pipe(Stream.withSpan(event.name, { attributes })))
176
185
  };
177
186
  };
178
187
  /**
@@ -1,5 +1,5 @@
1
1
  import { Any, Emitted } from "../Event.mjs";
2
- import { LogStorage } from "./log.mjs";
2
+ import "./log.mjs";
3
3
  import { Context, Effect, Layer, Scope, Stream } from "effect";
4
4
  /** What `notify` and `publish` take: the key whose subscribers they reach. */
5
5
  export interface KeyOptions {
@@ -9,22 +9,6 @@ export interface KeyOptions {
9
9
  */
10
10
  readonly key?: string | undefined;
11
11
  }
12
- type ErasedEmitted = Emitted<Any>;
13
- /**
14
- * Where an `Events` keeps its current sources' revisions: counters by name, which only count up,
15
- * in an `epoch` telling them from counters that started again.
16
- */
17
- export interface RevisionStorage {
18
- /**
19
- * The epoch the counters count in, run before each revision is built from it: one value until
20
- * the counters start again, so a cursor from before is behind every revision, kept by the time
21
- * it succeeds.
22
- */
23
- readonly epoch: Effect.Effect<string>;
24
- readonly get: (name: string) => Effect.Effect<number>;
25
- /** Adds one to each counter `names` names. */
26
- readonly bump: (names: readonly string[]) => Effect.Effect<void>;
27
- }
28
12
  declare const Events_base: Context.ServiceClass<Events, "effect-actions/Event/Events", {
29
13
  /** Wakes the subscribers of `event`'s check source to read it now, rather than at their next poll. */
30
14
  readonly notify: (event: Any, options?: KeyOptions) => Effect.Effect<void>;
@@ -35,7 +19,8 @@ declare const Events_base: Context.ServiceClass<Events, "effect-actions/Event/Ev
35
19
  * Where an event's occurrences are announced as they happen: `notify` wakes the subscribers of a
36
20
  * check source to read now, and `publish` appends an occurrence to a log source, both reaching
37
21
  * the subscribers of one `key` or every one. Domain code yields it as it yields a store, and an
38
- * entrypoint provides one implementation: `Event.layerMemory`, kept in a process's memory.
22
+ * entrypoint provides one implementation: `Event.layerMemory`, kept in a process's memory, or
23
+ * `Stored.layerEvents`, kept in a database.
39
24
  * Every surface serving events and `Action.client` watching them need it.
40
25
  *
41
26
  * **Gotchas**
@@ -43,47 +28,9 @@ declare const Events_base: Context.ServiceClass<Events, "effect-actions/Event/Ev
43
28
  * - The handlers announcing and the surfaces serving must share one, as they share a store: built separately, as a test building its handlers under a `provide` of their own does, each has its own, and an announcement reaches no subscriber of the other.
44
29
  * - An event no implementation attached here has no subscribers here: `publish` does nothing for it, and `notify` only moves its revision, so a current source attached later answers the change.
45
30
  * - `notify` of a log source and `publish` to a check source die naming the other: a check source reads your store, so write there and notify; a log source keeps what you publish.
46
- * - Implementations attach only to one `layerMemory` or `makeEvents` made: built over another, such as `Events.of` in a test, they die, naming both.
31
+ * - Implementations attach only to one `layerMemory` or `Stored.layerEvents` made: built over another, such as `Events.of` in a test, they die, naming both.
47
32
  */
48
33
  export declare class Events extends Events_base {}
49
- /** `makeEvents`' options: where it keeps logs, and whether check sources are read on a timer. */
50
- export interface MakeEventsOptions {
51
- /**
52
- * The storage of `event`'s log, made at its first attachment: the core keeps the log's cursors,
53
- * bounds and expiry over it.
54
- */
55
- readonly log: (event: Any) => LogStorage<ErasedEmitted>;
56
- /**
57
- * Whether a check source's subscribers also read it again on a timer, each page's `nextPoll`,
58
- * besides when notified; defaults to `true`. `false` where a pending timer would keep the host
59
- * awake, as it keeps a Durable Object from hibernating: its sources are read when notified, and
60
- * 5 seconds after a read that fails.
61
- */
62
- readonly polls?: boolean | undefined;
63
- /**
64
- * Whether a log source's `emit` is consumed; defaults to `true`. `false` where the host does not
65
- * last, as a Durable Object is evicted while idle and misses what a stream sends meanwhile: a
66
- * log source fed by `emit` dies as it attaches, naming `publish`.
67
- */
68
- readonly emits?: boolean | undefined;
69
- /**
70
- * Where current sources' revisions are kept; defaults to memory, a new epoch with each
71
- * `makeEvents`. A host keeping its logs in storage keeps them there too, so a subscriber's
72
- * cursor outlives the host.
73
- */
74
- readonly revisions?: RevisionStorage | undefined;
75
- }
76
- /**
77
- * An `Events` for as long as the scope lasts, over the log storage `log` makes: what a host keeping
78
- * logs elsewhere, such as a Durable Object's storage, provides as `Events`, its subscribers' wakes
79
- * in memory and its logs where `log` keeps them.
80
- *
81
- * **Gotchas**
82
- *
83
- * - Make it once per host, around the handlers that announce and the surfaces that serve, as `layerMemory` is built.
84
- * - A log's storage is made once per event for the life of the scope, its position read on every append and read: a storage emptied behind its back, as `storage.deleteAll` empties one, starts a new epoch, and a cursor from before reads a gap.
85
- */
86
- export declare const makeEvents: (options: MakeEventsOptions) => Effect.Effect<Events["Service"], never, Scope.Scope>;
87
34
  /**
88
35
  * An `Events` kept in the memory of the process that builds it: for a server holding its
89
36
  * subscribers' connections itself, such as Node's, and for tests.
@@ -18,7 +18,8 @@ const ofKey = (event, key) => `${event.name}\u0000=${key}`;
18
18
  * Where an event's occurrences are announced as they happen: `notify` wakes the subscribers of a
19
19
  * check source to read now, and `publish` appends an occurrence to a log source, both reaching
20
20
  * the subscribers of one `key` or every one. Domain code yields it as it yields a store, and an
21
- * entrypoint provides one implementation: `Event.layerMemory`, kept in a process's memory.
21
+ * entrypoint provides one implementation: `Event.layerMemory`, kept in a process's memory, or
22
+ * `Stored.layerEvents`, kept in a database.
22
23
  * Every surface serving events and `Action.client` watching them need it.
23
24
  *
24
25
  * **Gotchas**
@@ -26,13 +27,13 @@ const ofKey = (event, key) => `${event.name}\u0000=${key}`;
26
27
  * - The handlers announcing and the surfaces serving must share one, as they share a store: built separately, as a test building its handlers under a `provide` of their own does, each has its own, and an announcement reaches no subscriber of the other.
27
28
  * - An event no implementation attached here has no subscribers here: `publish` does nothing for it, and `notify` only moves its revision, so a current source attached later answers the change.
28
29
  * - `notify` of a log source and `publish` to a check source die naming the other: a check source reads your store, so write there and notify; a log source keeps what you publish.
29
- * - Implementations attach only to one `layerMemory` or `makeEvents` made: built over another, such as `Events.of` in a test, they die, naming both.
30
+ * - Implementations attach only to one `layerMemory` or `Stored.layerEvents` made: built over another, such as `Events.of` in a test, they die, naming both.
30
31
  */
31
32
  var Events = class extends Context.Service()("effect-actions/Event/Events") {};
32
33
  const attached = /* @__PURE__ */ new WeakMap();
33
34
  const attachmentsOf = (events) => Effect.suspend(() => {
34
35
  const attachments = attached.get(events);
35
- return attachments === void 0 ? Effect.die(/* @__PURE__ */ new Error("This Event.Events serves no event implementation: provide Event.layerMemory, or one Event.makeEvents builds")) : Effect.succeed(attachments);
36
+ return attachments === void 0 ? Effect.die(/* @__PURE__ */ new Error("This Event.Events serves no event implementation: provide Event.layerMemory or Stored.layerEvents")) : Effect.succeed(attachments);
36
37
  });
37
38
  const reaches = (target, key) => target === void 0 || key === void 0 || target === key;
38
39
  const holding = (set, value) => Effect.acquireRelease(Effect.sync(() => {
@@ -40,18 +41,16 @@ const holding = (set, value) => Effect.acquireRelease(Effect.sync(() => {
40
41
  return value;
41
42
  }), () => Effect.sync(() => set.delete(value)));
42
43
  /**
43
- * An `Events` for as long as the scope lasts, over the log storage `log` makes: what a host keeping
44
- * logs elsewhere, such as a Durable Object's storage, provides as `Events`, its subscribers' wakes
45
- * in memory and its logs where `log` keeps them.
44
+ * An `Events` for as long as the scope lasts, over the log storage `log` makes: what
45
+ * `Stored.layerEvents` provides over SQL, its subscribers' wakes in memory and its logs where
46
+ * `log` keeps them.
46
47
  *
47
48
  * **Gotchas**
48
49
  *
49
- * - Make it once per host, around the handlers that announce and the surfaces that serve, as `layerMemory` is built.
50
- * - A log's storage is made once per event for the life of the scope, its position read on every append and read: a storage emptied behind its back, as `storage.deleteAll` empties one, starts a new epoch, and a cursor from before reads a gap.
50
+ * - Make it once per database, around the handlers that announce and the surfaces that serve, as `layerMemory` is built.
51
+ * - A log's storage is made once per event for the life of the scope, its position read on every append and read: a storage emptied behind its back starts a new epoch, and a cursor from before reads a gap.
51
52
  */
52
53
  const makeEvents = (options) => Effect.gen(function* () {
53
- const polls = options.polls ?? true;
54
- const emits = options.emits ?? true;
55
54
  const revisions = options.revisions ?? memoryRevisions();
56
55
  const scope = yield* Effect.scope;
57
56
  const checks = /* @__PURE__ */ new Map();
@@ -84,7 +83,7 @@ const makeEvents = (options) => Effect.gen(function* () {
84
83
  notify: (event, notifyOptions) => Effect.suspend(() => {
85
84
  if (!isCheck(event) && logs.has(event)) return Effect.die(/* @__PURE__ */ new Error(`Event "${event.name}" has a log source, which keeps what is published: give each occurrence to publish (Event.Events.publish(event, { data }))`));
86
85
  const key = notifyOptions?.key;
87
- return Effect.andThen(checks.get(event)?.current === false ? Effect.void : revisions.bump([everyKey(event), key === void 0 ? noKey(event) : ofKey(event, key)]), Effect.sync(() => {
86
+ return Effect.andThen(revisions.bump([everyKey(event), key === void 0 ? noKey(event) : ofKey(event, key)]), Effect.sync(() => {
88
87
  for (const waiter of checkOf(event).waiters) if (reaches(key, waiter.key)) Queue.offerUnsafe(waiter.woken, void 0);
89
88
  }));
90
89
  }),
@@ -95,8 +94,7 @@ const makeEvents = (options) => Effect.gen(function* () {
95
94
  })
96
95
  });
97
96
  attached.set(events, {
98
- check: (event, current) => Effect.map(holding(Object.assign(checkOf(event), { current }).attached, {}), () => ({
99
- polls,
97
+ check: (event) => Effect.map(holding(checkOf(event).attached, {}), () => ({
100
98
  wakes: (key) => Effect.flatMap(Queue.sliding(1), (woken) => Effect.as(holding(checkOf(event).waiters, {
101
99
  key,
102
100
  woken
@@ -108,7 +106,6 @@ const makeEvents = (options) => Effect.gen(function* () {
108
106
  ]), ([epoch, unkeyed, keyed]) => `${epoch}:${unkeyed + keyed}:${key}`)
109
107
  })),
110
108
  log: (event, bounds, emit) => Effect.suspend(() => {
111
- if (emit !== void 0 && !emits) return Effect.die(/* @__PURE__ */ new Error(`Event "${event.name}" has a log source fed by emit, which this Event.Events does not consume, as its host does not last between requests (publish each occurrence with Event.Events.publish as the host receives it, such as in a call or a route)`));
112
109
  const kept = logs.get(event) ?? {
113
110
  log: makeLog(makeLogStore(options.log(event), bounds)),
114
111
  waiting: /* @__PURE__ */ new Set(),
@@ -131,4 +128,4 @@ const makeEvents = (options) => Effect.gen(function* () {
131
128
  * - Several builds of one log source share its log, and its `emit` feeds it from one build at a time, so nothing is appended twice.
132
129
  */
133
130
  const layerMemory = Layer.effect(Events)(makeEvents({ log: () => memoryStorage() }));
134
- export { Events, attachmentsOf, layerMemory, makeEvents, reaches };
131
+ export { Events, attachmentsOf, layerMemory, makeEvents, memoryRevisions, reaches };
@@ -1,12 +1,12 @@
1
1
  import "../Action.mjs";
2
2
  import "./implementation.mjs";
3
3
  import { Context, Effect, Layer, Schema } from "effect";
4
- declare const Kept: Schema.Struct<{
4
+ export declare const Kept: Schema.Struct<{
5
5
  readonly input: Schema.String;
6
6
  readonly outcome: Schema.String;
7
7
  readonly at: Schema.Finite;
8
8
  }>;
9
- type Kept = typeof Kept.Type;
9
+ export type Kept = typeof Kept.Type;
10
10
  declare const Idempotency_base: Context.ServiceClass<Idempotency, "effect-actions/Action/Idempotency", {
11
11
  /** What was kept under `id`, or `undefined`; one kept longer than 24 hours may be either. */
12
12
  readonly get: (id: string) => Effect.Effect<Kept | undefined>;
@@ -17,28 +17,16 @@ declare const Idempotency_base: Context.ServiceClass<Idempotency, "effect-action
17
17
  * Where the answers of calls given an idempotency key are kept, by the action's name and a
18
18
  * SHA-256 digest in hex of the key and its caller's principal, `<action>/<digest>`, for 24 hours
19
19
  * at least: what an implementation of an action naming `idempotencyKey` requires at startup.
20
- * `layerIdempotency` keeps them in memory; a Durable Object's `make` and `handlers` provide one
21
- * over its storage; another store, shared by several servers, implements `get` and `set`, keeping
22
- * `Idempotency.Kept` at least `Idempotency.keptFor` milliseconds.
20
+ * `layerIdempotency` keeps them in memory, and `Stored.layerIdempotency` in a table of the
21
+ * `SqlClient` it is built with, such as a cluster entity's own SQLite.
23
22
  *
24
23
  * **Gotchas**
25
24
  *
26
25
  * - Provide one per server, around the surfaces: an implementation built in another layer graph keeps its own.
27
26
  * - A server waits for a repeat's first call itself, in memory: two servers sharing a store run a call each, the later answer kept.
27
+ * - An answer is kept only after its handler returns: a crash between the handler's write and the kept answer lets a repeat run the handler again, so make the write itself idempotent where that matters, such as by a unique key on the idempotency key.
28
28
  */
29
- export declare class Idempotency extends Idempotency_base {
30
- /**
31
- * What is kept of a call answered under its key: the digest of its input, its outcome as JSON,
32
- * and when it was kept, in milliseconds since the epoch.
33
- */
34
- static readonly Kept: Schema.Struct<{
35
- readonly input: Schema.String;
36
- readonly outcome: Schema.String;
37
- readonly at: Schema.Finite;
38
- }>;
39
- /** How long, in milliseconds, a kept answer is kept at least: 24 hours. */
40
- static readonly keptFor: number;
41
- }
29
+ export declare class Idempotency extends Idempotency_base {}
42
30
  /**
43
31
  * `Idempotency` in the server's memory, each answer kept 24 hours after it was kept: lost when
44
32
  * the server stops, and kept apart from every other server's.
@@ -17,24 +17,16 @@ const keptFor = 864e5;
17
17
  * Where the answers of calls given an idempotency key are kept, by the action's name and a
18
18
  * SHA-256 digest in hex of the key and its caller's principal, `<action>/<digest>`, for 24 hours
19
19
  * at least: what an implementation of an action naming `idempotencyKey` requires at startup.
20
- * `layerIdempotency` keeps them in memory; a Durable Object's `make` and `handlers` provide one
21
- * over its storage; another store, shared by several servers, implements `get` and `set`, keeping
22
- * `Idempotency.Kept` at least `Idempotency.keptFor` milliseconds.
20
+ * `layerIdempotency` keeps them in memory, and `Stored.layerIdempotency` in a table of the
21
+ * `SqlClient` it is built with, such as a cluster entity's own SQLite.
23
22
  *
24
23
  * **Gotchas**
25
24
  *
26
25
  * - Provide one per server, around the surfaces: an implementation built in another layer graph keeps its own.
27
26
  * - A server waits for a repeat's first call itself, in memory: two servers sharing a store run a call each, the later answer kept.
27
+ * - An answer is kept only after its handler returns: a crash between the handler's write and the kept answer lets a repeat run the handler again, so make the write itself idempotent where that matters, such as by a unique key on the idempotency key.
28
28
  */
29
- var Idempotency = class extends Context.Service()("effect-actions/Action/Idempotency") {
30
- /**
31
- * What is kept of a call answered under its key: the digest of its input, its outcome as JSON,
32
- * and when it was kept, in milliseconds since the epoch.
33
- */
34
- static Kept = Kept;
35
- /** How long, in milliseconds, a kept answer is kept at least: 24 hours. */
36
- static keptFor = keptFor;
37
- };
29
+ var Idempotency = class extends Context.Service()("effect-actions/Action/Idempotency") {};
38
30
  /**
39
31
  * `Idempotency` in the server's memory, each answer kept 24 hours after it was kept: lost when
40
32
  * the server stops, and kept apart from every other server's.
@@ -47,7 +39,7 @@ const layerIdempotency = Layer.sync(Idempotency)(() => {
47
39
  held.delete(id);
48
40
  held.set(id, kept);
49
41
  for (const [oldest, { at }] of held) {
50
- if (at > kept.at - keptFor) break;
42
+ if (at > kept.at - 864e5) break;
51
43
  held.delete(oldest);
52
44
  }
53
45
  })
@@ -92,4 +84,4 @@ const keyed = (action, store, handle) => {
92
84
  return Effect.flatMap(Effect.all([Effect.service(CallerKeyed).pipe(Effect.flatMap((named) => principalOf(action, named)), Effect.flatMap((principal) => sha256Hex(JSON.stringify([principal ?? null, key])))), Effect.flatMap(canonicalInput(action.input, input), sha256Hex)]), ([id, digest]) => run(`${action.name}/${id}`, key, digest, answer));
93
85
  };
94
86
  };
95
- export { Idempotency, keyed, layerIdempotency };
87
+ export { Idempotency, Kept, keptFor, keyed, layerIdempotency };
@@ -1,7 +1,6 @@
1
1
  import { Anyone, CallerKeyed } from "./caller.mjs";
2
2
  import { projectedErrors } from "./declared.mjs";
3
3
  import { Unauthenticated } from "./errors.mjs";
4
- import { checkInput } from "./input-check.mjs";
5
4
  import { reportedTo, streamReportedTo } from "./progress.mjs";
6
5
  import { elementOf } from "./stream.mjs";
7
6
  import { Array, Cause, Context, Effect, Exit, Layer, Option, Predicate, References, Schema, Stream } from "effect";
@@ -40,12 +39,12 @@ const dispatch = (action, handle, before, keyed) => {
40
39
  } else reasons.push(reason);
41
40
  return yield* Effect.failCause(Cause.fromReasons(reasons));
42
41
  });
43
- const admitted = (input) => Effect.andThen(authentication, Effect.andThen(checkInput(action, input), authorization));
42
+ const admitted = Effect.andThen(authentication, authorization);
44
43
  const span = { attributes: actionAttributes };
45
44
  const trace = { captureStackTrace: false };
46
45
  if (elementOf(action.success) !== void 0) {
47
46
  const streamed = (answer) => Stream.isStream(answer) ? Stream.scoped(answer) : Stream.die(notAStream);
48
- return (input, sink) => Effect.succeed(Stream.unwrap(Effect.map(admitted(input), () => streamReportedTo(action.progress, sink, (reporting) => streamed(handle(input, reporting))))).pipe(Stream.catchCause((cause) => Stream.fromEffect(declaredOrDefect(cause))), Stream.updateService(References.CurrentLogAnnotations, (annotations) => ({
47
+ return (input, sink) => Effect.succeed(Stream.unwrap(Effect.map(admitted, () => streamReportedTo(action.progress, sink, (reporting) => streamed(handle(input, reporting))))).pipe(Stream.catchCause((cause) => Stream.fromEffect(declaredOrDefect(cause))), Stream.updateService(References.CurrentLogAnnotations, (annotations) => ({
49
48
  ...annotations,
50
49
  ...actionAttributes
51
50
  })), Stream.withSpan(action.name, {
@@ -53,7 +52,7 @@ const dispatch = (action, handle, before, keyed) => {
53
52
  ...trace
54
53
  })));
55
54
  }
56
- return (input, sink) => Effect.scoped(admitted(input).pipe(Effect.andThen(Effect.suspend(() => reportedTo(action.progress, sink, (reporting) => answered(handle(input, reporting))))), Effect.provideService(CallerKeyed, keyed), Effect.catchCause(declaredOrDefect))).pipe(Effect.annotateLogs(actionAttributes), Effect.withSpan(action.name, span, trace));
55
+ return (input, sink) => Effect.scoped(admitted.pipe(Effect.andThen(Effect.suspend(() => reportedTo(action.progress, sink, (reporting) => answered(handle(input, reporting))))), Effect.provideService(CallerKeyed, keyed), Effect.catchCause(declaredOrDefect))).pipe(Effect.annotateLogs(actionAttributes), Effect.withSpan(action.name, span, trace));
57
56
  };
58
57
  /**
59
58
  * Actions bound to their handlers and their authorizer: everything one `Action.implement` call
@@ -4,16 +4,6 @@ export interface Logged<A> {
4
4
  readonly value: A;
5
5
  readonly key: string | undefined;
6
6
  }
7
- /** Where a log stands: the epoch its cursors name, and the last sequence number it gave. */
8
- export interface Position {
9
- readonly epoch: string;
10
- readonly last: number;
11
- }
12
- /** One entry as a log's storage keeps it: when it was appended, and what was published. */
13
- export interface Stored<A> {
14
- readonly at: number;
15
- readonly logged: Logged<A>;
16
- }
17
7
  /**
18
8
  * One entry as a log's storage lists it: as it was kept, or with `logged` `undefined` where the
19
9
  * storage could not read it back, such as data an earlier deployment wrote in another shape,
@@ -22,20 +12,4 @@ export interface Stored<A> {
22
12
  export interface Listed<A> {
23
13
  readonly at: number;
24
14
  readonly logged: Logged<A> | undefined;
25
- }
26
- /**
27
- * Where a log keeps its position and its entries, by sequence number, as `Event.makeEvents` is
28
- * given it: storage alone, the log's cursors, bounds, truncation and expiry being the core's.
29
- */
30
- export interface LogStorage<A> {
31
- /** The position `put` last kept, or `undefined` for a storage never written or emptied. */
32
- readonly position: Effect.Effect<Position | undefined>;
33
- /** Keeps `position`, and `entry` with it where given, at once. */
34
- readonly put: (position: Position, entry?: {
35
- readonly seq: number;
36
- readonly stored: Stored<A>;
37
- }) => Effect.Effect<void>;
38
- /** The entries kept from sequence number `from` on, at most `limit`, in order. */
39
- readonly list: (from: number, limit: number) => Effect.Effect<ReadonlyArray<readonly [seq: number, listed: Listed<A>]>>;
40
- readonly delete: (seqs: readonly number[]) => Effect.Effect<void>;
41
15
  }
@@ -28,8 +28,11 @@ const memoryStorage = () => {
28
28
  }
29
29
  return listed;
30
30
  }),
31
- delete: (seqs) => Effect.sync(() => {
32
- for (const seq of seqs) entries.delete(seq);
31
+ deleteThrough: (through) => Effect.sync(() => {
32
+ for (const seq of entries.keys()) {
33
+ if (seq > through) return;
34
+ entries.delete(seq);
35
+ }
33
36
  })
34
37
  };
35
38
  };
@@ -44,6 +47,10 @@ const makeLogStore = (storage, { maxAge = defaultBounds.maxAge, maxEvents = defa
44
47
  if (!Number.isSafeInteger(maxEvents) || maxEvents < 1) throw new Error(`Invalid log maxEvents: ${maxEvents} (give a positive integer)`);
45
48
  const age = Duration.toMillis(Duration.fromInputUnsafe(maxAge));
46
49
  const turn = Semaphore.makeUnsafe(1);
50
+ const inTurn = (operation) => {
51
+ const locked = turn.withPermit(operation);
52
+ return storage.transaction === void 0 ? locked : storage.transaction(locked);
53
+ };
47
54
  const positioned = Effect.flatMap(storage.position, (found) => {
48
55
  if (found !== void 0) return Effect.succeed(found);
49
56
  const minted = {
@@ -56,15 +63,16 @@ const makeLogStore = (storage, { maxAge = defaultBounds.maxAge, maxEvents = defa
56
63
  for (let batch = 1;; batch = 64) {
57
64
  const listed = yield* storage.list(0, batch);
58
65
  const young = listed.findIndex(([, { at }]) => at >= now - age);
59
- const dropped = young === -1 ? listed : listed.slice(0, young);
60
- if (dropped.length > 0) yield* storage.delete(dropped.map(([seq]) => seq));
61
- const first = listed[dropped.length];
66
+ const dropped = young === -1 ? listed.length : young;
67
+ const newestDropped = listed[dropped - 1];
68
+ if (newestDropped !== void 0) yield* storage.deleteThrough(newestDropped[0]);
69
+ const first = listed[dropped];
62
70
  if (first !== void 0) return Math.max(first[0], last - maxEvents + 1);
63
71
  if (listed.length < batch) return last + 1;
64
72
  }
65
73
  });
66
74
  return {
67
- append: (logged) => turn.withPermit(Effect.gen(function* () {
75
+ append: (logged) => inTurn(Effect.gen(function* () {
68
76
  const { epoch, last } = yield* positioned;
69
77
  const seq = last + 1;
70
78
  const at = yield* Clock.currentTimeMillis;
@@ -78,9 +86,9 @@ const makeLogStore = (storage, { maxAge = defaultBounds.maxAge, maxEvents = defa
78
86
  logged
79
87
  }
80
88
  });
81
- if (seq > maxEvents) yield* storage.delete([seq - maxEvents]);
89
+ if (seq > maxEvents) yield* storage.deleteThrough(seq - maxEvents);
82
90
  })),
83
- read: (cursor, limit) => turn.withPermit(Effect.gen(function* () {
91
+ read: (cursor, limit) => inTurn(Effect.gen(function* () {
84
92
  const { epoch, last } = yield* positioned;
85
93
  const oldest = yield* oldestKept(last, yield* Clock.currentTimeMillis);
86
94
  const seq = cursor === null ? last : seqIn(epoch, cursor);
@@ -1,6 +1,6 @@
1
+ import { Checked, OccurrenceSchema } from "./occurrence.mjs";
1
2
  import { Any, Occurrence, Received } from "../Event.mjs";
2
- import { Checked } from "./occurrence.mjs";
3
- import { Duration, Effect, Stream } from "effect";
3
+ import { Duration, Effect, Schema, Stream } from "effect";
4
4
  /** One poll's answer, as a surface sends it and a client reads it. */
5
5
  export interface Page {
6
6
  readonly events: ReadonlyArray<Occurrence<Any>>;
@@ -9,5 +9,33 @@ export interface Page {
9
9
  readonly hasMore: boolean;
10
10
  readonly nextPoll: Duration.Duration;
11
11
  }
12
+ export declare const pageOf: <E extends Any>(event: E) => Schema.encodeKeys<Schema.Struct<{
13
+ events: Schema.$Array<OccurrenceSchema<E>>;
14
+ cursor: Schema.NullOr<Schema.String>;
15
+ truncated: Schema.Boolean;
16
+ hasMore: Schema.Boolean;
17
+ nextPoll: Schema.DurationFromMillis;
18
+ }>, {
19
+ readonly nextPoll: "nextPollMs";
20
+ }>;
21
+ /**
22
+ * The answer of an rpc's `<event>/poll`, `{ events, cursor, truncated, hasMore, nextPollMs,
23
+ * notified }`, its occurrences left undecoded: an HTTP poll's page and `notified`. `hasMore` is
24
+ * set when more are ready at once, `nextPollMs` is how long its client waits before it polls
25
+ * again, and `notified` is `true` when the server learns of each change to the event's source as
26
+ * it is made, an append to its log or a `notify`, so a host may hold a poll that found nothing
27
+ * until one, and `false` when only reading the source again finds a change, as for a check source
28
+ * not `notified` or an event `ActionEntity.reaching` reaches.
29
+ */
30
+ export declare const AnyPage: Schema.encodeKeys<Schema.Struct<{
31
+ readonly events: Schema.$Array<Schema.Unknown>;
32
+ readonly cursor: Schema.NullOr<Schema.String>;
33
+ readonly truncated: Schema.Boolean;
34
+ readonly hasMore: Schema.Boolean;
35
+ readonly nextPoll: Schema.DurationFromMillis;
36
+ readonly notified: Schema.Boolean;
37
+ }>, {
38
+ readonly nextPoll: "nextPollMs";
39
+ }>;
12
40
  /** What a feed's stream yields: what a subscriber receives, and where it has read up to. */
13
41
  export type Fed = Received<Any> | Checked;
@@ -1,6 +1,30 @@
1
- import { Checked, Gap } from "./occurrence.mjs";
2
- import { Duration, Effect, Option, Stream } from "effect";
1
+ import { Checked, Gap, OccurrenceOf } from "./occurrence.mjs";
2
+ import { Duration, Effect, Option, Schema, Stream } from "effect";
3
3
  // src/contract/pages.ts
4
+ const pageFields = (occurrence) => ({
5
+ events: Schema.Array(occurrence),
6
+ cursor: Schema.NullOr(Schema.String),
7
+ truncated: Schema.Boolean,
8
+ hasMore: Schema.Boolean,
9
+ nextPoll: Schema.DurationFromMillis
10
+ });
11
+ const nextPollKey = { nextPoll: "nextPollMs" };
12
+ const pageOf = (event) => Schema.Struct(pageFields(OccurrenceOf(event))).pipe(Schema.encodeKeys(nextPollKey));
13
+ const rpcPageWith = (occurrence) => Schema.Struct({
14
+ ...pageFields(occurrence),
15
+ notified: Schema.Boolean
16
+ }).pipe(Schema.encodeKeys(nextPollKey));
17
+ const rpcPageOf = (event) => rpcPageWith(OccurrenceOf(event));
18
+ /**
19
+ * The answer of an rpc's `<event>/poll`, `{ events, cursor, truncated, hasMore, nextPollMs,
20
+ * notified }`, its occurrences left undecoded: an HTTP poll's page and `notified`. `hasMore` is
21
+ * set when more are ready at once, `nextPollMs` is how long its client waits before it polls
22
+ * again, and `notified` is `true` when the server learns of each change to the event's source as
23
+ * it is made, an append to its log or a `notify`, so a host may hold a poll that found nothing
24
+ * until one, and `false` when only reading the source again finds a change, as for a check source
25
+ * not `notified` or an event `ActionEntity.reaching` reaches.
26
+ */
27
+ const AnyPage = rpcPageWith(Schema.Unknown);
4
28
  const pollFloor = Duration.seconds(1);
5
29
  const gapSkippingNoneOf = ({ items, from, to }) => items.length === 0 ? to : from;
6
30
  const fedOf = (delivered) => [
@@ -29,4 +53,4 @@ const paged = (poll, cursor) => pagedFrom((at) => Effect.map(poll(at), (page) =>
29
53
  to: page.cursor ?? at
30
54
  })
31
55
  })), cursor);
32
- export { fedOf, paged, pagedFrom };
56
+ export { AnyPage, fedOf, pageOf, paged, pagedFrom, rpcPageOf };
@@ -0,0 +1,9 @@
1
+ import { Context } from "effect";
2
+ // src/contract/wake.ts
3
+ /**
4
+ * How an entity's activation waits until a time, which `ActionEntity.layer` provides to its
5
+ * `services`: a wait that builds a stopped activation again when it is due, where a timer is cut
6
+ * by Effect's reaper and keeps a Durable Object awake. Absent outside an entity.
7
+ */
8
+ var Wake = class extends Context.Service()("effect-actions/Wake") {};
9
+ export { Wake };