@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
@@ -0,0 +1,165 @@
1
+ # ActionEntity
2
+
3
+ `ActionEntity` serves an [RPC binding](ActionRpc.md) as an Effect Cluster entity. An entity type is a kind of stateful object, such as a chat room, and an entity id names one of them, such as the room `lobby`. The cluster's `Sharding` runs each entity id in one place at a time, on whatever runtime provides it: a Node or SQL cluster, `TestRunner` in a test, or a host that runs one entity per object. Each call reaches the entity its input names, and that entity builds its own handlers.
4
+
5
+ The example is [shopping-carts](../examples/shopping-carts/), carts on one process over SQLite; the Cloudflare package's chat-rooms runs the same model on Durable Objects. A message the library throws says its fix; for a compiler diagnostic or Effect's own error, search [ActionEntity-failures.md](ActionEntity-failures.md). For one symbol, `grep -rn <symbol> node_modules/@gjermundgaraba/effect-actions/dist/`.
6
+
7
+ ## Define an entity
8
+
9
+ Bind the actions and event types with `ActionRpc.make`, as for any RPC server ([ActionRpc.md](ActionRpc.md#bind-actions-to-rpcs)), then give `ActionEntity.make` the entity type's name, the binding, and a `key`, which reads the entity id from the input: one function of every input, such as `({ cart }) => cart`, so every contract of an entity names its entity in its input. A field one input lacks is a type error.
10
+
11
+ ```ts example=shopping-carts/src/entities.ts
12
+ import * as ActionEntity from "@gjermundgaraba/effect-actions/ActionEntity";
13
+
14
+ import { CartRpc } from "./Rpc.js";
15
+
16
+ export const Cart = ActionEntity.make("Cart", CartRpc, {
17
+ key: ({ cart }) => cart,
18
+ });
19
+ ```
20
+
21
+ Each action is an rpc of the entity, named after it. Each event type is a unary rpc named `<event>/poll`, which answers the occurrences past a cursor, as an HTTP poll does, and `ActionRpc.layer` serves under the same name. The entity is Effect's own `Entity`, so `Entity.makeTestClient` and the rest of Effect's cluster functions take it. What its rpcs send, and why none of its actions' and event types' rpcs is persisted, is on `ActionEntity.make`.
22
+
23
+ An entity may also serve native rpcs of its own, given to `make` as `rpcs`: tells the entity or another entity sends through Effect's `Entity.client`, such as a persisted one annotated `ClusterSchema.Persisted` that the entity sends itself to run later, at the time its payload's `DeliverAt` names. They authenticate nothing, so no surface serves them.
24
+
25
+ ## Serve it
26
+
27
+ `ActionEntity.layer(entity, implementations)` registers the entity with `Sharding`. The implementations are those of the binding's actions and event types, one or a list, as on every surface ([Action.md](Action.md#implement-actions)), and they must cover the whole binding. Provide the layer with what the implementations read at startup, the authentication provider of the binding's descriptor ([Authentication.md](Authentication.md#verify-credentials)), `Event.Events` when the binding has event types, and the cluster's `Sharding`.
28
+
29
+ Each entity id builds the implementations itself, when the cluster first sends it a message, and shares no build with `Action.layer` provided above it. State an implementation's builder holds belongs to that one entity, and a builder may read `Entity.CurrentAddress` for the id it serves. A service provided to the layer is built once per runner and shared by every entity id on it.
30
+
31
+ What each entity id must build for itself, such as a store over its own database or `Event.Events` kept there by `Stored.layerEvents`, goes in the layer's `services` option: each entity id builds it as it activates, before its implementations' builders, which read it. The handlers of `make`'s native rpcs go in the layer's `rpcs` option, as Effect's `Entity.toLayer` takes them: each receives Effect's own `Entity.Request`, and an Effect building them runs after `services`, whose output it reads.
32
+
33
+ A handler, an authorizer or an event source reads per call only its caller and what `services` built; the rules, and what a defect does, are on `ActionEntity.layer`.
34
+
35
+ The example's carts build `CurrentCart` from the entity's address in `services`, and read their items from a store, which the entrypoint provides to the layer, so no state lives in the entity between calls, and the cluster may stop it while idle:
36
+
37
+ ```ts example=shopping-carts/src/routes.ts
38
+ import * as ActionEntity from "@gjermundgaraba/effect-actions/ActionEntity";
39
+ import * as ActionHttp from "@gjermundgaraba/effect-actions/ActionHttp";
40
+ import { Effect, Layer } from "effect";
41
+ import { Entity } from "effect/cluster";
42
+
43
+ import { CartHttp } from "./Api.js";
44
+ import { carts } from "./cart/handlers.js";
45
+ import { CurrentCart } from "./cart/held.js";
46
+ import { Cart } from "./entities.js";
47
+ import { authenticate } from "./identity/verifier.js";
48
+
49
+ const cartOfAddress = Layer.effect(CurrentCart)(
50
+ Effect.map(Entity.CurrentAddress, ({ entityId }) => entityId)
51
+ );
52
+
53
+ export const entities = ActionEntity.layer(Cart, carts, {
54
+ services: cartOfAddress,
55
+ }).pipe(Layer.provide(authenticate));
56
+
57
+ export const routes = ActionHttp.layer(
58
+ CartHttp,
59
+ ActionEntity.reaching(Cart)
60
+ ).pipe(Layer.provide(authenticate));
61
+ ```
62
+
63
+ Its [server.ts](../examples/shopping-carts/src/server.ts) runs both on Effect's `SingleRunner` over one SQLite file.
64
+
65
+ A protected action authenticates each call from the headers its envelope carries, as an RPC message does. Then the input decodes, and an input whose key names another entity is refused with `Forbidden` before the implementation's `authorize` runs.
66
+
67
+ ## Call it
68
+
69
+ `ActionEntity.client(entity)` is Effect's `Entity.client` with one typed method per action, each call sent to the entity its input's key names: `(yield* ActionEntity.client(Room)).postMessage({ room: "lobby", text })`. Send credentials by setting headers with `RpcClient.withHeaders` around a call. The entity's native rpcs stay on Effect's own client, `(yield* Room.client)("lobby")`. What a call fails with is `ActionEntity.MethodError`, and the transport rules are on `ActionEntity.client`.
70
+
71
+ ## Reach it from any surface
72
+
73
+ `ActionEntity.reaching(entity)` returns implementations of the entity's actions and event types that any surface serves beside its own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`, given a binding of the same contracts: each call goes through `Entity.client` to the entity its input's key names, with the caller's headers `ActionEntity.forwardedHeaders` keeps, so one HTTP or MCP endpoint serves every room. The example's `routes` above serve every cart that way.
74
+
75
+ The surface authenticates a protected call with its own binding's descriptor and the entity authenticates it again, so provide the authentication provider to both.
76
+
77
+ An event is followed through the entity's poll rpc, so no watcher holds an entity open; a stream polls it from the surface. What crosses the two hops, and what does not, is on `ActionEntity.reaching`.
78
+
79
+ A server outside the cluster that forwards a socket's calls into the entity, as the Cloudflare package's socket host does, forwards the rpcs of `ActionEntity.bindingRpcs(entity)` alone, never the entity's native rpcs, which authenticate nothing; its clients call them with `ActionRpc.client(binding)`, whose watch polls them.
80
+
81
+ ## Watch an event
82
+
83
+ The client's `watch(event, input, options)` follows an event by polling its rpc, as `Action.client`'s does, so an entity holds no stream open for a watcher and a runtime may put an idle entity to sleep. The rules are on `ActionEntity.client`, and what ends a watch on `ActionEntity.WatchError`.
84
+
85
+ ## Deliver its events by webhook
86
+
87
+ A protected event served through `ActionEntity.reaching` is offered webhook delivery ([Webhook.md](Webhook.md)), held by the entity its input's key names: the surface sends each subscribe and unsubscribe there with the caller's headers, and the entity delivers from the `Webhook.layer` in its layer's `services`. An entity without one refuses the subscribe as `Unsupported`.
88
+
89
+ Give that layer `persist`, so a later activation restores each entity id's subscriptions, and mark a check source over the entity's own store `notified`. The rules, retry waits and refusals included, are on `ActionEntity.LayerOptions`' `services`, and the rpcs carrying a subscription on `ActionEntity.make`.
90
+
91
+ ## Test it
92
+
93
+ Provide the layer with `TestRunner.layer`, the in-memory cluster, and call it through `ActionEntity.client`. A `TestRunner` keeps real time, so run such a test with `it.live`, not `it.effect`. `Entity.makeTestClient` runs the entity with no runner, and its client speaks the rpcs' JSON rather than typed methods. The example's test serves its routes over `Testing.layer` and its entity on `TestRunner`, each test on a fresh in-memory database:
94
+
95
+ ```ts example=shopping-carts/test/routes.test.ts
96
+ import { SqliteClient } from "@effect/sql-sqlite-node";
97
+ import { expect, it } from "@effect/vitest";
98
+ import * as ActionHttp from "@gjermundgaraba/effect-actions/ActionHttp";
99
+ import * as Testing from "@gjermundgaraba/effect-actions/Testing";
100
+ import { Effect, Layer, Result } from "effect";
101
+ import { TestRunner } from "effect/cluster";
102
+ import { HttpClient, HttpClientRequest } from "effect/http";
103
+
104
+ import { CartHttp } from "../src/Api.js";
105
+ import { cartLimit } from "../src/cart/Cart.js";
106
+ import { layerSqlCarts } from "../src/platform/sql-carts.js";
107
+ import { entities, routes } from "../src/routes.js";
108
+
109
+ const server = Testing.layer(routes).pipe(
110
+ Layer.provideMerge(entities),
111
+ Layer.provide([TestRunner.layer, layerSqlCarts]),
112
+ Layer.provide(Layer.orDie(SqliteClient.layer({ filename: ":memory:" })))
113
+ );
114
+
115
+ const shopperAs = (token: string) =>
116
+ ActionHttp.client(CartHttp, {
117
+ transformClient: HttpClient.mapRequest(
118
+ HttpClientRequest.bearerToken(token)
119
+ ),
120
+ });
121
+
122
+ it.live("keeps each cart in the entity its id names, its own shopper's", () =>
123
+ Effect.gen(function* () {
124
+ const ada = yield* shopperAs("ada");
125
+ const grace = yield* shopperAs("grace");
126
+
127
+ yield* ada.addItem({ cart: "ada", item: "tea" });
128
+ yield* grace.addItem({ cart: "grace", item: "milk" });
129
+
130
+ expect(yield* ada.viewCart({ cart: "ada" })).toStrictEqual({
131
+ items: ["tea"],
132
+ });
133
+
134
+ const refused = yield* Effect.flip(
135
+ grace.addItem({ cart: "ada", item: "salt" })
136
+ );
137
+
138
+ expect(refused._tag).toBe("Forbidden");
139
+ expect(yield* grace.viewCart({ cart: "grace" })).toStrictEqual({
140
+ items: ["milk"],
141
+ });
142
+ }).pipe(Effect.provide(server))
143
+ );
144
+
145
+ it.live(
146
+ "adds one item past the cart's limit nowhere, however many arrive at once",
147
+ () =>
148
+ Effect.gen(function* () {
149
+ const ada = yield* shopperAs("ada");
150
+
151
+ const added = yield* Effect.forEach(
152
+ Array.from({ length: cartLimit + 1 }, (_, n) => `item ${n}`),
153
+ (item) => Effect.result(ada.addItem({ cart: "ada", item })),
154
+ { concurrency: "unbounded" }
155
+ );
156
+
157
+ expect(added.filter(Result.isFailure)).toMatchObject([
158
+ { failure: { _tag: "CartFull", limit: cartLimit } },
159
+ ]);
160
+ expect((yield* ada.viewCart({ cart: "ada" })).items).toHaveLength(
161
+ cartLimit
162
+ );
163
+ }).pipe(Effect.provide(server))
164
+ );
165
+ ```
@@ -219,10 +219,6 @@ export const Http = ActionHttp.make(
219
219
 
220
220
  - **Which deployment.** As over MCP, a log source and a `subscription` hook need one server that outlives a request.
221
221
 
222
- ## Serve what another server serves
223
-
224
- `ActionHttp.placed(binding, client)` stands, in a surface's list of implementations, for the binding's actions and event types where another server serves them, such as a Worker in front of the Durable Object that holds the data: each call and subscription is sent on, with the caller's headers, to the server `client` reaches for its input and its contract, which serves them in its own `ActionHttp.layer` of the binding, and its answer is passed back. `ActionHttp.layer`, `ActionMcp.layerHttp` and `ActionRpc.layer` take it beside their own implementations. Both servers verify the credential, so both are given the verifier; the server reached authorizes. Its rules are on `ActionHttp.placed`. An application doing it, a Worker sending each room's calls to its Durable Object, is `@gjermundgaraba/effect-actions-cloudflare`'s chat-rooms, through `ActionDurableObject.placed`: that package's `docs/ActionDurableObject-placement.md`.
225
-
226
222
  ## Call the API from a browser
227
223
 
228
224
  Code outside an Effect builds the client once with `ActionHttp.fetchClient` and runs each call with `Effect.runPromise`. Files: [notes-service/src/browser.ts](../examples/notes-service/src/browser.ts), [kitchen-sink/src/sdk.ts](../examples/kitchen-sink/src/sdk.ts) (a `baseUrl`, two headers).
package/docs/ActionMcp.md CHANGED
@@ -26,7 +26,7 @@ export const routes = Layer.mergeAll(
26
26
 
27
27
  - Claude Code 2.1 and Codex CLI 0.162 connect: `claude mcp add --transport http <name> <url>/mcp --header "Authorization: Bearer <token>"`, `codex mcp add <name> --url <url>/mcp --bearer-token-env-var <VAR>`; [mcp-tools](../examples/mcp-tools/README.md#connect-a-client) has stdio and Claude Desktop.
28
28
  - Where an endpoint without `authentication` listens, and its body limit: [mcp-tools/src/server.ts](../examples/mcp-tools/src/server.ts).
29
- - **On a serverless host**, such as Cloudflare Workers, pass `requestScoped: true`: [notes-service/src/worker.ts](../examples/notes-service/src/worker.ts). For an endpoint in a Cloudflare Durable Object: the `@gjermundgaraba/effect-actions-cloudflare` package's docs.
29
+ - **On a serverless host**, such as Cloudflare Workers, pass `requestScoped: true`: [notes-service/src/worker.ts](../examples/notes-service/src/worker.ts). For an endpoint serving cluster entities on Cloudflare Durable Objects, also `requestScoped`: the `@gjermundgaraba/effect-actions-cloudflare` package's docs.
30
30
  - `McpServer.middleware` and `McpServer.visibility` provided around the endpoint run for its tools and its native features alike. A limit that must hold on every surface goes in the handlers: [kitchen-sink/src/issues/write-limit.ts](../examples/kitchen-sink/src/issues/write-limit.ts).
31
31
 
32
32
  ## Serve tools over stdio
@@ -138,7 +138,7 @@ export const routes = Layer.mergeAll(mcp, api, rpc).pipe(
138
138
 
139
139
  Webhook delivery, `events/subscribe` and `events/unsubscribe`, is `Webhook.layer`'s ([Webhook.md](Webhook.md)), provided to the endpoint.
140
140
 
141
- - **Which deployment.** Push needs a server that outlives a request, so a `requestScoped` endpoint serves events by poll, and by webhook where `Webhook.layer` is provided. Sources, logs, `subscription` hooks' leases and webhook subscriptions are built once with the endpoint, either way. On a host with no lasting process, such as a serverless platform, serve check sources alone, without a `subscription` hook or `Webhook.layer`: nothing refuses the others, and under `Event.layerMemory` each instance keeps its own log of a log source, whose cursors another reads as a gap, and its own leases and webhook subscriptions, lost as it ends.
141
+ - **Which deployment.** Push needs a server that outlives a request, so a `requestScoped` endpoint serves events by poll, and by webhook where `Webhook.layer` is provided or the event is a protected one `ActionEntity.reaching` serves ([ActionEntity.md](ActionEntity.md#deliver-its-events-by-webhook)). Sources, logs, `subscription` hooks' leases and webhook subscriptions are built once with the endpoint, either way. On a host with no lasting process, such as a serverless platform, serve check sources alone, without a `subscription` hook or `Webhook.layer`: nothing refuses the others, and under `Event.layerMemory` each instance keeps its own log of a log source, whose cursors another reads as a gap, and its own leases and webhook subscriptions, lost as it ends.
142
142
 
143
143
  ## Allow browser clients
144
144
 
@@ -1,6 +1,6 @@
1
1
  # Events over rpcs
2
2
 
3
- An [event type](Event.md) in an RPC binding is a stream rpc named after it, taking `{ input, cursor }`, which pushes each occurrence as the server reads it. A client's `watch(event, input, options)` holds it open over the client's protocol, a socket or HTTP, as `Action.client`'s does, and connects again after a drop, resuming from the last occurrence it delivered. Experimental, as [events](Event.md) are.
3
+ An [event type](Event.md) in an RPC binding is a stream rpc named after it, taking `{ input, cursor }`, which pushes each occurrence as the server reads it, beside a unary `<event>/poll` answering a page. A client's `watch(event, input, options)` holds it open over the client's protocol, a socket or HTTP, as `Action.client`'s does, and connects again after a drop, resuming from the last occurrence it delivered. Experimental, as [events](Event.md) are.
4
4
 
5
5
  A message the library throws says its fix; for a compiler diagnostic or Effect's own error, search [ActionRpc-failures.md](ActionRpc-failures.md). For one symbol, `grep -rn <symbol> node_modules/@gjermundgaraba/effect-actions/dist/`.
6
6
 
@@ -106,5 +106,5 @@ export const messageEvents = Event.implement(
106
106
 
107
107
  The page sends the room and its token with the watch: `RpcClient.withHeaders` wraps an Effect, so `browser.ts`'s `messages` sets them around the stream, and so on every request it sends again after a drop ([live-rpc/src/browser.ts](../examples/live-rpc/src/browser.ts)).
108
108
 
109
- - **No poll.** An rpc client holds the stream open; a client that cannot, such as a serverless function, watches over [HTTP](ActionHttp.md#serve-and-watch-events) or MCP.
109
+ - **Stream or poll.** A watch holds the stream open by default, and polls where the server serves no stream rpc, as an [entity](ActionEntity.md) does; one that should not hold it, such as a page whose socket an object holds while it hibernates, watches with `mode: "poll"`, a unary call for each page, which `ActionRpc.layer` and an entity both serve.
110
110
  - **Which deployment.** A notify wakes the watches its process holds, so the process serving the sockets is the one whose `Event.Events` the handlers notify; another process's watches read the post at their next read, 5 seconds on. A log source fed by `emit` and a `subscription` hook need a server that outlives a request, as over MCP.
package/docs/ActionRpc.md CHANGED
@@ -86,7 +86,7 @@ Layer.launch(server).pipe(NodeRuntime.runMain());
86
86
 
87
87
  Where the protocol goes, why one protocol takes one layer, and what a protocol with no router lacks are on `ActionRpc.layer`; the order of `middleware`, and which actions a middleware reading the identity may serve, on `ActionRpc.LayerOptions.middleware`. [kitchen-sink/src/identity/quota.ts](../examples/kitchen-sink/src/identity/quota.ts) is a limit in `middleware`, keyed on the caller, and [kitchen-sink/src/Rpc.ts](../examples/kitchen-sink/src/Rpc.ts) binds the protected actions alone for it.
88
88
 
89
- - **On Cloudflare Workers**, serve the rpcs from a Durable Object, with `@gjermundgaraba/effect-actions-cloudflare`'s `ActionDurableObject.layerWebSocket`.
89
+ - **Actions a cluster entity holds.** `ActionRpc.layer` serves `ActionEntity.reaching(entity)`'s implementations as it serves its own, each call sent to the entity its input names ([ActionEntity.md](ActionEntity.md)). The `@gjermundgaraba/effect-actions-cloudflare` package's example serves its entities over JSON and MCP, and its browser calls them with `ActionRpc.client` over the package's socket host.
90
90
  - **The same actions as JSON too.** Merge `ActionHttp.layer(Http, implementations)` beside the rpc layer, each given its descriptor's provider ([kitchen-sink/src/routes.ts](../examples/kitchen-sink/src/routes.ts) defines both, and [server.ts](../examples/kitchen-sink/src/server.ts) merges them): one provider given to both is built once. The routes need what the rpcs did not: an `httpApiStatus` on a declared error, by the rule on `Action.Options.error`, and router middleware for a service an `RpcMiddleware` provides ([ActionHttp.md](ActionHttp.md#serve-the-routes)).
91
91
  - **An rpc of your own beside the actions.** Give `ActionRpc.make` native rpcs in `rpcs`, `ActionRpc.make(actions, { authentication, rpcs: RpcGroup.make(Upload) })`, each with its own schemas: under the binding's `authentication` each message authenticates as a protected action's does, and the client has their methods beside the actions'. Implement them with the binding's own `Rpc.rpcs.toLayer(handlers)`, whose handlers read the identity and authorize it themselves, and provide that to `ActionRpc.layer`, which otherwise does not compile. The rules are on `ActionRpc.Options.rpcs`.
92
92
  - **An action reporting progress or answering a stream is a stream rpc.** Over a WebSocket, or HTTP under `RpcSerialization.layerNdjson`, its values and elements arrive as sent; under `layerJson` over HTTP, all at the end (`ActionRpc.layer`).
@@ -6,6 +6,7 @@ What you see when something is wrong, and the fix: compiler diagnostics and erro
6
6
 
7
7
  - `Provider<CurrentUser, "notes-service.Login">` among a layer's requirements, `Type 'Provider<...>' is not assignable to type 'never'` at `Layer.launch` or `NodeRuntime.runMain`, or `Expected 2 arguments, but got 1` at a web handler's `handler(request)`: a layer serving protected actions requires the provider of the descriptor it names, and nothing else satisfies it, neither the identity nor another descriptor's provider. Provide it, `Layer.provide(authenticate)` ([Verify credentials](Authentication.md#verify-credentials)).
8
8
  - `Property 'authentication' is missing`, or `No overload matches this call` with `"Protected actions take options naming their authentication"` or `"Authentication descriptor does not cover every protected action"`, at `ActionHttp.make`, `ActionRpc.make` or `ActionMcp.layerHttp`: a protected action is served and no descriptor is named. Give `{ authentication: Login }` ([Declare how callers sign in](Authentication.md#declare-how-callers-sign-in)).
9
+ - `Expected 3 arguments, but got 2`, or `is not assignable to parameter of type 'Options<never>`, at `Authentication.make`: a descriptor names its identity's stable id. Give it `{ principal: (user) => user.id }` ([Declare how callers sign in](Authentication.md#declare-how-callers-sign-in)).
9
10
  - `Type 'Other' is not assignable to type 'CurrentUser'` under `Descriptor<…>`, at `authentication`: the descriptor authenticates another identity than the action's `caller`. Name the descriptor made for the caller's identity service.
10
11
  - `is not assignable to type 'Forbidden | Unauthenticated'`, or `Property '…' is missing in type`, at `layer`'s verifier: it fails with an error that is neither a refusal nor one its descriptor declares, or succeeds with a value that is not the identity. Declare the error in the descriptor's `error`, or map it to a refusal where it is the caller's.
11
12
  - `Request<"Requires", WorkspaceHeader>` still owed although its middleware's layer is provided: it is in one `Layer.provide([...])` array with the provider, and an array's layers provide to the routes, not to one another. Provide it in a later `Layer.provide` of its own ([Read request context in a verifier](Authentication-advanced.md#read-request-context-in-a-verifier)).
@@ -26,7 +26,9 @@ export class CurrentUser extends Context.Service<CurrentUser, User>()(
26
26
  "notes-service/CurrentUser"
27
27
  ) {}
28
28
 
29
- export const Login = Authentication.make("notes-service.Login", CurrentUser);
29
+ export const Login = Authentication.make("notes-service.Login", CurrentUser, {
30
+ principal: (user) => user.id,
31
+ });
30
32
 
31
33
  export const WhoAmI = Action.make("whoAmI", {
32
34
  description: "Show who the credential identifies and which scopes it holds.",
@@ -36,7 +38,7 @@ export const WhoAmI = Action.make("whoAmI", {
36
38
  });
37
39
  ```
38
40
 
39
- Name it in every binding and MCP endpoint that serves a protected action: an HTTP binding ([notes-service/src/Api.ts](../examples/notes-service/src/Api.ts)), an MCP endpoint ([notes-service/src/routes.ts](../examples/notes-service/src/routes.ts)) and an RPC binding ([live-rpc/src/Rpc.ts](../examples/live-rpc/src/Rpc.ts)); a local surface takes none ([Action.md](Action.md#say-who-may-call-an-action)). The name's rules are on `Authentication.make`, the scheme's on `Authentication.Options.security`; a second credential for one identity is in [kitchen-sink/src/identity/Identity.ts](../examples/kitchen-sink/src/identity/Identity.ts). A descriptor of protected [events](Event.md) may also say which subscriber an identity is, its `principal`, for what a surface holds between one subscriber's requests: [build-events/src/identity/Identity.ts](../examples/build-events/src/identity/Identity.ts). When it is required is on `Authentication.Options.principal`; its `schema`, which keeps an identity past a restart, on `Authentication.Options.schema`.
41
+ Name it in every binding and MCP endpoint that serves a protected action: an HTTP binding ([notes-service/src/Api.ts](../examples/notes-service/src/Api.ts)), an MCP endpoint ([notes-service/src/routes.ts](../examples/notes-service/src/routes.ts)) and an RPC binding ([live-rpc/src/Rpc.ts](../examples/live-rpc/src/Rpc.ts)); a local surface takes none ([Action.md](Action.md#say-who-may-call-an-action)). The name's rules are on `Authentication.make`, the scheme's on `Authentication.Options.security`; a second credential for one identity is in [kitchen-sink/src/identity/Identity.ts](../examples/kitchen-sink/src/identity/Identity.ts). Its `principal` names the stable id of an identity, which a surface keys each caller's [event](Event.md) subscriptions and idempotency keys by; what it must tell apart is on `Authentication.Options.principal`. A descriptor of protected events delivered by webhook may also give a `schema`, which keeps an identity past a restart, on `Authentication.Options.schema`: [build-events/src/identity/Identity.ts](../examples/build-events/src/identity/Identity.ts).
40
42
 
41
43
  - **Protecting an action that tests already call breaks them**, at compile time ([Testing-failures.md](Testing-failures.md), [Authentication-failures.md](Authentication-failures.md#types-and-startup)), and a call over HTTP without a credential gets `Unauthenticated` at run time.
42
44
 
package/docs/Event.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Event
2
2
 
3
- `Event.make` defines an event type: something that happens, which subscribers receive as it happens, each subscription selecting with its own arguments. `Event.implement` binds it to the source its occurrences come from, behind an authorizer. Event implementations go in the same list as action implementations: `Action.client` watches them in process; an MCP endpoint ([ActionMcp.md](ActionMcp.md#serve-events)), HTTP routes ([ActionHttp.md](ActionHttp.md#serve-and-watch-events)) and rpcs ([ActionRpc-events.md](ActionRpc-events.md)) serve them; a server POSTs them to a subscriber's callback by webhook ([Webhook.md](Webhook.md)); and a CLI watches them ([ActionCli.md](ActionCli.md#watch-events)). Events are experimental: their surfaces follow MCP's events extension, SEP-3415, a draft, and may change with it.
3
+ `Event.make` defines an event type: something that happens, which subscribers receive as it happens, each subscription selecting with its own arguments. `Event.implement` binds it to the source its occurrences come from, behind an authorizer. Event implementations go in the same list as action implementations: `Action.client` watches them in process; an MCP endpoint ([ActionMcp.md](ActionMcp.md#serve-events)), HTTP routes ([ActionHttp.md](ActionHttp.md#serve-and-watch-events)) and rpcs ([ActionRpc-events.md](ActionRpc-events.md)) serve them, and a cluster entity serves them as polls alone ([ActionEntity.md](ActionEntity.md#watch-an-event)); a server POSTs them to a subscriber's callback by webhook ([Webhook.md](Webhook.md)); and a CLI watches them ([ActionCli.md](ActionCli.md#watch-events)). Events are experimental: their surfaces follow MCP's events extension, SEP-3415, a draft, and may change with it.
4
4
 
5
5
  A message the library throws says its fix; for a compiler diagnostic or Effect's own error, search [Event-failures.md](Event-failures.md). For one symbol, `grep -rn <symbol> node_modules/@gjermundgaraba/effect-actions/dist/`: each declaration's JSDoc carries its rules and gotchas, and this page only what an example cannot show.
6
6
 
@@ -159,7 +159,7 @@ export const buildEvents = Event.implement(
159
159
 
160
160
  [build-events/src/builds/store.ts](../examples/build-events/src/builds/store.ts) is the store. What a check answers for a first subscription and a stale cursor is on `Event.Page`; the rest of a check's rules are on `Event.Check`.
161
161
 
162
- A subscriber holding a stream open is read again every 5 seconds. Where the application writes the store itself, it wakes them at once: after the write, `Event.Events`' `notify`, as [build-events/src/builds/handlers.ts](../examples/build-events/src/builds/handlers.ts) does after each build finishes. A store another process writes is read at the next poll; when a Durable Object reads it is on the Cloudflare package's `ActionDurableObject.handlers`.
162
+ A subscriber holding a stream open is read again every 5 seconds. Where the application writes the store itself, it wakes them at once: after the write, `Event.Events`' `notify`, as [build-events/src/builds/handlers.ts](../examples/build-events/src/builds/handlers.ts) does after each build finishes. A store another process writes is read at the next poll.
163
163
 
164
164
  - **Check what a subscriber may see where the data is read**, as an action's handler does: `authorize` decides whether it may subscribe at all, and receives the event type, not the subscription's input.
165
165
 
@@ -227,9 +227,9 @@ export const deployEvents = Event.implement(
227
227
  );
228
228
  ```
229
229
 
230
- The action publishes each request with `Event.Events`' `publish`, in [build-events/src/deploys/handlers.ts](../examples/build-events/src/deploys/handlers.ts). An upstream that is a stream, such as a message bus, gives it as `log.emit`, each occurrence with the `key` `publish` would take, which the library consumes from the start of a surface serving its event type: kitchen-sink's [issues/events.ts](../examples/kitchen-sink/src/issues/events.ts). How much the log keeps, and what a cursor from another process or a restart reads as, are on `Event.Log`.
230
+ The action publishes each request with `Event.Events`' `publish`, in [build-events/src/deploys/handlers.ts](../examples/build-events/src/deploys/handlers.ts). An upstream that is a stream, such as a message bus, gives it as `log.emit`, each occurrence with the `key` `publish` would take, which the library consumes from the start of a surface serving its event type: kitchen-sink's [issues/events.ts](../examples/kitchen-sink/src/issues/events.ts). How much the log keeps, and what a cursor from another process or a restart reads as under each `Event.Events`, are on `Event.Log`.
231
231
 
232
- - **Prefer `check` wherever the upstream keeps a cursor of its own**: a subscriber then resumes after a restart without a gap.
232
+ - **Prefer `check` wherever the upstream keeps a cursor of its own**: a subscriber then resumes after a restart without a gap, whichever `Event.Events` the host provides.
233
233
 
234
234
  ## Set up a subscription upstream
235
235
 
@@ -237,7 +237,7 @@ When each subscription needs something set up upstream while it lasts, such as j
237
237
 
238
238
  ## Announce to the subscribers
239
239
 
240
- `Event.Events` is where occurrences are announced as they happen: `notify` for a check source, `publish` for a log source. Domain code yields it as it yields a store, and the entrypoint provides one, `Event.layerMemory`, around both the handlers that announce and the surfaces that serve, as [build-events/src/server.ts](../examples/build-events/src/server.ts) does; a host keeping logs elsewhere builds its own with `Event.makeEvents`, as the Cloudflare package's `ActionDurableObject.make` does. A source's `key`, such as the room a subscriber follows, lets an announcement given that key reach that room's subscribers alone, as [live-rpc/src/chat/events.ts](../examples/live-rpc/src/chat/events.ts) keys its messages by room. The rules are on `Event.Events`.
240
+ `Event.Events` is where occurrences are announced as they happen: `notify` for a check source, `publish` for a log source. Domain code yields it as it yields a store, and the entrypoint provides one, `Event.layerMemory`, around both the handlers that announce and the surfaces that serve, as [build-events/src/server.ts](../examples/build-events/src/server.ts) does. A host whose subscribers must outlive a restart, such as a cluster entity on its own SQLite, provides `Stored.layerEvents` over its `SqlClient` instead: logs, their cursors and check and current sources' revisions are kept in tables there, and a watch resumed from a cursor after a restart receives every occurrence past it within the log's bounds, `maxAge` (10 minutes by default) and `maxEvents`. A source's `key`, such as the room a subscriber follows, lets an announcement given that key reach that room's subscribers alone, as [live-rpc/src/chat/events.ts](../examples/live-rpc/src/chat/events.ts) keys its messages by room. The rules are on `Event.Events`.
241
241
 
242
242
  ## Watch in process
243
243
 
package/docs/README.md CHANGED
@@ -28,13 +28,14 @@ Where things are, in a project that installs the package: these pages in `node_m
28
28
  | [ActionMcp.md](ActionMcp.md) | serve MCP tools over HTTP or stdio, describe them to a model, return images, protect them, serve events, allow browser clients, add prompts and resources, send notifications |
29
29
  | [ActionRpc.md](ActionRpc.md) | bind actions to Effect rpcs, serve them on a protocol, call them, add native rpcs, send request context with a call |
30
30
  | [ActionRpc-events.md](ActionRpc-events.md) | serve and watch events over rpcs, follow what a request names, such as a room |
31
+ | [ActionEntity.md](ActionEntity.md) | serve an RPC binding as an Effect Cluster entity, each call in the entity its input names; call it, serve it from any surface by key, watch its events by polling, test it on a `TestRunner` |
31
32
  | [ActionToolkit.md](ActionToolkit.md) | give a model actions as a native Effect AI `Toolkit`, show it images, name the caller, ask for approval |
32
33
  | [ActionCli.md](ActionCli.md) | run actions as local commands, or call a server from commands; watch events; shape flags, input and output; name the caller; add a command of your own |
33
34
  | [Webhook.md](Webhook.md) | deliver events to a subscriber's callback by webhook, signed, and watch by webhook |
34
35
  | [Authentication.md](Authentication.md) | declare how callers sign in, verify credentials, publish OAuth discovery, step up for a scope |
35
36
  | [Authentication-advanced.md](Authentication-advanced.md) | use an API key or a cookie, read the request in a verifier, protect a route of your own, run a request policy before authentication |
36
37
  | [Testing.md](Testing.md) | test an implementation in process, and routes, tools and rpcs in memory, as a signed-in caller; test events and webhooks; assert on errors |
37
- | `@gjermundgaraba/effect-actions-cloudflare`'s `docs/README.md` | serve actions, events and Effect rpcs from Cloudflare Durable Objects: install that package; its pages and example are in its own `node_modules` folder |
38
+ | `@gjermundgaraba/effect-actions-cloudflare`'s `docs/README.md` | run actions and events in Cloudflare Durable Objects as cluster entities, served by a Worker over JSON and MCP: install that package; its pages and example are in its own `node_modules` folder |
38
39
 
39
40
  ## Examples
40
41
 
@@ -45,6 +46,7 @@ Where things are, in a project that installs the package: these pages in `node_m
45
46
  | [mcp-tools](../examples/mcp-tools/) | An MCP server whose tools wrap an upstream HTTP API, over stdio and over HTTP, with an image result. | You are putting an existing API in front of a model. |
46
47
  | [assistant](../examples/assistant/) | No server: the same implementations as a model's tools, with approval of writes, and as local commands. | A model calls your code in process, or you are building a local CLI. |
47
48
  | [live-rpc](../examples/live-rpc/) | Effect RPC over a WebSocket with a browser-shaped client, each message carrying its own token. | A client keeps a connection open, or the application speaks Effect RPC. |
49
+ | [shopping-carts](../examples/shopping-carts/) | Carts as Effect Cluster entities, one place and one call at a time each, reached from JSON routes, on one process over SQLite. | Each of many stateful objects, such as a cart or a room, must handle its calls in order. |
48
50
  | [build-events](../examples/build-events/) | A CI service whose members watch events over MCP, HTTP, RPC and a CLI: one read by cursor, one pushed upstream. | Something happens that subscribers should hear about. |
49
51
  | [kitchen-sink](../examples/kitchen-sink/) | The reference: a multi-tenant issue tracker using every module and nearly every option, with an index. | You need a working use of one specific feature. |
50
52
 
@@ -56,12 +58,13 @@ The index in [kitchen-sink](../examples/kitchen-sink/README.md#index) maps every
56
58
  | --- | --- |
57
59
  | Speak JSON over HTTP | `ActionHttp`; clients use `ActionHttp.client`, or `ActionHttp.fetchClient` outside an Effect |
58
60
  | Are Effect programs, such as a page over one WebSocket | `ActionRpc`; clients use `ActionRpc.client` |
61
+ | Reach a stateful object, such as a room, that an Effect Cluster places | `ActionEntity`; clients use `ActionEntity.client`, and any surface serves it with `ActionEntity.reaching` |
59
62
  | Are MCP clients | `ActionMcp.layerHttp` for a hosted endpoint, `ActionMcp.runStdio` for a subprocess, which runs the handlers itself |
60
63
  | Are a model in the same process | `ActionToolkit` |
61
64
  | Are people or scripts in a terminal | `ActionCli`: `make` runs handlers locally, `remote` calls a server through its HTTP binding |
62
65
  | Are your own code in the same process, such as a job or a test | `Action.client` |
63
66
 
64
- Surfaces combine: every one that runs handlers takes the same implementations, one or a list, and enforces each contract's `caller` and its implementation's `authorize` ([Action.md](Action.md#authorize-calls)). What a call answers on each surface, a success, bad input, a declared error, a refusal or a defect, is on `ActionHttp.layer`, `ActionMcp.layerHttp` and `runStdio`, `ActionRpc.layer`, `ActionToolkit.make`, `ActionCli.command`, each typed client, and each built-in error: grep the symbol.
67
+ Surfaces combine: every one that runs handlers takes the same implementations, one or a list, and enforces each contract's `caller` and its implementation's `authorize` ([Action.md](Action.md#authorize-calls)). What a call answers on each surface, a success, bad input, a declared error, a refusal or a defect, is on `ActionHttp.layer`, `ActionMcp.layerHttp` and `runStdio`, `ActionRpc.layer`, `ActionEntity.layer`, `ActionToolkit.make`, `ActionCli.command`, each typed client, and each built-in error: grep the symbol.
65
68
 
66
69
  ## What the library leaves to you
67
70
 
package/docs/Webhook.md CHANGED
@@ -62,7 +62,7 @@ The layer needs an `HttpClient` to POST, `Dns` to check where each callback reso
62
62
 
63
63
  Its options, how long a subscription is granted, which callbacks skip the handshake and the address check, and how long a failing delivery is retried, are `Webhook.Options`; what each POST holds is on `layer`.
64
64
 
65
- - **Which deployment.** Subscriptions are delivered from the server's memory, so a long-lived process serves them and a serverless host cannot; a Cloudflare Durable Object can, with `@gjermundgaraba/effect-actions-cloudflare`'s `ActionDurableObject.layerWebhooks`. A restart drops them until each subscriber's next refresh, unless the layer keeps them: `Webhook.layer({ persist: true })` writes each to the application's `KeyValueStore`, and each surface restores its own as it builds, the subscriber's identity kept by its authentication's `schema`, as `server.ts` and [build-events/src/identity/Identity.ts](../examples/build-events/src/identity/Identity.ts) show. What a restored delivery lacks is on `Webhook.Options.persist`. The layer is its store's one writer: give each process a store of its own, since replicas sharing one would each deliver every subscription and lose each other's writes.
65
+ - **Which deployment.** Subscriptions are delivered from the server's memory, so a long-lived process serves them and a serverless host cannot; an event served through `ActionEntity.reaching` is held and delivered by the entity its input names ([ActionEntity.md](ActionEntity.md#deliver-its-events-by-webhook)). A restart drops them until each subscriber's next refresh, unless the layer keeps them: `Webhook.layer({ persist: true })` writes each to the application's `KeyValueStore`, and each surface restores its own as it builds, the subscriber's identity kept by its authentication's `schema`, as `server.ts` and [build-events/src/identity/Identity.ts](../examples/build-events/src/identity/Identity.ts) show. What a restored delivery lacks is on `Webhook.Options.persist`. The layer is its store's one writer: give each process a store of its own, since replicas sharing one would each deliver every subscription and lose each other's writes.
66
66
 
67
67
  ## Subscribe a callback
68
68
 
@@ -8,5 +8,5 @@ What you see when something is wrong, and the fix. Search for a fragment of the
8
8
  - A page that loads Effect from an import map still bundles a second copy of Effect or of some of its modules, or fails to resolve `effect/Schema` in the browser when its bundler externalizes subpaths, as esbuild's `--external:effect` does: a module of the page imports an Effect specifier the map does not serve. Serve the specifiers [Bundle for a browser](setup.md#bundle-for-a-browser) lists, and import Effect through them in the page's own modules too.
9
9
  - A page loading Effect from an import map fails with `Failed to resolve module specifier "effect/Cause"` in Chromium: the map points at Effect's published files and lacks a specifier Effect imports itself. Map `effect/Cause`, `effect/Effect`, `effect/Exit` and `effect/Function` to the same files, or serve Effect from a build that resolves its own imports.
10
10
  - A page fails at load with `does not provide an export named …`: it serves only the names it uses of an Effect specifier, from a vendored module or a trimmed bundle, and the package imports another. Serve each specifier whole.
11
- - Type errors inside `effect/*` modules after install, an unmet peer warning for `effect`, such as `found 4.2.0`, or a start failing with `Cannot find module '…/effect/dist/…'` under an `@effect/*` package: more than one Effect release is installed, or one outside the peer range. Install the `effect` range [Install](setup.md#install) names, with every `@effect/*` package at the version `effect` resolved to, such as `@effect/platform-node@4.1.1` beside `effect@4.1.1`.
11
+ - Type errors inside `effect/*` modules after install, an unmet peer warning for `effect`, such as `found 4.2.0`, or a start failing with `Cannot find module '…/effect/dist/…'` under an `@effect/*` package: more than one Effect release is installed, or one outside the peer range. Install the `effect` range [Install](setup.md#install) names, with every `@effect/*` package at the version `effect` resolved to, such as `@effect/platform-node@4.1.4` beside `effect@4.1.4`.
12
12
  - `Cannot find module 'effect/unstable/http'` (or `…/httpapi`, `…/cli`, `…/ai`): these modules are now `effect/http`, `effect/http-api`, `effect/cli` and `effect/ai`.
package/docs/setup.md CHANGED
@@ -7,20 +7,21 @@ A message the library throws says its fix; for a compiler diagnostic or Effect's
7
7
  ## Install
8
8
 
9
9
  ```sh
10
- pnpm add @gjermundgaraba/effect-actions effect@~4.1.1
10
+ pnpm add @gjermundgaraba/effect-actions effect@~4.1.4
11
11
  ```
12
12
 
13
13
  | Need | Add |
14
14
  | --- | --- |
15
- | Node HTTP server, stdio host or CLI | `@effect/platform-node@~4.1.1` |
16
- | Tests | `vitest@^5` and `@effect/vitest@~4.1.1`, as dev dependencies |
15
+ | Node HTTP server, stdio host or CLI | `@effect/platform-node@~4.1.4` |
16
+ | `Stored`'s event logs and idempotency on Node's SQLite, or an entity's storage on Effect's SQL runners | `@effect/sql-sqlite-node@~4.1.4` |
17
+ | Tests | `vitest@^5` and `@effect/vitest@~4.1.4`, as dev dependencies |
17
18
  | Type checking | `typescript@^7.0.2`, as a dev dependency |
18
19
  | Node's types, for `node:` imports | `@types/node`, as a dev dependency |
19
20
  | Running a TypeScript entrypoint | `tsx`, as a dev dependency: `node --import tsx <entrypoint>.ts` |
20
21
 
21
22
  The `effect` peer admits the 4.1.x patches from the oldest whose APIs and behavior the package relies on, and no minor release: a minor release may change the unstable Effect modules the surfaces build on.
22
23
 
23
- Keep the tilde in `package.json`: `^4.1.1`, which npm writes for `effect@4.1.1`, admits a minor release outside the peer range. `npm install effect@~4.1.1` keeps it.
24
+ Keep the tilde in `package.json`: `^4.1.4`, which npm writes for `effect@4.1.4`, admits a minor release outside the peer range. `npm install effect@~4.1.4` keeps it.
24
25
 
25
26
  Node `>=26.13.0`: the package's `engines`, the Node the library is developed and tested on. TypeScript 7 or newer. ESM only. The repository checks the examples with a stricter `tsconfig.json`; this is the minimum a project needs. The package's modules resolve only through its `exports`, which `"module": "nodenext"` reads, as a bundler project's `"moduleResolution": "bundler"` does. `"strict": true` is required, by Effect:
26
27
 
@@ -41,7 +42,7 @@ Node `>=26.13.0`: the package's `engines`, the Node the library is developed and
41
42
 
42
43
  ## Entry points
43
44
 
44
- There is no package root. Import one module per subpath, as a namespace, `import * as Action from "@gjermundgaraba/effect-actions/Action"`. The modules: `RequestPolicy`, `Action`, `Event`, `ActionHttp`, `ActionMcp`, `ActionRpc`, `ActionToolkit`, `ActionCli`, `Authentication`, `Webhook`, `Testing`.
45
+ There is no package root. Import one module per subpath, as a namespace, `import * as Action from "@gjermundgaraba/effect-actions/Action"`. The modules: `RequestPolicy`, `Action`, `Event`, `ActionHttp`, `ActionMcp`, `ActionRpc`, `ActionEntity`, `ActionToolkit`, `ActionCli`, `Authentication`, `Webhook`, `Stored`, `Testing`.
45
46
 
46
47
  Effect's own modules are subpaths of `effect` too: `effect/http` (`HttpRouter`, `HttpClient`, `FetchHttpClient`), `effect/http-api` (`OpenApi`, `HttpApiMiddleware`), `effect/rpc` (`RpcServer`, `RpcClient`), `effect/ai` (`LanguageModel`, `Chat`), `effect/cli` (`Command`) and `effect/socket` (`Socket`).
47
48
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Complete applications built with `@gjermundgaraba/effect-actions`. Each is a directory you can run, with its own tests and a README that says what it shows and where. They are type-checked, linted and tested with the library, and they ship in the package, at `node_modules/@gjermundgaraba/effect-actions/examples`.
4
4
 
5
- [quickstart](quickstart/), [notes-service](notes-service/), [mcp-tools](mcp-tools/), [assistant](assistant/), [live-rpc](live-rpc/), [build-events](build-events/) and [kitchen-sink](kitchen-sink/): which to start from, by what you are building, is the table in [docs/README.md](../docs/README.md#examples).
5
+ [quickstart](quickstart/), [notes-service](notes-service/), [mcp-tools](mcp-tools/), [assistant](assistant/), [live-rpc](live-rpc/), [shopping-carts](shopping-carts/), [build-events](build-events/) and [kitchen-sink](kitchen-sink/): which to start from, by what you are building, is the table in [docs/README.md](../docs/README.md#examples).
6
6
 
7
7
  ## Run one
8
8
 
@@ -24,6 +24,7 @@ export const OperatorKey = Authentication.make(
24
24
  "tracker.OperatorKey",
25
25
  Operator,
26
26
  {
27
+ principal: (operator) => operator.id,
27
28
  security: HttpApiSecurity.apiKey({ in: "header", key: "x-operator-key" }),
28
29
  }
29
30
  );
@@ -26,12 +26,16 @@ export class IssuerUnavailable extends Schema.TaggedError<
26
26
  { httpApiStatus: 503 }
27
27
  ) {}
28
28
 
29
+ const principal = (member: Member) =>
30
+ JSON.stringify([member.workspace, member.id]);
31
+
29
32
  export const Login = Authentication.make("tracker.Login", CurrentMember, {
30
33
  error: IssuerUnavailable,
31
- principal: (member) => JSON.stringify([member.workspace, member.id]),
34
+ principal,
32
35
  });
33
36
 
34
37
  export const Session = Authentication.make("tracker.Session", CurrentMember, {
38
+ principal,
35
39
  security: HttpApiSecurity.apiKey({ in: "cookie", key: "tracker_session" }),
36
40
  });
37
41
 
@@ -10,4 +10,6 @@ export class CurrentMember extends Context.Service<CurrentMember, Member>()(
10
10
  "live-rpc/CurrentMember"
11
11
  ) {}
12
12
 
13
- export const Login = Authentication.make("live-rpc.Login", CurrentMember);
13
+ export const Login = Authentication.make("live-rpc.Login", CurrentMember, {
14
+ principal: (member) => member.id,
15
+ });
@@ -15,7 +15,9 @@ export class CurrentUser extends Context.Service<CurrentUser, User>()(
15
15
  "notes-service/CurrentUser"
16
16
  ) {}
17
17
 
18
- export const Login = Authentication.make("notes-service.Login", CurrentUser);
18
+ export const Login = Authentication.make("notes-service.Login", CurrentUser, {
19
+ principal: (user) => user.id,
20
+ });
19
21
 
20
22
  export const WhoAmI = Action.make("whoAmI", {
21
23
  description: "Show who the credential identifies and which scopes it holds.",
@@ -0,0 +1,46 @@
1
+ # shopping-carts
2
+
3
+ Shopping carts as Effect Cluster entities: each cart is one entity id of the `Cart` entity, which runs in one place at a time and one call at a time. Shoppers add items to their own cart and list it over JSON routes, which reach the cart the input names through `ActionEntity.reaching`. The server is one process, Effect's `SingleRunner`, keeping the cluster's messages and the carts in one SQLite file. The same entities on Cloudflare Durable Objects are the Cloudflare package's chat-rooms example.
4
+
5
+ ## Run it
6
+
7
+ From the repository root, after `vp install` (from an installed package, see [Run one](../README.md#run-one)):
8
+
9
+ ```sh
10
+ node --import tsx examples/shopping-carts/src/server.ts # 127.0.0.1:3000, writes shopping-carts.db
11
+ vp test examples/shopping-carts
12
+ ```
13
+
14
+ Beside what [Run one](../README.md#run-one) lists, it needs `@effect/sql-sqlite-node`. The tokens are fixed names (`ada`, `grace`): replace them, and the database's path, before deploying anything.
15
+
16
+ ## When you copy this
17
+
18
+ Each trap below is shown in the code of the files it names.
19
+
20
+ - **A cart is its entity's id, and its shopper's own**: the handlers and their rule read `CurrentCart`, which `routes.ts` builds from `Entity.CurrentAddress`, so another shopper's call reaches that cart and is refused: `src/cart/handlers.ts`, `src/routes.ts`.
21
+ - **A cart's limit needs no lock**: an entity id runs one call at a time, so reading the items and adding one never interleave: `src/cart/handlers.ts`.
22
+ - **The items live in the database, not in the entity**: the cluster stops an idle entity and builds it again for its next call: `src/platform/sql-carts.ts`.
23
+ - **One process, one runner**: a cluster of several processes uses Effect's other runners in place of `layerSingleRunner`: `src/platform/cluster.ts`, `src/server.ts`.
24
+
25
+ ## Layout
26
+
27
+ ```text
28
+ src/
29
+ ├── cart/
30
+ │ ├── Cart.ts contract: the actions and CartFull
31
+ │ ├── held.ts CurrentCart, the cart an entity holds: a startup service
32
+ │ ├── store.ts CartStore, the service the handlers call
33
+ │ └── handlers.ts Action.implement: contract to store, and the one authorization rule
34
+ ├── identity/
35
+ │ ├── Identity.ts contract: CurrentShopper and the Login descriptor
36
+ │ ├── shoppers.ts the demo shoppers
37
+ │ └── verifier.ts Authentication.layer: tokens to shoppers, server only
38
+ ├── platform/
39
+ │ ├── sql-carts.ts CartStore over a SqlClient
40
+ │ └── cluster.ts SingleRunner, the cluster in one process over that SqlClient
41
+ ├── Api.ts, Rpc.ts the HTTP binding, and the RPC binding the entity serves
42
+ ├── entities.ts Cart, the entity: which cart each action's input names
43
+ ├── routes.ts the entity's layer, and the JSON routes reaching it
44
+ └── server.ts entrypoint: both, with CartStore over SQL, on SingleRunner and one SQLite file
45
+ test/routes.test.ts the routes and the entity, in memory on TestRunner
46
+ ```
@@ -0,0 +1,9 @@
1
+ import * as ActionHttp from "@gjermundgaraba/effect-actions/ActionHttp";
2
+
3
+ import { Carts } from "./cart/Cart.js";
4
+ import { Login } from "./identity/Identity.js";
5
+
6
+ export const CartHttp = ActionHttp.make(Carts, {
7
+ prefix: "/api",
8
+ authentication: Login,
9
+ });
@@ -0,0 +1,6 @@
1
+ import * as ActionRpc from "@gjermundgaraba/effect-actions/ActionRpc";
2
+
3
+ import { Carts } from "./cart/Cart.js";
4
+ import { Login } from "./identity/Identity.js";
5
+
6
+ export const CartRpc = ActionRpc.make(Carts, { authentication: Login });
@@ -0,0 +1,47 @@
1
+ import * as Action from "@gjermundgaraba/effect-actions/Action";
2
+ import { Schema } from "effect";
3
+
4
+ import { CurrentShopper } from "../identity/Identity.js";
5
+
6
+ export const cartLimit = 10;
7
+
8
+ export class CartFull extends Schema.TaggedError<
9
+ CartFull,
10
+ { readonly brand: unique symbol }
11
+ >()(
12
+ "CartFull",
13
+ { cart: Schema.String, limit: Schema.Int },
14
+ { httpApiStatus: 409 }
15
+ ) {}
16
+
17
+ const inCart = {
18
+ cart: Schema.String.annotate({
19
+ description: "The cart's id, which is its shopper's id.",
20
+ }),
21
+ };
22
+
23
+ const items = { items: Schema.Array(Schema.String) };
24
+
25
+ const signedIn = { caller: CurrentShopper } as const;
26
+
27
+ export const AddItem = Action.make("addItem", {
28
+ ...signedIn,
29
+ description: `Add an item to the cart, which holds at most ${cartLimit}.`,
30
+ input: {
31
+ ...inCart,
32
+ item: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(100)),
33
+ },
34
+ success: items,
35
+ error: CartFull,
36
+ readOnly: false,
37
+ });
38
+
39
+ export const ViewCart = Action.make("viewCart", {
40
+ ...signedIn,
41
+ description: "List the cart's items, oldest first.",
42
+ input: inCart,
43
+ success: items,
44
+ readOnly: true,
45
+ });
46
+
47
+ export const Carts = [AddItem, ViewCart] as const;