@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/Action.d.mts +2 -2
- package/dist/Action.mjs +2 -2
- package/dist/ActionEntity.d.mts +209 -100
- package/dist/ActionEntity.mjs +129 -89
- package/dist/ActionHttp.d.mts +5 -2
- package/dist/ActionRpc.d.mts +65 -13
- package/dist/ActionRpc.mjs +22 -7
- package/dist/Event.d.mts +60 -6
- package/dist/Event.mjs +49 -2
- package/dist/RequestPolicy.d.mts +3 -9
- package/dist/RequestPolicy.mjs +18 -6
- package/dist/contract/errors.d.mts +5 -0
- package/dist/contract/errors.mjs +6 -1
- package/dist/contract/feed.mjs +41 -21
- package/dist/contract/serving.mjs +15 -9
- package/dist/contract/wake.d.mts +14 -0
- package/dist/contract/wake.mjs +4 -3
- package/dist/contract/watch.mjs +1 -2
- package/dist/entity/wakes.mjs +32 -22
- package/dist/http/unavailable.mjs +2 -2
- package/dist/rpc/erased.mjs +6 -2
- package/dist/rpc/watch.mjs +4 -2
- package/docs/Action.md +1 -1
- package/docs/ActionEntity-failures.md +0 -1
- package/docs/ActionEntity.md +19 -11
- package/docs/ActionHttp.md +1 -1
- package/docs/ActionRpc.md +21 -1
- package/docs/Authentication-failures.md +1 -1
- package/docs/Event.md +3 -1
- package/docs/setup.md +1 -1
- package/examples/kitchen-sink/src/browser.ts +9 -21
- package/examples/shopping-carts/README.md +1 -1
- package/examples/shopping-carts/src/entities.ts +4 -2
- package/package.json +1 -1
- package/examples/shopping-carts/src/Rpc.ts +0 -6
package/dist/ActionEntity.mjs
CHANGED
|
@@ -3,67 +3,94 @@ import { allowAll } from "./Action.mjs";
|
|
|
3
3
|
import { allowAll as allowAll$1 } from "./Event.mjs";
|
|
4
4
|
import { EventImplementation } from "./contract/feed.mjs";
|
|
5
5
|
import { Implementation, memoized } from "./contract/implementation.mjs";
|
|
6
|
+
import { reported } from "./contract/reported.mjs";
|
|
6
7
|
import { buildersOf, servingOf } from "./contract/serving.mjs";
|
|
7
8
|
import { Wake } from "./contract/wake.mjs";
|
|
8
9
|
import { polling } from "./contract/watch.mjs";
|
|
9
10
|
import { offersWebhook } from "./contract/webhooks.mjs";
|
|
11
|
+
import { make as make$1 } from "./ActionRpc.mjs";
|
|
10
12
|
import { actionMethodOf, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollOf, polledTransport, watchedOf, webhookCallsOf, webhookRpcsOf } from "./rpc/erased.mjs";
|
|
11
13
|
import { forwarded, forwardedHeaders } from "./entity/forwarded.mjs";
|
|
12
14
|
import { WakeRpc, makeWake, wakeTag } from "./entity/wakes.mjs";
|
|
13
|
-
import { Duration, Effect, Layer, Predicate, Schema, Stream } from "effect";
|
|
15
|
+
import { Cause, Context, DateTime, Duration, Effect, Function, Layer, Option, Predicate, Schema, Stream } from "effect";
|
|
14
16
|
import { ClusterError, Entity } from "effect/cluster";
|
|
15
17
|
import { Rpc, RpcGroup, RpcMessage } from "effect/rpc";
|
|
18
|
+
import { SqlClient } from "effect/sql";
|
|
16
19
|
// src/entity/ActionEntity.ts
|
|
17
20
|
const namedBy = (key) => (input) => {
|
|
18
21
|
const named = key(input);
|
|
19
22
|
return Predicate.isString(named) ? named : void 0;
|
|
20
23
|
};
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
* `{ events, cursor, truncated, hasMore, nextPollMs, notified }`, an HTTP poll's page and
|
|
27
|
-
* `notified`, `ActionRpc.Page`, as `ActionRpc.layer` serves it too, its subscription hook held
|
|
28
|
-
* for the caller's principal. A protected event type has two more, `<event>/subscribe` and
|
|
29
|
-
* `<event>/unsubscribe`, taking a webhook subscription and its cancellation, and the entity has
|
|
30
|
-
* its wake, `effect-actions/wake`, a persisted tell it sends itself to end a webhook delivery's
|
|
31
|
-
* retry wait. Guide: `docs/ActionEntity.md` in this package.
|
|
32
|
-
*
|
|
33
|
-
* **Gotchas**
|
|
34
|
-
*
|
|
35
|
-
* - The rpcs of its actions, event types and webhook subscriptions are volatile, as `ClusterSchema.Persisted` defaults, and its wake alone is persisted: annotated persisted, each envelope, its caller's headers and credential included, would be stored and replayed with them, on Effect's SQL runners until a `MessageRetention` layer deletes it, and on the Cloudflare runtime, which never prunes `cluster_messages`, for good, its credential headers redacted. `rpcs`' natives are persisted as their own annotations say.
|
|
36
|
-
* - A binding with native rpcs throws: give the entity's own rpcs to `make`'s `rpcs`.
|
|
37
|
-
* - A streaming action, one declaring `progress` or answering `Action.Stream`, is a stream rpc, its frames those `ActionRpc.make` states, `client`'s method handing each progress value to `onProgress` before it answers, and returning a `Stream` of the elements of an `Action.Stream` answer; it holds a slot of the entity's `concurrency`, by default its only one, until its stream ends, but on the Cloudflare runtime, which frees the slot while a frame waits for its client's acknowledgement.
|
|
38
|
-
* - `annotate` and its kin return a plain `Entity`, without `binding` and `key`, which `layer` and `client` do not take.
|
|
39
|
-
*/
|
|
40
|
-
const make = (type, binding, options) => {
|
|
41
|
-
const natives = [...nativeOf(binding.rpcs).requests.keys()];
|
|
42
|
-
if (natives.length > 0) throw new Error(`ActionEntity.make: the binding of ${type} holds native rpcs, ${natives.join(", ")} (give them to ActionEntity.make's rpcs, unauthenticated)`);
|
|
43
|
-
const erased = erasedOf(binding.actions, binding.events, "ActionEntity.layer").merge(webhookRpcsOf(binding.events)).add(WakeRpc);
|
|
44
|
-
const rpcs = options.rpcs ?? RpcGroup.make();
|
|
45
|
-
const taken = [...rpcs.requests.keys()].filter((tag) => erased.requests.has(tag) || binding.events.some(({ name }) => name === tag));
|
|
46
|
-
if (taken.length > 0) throw new Error(`ActionEntity.make: the native rpcs of ${type}, ${taken.join(", ")}, are named after an action, an event type, an event's poll, subscribe or unsubscribe, or the entity's wake, ${wakeTag} (rename them)`);
|
|
47
|
-
const protocol = erased.merge(rpcs);
|
|
24
|
+
const bindingOf = make$1;
|
|
25
|
+
const libraryRpcsOf = (binding) => erasedOf(binding.actions, binding.events, "ActionEntity.layer").merge(webhookRpcsOf(binding.events)).add(WakeRpc);
|
|
26
|
+
const entityOf = (type, binding, key, library, natives) => {
|
|
27
|
+
const rebuilt = (annotated) => entityOf(type, binding, key, library, annotated);
|
|
28
|
+
const protocol = library.merge(natives);
|
|
48
29
|
return Object.assign(Entity.fromRpcGroup(type, protocol), {
|
|
49
30
|
binding,
|
|
50
|
-
key
|
|
31
|
+
key,
|
|
32
|
+
of: (handlers) => handlers,
|
|
33
|
+
annotate: (tag, value) => rebuilt(natives.annotate(tag, value)),
|
|
34
|
+
annotateMerge: (annotations) => rebuilt(natives.annotateMerge(annotations)),
|
|
35
|
+
annotateRpcs: (tag, value) => rebuilt(natives.annotateRpcs(tag, value)),
|
|
36
|
+
annotateRpcsMerge: (annotations) => rebuilt(natives.annotateRpcsMerge(annotations))
|
|
51
37
|
});
|
|
52
38
|
};
|
|
39
|
+
function make(type, contracts, options) {
|
|
40
|
+
const { key, authentication } = options;
|
|
41
|
+
const rpcs = nativeOf(options.rpcs ?? RpcGroup.make());
|
|
42
|
+
const binding = bindingOf(contracts, authentication === void 0 ? {} : { authentication });
|
|
43
|
+
const erased = libraryRpcsOf(binding);
|
|
44
|
+
const taken = [...rpcs.requests.keys()].filter((tag) => erased.requests.has(tag) || binding.events.some(({ name }) => name === tag));
|
|
45
|
+
if (taken.length > 0) throw new Error(`ActionEntity.make: the native rpcs of ${type}, ${taken.join(", ")}, are named after an action, an event type, an event's poll, subscribe or unsubscribe, or the entity's wake, ${wakeTag} (rename them)`);
|
|
46
|
+
return entityOf(type, binding, key, erased, nativeOf(rpcs));
|
|
47
|
+
}
|
|
53
48
|
/**
|
|
54
49
|
* The rpcs of `entity`'s binding, as its `protocol` holds them without its native rpcs: one per
|
|
55
|
-
* action, and per event type its poll.
|
|
56
|
-
* cluster
|
|
57
|
-
* `ActionRpc.client`'s watch polls, finding
|
|
50
|
+
* action, the entity's internal actions included, and per event type its poll. A surface outside
|
|
51
|
+
* the cluster forwards to the entity those of them its own binding lists alone, as the Cloudflare
|
|
52
|
+
* package's socket host forwards its `actions`, which `ActionRpc.client`'s watch polls, finding
|
|
53
|
+
* no stream rpc.
|
|
58
54
|
*/
|
|
59
55
|
const bindingRpcs = (entity) => erasedOf(entity.binding.actions, entity.binding.events, "ActionEntity.layer");
|
|
56
|
+
/**
|
|
57
|
+
* Wake the entity at `at`: a persisted tell it sends itself, delivered then to `layer`'s
|
|
58
|
+
* `onWake`, through eviction, a restart and a deploy, in whichever activation is current, built
|
|
59
|
+
* again for it where the entity had stopped. It succeeds once the runtime stored the tell, and
|
|
60
|
+
* fails with `Action.Unavailable` where it could not, so a caller knows the wake is scheduled
|
|
61
|
+
* before it starts what the wake guards. Read it in the entity: `services`, a builder or a handler.
|
|
62
|
+
*
|
|
63
|
+
* **Gotchas**
|
|
64
|
+
*
|
|
65
|
+
* - The wake keeps the earliest time: a time no earlier than one this activation scheduled and has not seen fire sends nothing, as that wake's `onWake` asks for it again; a tell cannot be taken back, so a time moved later or dropped still fires.
|
|
66
|
+
* - Each wake is a row of the runtime's messages, kept once processed, on Effect's SQL runners until a `MessageRetention` layer deletes it, and on the Cloudflare runtime for good.
|
|
67
|
+
* - It holds nothing awake: work already running keeps its activation with `Entity.keepAlive` and its Durable Object event with `waitUntil`, beside the wake that resumes it later.
|
|
68
|
+
* - Asked for inside a transaction of the entity's or the runner's `SqlClient`, it dies, as the wake would be stored in that transaction and dropped by its rollback while the activation counted it pending: call it after the transaction commits.
|
|
69
|
+
* - A time between milliseconds is rounded up to the next one, as the runtime stores whole milliseconds.
|
|
70
|
+
*/
|
|
71
|
+
const wakeAt = (at) => Effect.flatMap(Wake, (wake) => wake.wakeAt(Math.ceil(DateTime.toEpochMillis(at))));
|
|
60
72
|
const callOf = (request, rpc) => ({
|
|
61
73
|
client: new Rpc.ServerClient(0),
|
|
62
74
|
requestId: RpcMessage.RequestId(String(request.requestId)),
|
|
63
75
|
headers: request.headers,
|
|
64
76
|
rpc
|
|
65
77
|
});
|
|
66
|
-
|
|
78
|
+
const ClusterFailures = Schema.Union([
|
|
79
|
+
ClusterError.MailboxFull,
|
|
80
|
+
ClusterError.PersistenceError,
|
|
81
|
+
ClusterError.AlreadyProcessingMessage,
|
|
82
|
+
ClusterError.EntityNotAssignedToRunner
|
|
83
|
+
]);
|
|
84
|
+
/**
|
|
85
|
+
* Whether a failure is one of those Effect's entity client fails with when the entity could not
|
|
86
|
+
* be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
|
|
87
|
+
* `EntityNotAssignedToRunner`, which `client`, `nativeClient` and `reaching` answer as
|
|
88
|
+
* `Action.Unavailable`: a server forwarding calls into an entity, as the Cloudflare package's
|
|
89
|
+
* socket host does, makes them a defect, and a Worker calling Effect's `Entity.client` itself
|
|
90
|
+
* answers them, as the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
|
|
91
|
+
*/
|
|
92
|
+
const isClusterFailure = Schema.is(ClusterFailures);
|
|
93
|
+
function layer(entity, served, { services = Layer.empty, rpcs = {}, onWake, ...options } = {}) {
|
|
67
94
|
const { binding } = entity;
|
|
68
95
|
const named = namedBy(entity.key);
|
|
69
96
|
const { apps, events, authentication } = servingOf("ActionEntity binding", binding, served, { actions: [...binding.actions, ...binding.events] });
|
|
@@ -71,10 +98,14 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
|
|
|
71
98
|
const build = Effect.gen(function* () {
|
|
72
99
|
const address = yield* Entity.CurrentAddress;
|
|
73
100
|
const sharding = yield* Effect.context();
|
|
74
|
-
const
|
|
101
|
+
const outsideTransactions = Effect.gen(function* () {
|
|
102
|
+
const clients = [yield* Effect.serviceOption(SqlClient.SqlClient), Context.getOption(sharding, SqlClient.SqlClient)].flatMap(Option.toArray);
|
|
103
|
+
for (const sql of clients) if (Option.isSome(yield* Effect.serviceOption(sql.transactionService))) return yield* Effect.die(/* @__PURE__ */ new Error(`ActionEntity.wakeAt: the wake of ${address.entityType}/${address.entityId} was asked for inside a SQL transaction, whose rollback would drop it unseen (call wakeAt after the transaction commits)`));
|
|
104
|
+
});
|
|
105
|
+
const { wake, woke } = yield* makeWake((payload) => Effect.andThen(outsideTransactions, Effect.flatMap(entity.client, (clientFor) => {
|
|
75
106
|
return clientFor(address.entityId)[wakeTag](payload, { discard: true });
|
|
76
|
-
}).pipe(Effect.provideContext(sharding)));
|
|
77
|
-
const built = yield* Layer.buildWithMemoMap(first === void 0 ? services : Layer.provideMerge(Layer.mergeAll(first, ...rest), services), Layer.makeMemoMapUnsafe(), yield* Effect.scope)
|
|
107
|
+
}).pipe(Effect.catchIf(isClusterFailure, ({ _tag }) => Effect.fail(new Unavailable({ message: `The wake of ${address.entityType}/${address.entityId} could not be scheduled (${_tag})` }))), Effect.provideContext(sharding))));
|
|
108
|
+
const built = yield* Layer.buildWithMemoMap(Layer.provideMerge(first === void 0 ? services : Layer.provideMerge(Layer.mergeAll(first, ...rest), services), Layer.succeed(Wake, wake)), Layer.makeMemoMapUnsafe(), yield* Effect.scope);
|
|
78
109
|
const check = (contract, input) => {
|
|
79
110
|
const entityId = named(input);
|
|
80
111
|
return entityId === address.entityId ? Effect.void : Effect.fail(new Forbidden({ message: `This entity is ${address.entityType}/${address.entityId}, and the input of ${contract.name} names ${entityId ?? "none"}` }));
|
|
@@ -89,9 +120,10 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
|
|
|
89
120
|
}
|
|
90
121
|
}), built);
|
|
91
122
|
const natives = yield* Effect.provideContext(Effect.isEffect(rpcs) ? rpcs : Effect.succeed(rpcs), built);
|
|
123
|
+
const woken = (at) => onWake === void 0 ? Effect.void : Effect.provideContext(Effect.catchCauseIf(onWake(DateTime.makeUnsafe(at)), (cause) => !Cause.hasInterruptsOnly(cause), reported), built);
|
|
92
124
|
const answering = (handler) => (request) => Rpc.wrapMap(handler(request), (answer) => Effect.isEffect(answer) ? Effect.provideContext(answer, built) : Stream.provideContext(answer, built));
|
|
93
125
|
return Object.fromEntries([...nativeOf(entity.protocol).requests.values()].map((rpc) => {
|
|
94
|
-
if (rpc._tag === "effect-actions/wake") return [rpc._tag, woke];
|
|
126
|
+
if (rpc._tag === "effect-actions/wake") return [rpc._tag, ({ payload }) => Rpc.fork(Effect.andThen(woke(payload.at), () => woken(payload.at)))];
|
|
95
127
|
const handler = handlers[rpc._tag];
|
|
96
128
|
if (handler !== void 0) return [rpc._tag, (request) => {
|
|
97
129
|
const answer = handler(request.payload, callOf(request, rpc));
|
|
@@ -107,56 +139,75 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
|
|
|
107
139
|
disableFatalDefects: true
|
|
108
140
|
});
|
|
109
141
|
}
|
|
110
|
-
const
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
}
|
|
130
|
-
const reachOf = (entity, headers) => (clientFor) => {
|
|
142
|
+
const defaultTimeout = Duration.seconds(20);
|
|
143
|
+
const sendingWithin = (type, options) => {
|
|
144
|
+
const timeout = Duration.fromInputUnsafe(options.timeout ?? defaultTimeout);
|
|
145
|
+
return (entityId, rpcs) => {
|
|
146
|
+
const unavailable = (tag, outcome) => new Unavailable({ message: `${tag}: the entity ${type}/${entityId} ${outcome}; the call's outcome is unknown, as the entity may still run it` });
|
|
147
|
+
const unreached = (tag) => ({ _tag }) => unavailable(tag, `could not be reached (${_tag})`);
|
|
148
|
+
return (tag, payload, callOptions) => {
|
|
149
|
+
const method = rpcs[tag];
|
|
150
|
+
if (method === void 0) return Effect.die(/* @__PURE__ */ new Error(`ActionEntity: no rpc ${tag}`));
|
|
151
|
+
const answer = method(payload, {
|
|
152
|
+
...callOptions,
|
|
153
|
+
asQueue: false
|
|
154
|
+
});
|
|
155
|
+
return Effect.isEffect(answer) ? Effect.catchIf(answer, isClusterFailure, (failure) => Effect.fail(unreached(tag)(failure))).pipe(Effect.timeoutOrElse({
|
|
156
|
+
duration: timeout,
|
|
157
|
+
orElse: () => Effect.fail(unavailable(tag, `did not answer within ${Duration.format(timeout)}`))
|
|
158
|
+
})) : Stream.catchIf(answer, isClusterFailure, (failure) => Stream.fail(unreached(tag)(failure)));
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
const reachOf = (entity, headers, options) => (clientFor) => {
|
|
131
163
|
const named = namedBy(entity.key);
|
|
164
|
+
const sending = sendingWithin(entity.type, options);
|
|
132
165
|
return (contract, input) => {
|
|
133
166
|
const entityId = named(input);
|
|
134
|
-
return entityId === void 0 ? Effect.fail(new Forbidden({ message: `The input of ${contract.name} names no entity of ${entity.type}` })) : Effect.map(headers, (sent) =>
|
|
167
|
+
return entityId === void 0 ? Effect.fail(new Forbidden({ message: `The input of ${contract.name} names no entity of ${entity.type}` })) : Effect.map(headers, (sent) => {
|
|
168
|
+
const send = sending(entityId, clientFor(entityId));
|
|
169
|
+
return erasedCallOf((tag, payload) => send(tag, payload, sent === void 0 ? void 0 : { headers: sent }));
|
|
170
|
+
});
|
|
135
171
|
};
|
|
136
172
|
};
|
|
137
173
|
/**
|
|
138
174
|
* The client of `entity` over Effect's own `Entity.client`: one method per action taking its
|
|
139
175
|
* input, `rooms.postMessage({ room: "lobby", text })`, and `watch(event, input, options)`, which
|
|
140
|
-
* polls the event's rpc, each call and watch sent to the entity its input's key names.
|
|
141
|
-
*
|
|
142
|
-
*
|
|
176
|
+
* polls the event's rpc, each call and watch sent to the entity its input's key names. A call
|
|
177
|
+
* the entity could not be reached for, or that did not answer within `options.timeout`, 20
|
|
178
|
+
* seconds by default, fails with the built-in `Action.Unavailable`, as through `reaching`.
|
|
179
|
+
* Requires `Sharding`, as `Entity.client` does: `TestRunner.layer` in a test. The entity's native
|
|
180
|
+
* rpcs are `nativeClient`'s methods.
|
|
143
181
|
*
|
|
144
182
|
* **Gotchas**
|
|
145
183
|
*
|
|
146
184
|
* - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
|
|
147
185
|
* - Headers set with `RpcClient.withHeaders` around a call go with its envelope, which is how a protected call sends its credential; a call without them fails `Unauthenticated`.
|
|
148
|
-
* -
|
|
149
|
-
* - A watch
|
|
186
|
+
* - What `Entity.client` fails with, `MailboxFull`, `AlreadyProcessingMessage`, `PersistenceError` or `EntityNotAssignedToRunner`, is the call's `Action.Unavailable`, its message naming that failure and saying the outcome is unknown, as the entity may still run the call.
|
|
187
|
+
* - A watch polls, its only `mode` `"poll"`, at the page's `nextPollMs`, each poll bounded by `timeout`, its polls holding the subscription hook of the caller's principal in the entity until its source's `lease` lapses after the last, whichever watch sent it.
|
|
188
|
+
* - A watch asks the entity again after `Action.Unavailable`, from where it reached, a second later and doubling to 30 seconds; another declared error, a refusal included, ends it.
|
|
150
189
|
*/
|
|
151
|
-
const client = (entity) => {
|
|
152
|
-
const methods = methodsOf(entity.binding, polledTransport(
|
|
153
|
-
const reach = reachOf(entity, Effect.undefined);
|
|
190
|
+
const client = (entity, options = {}) => {
|
|
191
|
+
const methods = methodsOf(entity.binding, polledTransport(Function.constFalse));
|
|
192
|
+
const reach = reachOf(entity, Effect.undefined, options);
|
|
154
193
|
return Effect.map(entity.client, (clientFor) => methods(reach(clientFor)));
|
|
155
194
|
};
|
|
156
|
-
|
|
195
|
+
function nativeClient(entity, options = {}) {
|
|
196
|
+
const sending = sendingWithin(entity.type, options);
|
|
197
|
+
const library = libraryRpcsOf(entity.binding).requests;
|
|
198
|
+
const tags = [...entity.protocol.requests.keys()].filter((tag) => !library.has(tag));
|
|
199
|
+
return Effect.map(entity.client, (clientFor) => (entityId) => {
|
|
200
|
+
const send = sending(entityId, clientFor(entityId));
|
|
201
|
+
return Object.fromEntries(tags.map((tag) => [tag, (payload, callOptions) => {
|
|
202
|
+
const answer = send(tag, payload, callOptions);
|
|
203
|
+
return Stream.isStream(answer) && callOptions?.asQueue === true ? Stream.toQueue(answer, { capacity: callOptions.streamBufferSize ?? 16 }) : answer;
|
|
204
|
+
}]));
|
|
205
|
+
});
|
|
206
|
+
}
|
|
157
207
|
/**
|
|
158
208
|
* The implementations of `entity`'s actions and event types that any surface serves beside its
|
|
159
|
-
* own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp
|
|
209
|
+
* own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`, one for every action the
|
|
210
|
+
* entity lists, those no surface's binding lists included: each call sent through
|
|
160
211
|
* `Entity.client` to the entity its contract's key names for its input, with the caller's
|
|
161
212
|
* headers, and its answer, declared errors and progress passed back; each event followed through
|
|
162
213
|
* the entity's poll rpc. A call the entity could not be reached for, or that did not answer
|
|
@@ -165,6 +216,7 @@ const defaultTimeout = Duration.seconds(20);
|
|
|
165
216
|
*
|
|
166
217
|
* **Gotchas**
|
|
167
218
|
*
|
|
219
|
+
* - A surface that serves every implementation it is given serves the entity's internal actions to its callers too: `ActionMcp.layerHttp` without `actions`, and `ActionRpc.layer` or `ActionHttp.layer` on `entity.binding`, so give MCP its `actions` and the others a binding of the public contracts.
|
|
168
220
|
* - The caller's credential is verified by the surface serving these and again by the entity reached, so both are given the verifier: a call the surface refuses reaches no entity.
|
|
169
221
|
* - A refusal by the entity, a credential expired since the surface verified it included, ends a stream after it answered 200, where the surface's own refusal would have answered its 401 or 403.
|
|
170
222
|
* - The caller's request's headers are sent on as `forwardedHeaders` keeps them: its connection's, its body's, what it accepts and an MCP request's routing headers are not.
|
|
@@ -177,26 +229,14 @@ const defaultTimeout = Duration.seconds(20);
|
|
|
177
229
|
* - HTTP's `text/event-stream` whose polling ended on a failure other than a refusal sends `Failed` and opens it again 5 seconds later, from where it reached; MCP's `events/stream` does what `ActionMcp.layerHttp` says of an upstream's failure, a `-32603` before `active`.
|
|
178
230
|
* - A stream's polls, and a poll, MCP's `events/poll` included, hold the subscriber's subscription hook in the entity until its source's `lease` lapses after the last, as on any surface.
|
|
179
231
|
* - A protected event's webhook subscription is held by the entity its input's key names, the subscribe and unsubscribe sent there with the caller's headers, and delivered by the `Webhook.layer` in that entity's `services`, never the serving surface's: an entity without one fails the subscribe with `Event.SubscriptionError`, reason `Unsupported`, a 409 over HTTP, before any callback is sent.
|
|
180
|
-
* - An error the entity declares beyond the action's own and the built-in ones, its
|
|
232
|
+
* - An error the entity declares beyond the action's own and the built-in ones, its verifier's, is undeclared where the serving surface's binding does not declare it too.
|
|
181
233
|
*/
|
|
182
234
|
const reaching = (entity, options = {}) => {
|
|
183
235
|
const { binding } = entity;
|
|
184
|
-
const reaches = Effect.map(entity.client, reachOf(entity, forwarded));
|
|
185
|
-
const named = namedBy(entity.key);
|
|
186
|
-
const timeout = Duration.fromInputUnsafe(options.timeout ?? defaultTimeout);
|
|
187
|
-
const unavailable = (contract, input) => (outcome) => new Unavailable({ message: `${contract.name}: the entity ${entity.type}/${named(input) ?? "none"} ${outcome}; the call's outcome is unknown, as the entity may still run it` });
|
|
188
|
-
const unreached = (contract, input, answer) => Effect.catchIf(answer, isClusterFailure, (failure) => Effect.fail(unavailable(contract, input)(`could not be reached (${failure._tag})`)));
|
|
189
|
-
const bounded = (contract, input, answer) => Effect.timeoutOrElse(unreached(contract, input, answer), {
|
|
190
|
-
duration: timeout,
|
|
191
|
-
orElse: () => Effect.fail(unavailable(contract, input)(`did not answer within ${Duration.format(timeout)}`))
|
|
192
|
-
});
|
|
236
|
+
const reaches = Effect.map(entity.client, reachOf(entity, forwarded, options));
|
|
193
237
|
const handlerOf = (action, reach) => {
|
|
194
238
|
const method = actionMethodOf(action, binding)(reach);
|
|
195
|
-
return (input, reporting) => {
|
|
196
|
-
const answer = method(input, ...reporting === void 0 ? [] : [{ onProgress: reporting.progress }]);
|
|
197
|
-
if (!Effect.isEffect(answer)) return Stream.catchIf(answer, isClusterFailure, (failure) => Stream.fail(unavailable(action, input)(`could not be reached (${failure._tag})`)));
|
|
198
|
-
return action.progress === void 0 ? bounded(action, input, answer) : unreached(action, input, answer);
|
|
199
|
-
};
|
|
239
|
+
return (input, reporting) => method(input, ...reporting === void 0 ? [] : [{ onProgress: reporting.progress }]);
|
|
200
240
|
};
|
|
201
241
|
const runOf = (event, reach) => {
|
|
202
242
|
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(event.input));
|
|
@@ -204,24 +244,24 @@ const reaching = (entity, options = {}) => {
|
|
|
204
244
|
const watched = watchedOf(event, binding);
|
|
205
245
|
const webhookCalls = webhookCallsOf(event, binding);
|
|
206
246
|
const reached = (input) => Effect.all([reach(event, input), Effect.orDie(encode(input))]);
|
|
207
|
-
const inEntity = (input, sent) => Effect.flatMap(reach(event, input), (call) =>
|
|
247
|
+
const inEntity = (input, sent) => Effect.flatMap(reach(event, input), (call) => sent(webhookCalls(call)));
|
|
208
248
|
return {
|
|
209
249
|
polls: true,
|
|
210
250
|
webhook: offersWebhook(event) ? {
|
|
211
251
|
subscribe: (subscribing) => inEntity(subscribing.input, (held) => held.subscribe(subscribing)),
|
|
212
252
|
unsubscribe: (subscription) => inEntity(subscription.input, (held) => held.unsubscribe(subscription))
|
|
213
253
|
} : void 0,
|
|
214
|
-
poll: (input, cursor, { maxEvents }) => Effect.flatMap(reached(input), ([call, json]) =>
|
|
254
|
+
poll: (input, cursor, { maxEvents }) => Effect.flatMap(reached(input), ([call, json]) => poll(call)({
|
|
215
255
|
input: json,
|
|
216
256
|
cursor,
|
|
217
257
|
...maxEvents === void 0 ? {} : { maxEvents }
|
|
218
|
-
}))
|
|
258
|
+
})),
|
|
219
259
|
stream: (input, cursor) => Stream.unwrap(Effect.map(reached(input), ([call, json]) => {
|
|
220
260
|
const transport = watched(call)(json);
|
|
221
|
-
return polling(
|
|
261
|
+
return polling(transport, Function.constFalse)(cursor);
|
|
222
262
|
}))
|
|
223
263
|
};
|
|
224
264
|
};
|
|
225
265
|
return [...binding.actions.length === 0 ? [] : [new Implementation(binding.actions, memoized(Effect.map(reaches, (reach) => binding.actions.map((action) => [action, handlerOf(action, reach)]))), memoized(Effect.succeed(allowAll)))], ...binding.events.length === 0 ? [] : [new EventImplementation(binding.events, binding.events.map((event) => [event, memoized(Effect.map(reaches, (reach) => runOf(event, reach)))]), memoized(Effect.succeed(allowAll$1)))]];
|
|
226
266
|
};
|
|
227
|
-
export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, reaching };
|
|
267
|
+
export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, nativeClient, reaching, wakeAt };
|
package/dist/ActionHttp.d.mts
CHANGED
|
@@ -145,8 +145,11 @@ export declare function make<const Contracts extends ReadonlyArray<Any$1 | Any$2
|
|
|
145
145
|
* Serve the binding's actions and event types among `implementations` in one layer, or those its
|
|
146
146
|
* `actions` lists, authenticating a protected action's request before decoding it, then running
|
|
147
147
|
* its implementation's `authorize` before each handler. An implementation's actions the binding
|
|
148
|
-
* leaves out have no route here, one holding none of those served is not built
|
|
149
|
-
*
|
|
148
|
+
* leaves out have no route here, and one holding none of those served is not built. Where the
|
|
149
|
+
* binding has no event types, implementations' event types are ignored, so
|
|
150
|
+
* `ActionEntity.reaching` serves a binding of the entity's actions alone, and the same holds for
|
|
151
|
+
* actions; otherwise implementations holding none of the binding's actions, or none of its event
|
|
152
|
+
* types, are refused when `layer` is called. Several layers
|
|
150
153
|
* may serve one binding, each with its own `actions` and `middleware` covering its routes only.
|
|
151
154
|
* The layer fails as the builders do, needs at startup what they need, and per request what the
|
|
152
155
|
* authorization and handlers of the actions it serves need, until its `middleware` or middleware
|
package/dist/ActionRpc.d.mts
CHANGED
|
@@ -16,7 +16,8 @@ import { Poll, ProgressedOf, pollTag } from "./rpc/erased.mjs";
|
|
|
16
16
|
import { AnyPage } from "./contract/pages.mjs";
|
|
17
17
|
import { Context, Duration, Effect, Layer, Schedule, Schema, Scope, Stream, Types } from "effect";
|
|
18
18
|
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
19
|
-
import { Rpc, RpcClient, RpcClientError, RpcGroup, RpcMiddleware, RpcSchema, RpcServer } from "effect/rpc";
|
|
19
|
+
import { Rpc, RpcClient, RpcClientError, RpcGroup, RpcMiddleware, RpcSchema, RpcSerialization, RpcServer } from "effect/rpc";
|
|
20
|
+
import { Socket } from "effect/socket";
|
|
20
21
|
type BindingError = Errors[number];
|
|
21
22
|
type ErrorOf<A extends Any$2, E extends Errors, D> = Schema.Union<ReadonlyArray<A["error"][number] | E[number] | VerifierError<A, D> | BuiltIns>>;
|
|
22
23
|
type ElementedOf<Element extends Schema.Constraint, P> = Schema.Union<readonly [Schema.TaggedStruct<"Element", {
|
|
@@ -235,10 +236,17 @@ type Watching<B extends Any> = [B["events"][number]] extends [never] ? unknown :
|
|
|
235
236
|
export type Client<B extends Any> = { readonly [A in B["actions"][number] as A["name"]]: Method<A, B["error"][number] | VerifierError<A, B["authentication"]>>; } & Watching<B> & RpcClient.RpcClient<RpcGroup.Rpcs<B["rpcs"]>, RpcClientError.RpcClientError>;
|
|
236
237
|
/**
|
|
237
238
|
* `client`'s options: the native `RpcClient.make` options, `spanPrefix`, `spanAttributes`,
|
|
238
|
-
* `generateRequestId` and `disableTracing`. `flatten` changes the client's
|
|
239
|
-
* method types cannot follow.
|
|
239
|
+
* `generateRequestId` and `disableTracing`, and `watchMode`. `flatten` changes the client's
|
|
240
|
+
* shape, which the method types cannot follow.
|
|
240
241
|
*/
|
|
241
|
-
export
|
|
242
|
+
export interface ClientOptions extends Omit<NonNullable<Parameters<typeof RpcClient.make>[1]>, "flatten"> {
|
|
243
|
+
/**
|
|
244
|
+
* The `mode` of a watch that gives none: `"poll"` reads its pages from the first, as a server
|
|
245
|
+
* serving events by poll alone, such as the Cloudflare package's socket host, needs, without the
|
|
246
|
+
* round trip a watch otherwise spends finding that out. A watch's own `mode` wins.
|
|
247
|
+
*/
|
|
248
|
+
readonly watchMode?: "stream" | "poll" | undefined;
|
|
249
|
+
}
|
|
242
250
|
/**
|
|
243
251
|
* How long a polling watch waits for a poll's answer, 4 minutes, before it sends the poll again
|
|
244
252
|
* from the same cursor and interrupts the first.
|
|
@@ -264,25 +272,69 @@ export declare const pollResentAfter: Duration.Duration;
|
|
|
264
272
|
* - A native rpc of the binding's `rpcs` is the native client's method: a stream rpc's is a `Stream`, its headers given as its options' `headers`, since `RpcClient.withHeaders` wraps an Effect.
|
|
265
273
|
*/
|
|
266
274
|
export declare function client<const B extends Any>(binding: B, options?: ClientOptions): Effect.Effect<Client<B>, never, RpcClient.Protocol | Scope.Scope | Rpc.MiddlewareClient<RpcGroup.Rpcs<B["rpcs"]>>>;
|
|
267
|
-
/**
|
|
268
|
-
* What `reconnectUntil`'s schedule reads of each failure to connect: the `reason` of the
|
|
269
|
-
* `Socket.SocketError` Effect's socket protocol retries after.
|
|
270
|
-
*/
|
|
271
|
-
export interface ReconnectReason {
|
|
272
|
-
readonly reason: unknown;
|
|
273
|
-
}
|
|
274
275
|
/**
|
|
275
276
|
* A socket client's `retryPolicy`, for `RpcClient.layerProtocolSocket`, that stops connecting
|
|
276
277
|
* again once the server closes the socket with one of `codes`, such as a refusal of its upgrade:
|
|
277
278
|
* until then it is Effect's own default, `Schedule.min([Schedule.exponential(500, 1.5),
|
|
278
279
|
* Schedule.spaced(5000)])`, which Effect does not export. A page refused with its code stops, its
|
|
279
280
|
* calls and streams failing with an `RpcClientError` whose `reason` is that `SocketCloseError`,
|
|
280
|
-
* its `code` the one it closed with.
|
|
281
|
+
* its `code` the one it closed with. `socketClient` stops at every application code already.
|
|
281
282
|
*
|
|
282
283
|
* **Gotchas**
|
|
283
284
|
*
|
|
284
285
|
* - A client without it connects again after a refusal as after any close, every five seconds for good.
|
|
285
286
|
* - Any other socket error, a drop included, is retried as Effect's default retries it.
|
|
287
|
+
* - A watch through `client` connects again after a close below 4000 whatever the protocol stopped at, failing each time: stop at codes from 4000 to 4999, which a watch ends at.
|
|
288
|
+
*/
|
|
289
|
+
export declare const reconnectUntil: (...codes: readonly number[]) => Schedule.Schedule<Duration.Duration, Socket.SocketError, never, never>;
|
|
290
|
+
/** Where `socketClient` connects: a URL, or a socket made elsewhere, never both. */
|
|
291
|
+
export type SocketTarget = {
|
|
292
|
+
/** The `ws:` or `wss:` URL the client dials, again after each drop. */
|
|
293
|
+
readonly url: string;
|
|
294
|
+
/**
|
|
295
|
+
* What makes each WebSocket. Omitted: the global `WebSocket`, looked up on every
|
|
296
|
+
* connection, as a browser has it. Node's `ws` package, `(url) => new WebSocket(url, {
|
|
297
|
+
* headers })`, sends headers on the upgrade, which a browser cannot.
|
|
298
|
+
*/
|
|
299
|
+
readonly webSocket?: Socket.WebSocketConstructor["Service"] | undefined;
|
|
300
|
+
readonly socket?: never;
|
|
301
|
+
} | {
|
|
302
|
+
/**
|
|
303
|
+
* A `Socket` made elsewhere, such as `Socket.fromWebSocket` over a socket a Worker's
|
|
304
|
+
* `fetch` returned: its acquisition runs again for each connection.
|
|
305
|
+
*/
|
|
306
|
+
readonly socket: Socket.Socket;
|
|
307
|
+
readonly url?: never;
|
|
308
|
+
readonly webSocket?: never;
|
|
309
|
+
};
|
|
310
|
+
/** What `socketClient` takes: where it connects, its connection hooks, and `client`'s options. */
|
|
311
|
+
export type SocketClientOptions = SocketTarget & ClientOptions & {
|
|
312
|
+
/**
|
|
313
|
+
* Effects run as each connection opens and as it ends, Effect's `RpcClient.ConnectionHooks`:
|
|
314
|
+
* a page showing that it is connected.
|
|
315
|
+
*/
|
|
316
|
+
readonly hooks?: Partial<RpcClient.ConnectionHooks["Service"]> | undefined;
|
|
317
|
+
/**
|
|
318
|
+
* How messages are written on the socket: `RpcSerialization.json` by default, which the
|
|
319
|
+
* Cloudflare package's socket host reads; the server's own, such as `RpcSerialization.ndjson`,
|
|
320
|
+
* for an `ActionRpc.layer` served under another.
|
|
321
|
+
*/
|
|
322
|
+
readonly serialization?: RpcSerialization.RpcSerialization["Service"] | undefined;
|
|
323
|
+
};
|
|
324
|
+
/**
|
|
325
|
+
* `client` over one WebSocket the client holds, for as long as the `Scope` it is built in:
|
|
326
|
+
* Effect's socket protocol, under JSON serialization unless `serialization` says otherwise, its
|
|
327
|
+
* calls and watches sharing the socket, which connects again after a drop as Effect's own socket client
|
|
328
|
+
* does. A close with an application code, 4000 to 4999, such as a server's refusal, stops it:
|
|
329
|
+
* every call and watch under way, and each later one, fails with an `RpcClientError` whose
|
|
330
|
+
* `reason` is that `SocketCloseError`. Guide: `docs/ActionRpc.md#call-the-rpcs`.
|
|
331
|
+
*
|
|
332
|
+
* **Gotchas**
|
|
333
|
+
*
|
|
334
|
+
* - The socket closes with the `Scope` the client was built in, not with each call's: a call or a watch run after that scope ends is interrupted.
|
|
335
|
+
* - Once stopped by a close it never connects again: build a new client, in a new `Scope`, such as after a page's reload.
|
|
336
|
+
* - It stops only at a close the socket delivers: a WebSocket firing `error` before a refusal's `close`, as Node's may, is read by Effect's `Socket.fromWebSocket` as a drop and connected again.
|
|
337
|
+
* - A protocol of your own takes `client` under `RpcClient.layerProtocolSocket`, its `retryPolicy` `reconnectUntil(code)`: a watch over it still connects again after a code below 4000.
|
|
286
338
|
*/
|
|
287
|
-
export declare const
|
|
339
|
+
export declare function socketClient<const B extends Any>(binding: B, options: SocketClientOptions): Effect.Effect<Client<B>, never, Scope.Scope | Rpc.MiddlewareClient<RpcGroup.Rpcs<B["rpcs"]>>>;
|
|
288
340
|
export { AnyPage as Page, Poll, pollTag };
|
package/dist/ActionRpc.mjs
CHANGED
|
@@ -5,10 +5,11 @@ import { reservedList, reservedNames } from "./contract/names.mjs";
|
|
|
5
5
|
import { PushedOf, SubscriptionOf } from "./contract/push.mjs";
|
|
6
6
|
import { provideServed, servingOf } from "./contract/serving.mjs";
|
|
7
7
|
import { Poll, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollTag, polledTransport, streamedOf, streamedTransport, verifyingNative } from "./rpc/erased.mjs";
|
|
8
|
-
import { isRpcTransient } from "./rpc/watch.mjs";
|
|
8
|
+
import { isApplicationCode, isRpcTransient } from "./rpc/watch.mjs";
|
|
9
9
|
import { AnyPage } from "./contract/pages.mjs";
|
|
10
10
|
import { Duration, Effect, Function, Layer, Predicate, Schedule, Schema } from "effect";
|
|
11
|
-
import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcServer } from "effect/rpc";
|
|
11
|
+
import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcSerialization, RpcServer } from "effect/rpc";
|
|
12
|
+
import { Socket } from "effect/socket";
|
|
12
13
|
// src/rpc/ActionRpc.ts
|
|
13
14
|
const authenticatedKey = "effect-actions/ActionRpc/Authenticated";
|
|
14
15
|
const authenticatedOf = (authentication) => RpcMiddleware.Service()(authenticatedKey, { error: Schema.Union([Unauthenticated, ...authentication.error]) });
|
|
@@ -77,27 +78,41 @@ function layer(binding, served, options = {}) {
|
|
|
77
78
|
* from the same cursor and interrupts the first.
|
|
78
79
|
*/
|
|
79
80
|
const pollResentAfter = Duration.minutes(4);
|
|
80
|
-
function client(binding, options = {}) {
|
|
81
|
+
function client(binding, { watchMode, ...options } = {}) {
|
|
81
82
|
return Effect.map(Effect.all([RpcClient.make(erasedOf(binding.actions, binding.events, "ActionRpc.layer").merge(nativeOf(binding.rpcs)), {
|
|
82
83
|
...options,
|
|
83
84
|
flatten: true
|
|
84
85
|
}), Effect.map(Effect.service(RpcClient.Protocol), ({ supportsAck }) => !supportsAck)]), ([call, silenceEnds]) => ({
|
|
85
|
-
...methodsOf(binding, streamedTransport(silenceEnds, polledTransport(isRpcTransient, pollResentAfter)))(Function.constant(Effect.succeed(erasedCallOf(call)))),
|
|
86
|
+
...methodsOf(binding, streamedTransport(silenceEnds, polledTransport(isRpcTransient, pollResentAfter)), watchMode)(Function.constant(Effect.succeed(erasedCallOf(call)))),
|
|
86
87
|
...Object.fromEntries([...nativeOf(binding.rpcs).requests.keys()].map((tag) => [tag, (payload, callOptions) => call(tag, payload, callOptions)]))
|
|
87
88
|
}));
|
|
88
89
|
}
|
|
90
|
+
const reconnectingUnless = (stops) => Schedule.min([Schedule.exponential(500, 1.5), Schedule.spaced(5e3)]).pipe(Schedule.setInputType(), Schedule.while(({ input: { reason } }) => !(reason._tag === "SocketCloseError" && stops(reason.code))));
|
|
89
91
|
/**
|
|
90
92
|
* A socket client's `retryPolicy`, for `RpcClient.layerProtocolSocket`, that stops connecting
|
|
91
93
|
* again once the server closes the socket with one of `codes`, such as a refusal of its upgrade:
|
|
92
94
|
* until then it is Effect's own default, `Schedule.min([Schedule.exponential(500, 1.5),
|
|
93
95
|
* Schedule.spaced(5000)])`, which Effect does not export. A page refused with its code stops, its
|
|
94
96
|
* calls and streams failing with an `RpcClientError` whose `reason` is that `SocketCloseError`,
|
|
95
|
-
* its `code` the one it closed with.
|
|
97
|
+
* its `code` the one it closed with. `socketClient` stops at every application code already.
|
|
96
98
|
*
|
|
97
99
|
* **Gotchas**
|
|
98
100
|
*
|
|
99
101
|
* - A client without it connects again after a refusal as after any close, every five seconds for good.
|
|
100
102
|
* - Any other socket error, a drop included, is retried as Effect's default retries it.
|
|
103
|
+
* - A watch through `client` connects again after a close below 4000 whatever the protocol stopped at, failing each time: stop at codes from 4000 to 4999, which a watch ends at.
|
|
101
104
|
*/
|
|
102
|
-
const reconnectUntil = (...codes) =>
|
|
103
|
-
|
|
105
|
+
const reconnectUntil = (...codes) => reconnectingUnless((code) => codes.includes(code));
|
|
106
|
+
function socketClient(binding, options) {
|
|
107
|
+
const { hooks, url: _url, webSocket: _webSocket, socket: _socket, serialization = RpcSerialization.json, ...clientOptions } = options;
|
|
108
|
+
const connection = options.socket === void 0 ? Socket.layerWebSocket(options.url).pipe(Layer.provide(options.webSocket === void 0 ? Socket.layerWebSocketConstructorGlobal : Layer.succeed(Socket.WebSocketConstructor)(options.webSocket))) : Layer.succeed(Socket.Socket)(options.socket);
|
|
109
|
+
return Effect.flatMap(Layer.build(RpcClient.layerProtocolSocket({ retryPolicy: reconnectingUnless(isApplicationCode) }).pipe(Layer.provide([
|
|
110
|
+
connection,
|
|
111
|
+
Layer.succeed(RpcSerialization.RpcSerialization)(serialization),
|
|
112
|
+
Layer.succeed(RpcClient.ConnectionHooks)({
|
|
113
|
+
onConnect: hooks?.onConnect ?? Effect.void,
|
|
114
|
+
onDisconnect: hooks?.onDisconnect ?? Effect.void
|
|
115
|
+
})
|
|
116
|
+
]))), (protocol) => Effect.provideContext(client(binding, clientOptions), protocol));
|
|
117
|
+
}
|
|
118
|
+
export { AnyPage as Page, Poll, client, layer, make, pollResentAfter, pollTag, reconnectUntil, socketClient };
|
package/dist/Event.d.mts
CHANGED
|
@@ -144,22 +144,76 @@ export interface Check<E extends Any, R = never> extends Hooked<E, R> {
|
|
|
144
144
|
readonly log?: never;
|
|
145
145
|
readonly current?: never;
|
|
146
146
|
}
|
|
147
|
+
/** What `appended` reads after a position: the entries past it, oldest first. */
|
|
148
|
+
export interface Appended<E extends Any> {
|
|
149
|
+
/** The occurrences' data, oldest first: none where every entry read was skipped. */
|
|
150
|
+
readonly items: ReadonlyArray<E["payload"]["Type"]>;
|
|
151
|
+
/**
|
|
152
|
+
* The id of the last entry read, where it is not the last item's, as where entries read are
|
|
153
|
+
* skipped: the next read goes on after it.
|
|
154
|
+
*
|
|
155
|
+
* **Gotchas**
|
|
156
|
+
*
|
|
157
|
+
* - One below the last item's id is read as the last item's, so no item is sent twice.
|
|
158
|
+
* - One past `newest` makes the next read answer `truncated: true` and the newest id, a gap the subscriber never had.
|
|
159
|
+
*/
|
|
160
|
+
readonly through?: number | undefined;
|
|
161
|
+
/**
|
|
162
|
+
* More entries are ready past `through`: the subscriber reads again without waiting. Ignored on a
|
|
163
|
+
* read that moved the cursor nowhere, which would read the same entries again at once forever.
|
|
164
|
+
*/
|
|
165
|
+
readonly hasMore?: boolean | undefined;
|
|
166
|
+
}
|
|
167
|
+
/** What `appended` needs to page a store appending entries under increasing integer ids. */
|
|
168
|
+
export interface AppendedOptions<E extends Any, RN = never, RA = never, RK = never, RS = never> extends Pick<Check<E>, "notified" | "lease"> {
|
|
169
|
+
/** The id of the newest entry, `0` while there is none, run as the subscriber. */
|
|
170
|
+
readonly newest: (input: E["input"]["Type"]) => Effect.Effect<number, Refusal, RN>;
|
|
171
|
+
/** The entries after `id`, oldest first, as many as one read takes, run as the subscriber. */
|
|
172
|
+
readonly after: (input: E["input"]["Type"], id: number) => Effect.Effect<Appended<E>, Refusal, RA>;
|
|
173
|
+
/** The id of the entry an occurrence's data was read from: its `eventId`, and a cursor. */
|
|
174
|
+
readonly id: (data: E["payload"]["Type"]) => number;
|
|
175
|
+
/** Each page's `nextPoll`; defaults to 5 seconds. */
|
|
176
|
+
readonly nextPoll?: Duration.Input | undefined;
|
|
177
|
+
readonly key?: Hooked<E, RK>["key"];
|
|
178
|
+
readonly subscription?: Hooked<E, RS>["subscription"];
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* A check source for a store that appends entries under increasing integer ids, such as a table's
|
|
182
|
+
* `INTEGER PRIMARY KEY`: its cursor is the id of the last entry a subscriber read, and an
|
|
183
|
+
* occurrence's `eventId` its entry's id. A new subscriber starts after the newest entry. `event`
|
|
184
|
+
* types the options alone, as `Event.appended(MessagePosted, { … })` in `implement`'s builder.
|
|
185
|
+
*
|
|
186
|
+
* **Gotchas**
|
|
187
|
+
*
|
|
188
|
+
* - 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.
|
|
189
|
+
* - A store deleting its oldest entries sends no gap for those a subscriber resuming before them missed: a cursor is stale only past `newest`.
|
|
190
|
+
* - 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.
|
|
191
|
+
*/
|
|
192
|
+
export declare const appended: <E extends Any, RN = never, RA = never, RK = never, RS = never>(_event: E, { newest, after, id, nextPoll, ...source }: AppendedOptions<E, RN, RA, RK, RS>) => Check<E, RN | RA | RK | RS>;
|
|
147
193
|
/**
|
|
148
194
|
* An event type whose occurrence is the whole value, such as a status or a list small enough to
|
|
149
195
|
* send whole: a subscriber receives the value as it is first, then again after each
|
|
150
|
-
* `Events.notify` that reaches it, never a change it missed one by one. The
|
|
151
|
-
* revision per key, which each such notify moves
|
|
152
|
-
*
|
|
153
|
-
*
|
|
196
|
+
* `Events.notify` that reaches it and changes it, never a change it missed one by one. The
|
|
197
|
+
* library keeps a revision per key, which each such notify moves; the revision and a digest of
|
|
198
|
+
* the subscription's input, its key and the value sent make the cursor and each occurrence's id.
|
|
199
|
+
* Its streams and webhook deliveries read it again only when notified, on no timer, so an idle
|
|
200
|
+
* Cloudflare Durable Object holding them hibernates; a polling client polls at `nextPoll`.
|
|
154
201
|
*
|
|
155
202
|
* **Gotchas**
|
|
156
203
|
*
|
|
157
|
-
* - A notify
|
|
158
|
-
* - The revision is read before `current`, so a value written between them is
|
|
204
|
+
* - A notify reads the value again for each subscriber it reaches, though a value equal to the one its cursor saw, for the same input and key, is not sent: notify after a write that may change it, not on a timer.
|
|
205
|
+
* - The revision is read before `current`, so a value written between them is read again at the next read, never missed: write the value, then notify.
|
|
206
|
+
* - A cursor is its subscription's own: one taken to another input of the same key, at a revision it already holds, is answered with nothing until the next notify.
|
|
159
207
|
*/
|
|
160
208
|
export interface Current<E extends Any, R = never> extends Hooked<E, R> {
|
|
161
209
|
/** The value as it is, as the subscriber's `input` selects it, run as the subscriber. */
|
|
162
210
|
readonly current: (input: E["input"]["Type"]) => Effect.Effect<E["payload"]["Type"], Refusal, R>;
|
|
211
|
+
/**
|
|
212
|
+
* How long a polling client waits before it asks again, read in the bounds of `Page`'s
|
|
213
|
+
* `nextPoll`; defaults to 5 seconds. Streams and webhook deliveries never wait on it: they read
|
|
214
|
+
* when notified.
|
|
215
|
+
*/
|
|
216
|
+
readonly nextPoll?: Duration.Input | undefined;
|
|
163
217
|
readonly check?: never;
|
|
164
218
|
readonly log?: never;
|
|
165
219
|
}
|