@gjermundgaraba/effect-actions 0.35.0 → 0.37.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 (48) hide show
  1. package/README.md +7 -7
  2. package/dist/Action.d.mts +2 -2
  3. package/dist/Action.mjs +1 -1
  4. package/dist/ActionEntity.d.mts +162 -75
  5. package/dist/ActionEntity.mjs +74 -55
  6. package/dist/ActionHttp.d.mts +7 -4
  7. package/dist/ActionRpc.d.mts +69 -17
  8. package/dist/ActionRpc.mjs +29 -11
  9. package/dist/Event.d.mts +62 -8
  10. package/dist/Event.mjs +49 -2
  11. package/dist/RequestPolicy.d.mts +3 -9
  12. package/dist/RequestPolicy.mjs +18 -6
  13. package/dist/authentication/provider.d.mts +0 -22
  14. package/dist/authentication/refusal.mjs +0 -4
  15. package/dist/contract/authorizer.d.mts +0 -4
  16. package/dist/contract/call.mjs +0 -4
  17. package/dist/contract/caller.mjs +0 -1
  18. package/dist/contract/declared.d.mts +0 -1
  19. package/dist/contract/feed.d.mts +0 -3
  20. package/dist/contract/feed.mjs +41 -24
  21. package/dist/contract/hub.mjs +0 -10
  22. package/dist/contract/implementation.d.mts +4 -27
  23. package/dist/contract/implementation.mjs +0 -9
  24. package/dist/contract/progress.d.mts +0 -1
  25. package/dist/contract/serving.mjs +15 -9
  26. package/dist/contract/subscribe.mjs +0 -1
  27. package/dist/contract/wake.d.mts +14 -0
  28. package/dist/contract/wake.mjs +4 -3
  29. package/dist/contract/webhooks.mjs +0 -13
  30. package/dist/entity/wakes.mjs +29 -22
  31. package/dist/http/client.mjs +8 -2
  32. package/dist/http/streamed.d.mts +6 -5
  33. package/dist/http/streamed.mjs +17 -3
  34. package/dist/rpc/erased.d.mts +0 -11
  35. package/dist/rpc/erased.mjs +7 -8
  36. package/dist/rpc/watch.mjs +4 -2
  37. package/docs/ActionEntity-failures.md +0 -1
  38. package/docs/ActionEntity.md +17 -9
  39. package/docs/ActionHttp.md +1 -1
  40. package/docs/ActionRpc.md +21 -1
  41. package/docs/Authentication-failures.md +1 -1
  42. package/docs/Event.md +3 -1
  43. package/docs/setup.md +2 -2
  44. package/examples/kitchen-sink/src/browser.ts +9 -21
  45. package/examples/shopping-carts/README.md +1 -1
  46. package/examples/shopping-carts/src/entities.ts +4 -2
  47. package/package.json +12 -12
  48. package/examples/shopping-carts/src/Rpc.ts +0 -6
@@ -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,36 @@ 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
+ * An entity's wake scheduler. Sending and recording a wake hold the same lock as delivery
16
+ * bookkeeping, so a delivery racing its own send cannot leave a fired time pending.
17
+ */
18
+ const makeWake = (send) => Effect.gen(function* () {
19
+ const clock = yield* Clock.Clock;
20
+ const lock = yield* Semaphore.make(1);
21
+ const pending = /* @__PURE__ */ new Set();
22
+ let latest = -Infinity;
23
+ let fired = Deferred.makeUnsafe();
24
+ 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
25
  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
- });
26
+ const due = (at) => Effect.suspend(() => latest >= at ? Effect.void : Effect.andThen(Deferred.await(fired), due(at)));
27
+ const until = (at) => stored(at, (sent) => sent === at).pipe(Effect.matchCauseEffect({
28
+ onFailure: (cause) => Effect.andThen(reported(cause), slept(at)),
29
+ onSuccess: () => due(at)
30
+ }));
31
+ const woke = (at) => lock.withPermit(Effect.sync(() => {
32
+ for (const sent of pending) if (sent <= at) pending.delete(sent);
33
+ latest = Math.max(latest, at);
34
+ const done = fired;
35
+ fired = Deferred.makeUnsafe();
36
+ return done;
37
+ })).pipe(Effect.flatMap((done) => Deferred.succeed(done, void 0)));
31
38
  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
- }))
39
+ wake: Wake.of({
40
+ wakeAt: (at) => stored(at, (sent) => sent <= at),
41
+ until
42
+ }),
43
+ woke
37
44
  };
38
45
  });
39
46
  export { WakeRpc, makeWake, wakeTag };
