@gjermundgaraba/effect-actions 0.34.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.
package/dist/Event.mjs CHANGED
@@ -5,7 +5,7 @@ import { EventImplementation, sourcesOf } from "./contract/feed.mjs";
5
5
  import { assertEventName, assertOnce } from "./contract/names.mjs";
6
6
  import { Events, layerMemory } from "./contract/hub.mjs";
7
7
  import { Gap } from "./contract/occurrence.mjs";
8
- import { Array as Array$1, Data, Effect, Match, Predicate, Schema } from "effect";
8
+ import { Array as Array$1, Data, Effect, Match, Option, Predicate, Schema } from "effect";
9
9
  // src/contract/Event.ts
10
10
  const TypeId = "~@gjermundgaraba/effect-actions/Event";
11
11
  /** Whether `u` is an event type `make` defined: a binding's list tells events from actions by it. */
@@ -24,6 +24,53 @@ function make(name, options) {
24
24
  payload: codecOf(options.payload)
25
25
  };
26
26
  }
27
+ const appendedId = (cursor) => {
28
+ const id = Number(cursor);
29
+ return cursor !== null && Number.isSafeInteger(id) && id >= 0 && String(id) === cursor ? Option.some(id) : Option.none();
30
+ };
31
+ /**
32
+ * A check source for a store that appends entries under increasing integer ids, such as a table's
33
+ * `INTEGER PRIMARY KEY`: its cursor is the id of the last entry a subscriber read, and an
34
+ * occurrence's `eventId` its entry's id. A new subscriber starts after the newest entry. `event`
35
+ * types the options alone, as `Event.appended(MessagePosted, { … })` in `implement`'s builder.
36
+ *
37
+ * **Gotchas**
38
+ *
39
+ * - A cursor that is not an id up to `newest`'s as the check spells one, digits without a sign, exponent or leading zero, such as another store's or one past a store emptied since, is answered with `truncated: true` and the newest id: the subscriber goes on from there.
40
+ * - A store deleting its oldest entries sends no gap for those a subscriber resuming before them missed: a cursor is stale only past `newest`.
41
+ * - Ids that start again, as a store kept in memory restarts them, make an old cursor read entries it never saw as the ones after it: such a store's cursor carries its epoch in a `check` of its own.
42
+ */
43
+ const appended = (_event, { newest, after, id, nextPoll, ...source }) => ({
44
+ ...source,
45
+ check: (input, cursor) => Effect.gen(function* () {
46
+ const last = yield* newest(input);
47
+ const from = Option.filter(appendedId(cursor), (at) => at <= last);
48
+ if (Option.isNone(from)) return {
49
+ events: [],
50
+ cursor: String(last),
51
+ truncated: cursor !== null,
52
+ nextPoll
53
+ };
54
+ if (from.value === last) return {
55
+ events: [],
56
+ cursor: String(last),
57
+ nextPoll
58
+ };
59
+ const read = yield* after(input, from.value);
60
+ const lastItem = read.items.at(-1);
61
+ const reached = lastItem === void 0 ? from.value : id(lastItem);
62
+ const through = Math.max(read.through ?? reached, reached);
63
+ return {
64
+ events: read.items.map((data) => ({
65
+ eventId: String(id(data)),
66
+ data
67
+ })),
68
+ cursor: String(through),
69
+ hasMore: read.hasMore === true && through > from.value,
70
+ nextPoll
71
+ };
72
+ })
73
+ });
27
74
  /** The server serves no event type of that name, or no longer does. */
28
75
  var NotServed = class extends Schema.TaggedError()("NotServed", {}) {};
29
76
  /**
@@ -100,4 +147,4 @@ function implement(events, sources, options) {
100
147
  }, listed.some((event) => event.caller !== Anyone), options?.authorize);
101
148
  return new EventImplementation(listed, sourcesOf(listed, !Array.isArray(events), sources), authorizer);
102
149
  }
103
- export { CallbackCategory, CallbackFailed, Events, Gap, NotServed, NotSubscribed, SubscriptionError, Unsupported, WebhookDelivery, allowAll, implement, isEvent, layerMemory, make };
150
+ export { CallbackCategory, CallbackFailed, Events, Gap, NotServed, NotSubscribed, SubscriptionError, Unsupported, WebhookDelivery, allowAll, appended, implement, isEvent, layerMemory, make };
@@ -13,22 +13,16 @@ export interface Options {
13
13
  */
14
14
  readonly allowedOrigins?: readonly string[];
15
15
  }
