@gjermundgaraba/effect-actions 0.35.0 → 0.36.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.
@@ -2,6 +2,13 @@ import { Effect } from "effect";
2
2
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
3
3
  // src/http/RequestPolicy.ts
4
4
  const uncheckedProbePath = "/healthz";
5
+ const authorityOf = (target) => {
6
+ const authority = target.indexOf("://");
7
+ if (authority === -1) return;
8
+ const rest = target.slice(authority + 3);
9
+ const stop = rest.search(/[/?#]/u);
10
+ return stop === -1 ? rest : rest.slice(0, stop);
11
+ };
5
12
  const pathOf = (target) => {
6
13
  const authority = target.indexOf("://");
7
14
  const start = authority === -1 ? 0 : target.indexOf("/", authority + 3);
@@ -12,28 +19,33 @@ const pathOf = (target) => {
12
19
  };
13
20
  const forbidden = HttpServerResponse.text("Forbidden", { status: 403 });
14
21
  /**
15
- * Build a Host/Origin policy once at startup. `allows` takes no services, so a
16
- * raw request or Node upgrade handler applies the same rule as the router.
22
+ * Build a Host/Origin policy once at startup. `allows` takes a web `Request` and no
23
+ * services, so a Worker's `fetch` or a raw web handler applies the same rule as the router.
17
24
  * The middleware answers refused requests with status 403 and text `Forbidden`.
18
25
  *
19
26
  * **Gotchas**
20
27
  * - `/healthz` is unchecked, including its query and fragment; do not serve application data there.
21
28
  * - Provide `middleware.layer` to every route layer to protect; it is not global middleware.
22
29
  * - This checks browser request headers, not caller identity; access control belongs to the application or its network.
30
+ * - A request sending no Host header is judged by its absolute target's host, as a Worker's in-process `fetch` sends one; a Node server's path-only target has none, and is refused.
23
31
  */
24
32
  const make = (options) => {
25
33
  const { host } = options.publicUrl;
26
34
  const origins = /* @__PURE__ */ new Set([options.publicUrl.origin, ...options.allowedOrigins ?? []]);
27
- const allows = (request) => {
35
+ const decide = (request) => {
28
36
  if (pathOf(request.target) === uncheckedProbePath) return true;
29
- if (request.host !== host) return false;
37
+ if ((request.host ?? authorityOf(request.target)) !== host) return false;
30
38
  return request.origin === void 0 || origins.has(request.origin);
31
39
  };
32
40
  return {
33
- allows,
41
+ allows: (request) => decide({
42
+ target: request.url,
43
+ host: request.headers.get("host") ?? void 0,
44
+ origin: request.headers.get("origin") ?? void 0
45
+ }),
34
46
  middleware: HttpRouter.middleware((httpEffect) => Effect.gen(function* () {
35
47
  const request = yield* HttpServerRequest.HttpServerRequest;
36
- return allows({
48
+ return decide({
37
49
  target: request.originalUrl,
38
50
  host: request.headers["host"],
39
51
  origin: request.headers["origin"]
@@ -1,6 +1,7 @@
1
1
  import { jsonRoundTrip } from "./call.mjs";
2
2
  import { Anyone } from "./caller.mjs";
3
- import { canonicalInput } from "./canonical.mjs";
3
+ import { canonical, canonicalInput } from "./canonical.mjs";
4
+ import { sha256Hex } from "./digest.mjs";
4
5
  import { Unauthenticated } from "./errors.mjs";
5
6
  import { Events, attachmentsOf, reaches } from "./hub.mjs";
6
7
  import { builderLayer, memoized, notMadeHere } from "./implementation.mjs";
@@ -10,9 +11,10 @@ import { AnyOccurrence, Gap } from "./occurrence.mjs";
10
11
  import { fedOf, pagedFrom } from "./pages.mjs";
11
12
  import { reported } from "./reported.mjs";
12
13
  import { Wake } from "./wake.mjs";
13
- import { Array, DateTime, Duration, Effect, Layer, Option, Predicate, Stream } from "effect";
14
+ import { Array, DateTime, Duration, Effect, Exit, Layer, Option, Predicate, Stream } from "effect";
14
15
  // src/contract/feed.ts
15
16
  const defaultNextPoll = Duration.seconds(5);
17
+ const shortestNextPoll = Duration.seconds(1);
16
18
  const longestNextPoll = Duration.minutes(5);
17
19
  const logPageSize = 100;
18
20
  const pageLimit = (maxEvents) => Math.min(Math.max(Math.floor(maxEvents), 1), logPageSize);
@@ -45,7 +47,10 @@ const answeredPage = ({ answered, items }) => pageFrom(items, {
45
47
  cursor: answered.cursor,
46
48
  truncated: answered.truncated === true,
47
49
  hasMore: answered.hasMore === true,
48
- nextPoll: Duration.min(Duration.fromInputUnsafe(answered.nextPoll ?? defaultNextPoll), longestNextPoll)
50
+ nextPoll: Duration.clamp(Duration.fromInputUnsafe(answered.nextPoll ?? defaultNextPoll), {
51
+ minimum: shortestNextPoll,
52
+ maximum: longestNextPoll
53
+ })
49
54
  });
50
55
  const checkRun = (event, source, { wakes }) => {
51
56
  const occurrenceOf = occurrencesOf(event);
@@ -68,24 +73,39 @@ const checkRun = (event, source, { wakes }) => {
68
73
  })), cursor, woken, polls)))
69
74
  };
70
75
  };
71
- const currentRun = (event, source, checking) => checkRun(event, {
72
- key: source.key,
73
- notified: true,
74
- check: (input, cursor) => Effect.gen(function* () {
75
- const at = yield* checking.revision(yield* keyOf(source, input));
76
- if (cursor === at) return {
77
- cursor: at,
78
- events: []
79
- };
80
- return {
81
- cursor: at,
82
- events: [{
83
- eventId: at,
84
- data: yield* source.current(input)
85
- }]
86
- };
87
- })
88
- }, checking);
76
+ const currentRun = (event, source, checking) => {
77
+ const sent = jsonRoundTrip(event.payload);
78
+ return checkRun(event, {
79
+ key: source.key,
80
+ notified: true,
81
+ check: (input, cursor) => Effect.gen(function* () {
82
+ const key = yield* keyOf(source, input);
83
+ const at = yield* checking.revision(key);
84
+ const { digest: seen, revision } = cursor?.match(/^(?<digest>[0-9a-f]*)\.(?<revision>.*)$/su)?.groups ?? {};
85
+ if (cursor !== null && revision === at) return {
86
+ cursor,
87
+ events: [],
88
+ nextPoll: source.nextPoll
89
+ };
90
+ const data = yield* source.current(input);
91
+ const snapshot = yield* Effect.exit(sent(data));
92
+ const digest = Exit.isSuccess(snapshot) ? yield* sha256Hex(canonical([
93
+ yield* canonicalInput(event.input, input),
94
+ key ?? null,
95
+ snapshot.value.json
96
+ ])) : "";
97
+ const next = `${digest}.${at}`;
98
+ return {
99
+ cursor: next,
100
+ events: digest === seen ? [] : [{
101
+ eventId: next,
102
+ data: Exit.isSuccess(snapshot) ? snapshot.value.value : data
103
+ }],
104
+ nextPoll: source.nextPoll
105
+ };
106
+ })
107
+ }, checking);
108
+ };
89
109
  const logRun = (event, source, log) => {
90
110
  const occurrenceOf = occurrencesOf(event);
91
111
  const delivered = (input, key, { cursor, at, value: logged }) => Effect.gen(function* () {
@@ -11,23 +11,29 @@ const selectFrom = (served, actions) => {
11
11
  events: select(eventKind, eventsOf(served), listed.events)
12
12
  };
13
13
  };
14
- const servedBy = (kind, what, bound, apps, listed) => {
14
+ const servedBy = (kind, bound, apps, listed) => {
15
15
  const { noun, holds } = kind;
16
16
  if (listed !== void 0) assertHeld(notHeld.byBinding, listed, bound);
17
- const held = apps.flatMap(holds);
18
- if (listed === void 0 && apps.length > 0 && !held.some((contract) => bound.includes(contract))) {
19
- const names = new Set(bound.map(({ name }) => name));
20
- throw new Error(`No ${noun} of these implementations is in this ${what}: ${markingOthers(held, names) || "none"} (pass an implementation of a bound ${noun}, or bind one of these)`);
21
- }
22
- const served = select(kind, apps, listed ?? bound.filter((contract) => held.includes(contract)));
17
+ const held = new Set(apps.flatMap(holds));
18
+ const served = select(kind, apps, listed ?? bound.filter((contract) => held.has(contract)));
23
19
  assertOnce(`served ${noun}`, served.flatMap(holds), heldOnce);
24
20
  return served;
25
21
  };
22
+ const assertBound = ({ noun, holds }, what, bound, apps, served, otherServed) => {
23
+ if (served.length === 0 && apps.length > 0 && (bound.length > 0 || otherServed.length === 0)) {
24
+ const names = new Set(bound.map(({ name }) => name));
25
+ throw new Error(`No ${noun} of these implementations is in this ${what}: ${markingOthers(apps.flatMap(holds), names) || "none"} (pass an implementation of a bound ${noun}, or bind one of these)`);
26
+ }
27
+ };
26
28
  const servingOf = (what, binding, served, options) => {
27
29
  const listed = selection(options.actions);
28
- const apps = servedBy(actionKind, what, binding.actions, toList(served), listed.actions);
30
+ const implementations = toList(served);
31
+ const eventImplementations = eventsOf(served);
32
+ const apps = servedBy(actionKind, binding.actions, implementations, listed.actions);
33
+ const events = servedBy(eventKind, binding.events, eventImplementations, listed.events);
34
+ if (listed.actions === void 0) assertBound(actionKind, what, binding.actions, implementations, apps, events);
35
+ if (listed.events === void 0) assertBound(eventKind, what, binding.events, eventImplementations, events, apps);
29
36
  const actions = apps.flatMap((app) => app.actions);
30
- const events = servedBy(eventKind, what, binding.events, eventsOf(served), listed.events);
31
37
  const eventTypes = events.flatMap((app) => app.events);
32
38
  assertAuthentication(actions, binding.authentication);
33
39
  assertAuthentication(eventTypes, binding.authentication, "event");
@@ -0,0 +1,14 @@
1
+ import { Unavailable } from "./errors.mjs";
2
+ import { Context, Effect } from "effect";
3
+ declare const Wake_base: Context.ServiceClass<Wake, "effect-actions/Wake", {
4
+ readonly wakeAt: (at: number) => Effect.Effect<void, Unavailable>;
5
+ readonly until: (at: number) => Effect.Effect<void>;
6
+ }>;
7
+ /**
8
+ * An entity's wake, which `ActionEntity.layer` provides to its activation: `wakeAt` schedules the
9
+ * persisted tell `ActionEntity.wakeAt` promises, and `until` waits in the activation for one, so
10
+ * a stopped activation is built again when it is due, where a timer is cut by Effect's reaper and
11
+ * keeps a Durable Object awake. Absent outside an entity.
12
+ */
13
+ export declare class Wake extends Wake_base {}
14
+ export {};
@@ -1,9 +1,10 @@
1
1
  import { Context } from "effect";
2
2
  // src/contract/wake.ts
3
3
  /**
4
- * How an entity's activation waits until a time, which `ActionEntity.layer` provides to its
5
- * `services`: a wait that builds a stopped activation again when it is due, where a timer is cut
6
- * by Effect's reaper and keeps a Durable Object awake. Absent outside an entity.
4
+ * An entity's wake, which `ActionEntity.layer` provides to its activation: `wakeAt` schedules the
5
+ * persisted tell `ActionEntity.wakeAt` promises, and `until` waits in the activation for one, so
6
+ * a stopped activation is built again when it is due, where a timer is cut by Effect's reaper and
7
+ * keeps a Durable Object awake. Absent outside an entity.
7
8
  */
8
9
  var Wake = class extends Context.Service()("effect-actions/Wake") {};
9
10
  export { Wake };
@@ -1,6 +1,6 @@
1
1
  import { reported } from "../contract/reported.mjs";
2
2
  import { Wake } from "../contract/wake.mjs";
3
- import { Clock, DateTime, Duration, Effect, Exit, Latch, Schema } from "effect";
3
+ import { Clock, DateTime, Deferred, Duration, Effect, Schema, Semaphore } from "effect";
4
4
  import { ClusterSchema, DeliverAt } from "effect/cluster";
5
5
  import { Rpc } from "effect/rpc";
6
6
  // src/entity/wakes.ts
@@ -11,29 +11,39 @@ var WakeAt = class extends Schema.Class("effect-actions/ActionEntity/WakeAt")({
11
11
  }
12
12
  };
13
13
  const WakeRpc = Rpc.make(wakeTag, { payload: WakeAt }).annotate(ClusterSchema.Persisted, true);
14
- const makeWake = (send) => Effect.map(Clock.Clock, (clock) => {
15
- const waiting = /* @__PURE__ */ new Set();
16
- const sent = /* @__PURE__ */ new Set();
14
+ /**
15
+ * The entity's wake. `wakeAt` sends the persisted tell unless one this activation stored, due no
16
+ * later, has not fired; `until` stores its own deadline, unless one at that time is pending, then
17
+ * waits for a wake due no earlier, so no earlier wake hands it over; `woke` takes a delivery,
18
+ * which may be stale or replayed. A send and its record hold the lock, uninterruptibly, and so
19
+ * does a delivery's bookkeeping, so a delivery racing its own send cannot leave a fired time pending.
20
+ */
21
+ const makeWake = (send) => Effect.gen(function* () {
22
+ const clock = yield* Clock.Clock;
23
+ const lock = yield* Semaphore.make(1);
24
+ const pending = /* @__PURE__ */ new Set();
25
+ let latest = -Infinity;
26
+ let fired = Deferred.makeUnsafe();
27
+ const stored = (at, covers) => lock.withPermit(Effect.suspend(() => [...pending].some(covers) ? Effect.void : Effect.uninterruptible(Effect.tap(send(new WakeAt({ at })), () => Effect.sync(() => pending.add(at))))));
17
28
  const slept = (at) => clock.sleep(Duration.millis(Math.max(at - clock.currentTimeMillisUnsafe(), 0)));
18
- const until = (at) => Effect.suspend(() => {
19
- const waiter = {
20
- at,
21
- woken: Latch.makeUnsafe()
22
- };
23
- waiting.add(waiter);
24
- return Effect.raceFirst(waiter.woken.await, sent.has(at) ? Effect.never : Effect.uninterruptible(Effect.exit(Effect.tap(send(new WakeAt({ at })), () => Effect.sync(() => sent.add(at))))).pipe(Effect.flatMap(Exit.match({
25
- onSuccess: () => Effect.never,
26
- onFailure: (cause) => Effect.andThen(reported(cause), slept(at))
27
- })))).pipe(Effect.ensuring(Effect.sync(() => {
28
- waiting.delete(waiter);
29
- })));
30
- });
29
+ const due = (at) => Effect.suspend(() => latest >= at ? Effect.void : Effect.andThen(Deferred.await(fired), due(at)));
30
+ const until = (at) => stored(at, (sent) => sent === at).pipe(Effect.matchCauseEffect({
31
+ onFailure: (cause) => Effect.andThen(reported(cause), slept(at)),
32
+ onSuccess: () => due(at)
33
+ }));
34
+ const woke = (at) => lock.withPermit(Effect.sync(() => {
35
+ for (const sent of pending) if (sent <= at) pending.delete(sent);
36
+ latest = Math.max(latest, at);
37
+ const done = fired;
38
+ fired = Deferred.makeUnsafe();
39
+ return done;
40
+ })).pipe(Effect.flatMap((done) => Deferred.succeed(done, void 0)));
31
41
  return {
32
- wake: Wake.of({ until }),
33
- woke: ({ payload }) => Rpc.fork(Effect.sync(() => {
34
- for (const each of sent) if (each <= payload.at) sent.delete(each);
35
- for (const waiter of waiting) if (waiter.at <= payload.at) waiter.woken.openUnsafe();
36
- }))
42
+ wake: Wake.of({
43
+ wakeAt: (at) => stored(at, (sent) => sent <= at),
44
+ until
45
+ }),
46
+ woke
37
47
  };
38
48
  });
39
49
  export { WakeRpc, makeWake, wakeTag };
@@ -200,7 +200,7 @@ const actionMethodOf = (action, binding) => {
200
200
  const answer = (reach, [input, ...rest]) => Effect.flatMap(sentInput(action, input), ({ value }) => Effect.map(reach(action, value), (call) => method(call)(value, ...rest)));
201
201
  return elementOf(action.success) === void 0 ? (reach) => (...args) => Effect.flatMap(answer(reach, args), answered) : (reach) => (...args) => elementsOf(answer(reach, args));
202
202
  };
203
- const methodsOf = (binding, transport) => {
203
+ const methodsOf = (binding, transport, watchMode) => {
204
204
  const actions = binding.actions.map((action) => [action.name, actionMethodOf(action, binding)]);
205
205
  const transports = new Map(binding.events.map((event) => [event.name, transport(event, binding)]));
206
206
  return (reach) => {
@@ -209,7 +209,11 @@ const methodsOf = (binding, transport) => {
209
209
  const watch = (event, input, watchOptions) => {
210
210
  const feed = transports.get(event.name);
211
211
  if (feed === void 0) return Stream.die(/* @__PURE__ */ new Error(`ActionRpc.client: the binding holds no event type ${event.name} (watch one the binding ActionRpc.make returned lists)`));
212
- return Stream.unwrap(Effect.flatMap(sentInput(event, input), ({ json, value }) => Effect.map(reach(event, value), (call) => watching(feed(call)(json, watchOptions?.mode === "stream"), watchOptions))));
212
+ const mode = watchOptions?.mode ?? watchMode;
213
+ return Stream.unwrap(Effect.flatMap(sentInput(event, input), ({ json, value }) => Effect.map(reach(event, value), (call) => watching(feed(call)(json, mode === "stream"), {
214
+ ...watchOptions,
215
+ mode
216
+ }))));
213
217
  };
214
218
  return {
215
219
  ...methods,
@@ -13,7 +13,9 @@ const isAnsweredReason = Schema.is(Schema.Union([
13
13
  Schema.instanceOf(HttpClientError.DecodeError)
14
14
  ]));
15
15
  const cutResponses = ["HTTP response ended before RPC request completed", "Received empty HTTP response"];
16
- const isRpcTransient = Predicate.or(Cause.isTimeoutError, (error) => isRpcClientError(error) && Match.value(error.reason).pipe(Match.tag("SocketReadError", "SocketWriteError", "SocketOpenError", () => true), Match.tag("SocketCloseError", ({ code }) => code < 4e3 || code > 4999), Match.tag("HttpError", ({ cause }) => isAnsweredReason(cause) && isTransientReason(cause)), Match.tag("RpcClientDefect", ({ message }) => cutResponses.some((fragment) => message.includes(fragment))), Match.orElse(() => false)));
16
+ /** A WebSocket close code an application sends, 4000 to 4999, such as a server's refusal. */
17
+ const isApplicationCode = (code) => code >= 4e3 && code <= 4999;
18
+ const isRpcTransient = Predicate.or(Cause.isTimeoutError, (error) => isRpcClientError(error) && Match.value(error.reason).pipe(Match.tag("SocketReadError", "SocketWriteError", "SocketOpenError", () => true), Match.tag("SocketCloseError", ({ code }) => !isApplicationCode(code)), Match.tag("HttpError", ({ cause }) => isAnsweredReason(cause) && isTransientReason(cause)), Match.tag("RpcClientDefect", ({ message }) => cutResponses.some((fragment) => message.includes(fragment))), Match.orElse(() => false)));
17
19
  const isUnknownTag = (tag) => {
18
20
  const message = `Unknown request tag: ${tag}`;
19
21
  return (cause) => cause.reasons.some((reason) => Cause.isDieReason(reason) && (Predicate.hasProperty(reason.defect, "message") ? reason.defect.message === message : reason.defect === message));
@@ -29,4 +31,4 @@ const polledTransportOf = (event, { poll }, transient, unserved) => ({
29
31
  stream: () => Stream.fail(deliveryUnsupported(event.name, "push")),
30
32
  transient
31
33
  });
32
- export { isRpcTransient, isUnknownTag, polledTransportOf, streamingOf };
34
+ export { isApplicationCode, isRpcTransient, isUnknownTag, polledTransportOf, streamingOf };
@@ -2,7 +2,6 @@
2
2
 
3
3
  What you see when something is wrong, and the fix. Search for a fragment of the message. The tasks are in [ActionEntity.md](ActionEntity.md).
4
4
 
5
- - `"An entity's binding holds no native rpcs"` in a type error on `ActionEntity.make`: the binding was made with `ActionRpc.make`'s `rpcs`. Make the binding of the actions and event types alone, and give the native rpcs to `ActionEntity.make`'s `rpcs`.
6
5
  - `An entity provides no service per call` in a type error on `ActionEntity.layer`: a handler, an authorizer or an event source reads per call a service other than its caller and `services`' output, named in the diagnostic. Yield it in the implementation's builder, where the layer requires it at startup, or build it in the layer's `services`. Where `services` already outputs it, and is written inline as a `Layer.merge` or another generic combinator's result, TypeScript infers its output too late: assign the layer to a `const` first.
7
6
  - `Service not found: effect/http/HttpRouter`, a defect as `ActionEntity.layer` builds, before any call: its authentication provider publishes a `protectedResource`, on a router an entity lacks. Give the provider serving the entity no `protectedResource`.
8
7
  - `Defect building entity handlers`, logged again and again while calls wait: an implementation's builder fails or dies, or reads a service the layer was not given. Fix the builder, or provide the service to `ActionEntity.layer`.
@@ -1,34 +1,36 @@
1
1
  # ActionEntity
2
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.
3
+ `ActionEntity` serves actions and event types 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
4
 
5
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
6
 
7
7
  ## Define an entity
8
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.
9
+ Give `ActionEntity.make` the entity type's name, its contracts, actions and event types, 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. Protected contracts name their `authentication`, as `ActionRpc.make` takes it ([ActionRpc.md](ActionRpc.md#bind-actions-to-rpcs)); the entity builds that RPC binding itself, as `Cart.binding`, which a socket client calls.
10
10
 
11
11
  ```ts example=shopping-carts/src/entities.ts
12
12
  import * as ActionEntity from "@gjermundgaraba/effect-actions/ActionEntity";
13
13
 
14
- import { CartRpc } from "./Rpc.js";
14
+ import { Carts } from "./cart/Cart.js";
15
+ import { Login } from "./identity/Identity.js";
15
16
 
16
- export const Cart = ActionEntity.make("Cart", CartRpc, {
17
+ export const Cart = ActionEntity.make("Cart", Carts, {
18
+ authentication: Login,
17
19
  key: ({ cart }) => cart,
18
20
  });
19
21
  ```
20
22
 
21
23
  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
24
 
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.
25
+ A call another part of the application makes, such as a Worker's settings reading an agent's model, is an action the entity lists and no surface's binding does: `ActionEntity.client` calls it, typed, failing with `Action.Unavailable` where the entity is out of reach. `ActionEntity.reaching` implements it too, so a surface given those implementations names what it serves: an HTTP or RPC binding of the public contracts, and MCP's `actions`. An entity may also serve native rpcs of its own, given to `make` as `rpcs`: tells, such as a persisted one another entity sends through Effect's `Entity.client`. They authenticate nothing, so no surface serves them. An entity scheduling work of its own for later needs none: it wakes itself with `wakeAt`, below.
24
26
 
25
27
  ## Serve it
26
28
 
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`.
29
+ `ActionEntity.layer(entity, implementations)` registers the entity with `Sharding`. The implementations are those of the entity's actions and event types, one or a list, as on every surface ([Action.md](Action.md#implement-actions)), and they must cover every one. Provide the layer with what the implementations read at startup, the authentication provider of the entity's descriptor ([Authentication.md](Authentication.md#verify-credentials)), `Event.Events` when the entity has event types, and the cluster's `Sharding`.
28
30
 
29
31
  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
32
 
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.
33
+ 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`. The handlers may be an object or an Effect that builds one; the Effect runs after `services` and may read their output. Their types come from `make`'s `rpcs`. Handlers written outside `layer` get their types from the entity's `of`, `Room.of({ expire: ({ payload }) => … })`, as with Effect's `Entity.of`. A layer of its own given to `services` reads what each activation provides as `ActionEntity.Activation`.
32
34
 
33
35
  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
36
 
@@ -64,13 +66,19 @@ Its [server.ts](../examples/shopping-carts/src/server.ts) runs both on Effect's
64
66
 
65
67
  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
68
 
69
+ ## Wake it later
70
+
71
+ An entity schedules work for later with `ActionEntity.wakeAt(at)`, read in its `services`, a builder or a handler: a persisted tell the entity sends itself, which succeeds once the runtime has stored it and fails with `Action.Unavailable` where it could not. When it is due, the layer's `onWake` runs with the time it was due, in whichever activation is current, built again where the entity had stopped, so the wake outlives eviction, a restart and a deploy.
72
+
73
+ `onWake` is a check, as a Durable Object's alarm handler is: it does what is due by then and asks `wakeAt` for the next time. The rules are on `ActionEntity.wakeAt` and `ActionEntity.LayerOptions`' `onWake`.
74
+
67
75
  ## Call it
68
76
 
69
77
  `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 are on `ActionEntity.nativeClient(entity)`, Effect's own client for an entity id, `(yield* ActionEntity.nativeClient(Room))("lobby").expire()`. A call through either that the entity could not be reached for, or that did not answer within `client(entity, { timeout })`, 20 seconds by default, fails with the built-in `Action.Unavailable`, as through `reaching` below. What a call fails with is `ActionEntity.MethodError`, and the transport rules are on `ActionEntity.client`.
70
78
 
71
79
  ## Reach it from any surface
72
80
 
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.
81
+ `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 or some of them, such as an HTTP binding of its actions alone: 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
82
 
75
83
  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
84
 
@@ -78,7 +86,7 @@ A call the entity could not be reached for, or that did not answer within `reach
78
86
 
79
87
  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`.
80
88
 
81
- 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.
89
+ A server outside the cluster that forwards a socket's calls into the entity, as the Cloudflare package's socket host does, forwards those rpcs of `ActionEntity.bindingRpcs(entity)` its own binding lists, never the entity's internal actions or native rpcs, which authenticate nothing; its clients call them with `ActionRpc.client` of that binding, whose watch polls them.
82
90
 
83
91
  ## Watch an event
84
92
 
@@ -138,7 +138,7 @@ export const withRequestPolicy = (publicUrl: URL) => {
138
138
  };
139
139
  ```
140
140
 
141
- Pass the deployed public URL from the host's configuration to `withRequestPolicy`, then serve its result as in [quickstart/src/server.ts](../examples/quickstart/src/server.ts). For a raw request, pass its target, Host and Origin to `policy.allows`; use `undefined` for absent headers. Allowing an additional browser origin through `RequestPolicy.Options` does not install CORS response headers; configure `HttpRouter.cors` too when the browser needs them.
141
+ Pass the deployed public URL from the host's configuration to `withRequestPolicy`, then serve its result as in [quickstart/src/server.ts](../examples/quickstart/src/server.ts). For a raw web `Request`, such as a Worker's, pass it to `policy.allows`, which reads its Host header, or its URL's host where it sends none, and its Origin. Allowing an additional browser origin through `RequestPolicy.Options` does not install CORS response headers; configure `HttpRouter.cors` too when the browser needs them.
142
142
 
143
143
  ### Split a binding across layers, and add middleware
144
144
 
package/docs/ActionRpc.md CHANGED
@@ -169,7 +169,27 @@ export const openChat = Effect.gen(function* () {
169
169
 
170
170
  [live-rpc/src/client.ts](../examples/live-rpc/src/client.ts) runs it from Node, and [live-rpc/src/page.ts](../examples/live-rpc/src/page.ts) wraps it in promises for a page that is not one Effect program. The client's traps are on `ActionRpc.client`.
171
171
 
172
- - **A server that closes a socket to refuse it.** Effect's socket client connects again after any close, backing off to every five seconds, for good. Give `RpcClient.layerProtocolSocket` the `retryPolicy` `ActionRpc.reconnectUntil(code)`, and a close with that code ends its calls instead.
172
+ A page that holds one socket of its own builds the client with `ActionRpc.socketClient(Rpc, { url })`: one WebSocket for the client's `Scope`, JSON, reconnecting after a drop and stopping at a server's refusal. Its options, a constructor, `hooks`, `serialization` and `watchMode`, are on `ActionRpc.SocketClientOptions`:
173
+
174
+ ```ts example=kitchen-sink/src/browser.ts
175
+ import * as ActionRpc from "@gjermundgaraba/effect-actions/ActionRpc";
176
+ import { Effect } from "effect";
177
+
178
+ import { Rpc } from "./Rpc.js";
179
+
180
+ export const board = (url: string) =>
181
+ Effect.gen(function* () {
182
+ const tracker = yield* ActionRpc.socketClient(Rpc, { url });
183
+
184
+ const me = yield* tracker.whoAmI();
185
+ const { issues } = yield* tracker.listIssues({ status: "open", limit: 50 });
186
+
187
+ return { me, issues };
188
+ });
189
+
190
+ export const open = async (url: string) =>
191
+ await Effect.runPromise(Effect.scoped(board(url)));
192
+ ```
173
193
 
174
194
  ## Serve and watch events
175
195
 
@@ -5,7 +5,7 @@ What you see when something is wrong, and the fix: compiler diagnostics and erro
5
5
  ## Types and startup
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
- - `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)).
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`, `ActionEntity.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
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)).
10
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.
11
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.
package/docs/Event.md CHANGED
@@ -161,6 +161,8 @@ export const buildEvents = Event.implement(
161
161
 
162
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
+ Where the store appends entries under increasing integer ids that last as long as it does, such as a SQLite table's `INTEGER PRIMARY KEY`, `Event.appended` builds the check from the newest id and a read after an id, as the Cloudflare package's chat-rooms example does for its messages: the cursor is the last id read, and what a stale cursor answers is on `Event.appended`.
165
+
164
166
  - **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
167
 
166
168
  ## Send a value whole
@@ -194,7 +196,7 @@ export const statusEvents = Event.implement(
194
196
  );
195
197
  ```
196
198
 
197
- [build-events/src/builds/handlers.ts](../examples/build-events/src/builds/handlers.ts) notifies after each build with its pipeline as the key, so a build wakes only that pipeline's subscribers. What a notify without a change sends, and why a value written as it is read is not missed, is on `Event.Current`.
199
+ [build-events/src/builds/handlers.ts](../examples/build-events/src/builds/handlers.ts) notifies after each build with its pipeline as the key, so a build wakes only that pipeline's subscribers. A notify that leaves the value as the subscriber saw it sends nothing. A polling client asks again at the source's `nextPoll`, 5 seconds by default, where a value changing faster is worth a quicker poll; why a value written as it is read is not missed is on `Event.Current`.
198
200
 
199
201
  ## Keep what nothing else keeps
200
202
 
package/docs/setup.md CHANGED
@@ -108,4 +108,4 @@ Import into the page only the contract files, the binding and a client module of
108
108
 
109
109
  - `Action`, `Event`, `ActionHttp`, `ActionRpc` and `Authentication` are the browser-safe modules: they use nothing of Node or a server platform.
110
110
  - Keep `Action.implement` and `Authentication.layer` out of every file the page imports: a bundler keeps such a call, and what its handlers or verifier import, even unused.
111
- - Those five modules import Effect through `effect`, `effect/http` and `effect/http-api` alone, and `ActionRpc` through `effect/rpc` too. A page loading Effect from an import map serves those, and `effect/socket` for a WebSocket client.
111
+ - Those five modules import Effect through `effect`, `effect/http` and `effect/http-api` alone, and `ActionRpc` through `effect/rpc` and `effect/socket` too. A page loading Effect from an import map serves those.
@@ -1,29 +1,17 @@
1
1
  import * as ActionRpc from "@gjermundgaraba/effect-actions/ActionRpc";
2
- import { Effect, Layer } from "effect";
3
- import { RpcClient, RpcSerialization } from "effect/rpc";
4
- import { Socket } from "effect/socket";
2
+ import { Effect } from "effect";
5
3
 
6
4
  import { Rpc } from "./Rpc.js";
7
5
 
8
- export const board = Effect.gen(function* () {
9
- const tracker = yield* ActionRpc.client(Rpc);
6
+ export const board = (url: string) =>
7
+ Effect.gen(function* () {
8
+ const tracker = yield* ActionRpc.socketClient(Rpc, { url });
10
9
 
11
- const me = yield* tracker.whoAmI();
12
- const { issues } = yield* tracker.listIssues({ status: "open", limit: 50 });
10
+ const me = yield* tracker.whoAmI();
11
+ const { issues } = yield* tracker.listIssues({ status: "open", limit: 50 });
13
12
 
14
- return { me, issues };
15
- });
16
-
17
- export const protocol = (url: string) =>
18
- RpcClient.layerProtocolSocket().pipe(
19
- Layer.provide(Socket.layerWebSocket(url)),
20
- Layer.provide([
21
- RpcSerialization.layerJson,
22
- Socket.layerWebSocketConstructorGlobal,
23
- ])
24
- );
13
+ return { me, issues };
14
+ });
25
15
 
26
16
  export const open = async (url: string) =>
27
- await Effect.runPromise(
28
- board.pipe(Effect.scoped, Effect.provide(protocol(url)))
29
- );
17
+ await Effect.runPromise(Effect.scoped(board(url)));
@@ -38,7 +38,7 @@ src/
38
38
  ├── platform/
39
39
  │ ├── sql-carts.ts CartStore over a SqlClient
40
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
41
+ ├── Api.ts the HTTP binding
42
42
  ├── entities.ts Cart, the entity: which cart each action's input names
43
43
  ├── routes.ts the entity's layer, and the JSON routes reaching it
44
44
  └── server.ts entrypoint: both, with CartStore over SQL, on SingleRunner and one SQLite file
@@ -1,7 +1,9 @@
1
1
  import * as ActionEntity from "@gjermundgaraba/effect-actions/ActionEntity";
2
2
 
3
- import { CartRpc } from "./Rpc.js";
3
+ import { Carts } from "./cart/Cart.js";
4
+ import { Login } from "./identity/Identity.js";
4
5
 
5
- export const Cart = ActionEntity.make("Cart", CartRpc, {
6
+ export const Cart = ActionEntity.make("Cart", Carts, {
7
+ authentication: Login,
6
8
  key: ({ cart }) => cart,
7
9
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/effect-actions",
3
- "version": "0.35.0",
3
+ "version": "0.36.0",
4
4
  "description": "Define Effect action contracts once and project them onto HTTP, MCP, Effect RPC, native Toolkits, and CLIs.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -1,6 +0,0 @@
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 });