@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
package/dist/Event.d.mts CHANGED
@@ -3,10 +3,10 @@ import { Authorizer, Deferred as Deferred$1 } from "./contract/authorizer.mjs";
3
3
  import { Codec, CodecOf, Fields, NoInput } from "./contract/codec.mjs";
4
4
  import { Refusal } from "./contract/errors.mjs";
5
5
  import { AnyEventImplementation, EventImplementation } from "./contract/feed.mjs";
6
- import { Events, KeyOptions, MakeEventsOptions, RevisionStorage, layerMemory, makeEvents } from "./contract/hub.mjs";
6
+ import { Events, KeyOptions, layerMemory } from "./contract/hub.mjs";
7
7
  import { Protected } from "./contract/implementation.mjs";
8
8
  import { Gap, OccurrenceSchema } from "./contract/occurrence.mjs";
9
- import { Listed, LogStorage } from "./contract/log.mjs";
9
+ import { Listed } from "./contract/log.mjs";
10
10
  import { DateTime, Duration, Effect, Schema, Scope, Stream } from "effect";
11
11
  declare const TypeId = "~@gjermundgaraba/effect-actions/Event";
12
12
  /** What `make` needs to define an event type. */
@@ -101,7 +101,10 @@ export interface Page<E extends Any> {
101
101
  readonly truncated?: boolean | undefined;
102
102
  /** More occurrences are ready: the subscriber asks again without waiting. */
103
103
  readonly hasMore?: boolean | undefined;
104
- /** How long a subscriber waits before it asks again; defaults to 5 seconds. */
104
+ /**
105
+ * How long a subscriber waits before it asks again, a `notified` source's streams and webhooks
106
+ * excepted; defaults to 5 seconds.
107
+ */
105
108
  readonly nextPoll?: Duration.Input | undefined;
106
109
  }
107
110
  interface Hooked<E extends Any, R> {
@@ -124,6 +127,20 @@ export interface Check<E extends Any, R = never> extends Hooked<E, R> {
124
127
  * occurrence. An event whose occurrence is the whole value, such as a status, is a `Current`.
125
128
  */
126
129
  readonly check: (input: E["input"]["Type"], cursor: string | null) => Effect.Effect<Page<E>, Refusal, R>;
130
+ /**
131
+ * Every change `check` reads is announced by an `Events.notify` the server serving it receives,
132
+ * as a store only that server's handlers write is: its streams and webhook deliveries then ask
133
+ * `check` again only when notified, on no timer, so an idle Cloudflare Durable Object holding
134
+ * them hibernates. Defaults to `false`, asking again at each page's `nextPoll` too. A polling
135
+ * client polls at `nextPoll` either way, and an rpc's poll page says `notified`, so a host that
136
+ * holds polls, as the Cloudflare package's socket host does, holds one of this source alone.
137
+ *
138
+ * **Gotchas**
139
+ *
140
+ * - A change no `notify` on that server announces, as another server's write to a shared database or an upstream's own, reaches its streams, its webhooks and a poll a host holds only with the next `notify`.
141
+ * - A `notify` that `check` runs before it can read the write waits for the next `notify` too: notify after the write commits, or inside its transaction only where `check` reads through the same connection, as one SQLite client's reads wait for its transaction.
142
+ */
143
+ readonly notified?: boolean | undefined;
127
144
  readonly log?: never;
128
145
  readonly current?: never;
129
146
  }
@@ -131,7 +148,9 @@ export interface Check<E extends Any, R = never> extends Hooked<E, R> {
131
148
  * An event type whose occurrence is the whole value, such as a status or a list small enough to
132
149
  * send whole: a subscriber receives the value as it is first, then again after each
133
150
  * `Events.notify` that reaches it, never a change it missed one by one. The library keeps a
134
- * revision per key, which each such notify moves, as the cursor and each occurrence's id.
151
+ * revision per key, which each such notify moves, as the cursor and each occurrence's id. Its
152
+ * streams and webhook deliveries read it again only when notified, on no timer, so an idle
153
+ * Cloudflare Durable Object holding them hibernates; a polling client polls every 5 seconds.
135
154
  *
136
155
  * **Gotchas**
137
156
  *
@@ -151,9 +170,10 @@ export interface Current<E extends Any, R = never> extends Hooked<E, R> {
151
170
  *
152
171
  * **Gotchas**
153
172
  *
154
- * - A cursor is only good where the log that minted it lives, for as long as it keeps its occurrences: after a restart, or once they are dropped, a subscriber resuming from it receives `truncated` and a fresh cursor.
173
+ * - A cursor is only good where the log that minted it lives, for as long as it keeps its occurrences: once they are dropped, or after a restart under `Event.layerMemory`, a subscriber resuming from it receives `truncated` and a fresh cursor; `Stored.layerEvents` keeps a log across a restart on the same database.
155
174
  * - A subscriber reading slower than occurrences arrive falls behind the log like a resumed one: it receives `truncated`, never a backlog held for it alone.
156
175
  * - An `emit` stream is consumed from startup, in the server's scope, by one build at a time, until it ends, even past its build's release: a failure ends it and is reported, an end is logged, and the next held build's stream, if any, takes over; the log then holds what was published.
176
+ * - A cluster entity refuses an `emit` stream, its activation dying as it builds: Effect's entity reaper stops an entity while its stream runs, and what the stream sends meanwhile is lost; append with `Events.publish` from a handler.
157
177
  */
158
178
  export interface Log<E extends Any, R = never> extends Hooked<E, R> {
159
179
  /** What the log keeps, and the stream feeding it besides `Events.publish`; `{}` for none. */
@@ -344,4 +364,4 @@ export declare function implement<const T extends Target, RequestServices extend
344
364
  readonly authorize: Authorizer<Protected<EventsOf<T>>, RA, EAX, RAX>;
345
365
  }): Implemented<T, RequestServices, R, EX, RX, RA, EAX, RAX>;
346
366
  export declare function implement<const T extends Target, RequestServices extends (T extends readonly Any[] ? { readonly [K in NamesOf<T>]: unknown; } : never), R = never, EX = never, RX = never>(events: T & TakesNoAuthorize<T>, sources: SourcesOf<T, R, RequestServices> | Effect.Effect<SourcesOf<T, R, RequestServices>, EX, RX>): Implemented<T, RequestServices, R, EX, RX, never, never, never>;
347
- export { type AnyEventImplementation as AnyImplementation, Events, Gap, type EventImplementation as Implementation, type KeyOptions, type Listed, type LogStorage, type MakeEventsOptions, type RevisionStorage, layerMemory, makeEvents };
367
+ export { type AnyEventImplementation as AnyImplementation, Events, Gap, type EventImplementation as Implementation, type KeyOptions, type Listed, layerMemory };
package/dist/Event.mjs CHANGED
@@ -3,7 +3,7 @@ import { Anyone, assertCaller } from "./contract/caller.mjs";
3
3
  import { codecOf } from "./contract/codec.mjs";
4
4
  import { EventImplementation, sourcesOf } from "./contract/feed.mjs";
5
5
  import { assertEventName, assertOnce } from "./contract/names.mjs";
6
- import { Events, layerMemory, makeEvents } from "./contract/hub.mjs";
6
+ import { Events, layerMemory } from "./contract/hub.mjs";
7
7
  import { Gap } from "./contract/occurrence.mjs";
8
8
  import { Array as Array$1, Data, Effect, Match, Predicate, Schema } from "effect";
9
9
  // src/contract/Event.ts
@@ -100,4 +100,4 @@ function implement(events, sources, options) {
100
100
  }, listed.some((event) => event.caller !== Anyone), options?.authorize);
101
101
  return new EventImplementation(listed, sourcesOf(listed, !Array.isArray(events), sources), authorizer);
102
102
  }