16
- /** One request, as a Node `upgrade` handler or a router middleware sees it. */
17
- export interface Request {
18
- /** The request target: `/a?b` or an absolute URL. Only its path is read. */
19
- readonly target: string;
20
- readonly host: string | undefined;
21
- readonly origin: string | undefined;
22
- }
23
16
  /**
24
- * Build a Host/Origin policy once at startup. `allows` takes no services, so a
25
- * raw request or Node upgrade handler applies the same rule as the router.
17
+ * Build a Host/Origin policy once at startup. `allows` takes a web `Request` and no
18
+ * services, so a Worker's `fetch` or a raw web handler applies the same rule as the router.
26
19
  * The middleware answers refused requests with status 403 and text `Forbidden`.
27
20
  *
28
21
  * **Gotchas**
29
22
  * - `/healthz` is unchecked, including its query and fragment; do not serve application data there.
30
23
  * - Provide `middleware.layer` to every route layer to protect; it is not global middleware.
31
24
  * - This checks browser request headers, not caller identity; access control belongs to the application or its network.
25
+ * - 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.
32
26
  */
33
27
  export declare const make: (options: Options) => {
34
28
  allows: (request: Request) => boolean;
@@ -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"]
@@ -109,6 +109,11 @@ declare const Unavailable_base: Schema.Class<Unavailable, Schema.TaggedStruct<"U
109
109
  export declare class Unavailable extends Unavailable_base {
110
110
  private readonly "~declared in the action's error, or built in";
111
111
  }
112
+ /**
113
+ * Whether a value is `Unavailable`, the built-in error a caller may try again later, such as one
114
+ * `ActionEntity.client` failed with: `Effect.catchIf(call, Action.isUnavailable, retryLater)`.
115
+ */
116
+ export declare const isUnavailable: <I>(input: I) => input is I & Unavailable;
112
117
  /**
113
118
  * What authentication or an implementation's `authorize` refuses a caller with, instead of
114
119
  * running a handler. As a schema, it tells a refusal apart: `Schema.is(Action.Refusal)(error)`.
@@ -91,6 +91,11 @@ var Forbidden = class extends Schema.TaggedError()("Forbidden", {
91
91
  * - An answer `Action.Idempotency` keeps is never this error, as for any 5xx: a repeat runs the call again.
92
92
  */
93
93
  var Unavailable = class extends Schema.TaggedError()("Unavailable", { message: defaultedMessage("The service is unavailable: try again later.") }, { httpApiStatus: 503 }) {};
94
+ /**
95
+ * Whether a value is `Unavailable`, the built-in error a caller may try again later, such as one
96
+ * `ActionEntity.client` failed with: `Effect.catchIf(call, Action.isUnavailable, retryLater)`.
97
+ */
98
+ const isUnavailable = Schema.is(Unavailable);
94
99
  const refusals = [Unauthenticated, Forbidden];
95
100
  /**
96
101
  * What authentication or an implementation's `authorize` refuses a caller with, instead of
@@ -104,4 +109,4 @@ const builtIns = [
104
109
  ];
105
110
  /** The built-in failures as one schema: `Schema.is(Action.BuiltIn)(error)`. */
106
111
  const BuiltIn = Schema.Union(builtIns);
107
- export { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, Unavailable, builtIns, scopeToken };
112
+ export { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, Unavailable, builtIns, isUnavailable, scopeToken };
@@ -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,5 +1,5 @@
1
1
  import { CallbackUrl } from "./callback.mjs";
2
- import { Unavailable } from "./errors.mjs";
2
+ import { isUnavailable } from "./errors.mjs";
3
3
  import { SubscriptionError } from "../Event.mjs";
4
4
  import { Checked, Gap } from "./occurrence.mjs";
5
5
  import { paged } from "./pages.mjs";
@@ -11,7 +11,6 @@ import { Cause, Clock, Duration, Effect, Predicate, Queue, Schedule, Schema, Str
11
11
  const reconnectDelay = Duration.seconds(1);
12
12
  const maxReconnectDelay = Duration.seconds(30);
13
13
  const afterFailures = (transient) => Schedule.min([Schedule.exponential(reconnectDelay), Schedule.spaced(maxReconnectDelay)]).pipe(Schedule.setInputType(), Schedule.while(({ input }) => transient(input)), Schedule.tap(({ input, duration }) => Effect.logWarning(`A watch reconnects in ${Duration.format(duration)} after a failure`, input)));
14
- const isUnavailable = Schema.is(Unavailable);
15
14
  const isSubscriptionError = Schema.is(SubscriptionError);
16
15
  const pushRefused = Predicate.compose(isSubscriptionError, ({ reason }) => Predicate.isTagged(reason, "Unsupported") && reason.feature === "deliveryMode" && reason.value === "push");
17
16
  const reconnecting = (transient, open, cursor, polled) => {
@@ -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 };
@@ -1,11 +1,11 @@
1
- import { Unavailable } from "../contract/errors.mjs";
1
+ import { Unavailable, isUnavailable } from "../contract/errors.mjs";
2
2
  import { Cause, Effect, ErrorReporter, Layer, Schema } from "effect";
3
3
  import { HttpServerResponse } from "effect/http";
4
4
  import { HttpApiMiddleware } from "effect/http-api";
5
5
  // src/http/unavailable.ts
6
6
  const encode = Schema.encodeUnknownSync(Schema.toCodecJson(Unavailable));
7
7
  var RetryAfter = class extends HttpApiMiddleware.Service()("effect-actions/http/RetryAfter") {};
8
- const retryAfter = Layer.succeed(RetryAfter, (route) => Effect.catchIf(route, Schema.is(Unavailable), (error) => Effect.as(ErrorReporter.report(Cause.fail(error)), HttpServerResponse.jsonUnsafe(encode(error), {
8
+ const retryAfter = Layer.succeed(RetryAfter, (route) => Effect.catchIf(route, isUnavailable, (error) => Effect.as(ErrorReporter.report(Cause.fail(error)), HttpServerResponse.jsonUnsafe(encode(error), {
9
9
  status: 503,
10
10
  headers: { "retry-after": "1" }
11
11
  }))));
@@ -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 };
package/docs/Action.md CHANGED
@@ -120,7 +120,7 @@ Actions under another rule go in another `Action.implement` with its own `author
120
120
 
121
121
  ## Fail with declared and built-in errors
122
122
 
123
- A handler fails with the errors its action lists in `error`, and with the four built-in errors, `InvalidInput`, `Unauthenticated`, `Forbidden` and `Unavailable`. What a refusal answers on each surface is on `Action.Unauthenticated` and `Action.Forbidden`, and what `Unavailable`, the answer when the call could not be served now and its outcome is unknown, answers is on `Action.Unavailable`; what a declared error and bad input answer, on each surface's `layer`, `layerHttp`, `runStdio`, `make` or `command`; when to fail with `InvalidInput` yourself, on that class, as [kitchen-sink/src/attachments/handlers.ts](../examples/kitchen-sink/src/attachments/handlers.ts) does.
123
+ A handler fails with the errors its action lists in `error`, and with the four built-in errors, `InvalidInput`, `Unauthenticated`, `Forbidden` and `Unavailable`. What a refusal answers on each surface is on `Action.Unauthenticated` and `Action.Forbidden`, and what `Unavailable`, the answer when the call could not be served now and its outcome is unknown, answers is on `Action.Unavailable`, which a caller tells apart with `Action.isUnavailable`, `Effect.catchIf(call, Action.isUnavailable, retryLater)`; what a declared error and bad input answer, on each surface's `layer`, `layerHttp`, `runStdio`, `make` or `command`; when to fail with `InvalidInput` yourself, on that class, as [kitchen-sink/src/attachments/handlers.ts](../examples/kitchen-sink/src/attachments/handlers.ts) does.
124
124
 
125
125
  - **Add the errors a module adds to every action it serves, a proxy's or a store's, to contracts written elsewhere with `Action.withErrors`**, `pipe(action, Action.withErrors([Throttled]))`, rather than restating each contract. It returns a new contract, which the module then implements and lists; its rules are on `Action.withErrors`.
126
126
  - **Map a client's `HttpClientError` and `SchemaError` to one declared error a caller can act on** ([mcp-tools/src/platform/print-farm.ts](../examples/mcp-tools/src/platform/print-farm.ts)). As defects, a model reads only a generic text.
@@ -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,21 +66,27 @@ 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
- `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`.
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
 
77
- A call the entity could not be reached for, or that did not answer within `reaching(entity, { timeout })`, 20 seconds by default, fails with the built-in `Action.Unavailable`, a 503 with `Retry-After` over HTTP, whose message says the entity may still run it. The deadline bounds each call and each poll, never a stream or a watch; its rules are on `ActionEntity.ReachingOptions`.
85
+ A call the entity could not be reached for, or that did not answer within `reaching(entity, { timeout })`, 20 seconds by default, fails with the built-in `Action.Unavailable`, a 503 with `Retry-After` over HTTP, whose message says the entity may still run it. The deadline bounds each call and each poll, never a stream or a watch; its rules are on `ActionEntity.EntityCallOptions`, the options `client` and `nativeClient` take too.
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