@@ -21,8 +21,14 @@ const actionMethodOf = (action, native) => {
21
21
  const method = methodOf(native, action.name, "action");
22
22
  return Answering.$match(answeringOf(action), {
23
23
  Value: () => checked(action, sendingValue, (payload) => method({ payload })),
24
- Progressed: () => checked(action, sendingValue, (payload, onProgress) => Effect.flatMap(method({ payload }), (answer) => readWithProgress(answer, onProgress))),
25
- Elements: () => checkedStream(action, sendingValue, (payload, onProgress) => Stream.unwrap(Effect.map(method({ payload }), (answer) => readElements(answer, onProgress))))
24
+ Progressed: () => checked(action, sendingValue, (payload, onProgress) => Effect.flatMap(method({
25
+ payload,
26
+ responseMode: "decoded-and-response"
27
+ }), (answer) => readWithProgress(answer, onProgress))),
28
+ Elements: () => checkedStream(action, sendingValue, (payload, onProgress) => Stream.unwrap(Effect.map(method({
29
+ payload,
30
+ responseMode: "decoded-and-response"
31
+ }), (answer) => readElements(answer, onProgress))))
26
32
  });
27
33
  };
28
34
  const sendersWith = (http, httpClient, baseUrl) => Effect.gen(function* () {
@@ -1,15 +1,16 @@
1
1
  import { Any } from "../Action.mjs";
2
2
  import { Codec } from "../contract/codec.mjs";
3
- import { ErasedValue } from "../contract/implementation.mjs";
3
+ import "../contract/implementation.mjs";
4
4
  import "../contract/progress.mjs";
5
5
  import { StreamOf } from "../contract/stream.mjs";
6
6
  import { Effect, Schema, Stream } from "effect";
7
7
  import { HttpServerRequest } from "effect/http";
8
8
  import { HttpApiSchema } from "effect/http-api";
9
- interface Sent {
10
- readonly event: "progress" | "element" | "final";
11
- readonly data: ErasedValue;
12
- }
9
+ declare const Sent: Schema.Struct<{
10
+ readonly event: Schema.Literals<readonly ["progress", "element", "final"]>;
11
+ readonly data: Schema.Unknown;
12
+ }>;
13
+ type Sent = typeof Sent.Type;
13
14
  declare const eventOf: <const N extends Sent["event"], D extends Codec>(event: N, data: D) => Schema.Struct<{
14
15
  readonly id: Schema.optional<Schema.String>;
15
16
  readonly event: Schema.Literal<N>;
@@ -5,6 +5,15 @@ import { Cause, Duration, Effect, ErrorReporter, Queue, Schema, Stream } from "e
5
5
  import { HttpServerRequest } from "effect/http";
6
6
  import { HttpApiSchema } from "effect/http-api";
7
7
  // src/http/streamed.ts
8
+ const Sent = Schema.Struct({
9
+ event: Schema.Literals([
10
+ "progress",
11
+ "element",
12
+ "final"
13
+ ]),
14
+ data: Schema.Unknown
15
+ });
16
+ const isSent = Schema.is(Sent);
8
17
  const eventOf = (event, data) => Schema.Struct({
9
18
  id: Schema.optional(Schema.String),
10
19
  event: Schema.Literal(event),
@@ -44,8 +53,13 @@ const checkedBy = (schema) => {
44
53
  const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(schema));
45
54
  return (data) => Effect.orDie(encode(data));
46
55
  };
47
- /** Whether `request` asks for an SSE stream, `text/event-stream` among whatever else it accepts. */
48
- const acceptsEventStream = (request) => (request.headers["accept"] ?? "").includes("text/event-stream");
56
+ const acceptsEventStream = (request) => ((request.headers["accept"] ?? "").match(/(?:[^",]|"(?:[^"\\]|\\.)*")+/gu) ?? []).some((range) => {
57
+ const [media, ...parameters] = range.match(/(?:[^";]|"(?:[^"\\]|\\.)*")+/gu) ?? [];
58
+ if (media?.trim().toLowerCase() !== "text/event-stream") return false;
59
+ const quality = parameters.find((parameter) => /^\s*q\s*=/iu.test(parameter));
60
+ const weight = quality === void 0 ? 1 : Number(quality.split("=")[1]);
61
+ return weight > 0 && weight <= 1;
62
+ });
49
63
  const answeringWithProgress = (success, run) => {
50
64
  const check = checkedBy(success);
51
65
  return (payload) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => acceptsEventStream(request) ? streamed((reporting, send) => run(payload, reporting).pipe(Effect.tap(check), Effect.flatMap((data) => send({
@@ -65,7 +79,7 @@ const progressedOf = ({ event, data }) => {
65
79
  return event === "final" ? Progressed.Final({ value: data }) : Progressed.Element({ value: data });
66
80
  };
67
81
  const answeredWithout = /* @__PURE__ */ new Error("A route of an action declaring progress or answering a stream answered without its event stream");
68
- const sentFrom = (answer) => Stream.isStream(answer) ? Stream.map(answer, progressedOf) : Stream.die(answeredWithout);
82
+ const sentFrom = ([answer, response]) => response.headers["content-type"]?.split(";")[0]?.trim().toLowerCase() === "text/event-stream" && Stream.isStream(answer) ? Stream.mapEffect(answer, (event) => isSent(event) ? Effect.succeed(progressedOf(event)) : Effect.die(answeredWithout)) : Stream.die(answeredWithout);
69
83
  const readWithProgress = (answer, onProgress) => answerFrom(sentFrom(answer), onProgress);
70
84
  const readElements = (answer, onProgress) => elementsFrom(sentFrom(answer), onProgress);
71
85
  export { acceptsEventStream, answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf, readElements, readWithProgress };
@@ -18,11 +18,6 @@ export declare class DeclaredFailure {
18
18
  constructor(json: Schema.Json);
19
19
  toString(): string;
20
20
  }
21
- /**
22
- * What serves a binding's erased rpcs: `ActionRpc.layer`, which streams each event type beside
23
- * polling it, through its `middleware`, or an entity, which only polls them, holds their webhooks
24
- * and runs `check` on each input.
25
- */
26
21
  export type Server = {
27
22
  readonly _tag: "ActionRpc.layer";
28
23
  readonly middleware: readonly RpcMiddleware.AnyService[];
@@ -36,7 +31,6 @@ export type Server = {
36
31
  * `ActionRpc.client`'s polling watch calls.
37
32
  */
38
33
  export declare const pollTag: (name: string) => string;
39
- /** The rpcs `server` serves for `actions` and `events`, and its clients call. */
40
34
  export declare const erasedOf: (actions: readonly Any[], events: readonly Any$1[], server: Server["_tag"]) => RpcGroup.RpcGroup<Rpc.Rpc<string, Schema.Codec<Schema.Json, Schema.Json, never, never>, Schema.Codec<Schema.Json, Schema.Json, never, never>, Schema.instanceOf<DeclaredFailure, DeclaredFailure>, never, never> | Rpc.Rpc<string, Schema.Codec<Schema.Json, Schema.Json, never, never>, import("effect/rpc/RpcSchema").Stream<Schema.Codec<Schema.Json, Schema.Json, never, never>, Schema.instanceOf<DeclaredFailure, DeclaredFailure>>, Schema.Never, never, never>>;
41
35
  /**
42
36
  * The payload of an event type's poll rpc, `<event>/poll`, past its `input`, as a client sends
@@ -54,9 +48,4 @@ export declare const ProgressedOf: <P extends Codec, S extends Codec>(progress:
54
48
  }>, Schema.TaggedStruct<"Final", {
55
49
  readonly value: S;
56
50
  }>]>;
57
- /**
58
- * What a server checks of each call's and subscription's decoded input, once it has verified its
59
- * caller and before the implementation's authorizer: an entity refuses an input whose key names
60
- * another entity.
61
- */
62
51
  export type InputCheck = (contract: Any | Any$1, input: ErasedValue) => Effect.Effect<void, Forbidden>;
@@ -31,7 +31,7 @@ const throughSteps = (steps, call, options) => {
31
31
  };
32
32
  const authenticatingOf = (authentication) => Effect.map(providerOf(authentication), (provider) => {
33
33
  const verify = Effect.flatMap(HttpApiBuilder.securityDecode(authentication.security), provider.authenticate);
34
- return (verifying) => (effect, options) => Effect.flatMap(verifying(verify, options), (actor) => Effect.provideService(effect, authentication.identity, actor));
34
+ return (verifying) => (effect, options) => Effect.provideServiceEffect(effect, authentication.identity, verifying(verify, options));
35
35
  });
36
36
  var DeclaredFailure = class {
37
37
  [ErrorReporter.ignore] = true;
@@ -73,7 +73,6 @@ const subscribeTag = (name) => `${name}/subscribe`;
73
73
  const unsubscribeTag = (name) => `${name}/unsubscribe`;
74
74
  const webhookRpcsOf = (events) => RpcGroup.make(...events.filter(offersWebhook).flatMap((event) => [unaryOf(subscribeTag(event.name)), unaryOf(unsubscribeTag(event.name))]));
75
75
  const webhookErrors = (event, binding) => Schema.Union([...eventErrors(event, binding), SubscriptionError]);
76
- /** The rpcs `server` serves for `actions` and `events`, and its clients call. */
77
76
  const erasedOf = (actions, events, server) => RpcGroup.make(...actions.map((action) => streams(action) ? streamOf(action.name) : unaryOf(action.name)), ...events.flatMap((event) => [...streamsEvents(server) ? [streamOf(event.name)] : [], unaryOf(pollTag(event.name))]));
78
77
  const Watch = Schema.String.check(Schema.isUUID());
79
78
  /**
@@ -191,16 +190,12 @@ const polledTransport = (transient, resendAfter) => (event, binding) => {
191
190
  };
192
191
  };
193
192
  };
194
- /**
195
- * An action's client method over `reach`: its call goes where its input, decoded as the server
196
- * will decode it, a decoding default included, says.
197
- */
198
193
  const actionMethodOf = (action, binding) => {
199
194
  const method = calledMethodOf(action, binding);
200
195
  const answer = (reach, [input, ...rest]) => Effect.flatMap(sentInput(action, input), ({ value }) => Effect.map(reach(action, value), (call) => method(call)(value, ...rest)));
201
196
  return elementOf(action.success) === void 0 ? (reach) => (...args) => Effect.flatMap(answer(reach, args), answered) : (reach) => (...args) => elementsOf(answer(reach, args));
202
197
  };
203
- const methodsOf = (binding, transport) => {
198
+ const methodsOf = (binding, transport, watchMode) => {
204
199
  const actions = binding.actions.map((action) => [action.name, actionMethodOf(action, binding)]);
205
200
  const transports = new Map(binding.events.map((event) => [event.name, transport(event, binding)]));
206
201
  return (reach) => {
@@ -209,7 +204,11 @@ const methodsOf = (binding, transport) => {
209
204
  const watch = (event, input, watchOptions) => {
210
205
  const feed = transports.get(event.name);
211
206
  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))));
207
+ const mode = watchOptions?.mode ?? watchMode;
208
+ return Stream.unwrap(Effect.flatMap(sentInput(event, input), ({ json, value }) => Effect.map(reach(event, value), (call) => watching(feed(call)(json, mode === "stream"), {
209
+ ...watchOptions,
210
+ mode
211
+ }))));
213
212
  };
214
213
  return {
215
214
  ...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
@@ -23,7 +23,7 @@ The `effect` peer admits the 4.1.x patches from the oldest whose APIs and behavi
23
23
 
24
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.
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
+ Node `>=26.13.1`: 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:
27
27
 
28
28
  ```json
29
29
  {
@@ -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.37.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",
@@ -54,19 +54,19 @@
54
54
  "access": "public"
55
55
  },
56
56
  "devDependencies": {
57
- "@clanker-stuff/oxlint-config": "0.5.0",
58
- "@effect/platform-node": "4.1.4",
59
- "@effect/sql-sqlite-node": "4.1.4",
60
- "@effect/tsgo": "0.67.7",
61
- "@effect/vitest": "4.1.4",
57
+ "@clanker-stuff/oxlint-config": "0.5.1",
58
+ "@effect/platform-node": "4.1.5",
59
+ "@effect/sql-sqlite-node": "4.1.5",
60
+ "@effect/tsgo": "0.73.2",
61
+ "@effect/vitest": "4.1.5",
62
62
  "@modelcontextprotocol/client": "2.4.0",
63
63
  "@types/node": "26.6.6",
64
- "effect": "4.1.4",
64
+ "effect": "4.1.5",
65
65
  "tsx": "4.23.15",
66
66
  "typescript": "7.0.2",
67
- "ultracite": "8.1.1",
68
- "vite": "npm:@voidzero-dev/vite-plus-core@1.5.1",
69
- "vite-plus": "1.5.1",
67
+ "ultracite": "8.3.1",
68
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
69
+ "vite-plus": "1.7.0",
70
70
  "vitest": "5.1.0"
71
71
  },
72
72
  "peerDependencies": {
@@ -75,12 +75,12 @@
75
75
  "devEngines": {
76
76
  "packageManager": {
77
77
  "name": "pnpm",
78
- "version": "12.18.0",
78
+ "version": "12.21.0",
79
79
  "onFail": "download"
80
80
  }
81
81
  },
82
82
  "engines": {
83
- "node": ">=26.13.0"
83
+ "node": ">=26.13.1"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "vp pack",
@@ -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 });