103
- export { CallbackCategory, CallbackFailed, Events, Gap, NotServed, NotSubscribed, SubscriptionError, Unsupported, WebhookDelivery, allowAll, implement, isEvent, layerMemory, make, makeEvents };
103
+ export { CallbackCategory, CallbackFailed, Events, Gap, NotServed, NotSubscribed, SubscriptionError, Unsupported, WebhookDelivery, allowAll, implement, isEvent, layerMemory, make };
@@ -0,0 +1,49 @@
1
+ import { Events } from "./contract/hub.mjs";
2
+ import { Idempotency } from "./contract/idempotency.mjs";
3
+ import { Layer } from "effect";
4
+ import { SqlClient } from "effect/sql";
5
+ /**
6
+ * An `Events` kept in tables through the `SqlClient` it is built with, created as it builds:
7
+ * each log source's occurrences in `effect_actions_event_log`, by event name and sequence number,
8
+ * with its key and the occurrence as JSON, and its position in `effect_actions_event_position`;
9
+ * each `notify` moves a counter in `effect_actions_event_revision`, the event's name counting
10
+ * every one. For a host whose subscribers outlive it, such as a cluster entity on its own
11
+ * SQLite: a watch resumed from a cursor after a restart on the same database receives every
12
+ * occurrence past it within the log's bounds, `maxAge` (10 minutes by default) and `maxEvents`.
13
+ * Its change signal, which `changeSignal` reads, moves at each `notify` and each append to a
14
+ * log, published or emitted, and at no read or restart: a host reads it to learn whether a poll
15
+ * could answer anything new.
16
+ *
17
+ * **Gotchas**
18
+ *
19
+ * - Written for SQLite, such as a cluster entity's own on a Durable Object, `CloudflareCluster.DurableObjectSqlClient`, and tested on `@effect/sql-sqlite-node`'s and on workerd: another dialect is unsupported.
20
+ * - Build it once per database, as `Event.layerMemory` is built once per process: two builds over one database each wake only their own subscribers, and their appends to one log collide, dying on the table's key.
21
+ * - Logs are kept by their event's name: two event types of one name attached to one build die, naming it.
22
+ * - A `key` holding a lone surrogate, not well-formed UTF-16, is kept with U+FFFD in its place: its occurrences no longer reach that key's subscribers.
23
+ * - A query that fails dies: the database is the host's own, and nothing else can answer for it.
24
+ * - Each append and read of a log is a transaction, joining the caller's: on a Durable Object, `CloudflareCluster.DurableObjectSqlClient` is `@effect/sql-sqlite-do`'s `SqliteClient` built with `storage`, and one built with `db` alone fails every one, which dies; an occurrence published in a transaction that rolls back is not kept, though its subscribers are woken to read nothing.
25
+ */
26
+ export declare const layerEvents: Layer.Layer<Events, never, SqlClient.SqlClient>;
27
+ /**
28
+ * The SQL query reading `layerEvents`' change signal from its database, one row whose `signal`
29
+ * column is the sum of `effect_actions_event_revision`'s counts and of
30
+ * `effect_actions_event_position`'s `last` sequence numbers: it moves at each `notify` and each
31
+ * append to a log, and at no read or restart, so a host that runs it after each handler, as the
32
+ * Cloudflare package's socket host does, learns whether a parked poll could answer anything new.
33
+ *
34
+ * **Gotchas**
35
+ *
36
+ * - Before `layerEvents` first builds on the database its tables are missing, and the query fails with SQLite's `no such table`: the Cloudflare package's socket host reads that as no signal, answering polls at once as for an entity whose events are kept elsewhere, and fails a poll with a defect on any other failure, as on tables of another shape.
37
+ */
38
+ export declare const changeSignal: string;
39
+ /**
40
+ * `Idempotency` in a table of the `SqlClient` it is built with, created as it builds,
41
+ * `effect_persistence_effect_actions_idempotency`, each answer kept 24 hours: in a database that
42
+ * outlives the server, such as a cluster entity's own SQLite.
43
+ *
44
+ * **Gotchas**
45
+ *
46
+ * - An expired answer is never read back, and is deleted as the layer builds: a long-running server keeps the rows of expired answers until it builds again, as a cluster entity does each time it activates.
47
+ * - A database failing to read or keep an answer dies: the call fails, its answer not kept.
48
+ */
49
+ export declare const layerIdempotency: Layer.Layer<Idempotency, never, SqlClient.SqlClient>;
@@ -0,0 +1,78 @@
1
+ import { changeSignalQuery, createLogTables, sqlRevisions, sqlStorage } from "./contract/event-tables.mjs";
2
+ import { Events, makeEvents } from "./contract/hub.mjs";
3
+ import { Idempotency, Kept, keptFor } from "./contract/idempotency.mjs";
4
+ import { Duration, Effect, Layer, Option, Schema } from "effect";
5
+ import { Persistence } from "effect/persistence";
6
+ import { SqlClient } from "effect/sql";
7
+ // src/contract/Stored.ts
8
+ /**
9
+ * An `Events` kept in tables through the `SqlClient` it is built with, created as it builds:
10
+ * each log source's occurrences in `effect_actions_event_log`, by event name and sequence number,
11
+ * with its key and the occurrence as JSON, and its position in `effect_actions_event_position`;
12
+ * each `notify` moves a counter in `effect_actions_event_revision`, the event's name counting
13
+ * every one. For a host whose subscribers outlive it, such as a cluster entity on its own
14
+ * SQLite: a watch resumed from a cursor after a restart on the same database receives every
15
+ * occurrence past it within the log's bounds, `maxAge` (10 minutes by default) and `maxEvents`.
16
+ * Its change signal, which `changeSignal` reads, moves at each `notify` and each append to a
17
+ * log, published or emitted, and at no read or restart: a host reads it to learn whether a poll
18
+ * could answer anything new.
19
+ *
20
+ * **Gotchas**
21
+ *
22
+ * - Written for SQLite, such as a cluster entity's own on a Durable Object, `CloudflareCluster.DurableObjectSqlClient`, and tested on `@effect/sql-sqlite-node`'s and on workerd: another dialect is unsupported.
23
+ * - Build it once per database, as `Event.layerMemory` is built once per process: two builds over one database each wake only their own subscribers, and their appends to one log collide, dying on the table's key.
24
+ * - Logs are kept by their event's name: two event types of one name attached to one build die, naming it.
25
+ * - A `key` holding a lone surrogate, not well-formed UTF-16, is kept with U+FFFD in its place: its occurrences no longer reach that key's subscribers.
26
+ * - A query that fails dies: the database is the host's own, and nothing else can answer for it.
27
+ * - Each append and read of a log is a transaction, joining the caller's: on a Durable Object, `CloudflareCluster.DurableObjectSqlClient` is `@effect/sql-sqlite-do`'s `SqliteClient` built with `storage`, and one built with `db` alone fails every one, which dies; an occurrence published in a transaction that rolls back is not kept, though its subscribers are woken to read nothing.
28
+ */
29
+ const layerEvents = Layer.effect(Events)(Effect.gen(function* () {
30
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
31
+ yield* createLogTables(sql);
32
+ const revisions = yield* sqlRevisions(sql);
33
+ const named = /* @__PURE__ */ new Map();
34
+ return yield* makeEvents({
35
+ log: (event) => {
36
+ const prior = named.get(event.name);
37
+ if (prior !== void 0 && prior !== event) throw new Error(`Stored.layerEvents keeps each log source's log by its event's name, and two event types are named "${event.name}" (give each event type a name of its own)`);
38
+ named.set(event.name, event);
39
+ return sqlStorage(sql, event.name, Schema.fromJsonString(Schema.toCodecJson(Schema.Struct({
40
+ data: event.payload,
41
+ eventId: Schema.optional(Schema.String),
42
+ timestamp: Schema.optional(Schema.DateTimeUtcFromMillis)
43
+ }))));
44
+ },
45
+ revisions
46
+ });
47
+ }).pipe(Effect.orDie));
48
+ /**
49
+ * The SQL query reading `layerEvents`' change signal from its database, one row whose `signal`
50
+ * column is the sum of `effect_actions_event_revision`'s counts and of
51
+ * `effect_actions_event_position`'s `last` sequence numbers: it moves at each `notify` and each
52
+ * append to a log, and at no read or restart, so a host that runs it after each handler, as the
53
+ * Cloudflare package's socket host does, learns whether a parked poll could answer anything new.
54
+ *
55
+ * **Gotchas**
56
+ *
57
+ * - Before `layerEvents` first builds on the database its tables are missing, and the query fails with SQLite's `no such table`: the Cloudflare package's socket host reads that as no signal, answering polls at once as for an entity whose events are kept elsewhere, and fails a poll with a defect on any other failure, as on tables of another shape.
58
+ */
59
+ const changeSignal = changeSignalQuery;
60
+ const decodeKept = Schema.decodeUnknownOption(Kept);
61
+ /**
62
+ * `Idempotency` in a table of the `SqlClient` it is built with, created as it builds,
63
+ * `effect_persistence_effect_actions_idempotency`, each answer kept 24 hours: in a database that
64
+ * outlives the server, such as a cluster entity's own SQLite.
65
+ *
66
+ * **Gotchas**
67
+ *
68
+ * - An expired answer is never read back, and is deleted as the layer builds: a long-running server keeps the rows of expired answers until it builds again, as a cluster entity does each time it activates.
69
+ * - A database failing to read or keep an answer dies: the call fails, its answer not kept.
70
+ */
71
+ const layerIdempotency = Layer.effect(Idempotency)(Effect.gen(function* () {
72
+ const store = yield* (yield* Persistence.BackingPersistence).make("effect_actions_idempotency");
73
+ return Idempotency.of({
74
+ get: (id) => store.get(id).pipe(Effect.orDie, Effect.map((value) => Option.getOrUndefined(decodeKept(value)))),
75
+ set: (id, kept) => Effect.orDie(store.set(id, kept, Duration.millis(keptFor)))
76
+ });
77
+ })).pipe(Layer.provide(Persistence.layerBackingSqlMultiTable));
78
+ export { changeSignal, layerEvents, layerIdempotency };
@@ -29,6 +29,7 @@ export interface Options {
29
29
  * **Gotchas**
30
30
  *
31
31
  * - The failures are timed from the subscription's `failedSince`, which `persist` keeps: a restart goes on with the waits and the budget it reached, and a refresh of a subscription still delivering does not extend it.
32
+ * - In an entity's `services`, each wait is a wake the entity sends itself, which `ActionEntity.LayerOptions`' `services` describes.
32
33
  */
33
34
  readonly retryFor?: Duration.Input | undefined;
34
35
  /**
@@ -38,13 +39,13 @@ export interface Options {
38
39
  *
39
40
  * **Gotchas**
40
41
  *
41
- * - Each subscriber's identity is kept by its authentication's `schema`, encoded at each grant: a surface offering a protected event by webhook refuses to start without it, or where two authentications with different schemas serve one event.
42
+ * - Each subscriber's identity is kept by its authentication's `schema`, encoded at each grant: a surface offering a protected event by webhook refuses to start without it, or where two authentications with different schemas serve one event; in an entity's `services` it is each activation that dies, as `ActionEntity.LayerOptions`' `services` says.
42
43
  * - A restored delivery runs in the layer's context and that identity alone, until the subscriber's next refresh: an authorizer or a source reading a service middleware or the surface's layer provides fails, each read reported and retried every 5 seconds.
43
44
  * - A subscriber refused as its subscription is restored is POSTed `terminated`; an authorizer or a source failing its first read with no refusal is retried, as later.
44
45
  * - A subscription suspended stays suspended when restored, until its subscriber's refresh delivers again.
45
46
  * - Secrets and identities are kept as JSON, as given, so give the layer a store only the server reads.
46
47
  * - A kept subscription whose input or identity no longer decodes, as after a schema change, is reported at each build and never restored, until its subscriber unsubscribes it.
47
- * - The build lists every key of the store, a `SELECT id` over a SQL store's whole table or a read of the file store's directory, and restores those under `effect-actions/webhook/`: where the application keeps many keys in that store, give the layer one of its own.
48
+ * - The build lists every key of the store, a `SELECT id` over a SQL store's whole table or a read of the file store's directory, and restores those under `effect-actions/webhook/`, or in an entity's `services` under `effect-actions/entity-webhook/<type>/<id>/`, the entity's address percent-encoded, so the root layer and each entity id restore their own from one store; each entity id's activation lists the whole store again: where the application keeps many keys, or many entities keep subscriptions, in that store, give the layer one of its own.
48
49
  * - A store whose keys cannot be listed as the layer builds fails the build, as the file store's does on a file name that is not percent-encoding, such as `100%.txt`; a write that fails later is reported and tried again with the next.
49
50
  * - Writes still pending 5 seconds into the layer's close are reported as `UnfinishedWrites` and dropped: the next build restores each subscription as last written, missing one subscribed since and keeping one removed since.
50
51
  * - A callback's verification is not kept: a restored subscription delivers on, and a new one to the same callback after a restart is verified again.
@@ -77,7 +78,7 @@ export interface Options {
77
78
  *
78
79
  * **Gotchas**
79
80
  *
80
- * - Only a protected event whose descriptor has `principal` is offered webhook delivery: elsewhere `events/list` lists no `webhook`, and a subscribe is `Unsupported`.
81
+ * - Only a protected event is offered webhook delivery, each subscription its subscriber's principal's: a public event's `events/list` entry lists no `webhook`, and its subscribe is `Unsupported`.
81
82
  * - A `requestScoped` MCP endpoint offers it too, its subscriptions built once with the endpoint: on a host with no lasting process, leave this layer out, as `ActionHttp.layer` says, since each instance keeps its own subscriptions, lost as it ends.
82
83
  * - A callback resolving to an address that is not globally reachable, a loopback or a private one included, is never POSTed to unless `allowedCallbacks` trusts it: a local receiver needs a public name, a trusted URL, or a test's `Dns.layerStatic`; an IPv6-only server behind NAT64 cannot deliver to an IPv4-only callback.
83
84
  * - Each POST is checked against the address it resolves to, but fetch connects to the name again, so a name rebinding between the check and the connection is not caught: front the server with an egress proxy that refuses private addresses where that matters.
@@ -87,7 +88,7 @@ export interface Options {
87
88
  * - A callback verified for a subscriber is not challenged again for that subscriber's other subscriptions to it while one is granted, as SEP-3415's soft state allows.
88
89
  * - Deliveries are one at a time, in order: one failing holds back those after it, for `retryFor`, then the subscription suspends until a refresh, which delivers it again.
89
90
  * - An occurrence given up, its body over 256 KiB or its POST answered `410` or `413`, is POSTed as a `gap` at its cursor; one whose admission fails with no refusal is reported and read again, from before it, every 5 seconds.
90
- * - A refresh restarts its subscription's reading under the refreshed subscriber, from where delivery reached: the subscription hook set up again once the old one is released, and a delivery in flight sent again, which the subscriber drops by its `eventId`.
91
+ * - A refresh restarts its subscription's reading under the refreshed subscriber, from where delivery reached: the subscription hook set up again once the old one is released, and a delivery in flight sent again, which the subscriber drops by its `eventId`, though one waiting to retry is sent at its retry's time, signed with the refreshed secret.
91
92
  * - A refresh its authorizer refuses ends the subscription it names, POSTing `terminated`, though each delivery, admitted as the subscriber of the last grant, would still pass.
92
93
  * - A `terminated` POST is tried four times, and one never accepted is logged as a warning naming the subscription; one answered `410` or `413` is given up at once, unlogged.
93
94
  * - A refresh with a new secret signs each POST with both secrets for 5 minutes, `webhook-signature` holding two, so a receiver may switch over; after that, with the new one alone.
package/dist/Webhook.mjs CHANGED
@@ -1,10 +1,12 @@
1
1
  import { WebhookDelivery } from "./Event.mjs";
2
2
  import { Receiving } from "./contract/receiving.mjs";
3
+ import { Wake } from "./contract/wake.mjs";
3
4
  import { Webhooks } from "./contract/webhooks.mjs";
4
5
  import { makeReceiver } from "./webhook/receiver.mjs";
5
- import { makeWriteBehindStorage } from "./webhook/stored.mjs";
6
+ import { entityStorePrefix, makeWriteBehindStorage, storePrefix } from "./webhook/stored.mjs";
6
7
  import { makeWebhooks } from "./webhook/subscriptions.mjs";
7
- import { Duration, Effect, Layer } from "effect";
8
+ import { Duration, Effect, Layer, Option } from "effect";
9
+ import { Entity } from "effect/cluster";
8
10
  import { HttpRouter } from "effect/http";
9
11
  import { Dns } from "effect/net";
10
12
  import { KeyValueStore } from "effect/persistence";
@@ -24,13 +26,18 @@ function layer(options = {}) {
24
26
  const maxTtl = maxTtlOf(options.maxTtl ?? "1 hour");
25
27
  return Layer.effect(Webhooks, Effect.gen(function* () {
26
28
  const dns = options.resolveCallbacks === false ? void 0 : yield* Dns.Dns;
27
- const storage = options.persist === true ? yield* Effect.flatMap(KeyValueStore.KeyValueStore, makeWriteBehindStorage) : void 0;
29
+ const prefix = Option.match(yield* Effect.serviceOption(Entity.CurrentAddress), {
30
+ onNone: () => storePrefix,
31
+ onSome: ({ entityType, entityId }) => entityStorePrefix(entityType, entityId)
32
+ });
33
+ const storage = options.persist === true ? yield* Effect.flatMap(KeyValueStore.KeyValueStore, (store) => makeWriteBehindStorage(store, prefix)) : void 0;
28
34
  return yield* makeWebhooks({
29
35
  maxTtl,
30
36
  allowedCallbacks,
31
37
  retryFor: Duration.fromInputUnsafe(options.retryFor ?? "1 hour"),
32
38
  storage,
33
- dns
39
+ dns,
40
+ wake: yield* Effect.serviceOption(Wake)
34
41
  });
35
42
  }));
36
43
  }
@@ -75,8 +75,8 @@ export interface Descriptor<I, A, S extends Security, Name extends string = stri
75
75
  readonly security: S;
76
76
  /** `Options.error` of `make`, as a list. */
77
77
  readonly error: E;
78
- /** `Options.principal` of `make`, the stable id of an identity, where given. */
79
- principal?(identity: A): string;
78
+ /** `Options.principal` of `make`, the stable id of an identity. */
79
+ principal(identity: A): string;
80
80
  /** `Options.schema` of `make`, how an identity is kept, where given. */
81
81
  readonly schema?: Codec | undefined;
82
82
  readonly "~provider": Context.Key<Provider<I, Name>, Runtime$1>;
@@ -1,12 +1,14 @@
1
+ import { Anyone } from "../contract/caller.mjs";
1
2
  import { errorSchemas } from "../contract/declared.mjs";
2
3
  import { Forbidden, Refusal, Unauthenticated } from "../contract/errors.mjs";
3
- import { declared, httpApiStatusOf } from "../contract/status.mjs";
4
+ import { declaredStatus } from "../contract/status.mjs";
5
+ import { promote } from "./provider.mjs";
4
6
  import { Cause, Context, Effect, Exit, Option, Predicate, Ref, Schema } from "effect";
5
7
  import { HttpServerResponse } from "effect/http";
6
8
  // src/authentication/refusal.ts
7
- const responseOf = (schema, error) => HttpServerResponse.jsonUnsafe(Schema.encodeUnknownSync(Schema.toCodecJson(schema))(error), { status: httpApiStatusOf(schema.ast) ?? 422 });
9
+ const responseOf = (schema, error) => HttpServerResponse.jsonUnsafe(Schema.encodeUnknownSync(Schema.toCodecJson(schema))(error), { status: declaredStatus(schema) });
8
10
  const declaredResponse = (errors, error) => {
9
- const schema = errorSchemas(errors).map(declared).find((each) => Schema.is(each)(error));
11
+ const schema = errorSchemas(errors).find((each) => Schema.is(each)(error));
10
12
  return schema === void 0 ? void 0 : responseOf(schema, error);
11
13
  };
12
14
  const rfc6750ErrorDescriptionCharacters = /^[\u0020\u0021\u0023-\u005B\u005D-\u007E]+$/u;
@@ -35,6 +37,11 @@ const answer = (error, metadataUrl) => {
35
37
  var SteppedUpRefusal = class extends Context.Service()("effect-actions/SteppedUp") {};
36
38
  const isStepUp = (error) => isRefusal(error) && (!Predicate.isTagged(error, "Forbidden") || error.scopes !== void 0);
37
39
  const recordStepUp = (call) => Effect.tapError(call, (error) => isStepUp(error) ? Effect.flatMap(Effect.serviceOption(SteppedUpRefusal), (slot) => Option.isSome(slot) ? Ref.set(slot.value, Option.some(error)) : Effect.void) : Effect.void);
40
+ /**
41
+ * `run` as the caller of `called`: unchanged where it is public or nothing authenticates, and
42
+ * otherwise with the identity its request verified, a step-up it fails with recorded.
43
+ */
44
+ const asCaller = (authentication, called, run) => authentication === void 0 || called.caller === Anyone ? run : recordStepUp(promote(authentication, run));
38
45
  const answerStepUp = (route, metadataUrl) => Effect.gen(function* () {
39
46
  const slot = yield* Ref.make(Option.none());
40
47
  const exit = yield* Effect.exit(Effect.provideService(route, SteppedUpRefusal, slot));
@@ -42,4 +49,4 @@ const answerStepUp = (route, metadataUrl) => Effect.gen(function* () {
42
49
  const diedOrInterruptedAfterRefusal = Exit.isFailure(exit) && (Cause.hasDies(exit.cause) || Cause.hasInterrupts(exit.cause));
43
50
  return Option.isSome(refused) && !diedOrInterruptedAfterRefusal ? answer(refused.value, metadataUrl) : yield* exit;
44
51
  });
45
- export { answer, answerStepUp, bearer, challenge, declaredResponse, isRefusal, isStepUp, plain, recordStepUp };
52
+ export { answer, answerStepUp, asCaller, bearer, challenge, declaredResponse, isRefusal, isStepUp, plain, recordStepUp };
@@ -177,7 +177,6 @@ const positionalOrder = (params, positional) => {
177
177
  return ordered;
178
178
  };
179
179
  const wholeInputFlag = (encoded) => Flag.String("input").pipe(Flag.withSchema(jsonOfAcceptedKindOrText(encoded)), Flag.withDescription("Whole action input as JSON; omitted, {}"), Flag.optional);
180
- const printedOutput = (action, value, render) => Effect.map(Effect.orDie(Schema.encodeEffect(Schema.toCodecJson(action.success))(value)), (encoded) => render === void 0 && SchemaAST.isVoid(action.success.ast) ? Option.none() : Option.some(render === void 0 ? JSON.stringify(encoded, null, 2) : render(value)));
181
180
  /**
182
181
  * What a command fails with when its action fails: Effect CLI's `UserError`, typed with the
183
182
  * action's failure as its `cause` and `reason`, and whose `userMessage` is its JSON, or for a
@@ -292,12 +291,13 @@ const progressLinesOf = (progress) => {
292
291
  };
293
292
  const printedOf = (action) => {
294
293
  const element = elementOf(action.success);
295
- if (element === void 0) return (value, render, print) => Effect.flatMap(printedOutput(action, value, render), Option.match({
296
- onNone: () => Effect.void,
297
- onSome: (line) => Effect.sync(() => {
298
- print(line);
299
- })
300
- }));
294
+ if (element === void 0) {
295
+ const encode = Schema.encodeEffect(Schema.toCodecJson(action.success));
296
+ const silent = SchemaAST.isVoid(action.success.ast);
297
+ return (value, render, print) => Effect.flatMap(Effect.orDie(encode(value)), (encoded) => render === void 0 && silent ? Effect.void : Effect.sync(() => {
298
+ print(render === void 0 ? JSON.stringify(encoded, null, 2) : render(value));
299
+ }));
300
+ }
301
301
  const encode = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.toCodecJson(element)));
302
302
  return (value, render, print) => Stream.runForEach(elementsOf(Effect.succeed(value)), (each) => Effect.map(Effect.orDie(encode(each)), (json) => {
303
303
  print(render === void 0 ? json : render(each));
@@ -370,4 +370,4 @@ const watchCommand = (event, watch, errors) => {
370
370
  stdout.log(line);
371
371
  })))), failing, withStderrConsole))).pipe(Command.withDescription(event.description));
372
372
  };
373
- export { UserError, command, failingAsDerived, kebab, watchCommand };
373
+ export { UserError, command, failingAsDerived, watchCommand };
@@ -24,7 +24,11 @@ const jsonRoundTrip = (schema) => {
24
24
  value: received
25
25
  })));
26
26
  };
27
- const watchInput = (event, input) => inputOf(event, input === void 0 ? [] : [input]).pipe(Effect.flatMap(jsonRoundTrip(event.input)), Effect.mapError(InvalidInput.fromSchemaError));
27
+ /**
28
+ * A call's or a watch's input as it is sent, `{}` decoded where it is left out: its JSON, and the
29
+ * value the server decodes from it.
30
+ */
31
+ const sentInput = (event, input) => inputOf(event, input === void 0 ? [] : [input]).pipe(Effect.flatMap(jsonRoundTrip(event.input)), Effect.mapError(InvalidInput.fromSchemaError));
28
32
  const sendingJson = (action) => Schema.encodeUnknownEffect(Schema.toCodecJson(action.input), { errors: "all" });
29
33
  const sendingValue = (action) => {
30
34
  const encode = sendingJson(action);
@@ -38,4 +42,4 @@ const checkedStream = (action, check, send) => {
38
42
  const method = checked(action, check, (input, onProgress) => Effect.succeed(send(input, onProgress)));
39
43
  return (...args) => Stream.unwrap(method(...args));
40
44
  };
41
- export { checked, checkedStream, decodeInput, inputOf, inputParseOptions, jsonRoundTrip, onProgressOf, sendingJson, sendingValue, watchInput };
45
+ export { checked, checkedStream, decodeInput, inputParseOptions, jsonRoundTrip, sendingJson, sendingValue, sentInput };
@@ -7,6 +7,11 @@ const SigningSecret = Schema.Struct({
7
7
  key: Schema.Uint8Array
8
8
  });
9
9
  const secretPrefix = "whsec_";
10
+ const encodeBase64 = Schema.encodeSync(Schema.Uint8ArrayFromBase64);
11
+ const signingSecretOf = (key) => ({
12
+ text: `${secretPrefix}${encodeBase64(key)}`,
13
+ key
14
+ });
10
15
  const decodeBase64 = Schema.decodeUnknownOption(Schema.Uint8ArrayFromBase64);
11
16
  const keyOf = (text) => text.startsWith(secretPrefix) ? Option.filter(decodeBase64(text.slice(6)), (key) => key.length >= 24 && key.length <= 64) : Option.none();
12
17
  const WebhookSecret = Schema.String.annotate({ description: "whsec_ and the base64 of 24 to 64 random bytes, which signs each delivery." }).pipe(Schema.decodeTo(SigningSecret, SchemaTransformation.transformEffect({
@@ -19,4 +24,4 @@ const WebhookSecret = Schema.String.annotate({ description: "whsec_ and the base
19
24
  }),
20
25
  encode: ({ text }) => Effect.succeed(text)
21
26
  })));
22
- export { CallbackUrl, SigningSecret, WebhookSecret };
27
+ export { CallbackUrl, SigningSecret, WebhookSecret, signingSecretOf };
@@ -7,12 +7,8 @@ import { Context, Effect } from "effect";
7
7
  * agree on a name.
8
8
  */
9
9
  export declare const Anyone: unique symbol;
10
- /** What names one caller of a surface: its authentication's `principal`, where it has one. */
10
+ /** What names one caller of a surface: its authentication's `principal`. */
11
11
  export interface Keyed {
12
- readonly principal?: (identity: Any["input"]["Type"]) => string;
13
- readonly schema?: Codec | undefined;
14
- }
15
- /** A surface's authentication that names each caller: its `principal` given. */
16
- export interface Named extends Keyed {
17
12
  readonly principal: (identity: Any["input"]["Type"]) => string;
13
+ readonly schema?: Codec | undefined;
18
14
  }
@@ -7,8 +7,8 @@ import { Context, Effect, Function } from "effect";
7
7
  */
8
8
  const Anyone = Symbol.for("@gjermundgaraba/effect-actions/Anyone");
9
9
  const CallerKeyed = Context.Reference("effect-actions/CallerKeyed", { defaultValue: Function.constUndefined });
10
- const isNamed = (keyed) => keyed?.principal !== void 0;
11
- const principalOf = (called, keyed) => keyed?.principal === void 0 || called.caller === Anyone ? Effect.undefined : Effect.map(Effect.service(called.caller), (identity) => keyed.principal?.(identity));
10
+ /** The caller's principal: none for a public one, or on a surface with no authentication. */
11
+ const principalOf = (called, keyed) => keyed === void 0 || called.caller === Anyone ? Effect.undefined : Effect.map(Effect.service(called.caller), keyed.principal);
12
12
  const assertAuthentication = (contracts, authentication, noun = "action") => {
13
13
  for (const contract of contracts) if (contract.caller !== Anyone && (authentication === void 0 || contract.caller.key !== authentication.identity.key)) throw new Error(`Protected ${noun} '${contract.name}' requires its matching authentication descriptor (give it the authentication whose identity the ${noun}'s caller names)`);
14
14
  };
@@ -16,4 +16,4 @@ const assertCaller = (caller) => {
16
16
  if (caller !== Anyone && !Context.isKey(caller)) throw new Error("Missing caller: declare Action.Anyone or an identity service key");
17
17
  if (caller !== Anyone && Context.isReference(caller)) throw new Error("Invalid caller: an identity is a Context.Service, not a Context.Reference");
18
18
  };
19
- export { Anyone, CallerKeyed, assertAuthentication, assertCaller, isNamed, principalOf };
19
+ export { Anyone, CallerKeyed, assertAuthentication, assertCaller, principalOf };
@@ -1,5 +1,6 @@
1
- import { Effect } from "effect";
1
+ import { Effect, Schema } from "effect";
2
2
  // src/contract/digest.ts
3
3
  const encoder = new TextEncoder();
4
- const sha256Hex = (text) => Effect.promise(async () => Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(text))), (byte) => byte.toString(16).padStart(2, "0")).join(""));
4
+ const encodeHex = Schema.encodeSync(Schema.Uint8ArrayFromHex);
5
+ const sha256Hex = (text) => Effect.promise(async () => encodeHex(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(text)))));
5
6
  export { sha256Hex };
@@ -0,0 +1,90 @@
1
+ import { Array, Effect, Option, Schema } from "effect";
2
+ // src/contract/event-tables.ts
3
+ const entryTable = "effect_actions_event_log";
4
+ const positionTable = "effect_actions_event_position";
5
+ const createLogTables = (sql) => Effect.andThen(sql`CREATE TABLE IF NOT EXISTS ${sql(positionTable)} (
6
+ event TEXT PRIMARY KEY,
7
+ epoch TEXT NOT NULL,
8
+ last BIGINT NOT NULL
9
+ )`, sql`CREATE TABLE IF NOT EXISTS ${sql(entryTable)} (
10
+ event TEXT NOT NULL,
11
+ seq BIGINT NOT NULL,
12
+ at BIGINT NOT NULL,
13
+ key TEXT,
14
+ value TEXT,
15
+ PRIMARY KEY (event, seq)
16
+ )`);
17
+ const PositionRows = Schema.Array(Schema.Struct({
18
+ epoch: Schema.String,
19
+ last: Schema.Int
20
+ }));
21
+ const EntryRows = Schema.Array(Schema.Struct({
22
+ seq: Schema.Int,
23
+ at: Schema.Finite,
24
+ key: Schema.NullOr(Schema.String),
25
+ value: Schema.NullOr(Schema.String)
26
+ }));
27
+ const decodePositions = Schema.decodeUnknownEffect(PositionRows);
28
+ const decodeEntries = Schema.decodeUnknownEffect(EntryRows);
29
+ const sqlStorage = (sql, name, codec) => {
30
+ const encode = Schema.encodeEffect(codec);
31
+ const decode = Schema.decodeEffect(codec);
32
+ const positions = sql(positionTable);
33
+ const entries = sql(entryTable);
34
+ const upsertPosition = ({ epoch, last }) => sql`INSERT INTO ${positions} (event, epoch, last) VALUES (${name}, ${epoch}, ${last})
35
+ ON CONFLICT (event) DO UPDATE SET epoch = excluded.epoch, last = excluded.last`;
36
+ return {
37
+ position: sql`SELECT epoch, last FROM ${positions} WHERE event = ${name}`.pipe(Effect.flatMap(decodePositions), Effect.map((rows) => rows[0]), Effect.orDie),
38
+ put: (position, entry) => Effect.gen(function* () {
39
+ if (entry === void 0) {
40
+ yield* upsertPosition(position);
41
+ return;
42
+ }
43
+ const { at, logged } = entry.stored;
44
+ const value = yield* encode(logged.value).pipe(Effect.catch((error) => Effect.as(Effect.logError(`An occurrence published to the log of event "${name}" does not encode as its payload, and is kept as a gap`, error), null)));
45
+ yield* upsertPosition(position);
46
+ yield* sql`INSERT INTO ${entries} (event, seq, at, key, value)
47
+ VALUES (${name}, ${entry.seq}, ${at}, ${logged.key ?? null}, ${value})`;
48
+ }).pipe(Effect.orDie),
49
+ list: (from, limit) => sql`SELECT seq, at, key, value FROM ${entries}
50
+ WHERE event = ${name} AND seq >= ${from} ORDER BY seq LIMIT ${limit}`.pipe(Effect.flatMap(decodeEntries), Effect.flatMap((rows) => Effect.forEach(rows, ({ seq, at, key, value }) => Effect.map(value === null ? Effect.succeedNone : Effect.option(decode(value)), (decoded) => [seq, {
51
+ at,
52
+ logged: Option.getOrUndefined(Option.map(decoded, (kept) => ({
53
+ value: kept,
54
+ key: key ?? void 0
55
+ })))
56
+ }]))), Effect.orDie),
57
+ deleteThrough: (seq) => Effect.orDie(sql`DELETE FROM ${entries} WHERE event = ${name} AND seq <= ${seq}`),
58
+ transaction: (operation) => Effect.orDie(sql.withTransaction(operation))
59
+ };
60
+ };
61
+ const revisionTable = "effect_actions_event_revision";
62
+ const revisionEpochTable = "effect_actions_event_revision_epoch";
63
+ const changeSignalQuery = `SELECT (SELECT total(count) FROM ${revisionTable}) + (SELECT total(last) FROM ${positionTable}) AS signal`;
64
+ const Counts = Schema.Array(Schema.Struct({ count: Schema.Int }));
65
+ const Epochs = Schema.NonEmptyArray(Schema.Struct({ epoch: Schema.String }));
66
+ const sqlRevisions = (sql) => Effect.gen(function* () {
67
+ const counts = sql(revisionTable);
68
+ const epochs = sql(revisionEpochTable);
69
+ yield* sql`CREATE TABLE IF NOT EXISTS ${counts} (
70
+ name TEXT PRIMARY KEY,
71
+ count BIGINT NOT NULL
72
+ )`;
73
+ yield* sql`CREATE TABLE IF NOT EXISTS ${epochs} (
74
+ id INTEGER PRIMARY KEY CHECK (id = 0),
75
+ epoch TEXT NOT NULL
76
+ )`;
77
+ yield* sql`INSERT INTO ${epochs} (id, epoch) VALUES (0, ${globalThis.crypto.randomUUID()})
78
+ ON CONFLICT (id) DO NOTHING`;
79
+ const [{ epoch }] = yield* sql`SELECT epoch FROM ${epochs}`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Epochs)));
80
+ return {
81
+ epoch: Effect.succeed(epoch),
82
+ get: (name) => sql`SELECT count FROM ${counts} WHERE name = ${name}`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Counts)), Effect.map((rows) => rows[0]?.count ?? 0), Effect.orDie),
83
+ bump: (names) => Array.isReadonlyArrayNonEmpty(names) ? sql`INSERT INTO ${counts} ${sql.insert(Array.map(names, (name) => ({
84
+ name,
85
+ count: 1
86
+ })))}
87
+ ON CONFLICT (name) DO UPDATE SET count = ${counts}.count + 1`.pipe(Effect.asVoid, Effect.orDie) : Effect.void
88
+ };
89
+ });
90
+ export { changeSignalQuery, createLogTables, sqlRevisions, sqlStorage };
@@ -2,6 +2,7 @@ import { Anyone } from "./caller.mjs";
2
2
  import { Any } from "../Event.mjs";
3
3
  import { ErasedAuthorize, ErasedValue, Memoized, Protected } from "./implementation.mjs";
4
4
  import { Fed, Page } from "./pages.mjs";
5
+ import { WebhookHolder } from "./webhooks.mjs";
5
6
  import { Context, Duration, Effect, Layer, Stream } from "effect";
6
7
  /**
7
8
  * An implemented event type, behind its authorizer, as a surface serves it: a poll, whose
@@ -10,16 +11,27 @@ import { Context, Duration, Effect, Layer, Stream } from "effect";
10
11
  */
11
12
  export interface Feed {
12
13
  readonly event: Any;
14
+ /**
15
+ * Whether its stream reads the source again at each page's `nextPoll`, on a timer, as a check
16
+ * source not `notified` and a reached entity's polls do, rather than only when notified or
17
+ * appended to.
18
+ */
19
+ readonly polls: boolean;
13
20
  /**
14
21
  * Releases the `subscription` hook `subscriber`'s polls of `input` hold: present exactly where
15
22
  * its source has a hook, held per subscriber.
16
23
  */
17
24
  readonly release?: ((input: ErasedValue, subscriber: string) => Effect.Effect<void>) | undefined;
18
25
  /**
19
- * Authenticates the subscriber, checks `input` by `Action.InputCheck` and authorizes it, as
20
- * `poll` and `stream` do first.
26
+ * Where its webhook subscriptions are held, in place of the surface's `Webhooks`: present where
27
+ * `ActionEntity.reaching` reaches a protected event, whose entity holds them, so a subscribe
28
+ * goes to that entity with the subscriber's request.
29
+ */
30
+ readonly webhook?: WebhookHolder | undefined;
31
+ /**
32
+ * Authenticates the subscriber and authorizes it, as `poll` and `stream` do first.
21
33
  */
22
- readonly admit: (input: ErasedValue) => Effect.Effect<void, unknown, unknown>;
34
+ readonly admit: Effect.Effect<void, unknown, unknown>;
23
35
  readonly poll: (input: ErasedValue, cursor: string | null, options: PollOptions) => Effect.Effect<Page, unknown, unknown>;
24
36
  /**
25
37
  * Admits the subscriber, then reads the feed from a cursor, as often as a subscription