@gjermundgaraba/effect-actions 0.33.0 → 0.35.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 +4 -4
- package/dist/Action.mjs +4 -4
- package/dist/ActionEntity.d.mts +65 -25
- package/dist/ActionEntity.mjs +76 -38
- package/dist/ActionHttp.d.mts +2 -2
- package/dist/ActionHttp.mjs +3 -1
- package/dist/ActionRpc.d.mts +2 -2
- package/dist/contract/errors.d.mts +30 -3
- package/dist/contract/errors.mjs +26 -2
- package/dist/contract/watch.mjs +2 -1
- package/dist/http/client.d.mts +1 -1
- package/dist/http/unavailable.mjs +12 -0
- package/dist/mcp/client.d.mts +1 -1
- package/docs/Action-failures.md +1 -1
- package/docs/Action.md +2 -2
- package/docs/ActionEntity.md +3 -1
- package/package.json +1 -1
package/dist/Action.d.mts
CHANGED
|
@@ -2,7 +2,7 @@ import { Authorizer, Deferred as Deferred$1 } from "./contract/authorizer.mjs";
|
|
|
2
2
|
import { Call } from "./contract/call.mjs";
|
|
3
3
|
import { Anyone } from "./contract/caller.mjs";
|
|
4
4
|
import { Codec, CodecOf, Fields, NoInput } from "./contract/codec.mjs";
|
|
5
|
-
import { BuiltIn, Forbidden, InvalidInput, Issue, Refusal, Unauthenticated } from "./contract/errors.mjs";
|
|
5
|
+
import { BuiltIn, Forbidden, InvalidInput, Issue, Refusal, Unauthenticated, Unavailable, isUnavailable } from "./contract/errors.mjs";
|
|
6
6
|
import { Any as Any$1, Received, SubscriptionError } from "./Event.mjs";
|
|
7
7
|
import { EventBuildError, EventBuildServices, EventOf, EventRequestOf, HoldingEvents, ServingEvents } from "./contract/feed.mjs";
|
|
8
8
|
import { Idempotency, layerIdempotency } from "./contract/idempotency.mjs";
|
|
@@ -225,8 +225,8 @@ export declare function make<const Name extends string, const O extends Options>
|
|
|
225
225
|
* `action` with the errors `more` declared after its own, as if `make` had been given them in
|
|
226
226
|
* `error`: its handler may fail with them, and every surface answers and every client decodes
|
|
227
227
|
* them. For errors a module adds to the actions it serves, such as a proxy's or a store's,
|
|
228
|
-
* whose contracts are written elsewhere: `pipe(action, Action.withErrors([
|
|
229
|
-
* `Action.withErrors(action, [
|
|
228
|
+
* whose contracts are written elsewhere: `pipe(action, Action.withErrors([Throttled]))`, or
|
|
229
|
+
* `Action.withErrors(action, [Throttled])`.
|
|
230
230
|
*
|
|
231
231
|
* **Gotchas**
|
|
232
232
|
*
|
|
@@ -352,4 +352,4 @@ export interface ClientOptions<A extends Any | Any$1> {
|
|
|
352
352
|
* - `watch` runs as the caller around the stream, authorized when it starts.
|
|
353
353
|
*/
|
|
354
354
|
export declare function client<const Apps extends Served, const O extends ClientOptions<ActionOf<Member<Apps>> | EventOf<Member<Apps>>> = {}>(implementations: Apps, ...options: OptionalUnless<O, ClientOptions<ActionOf<Member<Apps>> | EventOf<Member<Apps>>> & O & NoInfer<Known<O, ClientOptions<Any>>>>): Effect.Effect<Client<Apps, Offered<O, ActionOf<Member<Apps>>>, Offered<O, EventOf<Member<Apps>>>>, BuildError<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventBuildError<HoldingEvents<Member<Apps>, SelectedEventsOf<O, Apps>>, SelectedEventsOf<O, Apps>>, BuildServices<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventBuildServices<HoldingEvents<Member<Apps>, SelectedEventsOf<O, Apps>>, SelectedEventsOf<O, Apps>> | Scope.Scope>;
|
|
355
|
-
export { type AnyImplementation, Anyone, type Authorize, type BuildError, type BuildServices, BuiltIn, Forbidden, Idempotency, Image, type Implementation, InvalidInput, type Issue, Refusal, Stream, type StreamOf, Unauthenticated, layerIdempotency };
|
|
355
|
+
export { type AnyImplementation, Anyone, type Authorize, type BuildError, type BuildServices, BuiltIn, Forbidden, Idempotency, Image, type Implementation, InvalidInput, type Issue, Refusal, Stream, type StreamOf, Unauthenticated, Unavailable, isUnavailable, layerIdempotency };
|
package/dist/Action.mjs
CHANGED
|
@@ -13,7 +13,7 @@ import { polledOn, queuedPush, readOn } from "./contract/push.mjs";
|
|
|
13
13
|
import { buildersOf, provideServed, selectFrom } from "./contract/serving.mjs";
|
|
14
14
|
import { Stream, elementOf } from "./contract/stream.mjs";
|
|
15
15
|
import { watching } from "./contract/watch.mjs";
|
|
16
|
-
import { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated } from "./contract/errors.mjs";
|
|
16
|
+
import { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, Unavailable, isUnavailable } from "./contract/errors.mjs";
|
|
17
17
|
import { Image } from "./contract/media.mjs";
|
|
18
18
|
import { Array as Array$1, Cause, Effect, Function, Layer, Predicate, Schema, Stream as Stream$1 } from "effect";
|
|
19
19
|
// src/contract/Action.ts
|
|
@@ -51,8 +51,8 @@ const appendErrors = (action, more) => {
|
|
|
51
51
|
* `action` with the errors `more` declared after its own, as if `make` had been given them in
|
|
52
52
|
* `error`: its handler may fail with them, and every surface answers and every client decodes
|
|
53
53
|
* them. For errors a module adds to the actions it serves, such as a proxy's or a store's,
|
|
54
|
-
* whose contracts are written elsewhere: `pipe(action, Action.withErrors([
|
|
55
|
-
* `Action.withErrors(action, [
|
|
54
|
+
* whose contracts are written elsewhere: `pipe(action, Action.withErrors([Throttled]))`, or
|
|
55
|
+
* `Action.withErrors(action, [Throttled])`.
|
|
56
56
|
*
|
|
57
57
|
* **Gotchas**
|
|
58
58
|
*
|
|
@@ -134,4 +134,4 @@ function client(served, options) {
|
|
|
134
134
|
...feeds.length === 0 ? {} : { watch: watcherOf(feeds) }
|
|
135
135
|
}));
|
|
136
136
|
}
|
|
137
|
-
export { Anyone, BuiltIn, Forbidden, Idempotency, Image, InvalidInput, Refusal, Stream, Unauthenticated, allowAll, byName, client, implement, layer, layerIdempotency, make, withErrors };
|
|
137
|
+
export { Anyone, BuiltIn, Forbidden, Idempotency, Image, InvalidInput, Refusal, Stream, Unauthenticated, Unavailable, allowAll, byName, client, implement, isUnavailable, layer, layerIdempotency, make, withErrors };
|
package/dist/ActionEntity.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { RemoteRequest, ServedProvider, ServerBuildServices, VerifierError } from "./authentication/provider.mjs";
|
|
2
2
|
import { Any as Any$1, Errors } from "./Action.mjs";
|
|
3
3
|
import { Call } from "./contract/call.mjs";
|
|
4
|
-
import { BuiltIns } from "./contract/errors.mjs";
|
|
4
|
+
import { BuiltIns, Unavailable } from "./contract/errors.mjs";
|
|
5
5
|
import { Any as Any$2, Received, SubscriptionError } from "./Event.mjs";
|
|
6
6
|
import { EventBuildServices, EventImplementation, EventServedRequest, HoldingEvents, ServingEvents } from "./contract/feed.mjs";
|
|
7
7
|
import { Holding, Implementation, Member, Served } from "./contract/implementation.mjs";
|
|
@@ -10,10 +10,10 @@ import { WatchArgs } from "./contract/watch.mjs";
|
|
|
10
10
|
import { Any as Any$3 } from "./ActionRpc.mjs";
|
|
11
11
|
import { erasedOf } from "./rpc/erased.mjs";
|
|
12
12
|
import { forwardedHeaders } from "./entity/forwarded.mjs";
|
|
13
|
-
import { Effect, Layer,
|
|
13
|
+
import { Duration, Effect, Layer, Scope, Stream } from "effect";
|
|
14
14
|
import { ClusterError, Entity as Entity$1, Sharding } from "effect/cluster";
|
|
15
15
|
import { HttpServerRequest } from "effect/http";
|
|
16
|
-
import { Rpc, RpcGroup } from "effect/rpc";
|
|
16
|
+
import { Rpc, RpcClient, RpcGroup } from "effect/rpc";
|
|
17
17
|
type Contract<B extends Any$3> = B["actions"][number] | B["events"][number];
|
|
18
18
|
/**
|
|
19
19
|
* The key of the binding `B`'s actions and event types, the id of the entity that serves a call
|
|
@@ -160,29 +160,28 @@ type EntityLayer<B extends Any$3, Apps extends Served, N extends Rpc.Any, ROut,
|
|
|
160
160
|
* - An implementation missing for one of the binding's actions or event types throws as the layer is made: an entity serves its whole binding.
|
|
161
161
|
*/
|
|
162
162
|
export declare function layer<const Type extends string, const B extends Any$3, N extends Rpc.Any, const Apps extends Served, ROut = never, RIn = never, Handlers extends Entity$1.HandlersFrom<N> = never, RX = never>(entity: Entity<Type, B, N>, implementations: Apps & NoPerCall<B, Apps, ROut>, ...options: NativeLayerOptions<N, ROut, RIn, Handlers, RX>): EntityLayer<B, Apps, N, ROut, RIn, Handlers, RX>;
|
|
163
|
-
declare const ClusterFailures: Schema.Union<readonly [typeof ClusterError.MailboxFull, typeof ClusterError.PersistenceError, typeof ClusterError.AlreadyProcessingMessage, typeof ClusterError.EntityNotAssignedToRunner]>;
|
|
164
|
-
type ClusterFailure = typeof ClusterFailures.Type;
|
|
165
163
|
/**
|
|
166
164
|
* Whether a failure is one of those Effect's entity client fails with when the entity could not
|
|
167
165
|
* be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
|
|
168
|
-
* `EntityNotAssignedToRunner`, which `client
|
|
169
|
-
*
|
|
170
|
-
* does, makes them
|
|
166
|
+
* `EntityNotAssignedToRunner`, which `client`, `nativeClient` and `reaching` answer as
|
|
167
|
+
* `Action.Unavailable`: a server forwarding calls into an entity, as the Cloudflare package's
|
|
168
|
+
* socket host does, makes them a defect, and a Worker calling Effect's `Entity.client` itself
|
|
169
|
+
* answers them, as the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
|
|
171
170
|
*/
|
|
172
171
|
export declare const isClusterFailure: <I>(input: I) => input is I & (ClusterError.AlreadyProcessingMessage | ClusterError.EntityNotAssignedToRunner | ClusterError.MailboxFull | ClusterError.PersistenceError);
|
|
173
172
|
/**
|
|
174
173
|
* What one call of an action `A` fails with, beside the binding's errors `E`: its declared and
|
|
175
|
-
* built-in errors,
|
|
176
|
-
*
|
|
174
|
+
* built-in errors, `Action.Unavailable` among them where the entity could not be reached or did
|
|
175
|
+
* not answer in time. An answer that does not decode is a defect.
|
|
177
176
|
*/
|
|
178
|
-
export type MethodError<A extends Any$1, E extends Errors[number] = never> = A["error"][number]["Type"] | E["Type"] | BuiltIns["Type"]
|
|
177
|
+
export type MethodError<A extends Any$1, E extends Errors[number] = never> = A["error"][number]["Type"] | E["Type"] | BuiltIns["Type"];
|
|
179
178
|
type Method<A extends Any$1, E extends Errors[number]> = Call<A, Answer<A["success"], MethodError<A, E>, never>>;
|
|
180
179
|
/**
|
|
181
180
|
* What a watch of `W` over the binding `B` may fail with: a refusal, `InvalidInput`, the
|
|
182
|
-
* binding's errors
|
|
183
|
-
* serve)
|
|
181
|
+
* binding's errors or an `Event.SubscriptionError` (`NotServed` for an event the entity does not
|
|
182
|
+
* serve).
|
|
184
183
|
*/
|
|
185
|
-
export type WatchError<W extends Any$2, B extends Any$3> = SubscriptionError | BuiltIns["Type"] | B["error"][number]["Type"] | VerifierError<W, B["authentication"]>["Type"]
|
|
184
|
+
export type WatchError<W extends Any$2, B extends Any$3> = SubscriptionError | BuiltIns["Type"] | B["error"][number]["Type"] | VerifierError<W, B["authentication"]>["Type"];
|
|
186
185
|
type Watching<B extends Any$3> = [B["events"][number]] extends [never] ? unknown : {
|
|
187
186
|
readonly watch: <W extends B["events"][number], SE = never>(event: W, ...args: WatchArgs<W, SE, {
|
|
188
187
|
readonly mode?: "poll" | undefined;
|
|
@@ -194,28 +193,69 @@ type Watching<B extends Any$3> = [B["events"][number]] extends [never] ? unknown
|
|
|
194
193
|
* options)` follows one by polling.
|
|
195
194
|
*/
|
|
196
195
|
export type Client<B extends Any$3> = { readonly [A in B["actions"][number] as A["name"]]: Method<A, B["error"][number] | VerifierError<A, B["authentication"]>>; } & Watching<B>;
|
|
196
|
+
/** `client`'s, `nativeClient`'s and `reaching`'s options. */
|
|
197
|
+
export interface EntityCallOptions {
|
|
198
|
+
/**
|
|
199
|
+
* How long one call to the entity waits for its answer before failing with
|
|
200
|
+
* `Action.Unavailable`: an action's call, a native rpc's, a poll, and a webhook subscribe or
|
|
201
|
+
* unsubscribe. 20 seconds by default.
|
|
202
|
+
*
|
|
203
|
+
* **Gotchas**
|
|
204
|
+
*
|
|
205
|
+
* - It bounds the wait for the entity's answer alone, as the `Unavailable` it fails with says the entity did not answer: encoding the input and decoding the answer, in the caller's process, run outside it.
|
|
206
|
+
* - It bounds each call and each poll alone: a stream following an event, HTTP's `text/event-stream`, an RPC subscription or a watch, outlives it, each of its polls bounded by it.
|
|
207
|
+
* - A streaming rpc, a streaming action's, one declaring `progress` or answering `Action.Stream`, or a native one's, its `asQueue` call's included, has no deadline, as it may answer for longer: bound it with the host's request timeout.
|
|
208
|
+
* - The call is interrupted at the deadline, and the entity may have run part of it or all of it: the answer is `Unavailable`, the outcome unknown.
|
|
209
|
+
*/
|
|
210
|
+
readonly timeout?: Duration.Input | undefined;
|
|
211
|
+
}
|
|
197
212
|
/**
|
|
198
213
|
* The client of `entity` over Effect's own `Entity.client`: one method per action taking its
|
|
199
214
|
* input, `rooms.postMessage({ room: "lobby", text })`, and `watch(event, input, options)`, which
|
|
200
|
-
* polls the event's rpc, each call and watch sent to the entity its input's key names.
|
|
201
|
-
*
|
|
202
|
-
*
|
|
215
|
+
* polls the event's rpc, each call and watch sent to the entity its input's key names. A call
|
|
216
|
+
* the entity could not be reached for, or that did not answer within `options.timeout`, 20
|
|
217
|
+
* seconds by default, fails with the built-in `Action.Unavailable`, as through `reaching`.
|
|
218
|
+
* Requires `Sharding`, as `Entity.client` does: `TestRunner.layer` in a test. The entity's native
|
|
219
|
+
* rpcs are `nativeClient`'s methods.
|
|
203
220
|
*
|
|
204
221
|
* **Gotchas**
|
|
205
222
|
*
|
|
206
223
|
* - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
|
|
207
224
|
* - 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`.
|
|
208
|
-
* -
|
|
209
|
-
* - A watch
|
|
225
|
+
* - 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.
|
|
226
|
+
* - 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.
|
|
227
|
+
* - 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.
|
|
228
|
+
*/
|
|
229
|
+
export declare const client: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(entity: Entity<Type, B, N>, options?: EntityCallOptions) => Effect.Effect<Client<B>, never, Sharding.Sharding>;
|
|
230
|
+
/**
|
|
231
|
+
* Effect's own client of an entity's native rpcs `N`, `make`'s `rpcs`, its methods keyed by rpc
|
|
232
|
+
* tag, each failing with its rpc's errors and `Action.Unavailable` in place of what Effect's
|
|
233
|
+
* entity client fails with.
|
|
234
|
+
*/
|
|
235
|
+
export type NativeClient<N extends Rpc.Any> = RpcClient.RpcClient.From<N, Unavailable>;
|
|
236
|
+
/**
|
|
237
|
+
* The client of `entity`'s native rpcs, `make`'s `rpcs`, over Effect's own `Entity.client`, for
|
|
238
|
+
* the entity id it is given: `(yield* ActionEntity.nativeClient(Room))("lobby").expire()`. Each
|
|
239
|
+
* call answers as `client`'s do: one the entity could not be reached for, or that did not answer
|
|
240
|
+
* within `options.timeout`, 20 seconds by default, fails with `Action.Unavailable`. Requires
|
|
241
|
+
* `Sharding`, as `Entity.client` does.
|
|
242
|
+
*
|
|
243
|
+
* **Gotchas**
|
|
244
|
+
*
|
|
245
|
+
* - A tell, a call with `discard: true`, is bounded too: it fails with `Unavailable` where the entity's mailbox did not take it within `timeout`.
|
|
246
|
+
* - A stream rpc's call has no deadline, and a cluster failure ends its stream with `Unavailable`; a call with `asQueue: true` makes its queue from that stream, buffering `streamBufferSize` elements, 16 by default, so a take fails with `Unavailable` too.
|
|
247
|
+
* - Effect's own `entity.client` still fails with the cluster's errors, and waits without end on an entity no runner is assigned: call it only where that is wanted.
|
|
210
248
|
*/
|
|
211
|
-
export declare
|
|
249
|
+
export declare function nativeClient<const Type extends string, const B extends Any$3, N extends Rpc.Any>(entity: Entity<Type, B, N>, options?: EntityCallOptions): Effect.Effect<(entityId: string) => NativeClient<N>, never, Sharding.Sharding>;
|
|
212
250
|
type Nothing<C extends Any$1 | Any$2> = { readonly [K in C["name"]]: never; };
|
|
213
251
|
/**
|
|
214
252
|
* The implementations of `entity`'s actions and event types that any surface serves beside its
|
|
215
253
|
* own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
|
|
216
254
|
* `Entity.client` to the entity its contract's key names for its input, with the caller's
|
|
217
255
|
* headers, and its answer, declared errors and progress passed back; each event followed through
|
|
218
|
-
* the entity's poll rpc.
|
|
256
|
+
* the entity's poll rpc. A call the entity could not be reached for, or that did not answer
|
|
257
|
+
* within `timeout`, fails with the built-in `Action.Unavailable`, whose message says the entity
|
|
258
|
+
* may still run it.
|
|
219
259
|
*
|
|
220
260
|
* **Gotchas**
|
|
221
261
|
*
|
|
@@ -224,14 +264,14 @@ type Nothing<C extends Any$1 | Any$2> = { readonly [K in C["name"]]: never; };
|
|
|
224
264
|
* - 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.
|
|
225
265
|
* - A credential in the query, an API key the serving surface's HTTP binding reads `in: "query"`, never reaches the entity, whose binding reads headers alone, so it refuses the call with `Unauthenticated`: read the key from a header on the HTTP binding too.
|
|
226
266
|
* - A call with no HTTP request, as through `Action.client` in process or an MCP stdio surface, sends only the headers `RpcClient.withHeaders` sets around it: without them the entity refuses a protected one with `Unauthenticated`.
|
|
227
|
-
* -
|
|
267
|
+
* - What `Entity.client` fails with, `MailboxFull`, `AlreadyProcessingMessage`, `PersistenceError` or `EntityNotAssignedToRunner`, is the call's `Action.Unavailable`, its message naming that failure: a 503 with `Retry-After: 1` over HTTP, an `isError: true` tool result over MCP, the typed failure over RPC.
|
|
268
|
+
* - A call to an entity no runner is assigned, which Effect's entity client retries every `sendRetryInterval`, 100 milliseconds by default, without limit, answers `Action.Unavailable` at `timeout`.
|
|
228
269
|
* - A stream, HTTP's `text/event-stream`, an RPC subscription or MCP's `events/stream`, polls the entity from the surface, at once while a page has more and otherwise at its `nextPollMs`, a second at least: it holds the caller's request open but no entity, an occurrence arrives up to that interval late, and the entity's object takes a call each `nextPollMs` while the stream is open, so on Cloudflare a stream polling every few seconds keeps it from ever hibernating.
|
|
229
|
-
* - A stream asks the entity again after
|
|
270
|
+
* - A stream asks the entity again after a poll failed with `Action.Unavailable`, from where it reached, a second later and doubling to 30 seconds, as `client`'s watch does; any other failure, a declared error or a defect, ends its polling.
|
|
230
271
|
* - 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`.
|
|
231
272
|
* - 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.
|
|
232
273
|
* - 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.
|
|
233
|
-
* - What `Entity.client` fails with, `MailboxFull`, `AlreadyProcessingMessage`, `PersistenceError` or `EntityNotAssignedToRunner`, is the call's defect, carrying that error alone, since no action declares it: a 500 over HTTP and a defect through `Action.client`, never a typed error.
|
|
234
274
|
* - An error the entity declares beyond the action's own and the built-in ones, its binding's `error` or its verifier's, is undeclared where the serving surface's binding does not declare it too.
|
|
235
275
|
*/
|
|
236
|
-
export declare const reaching: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(entity: Entity<Type, B, N
|
|
276
|
+
export declare const reaching: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(entity: Entity<Type, B, N>, options?: EntityCallOptions) => ReadonlyArray<Implementation<B["actions"][number], Nothing<B["actions"][number]>, never, Sharding.Sharding> | EventImplementation<B["events"][number], Nothing<B["events"][number]>, never, Sharding.Sharding>>;
|
|
237
277
|
export { forwardedHeaders };
|
package/dist/ActionEntity.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Forbidden } from "./contract/errors.mjs";
|
|
1
|
+
import { Forbidden, Unavailable } from "./contract/errors.mjs";
|
|
2
2
|
import { allowAll } from "./Action.mjs";
|
|
3
3
|
import { allowAll as allowAll$1 } from "./Event.mjs";
|
|
4
4
|
import { EventImplementation } from "./contract/feed.mjs";
|
|
@@ -10,7 +10,7 @@ import { offersWebhook } from "./contract/webhooks.mjs";
|
|
|
10
10
|
import { actionMethodOf, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollOf, polledTransport, watchedOf, webhookCallsOf, webhookRpcsOf } from "./rpc/erased.mjs";
|
|
11
11
|
import { forwarded, forwardedHeaders } from "./entity/forwarded.mjs";
|
|
12
12
|
import { WakeRpc, makeWake, wakeTag } from "./entity/wakes.mjs";
|
|
13
|
-
import { Effect, Layer, Predicate, Schema, Stream } from "effect";
|
|
13
|
+
import { Duration, Effect, Function, Layer, Predicate, Schema, Stream } from "effect";
|
|
14
14
|
import { ClusterError, Entity } from "effect/cluster";
|
|
15
15
|
import { Rpc, RpcGroup, RpcMessage } from "effect/rpc";
|
|
16
16
|
// src/entity/ActionEntity.ts
|
|
@@ -18,6 +18,7 @@ const namedBy = (key) => (input) => {
|
|
|
18
18
|
const named = key(input);
|
|
19
19
|
return Predicate.isString(named) ? named : void 0;
|
|
20
20
|
};
|
|
21
|
+
const libraryRpcsOf = (binding) => erasedOf(binding.actions, binding.events, "ActionEntity.layer").merge(webhookRpcsOf(binding.events)).add(WakeRpc);
|
|
21
22
|
/**
|
|
22
23
|
* The cluster entity of type `type` serving the actions and event types of `binding`, an
|
|
23
24
|
* `ActionRpc` binding, each call and subscription in the entity its contract's `key` names for
|
|
@@ -40,7 +41,7 @@ const namedBy = (key) => (input) => {
|
|
|
40
41
|
const make = (type, binding, options) => {
|
|
41
42
|
const natives = [...nativeOf(binding.rpcs).requests.keys()];
|
|
42
43
|
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 =
|
|
44
|
+
const erased = libraryRpcsOf(binding);
|
|
44
45
|
const rpcs = options.rpcs ?? RpcGroup.make();
|
|
45
46
|
const taken = [...rpcs.requests.keys()].filter((tag) => erased.requests.has(tag) || binding.events.some(({ name }) => name === tag));
|
|
46
47
|
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)`);
|
|
@@ -107,60 +108,94 @@ function layer(entity, served, { services = Layer.empty, rpcs = {}, ...options }
|
|
|
107
108
|
disableFatalDefects: true
|
|
108
109
|
});
|
|
109
110
|
}
|
|
110
|
-
const Transients = Schema.Union([ClusterError.MailboxFull, ClusterError.PersistenceError]);
|
|
111
111
|
const ClusterFailures = Schema.Union([
|
|
112
|
-
|
|
112
|
+
ClusterError.MailboxFull,
|
|
113
|
+
ClusterError.PersistenceError,
|
|
113
114
|
ClusterError.AlreadyProcessingMessage,
|
|
114
115
|
ClusterError.EntityNotAssignedToRunner
|
|
115
116
|
]);
|
|
116
117
|
/**
|
|
117
118
|
* Whether a failure is one of those Effect's entity client fails with when the entity could not
|
|
118
119
|
* be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
|
|
119
|
-
* `EntityNotAssignedToRunner`, which `client
|
|
120
|
-
*
|
|
121
|
-
* does, makes them
|
|
120
|
+
* `EntityNotAssignedToRunner`, which `client`, `nativeClient` and `reaching` answer as
|
|
121
|
+
* `Action.Unavailable`: a server forwarding calls into an entity, as the Cloudflare package's
|
|
122
|
+
* socket host does, makes them a defect, and a Worker calling Effect's `Entity.client` itself
|
|
123
|
+
* answers them, as the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
|
|
122
124
|
*/
|
|
123
125
|
const isClusterFailure = Schema.is(ClusterFailures);
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
126
|
+
const defaultTimeout = Duration.seconds(20);
|
|
127
|
+
const sendingWithin = (type, options) => {
|
|
128
|
+
const timeout = Duration.fromInputUnsafe(options.timeout ?? defaultTimeout);
|
|
129
|
+
return (entityId, rpcs) => {
|
|
130
|
+
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` });
|
|
131
|
+
const unreached = (tag) => ({ _tag }) => unavailable(tag, `could not be reached (${_tag})`);
|
|
132
|
+
return (tag, payload, callOptions) => {
|
|
133
|
+
const method = rpcs[tag];
|
|
134
|
+
if (method === void 0) return Effect.die(/* @__PURE__ */ new Error(`ActionEntity: no rpc ${tag}`));
|
|
135
|
+
const answer = method(payload, {
|
|
136
|
+
...callOptions,
|
|
137
|
+
asQueue: false
|
|
138
|
+
});
|
|
139
|
+
return Effect.isEffect(answer) ? Effect.catchIf(answer, isClusterFailure, (failure) => Effect.fail(unreached(tag)(failure))).pipe(Effect.timeoutOrElse({
|
|
140
|
+
duration: timeout,
|
|
141
|
+
orElse: () => Effect.fail(unavailable(tag, `did not answer within ${Duration.format(timeout)}`))
|
|
142
|
+
})) : Stream.catchIf(answer, isClusterFailure, (failure) => Stream.fail(unreached(tag)(failure)));
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
};
|
|
146
|
+
const reachOf = (entity, headers, options) => (clientFor) => {
|
|
133
147
|
const named = namedBy(entity.key);
|
|
148
|
+
const sending = sendingWithin(entity.type, options);
|
|
134
149
|
return (contract, input) => {
|
|
135
150
|
const entityId = named(input);
|
|
136
|
-
return entityId === void 0 ? Effect.fail(new Forbidden({ message: `The input of ${contract.name} names no entity of ${entity.type}` })) : Effect.map(headers, (sent) =>
|
|
151
|
+
return entityId === void 0 ? Effect.fail(new Forbidden({ message: `The input of ${contract.name} names no entity of ${entity.type}` })) : Effect.map(headers, (sent) => {
|
|
152
|
+
const send = sending(entityId, clientFor(entityId));
|
|
153
|
+
return erasedCallOf((tag, payload) => send(tag, payload, sent === void 0 ? void 0 : { headers: sent }));
|
|
154
|
+
});
|
|
137
155
|
};
|
|
138
156
|
};
|
|
139
157
|
/**
|
|
140
158
|
* The client of `entity` over Effect's own `Entity.client`: one method per action taking its
|
|
141
159
|
* input, `rooms.postMessage({ room: "lobby", text })`, and `watch(event, input, options)`, which
|
|
142
|
-
* polls the event's rpc, each call and watch sent to the entity its input's key names.
|
|
143
|
-
*
|
|
144
|
-
*
|
|
160
|
+
* polls the event's rpc, each call and watch sent to the entity its input's key names. A call
|
|
161
|
+
* the entity could not be reached for, or that did not answer within `options.timeout`, 20
|
|
162
|
+
* seconds by default, fails with the built-in `Action.Unavailable`, as through `reaching`.
|
|
163
|
+
* Requires `Sharding`, as `Entity.client` does: `TestRunner.layer` in a test. The entity's native
|
|
164
|
+
* rpcs are `nativeClient`'s methods.
|
|
145
165
|
*
|
|
146
166
|
* **Gotchas**
|
|
147
167
|
*
|
|
148
168
|
* - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
|
|
149
169
|
* - 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`.
|
|
150
|
-
* -
|
|
151
|
-
* - A watch
|
|
170
|
+
* - 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.
|
|
171
|
+
* - 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.
|
|
172
|
+
* - 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.
|
|
152
173
|
*/
|
|
153
|
-
const client = (entity) => {
|
|
154
|
-
const methods = methodsOf(entity.binding, polledTransport(
|
|
155
|
-
const reach = reachOf(entity, Effect.undefined);
|
|
174
|
+
const client = (entity, options = {}) => {
|
|
175
|
+
const methods = methodsOf(entity.binding, polledTransport(Function.constFalse));
|
|
176
|
+
const reach = reachOf(entity, Effect.undefined, options);
|
|
156
177
|
return Effect.map(entity.client, (clientFor) => methods(reach(clientFor)));
|
|
157
178
|
};
|
|
179
|
+
function nativeClient(entity, options = {}) {
|
|
180
|
+
const sending = sendingWithin(entity.type, options);
|
|
181
|
+
const library = libraryRpcsOf(entity.binding).requests;
|
|
182
|
+
const tags = [...entity.protocol.requests.keys()].filter((tag) => !library.has(tag));
|
|
183
|
+
return Effect.map(entity.client, (clientFor) => (entityId) => {
|
|
184
|
+
const send = sending(entityId, clientFor(entityId));
|
|
185
|
+
return Object.fromEntries(tags.map((tag) => [tag, (payload, callOptions) => {
|
|
186
|
+
const answer = send(tag, payload, callOptions);
|
|
187
|
+
return Stream.isStream(answer) && callOptions?.asQueue === true ? Stream.toQueue(answer, { capacity: callOptions.streamBufferSize ?? 16 }) : answer;
|
|
188
|
+
}]));
|
|
189
|
+
});
|
|
190
|
+
}
|
|
158
191
|
/**
|
|
159
192
|
* The implementations of `entity`'s actions and event types that any surface serves beside its
|
|
160
193
|
* own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
|
|
161
194
|
* `Entity.client` to the entity its contract's key names for its input, with the caller's
|
|
162
195
|
* headers, and its answer, declared errors and progress passed back; each event followed through
|
|
163
|
-
* the entity's poll rpc.
|
|
196
|
+
* the entity's poll rpc. A call the entity could not be reached for, or that did not answer
|
|
197
|
+
* within `timeout`, fails with the built-in `Action.Unavailable`, whose message says the entity
|
|
198
|
+
* may still run it.
|
|
164
199
|
*
|
|
165
200
|
* **Gotchas**
|
|
166
201
|
*
|
|
@@ -169,21 +204,21 @@ const client = (entity) => {
|
|
|
169
204
|
* - 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.
|
|
170
205
|
* - A credential in the query, an API key the serving surface's HTTP binding reads `in: "query"`, never reaches the entity, whose binding reads headers alone, so it refuses the call with `Unauthenticated`: read the key from a header on the HTTP binding too.
|
|
171
206
|
* - A call with no HTTP request, as through `Action.client` in process or an MCP stdio surface, sends only the headers `RpcClient.withHeaders` sets around it: without them the entity refuses a protected one with `Unauthenticated`.
|
|
172
|
-
* -
|
|
207
|
+
* - What `Entity.client` fails with, `MailboxFull`, `AlreadyProcessingMessage`, `PersistenceError` or `EntityNotAssignedToRunner`, is the call's `Action.Unavailable`, its message naming that failure: a 503 with `Retry-After: 1` over HTTP, an `isError: true` tool result over MCP, the typed failure over RPC.
|
|
208
|
+
* - A call to an entity no runner is assigned, which Effect's entity client retries every `sendRetryInterval`, 100 milliseconds by default, without limit, answers `Action.Unavailable` at `timeout`.
|
|
173
209
|
* - A stream, HTTP's `text/event-stream`, an RPC subscription or MCP's `events/stream`, polls the entity from the surface, at once while a page has more and otherwise at its `nextPollMs`, a second at least: it holds the caller's request open but no entity, an occurrence arrives up to that interval late, and the entity's object takes a call each `nextPollMs` while the stream is open, so on Cloudflare a stream polling every few seconds keeps it from ever hibernating.
|
|
174
|
-
* - A stream asks the entity again after
|
|
210
|
+
* - A stream asks the entity again after a poll failed with `Action.Unavailable`, from where it reached, a second later and doubling to 30 seconds, as `client`'s watch does; any other failure, a declared error or a defect, ends its polling.
|
|
175
211
|
* - 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`.
|
|
176
212
|
* - 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.
|
|
177
213
|
* - 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.
|
|
178
|
-
* - What `Entity.client` fails with, `MailboxFull`, `AlreadyProcessingMessage`, `PersistenceError` or `EntityNotAssignedToRunner`, is the call's defect, carrying that error alone, since no action declares it: a 500 over HTTP and a defect through `Action.client`, never a typed error.
|
|
179
214
|
* - An error the entity declares beyond the action's own and the built-in ones, its binding's `error` or its verifier's, is undeclared where the serving surface's binding does not declare it too.
|
|
180
215
|
*/
|
|
181
|
-
const reaching = (entity) => {
|
|
216
|
+
const reaching = (entity, options = {}) => {
|
|
182
217
|
const { binding } = entity;
|
|
183
|
-
const reaches = Effect.map(entity.client, reachOf(entity, forwarded));
|
|
218
|
+
const reaches = Effect.map(entity.client, reachOf(entity, forwarded, options));
|
|
184
219
|
const handlerOf = (action, reach) => {
|
|
185
220
|
const method = actionMethodOf(action, binding)(reach);
|
|
186
|
-
return (input, reporting) =>
|
|
221
|
+
return (input, reporting) => method(input, ...reporting === void 0 ? [] : [{ onProgress: reporting.progress }]);
|
|
187
222
|
};
|
|
188
223
|
const runOf = (event, reach) => {
|
|
189
224
|
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(event.input));
|
|
@@ -191,21 +226,24 @@ const reaching = (entity) => {
|
|
|
191
226
|
const watched = watchedOf(event, binding);
|
|
192
227
|
const webhookCalls = webhookCallsOf(event, binding);
|
|
193
228
|
const reached = (input) => Effect.all([reach(event, input), Effect.orDie(encode(input))]);
|
|
194
|
-
const inEntity = (input, sent) =>
|
|
229
|
+
const inEntity = (input, sent) => Effect.flatMap(reach(event, input), (call) => sent(webhookCalls(call)));
|
|
195
230
|
return {
|
|
196
231
|
polls: true,
|
|
197
232
|
webhook: offersWebhook(event) ? {
|
|
198
233
|
subscribe: (subscribing) => inEntity(subscribing.input, (held) => held.subscribe(subscribing)),
|
|
199
234
|
unsubscribe: (subscription) => inEntity(subscription.input, (held) => held.unsubscribe(subscription))
|
|
200
235
|
} : void 0,
|
|
201
|
-
poll: (input, cursor, { maxEvents }) =>
|
|
236
|
+
poll: (input, cursor, { maxEvents }) => Effect.flatMap(reached(input), ([call, json]) => poll(call)({
|
|
202
237
|
input: json,
|
|
203
238
|
cursor,
|
|
204
239
|
...maxEvents === void 0 ? {} : { maxEvents }
|
|
205
|
-
}))
|
|
206
|
-
stream: (input, cursor) =>
|
|
240
|
+
})),
|
|
241
|
+
stream: (input, cursor) => Stream.unwrap(Effect.map(reached(input), ([call, json]) => {
|
|
242
|
+
const transport = watched(call)(json);
|
|
243
|
+
return polling(transport, Function.constFalse)(cursor);
|
|
244
|
+
}))
|
|
207
245
|
};
|
|
208
246
|
};
|
|
209
247
|
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)))]];
|
|
210
248
|
};
|
|
211
|
-
export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, reaching };
|
|
249
|
+
export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, nativeClient, reaching };
|
package/dist/ActionHttp.d.mts
CHANGED
|
@@ -127,7 +127,7 @@ export interface Binding<Actions extends readonly Any$1[], E extends Errors = []
|
|
|
127
127
|
* Bind actions once, for servers and clients alike, each at `POST <prefix>/<action>`, a
|
|
128
128
|
* `readOnly` one too, and event types, each at `POST <prefix>/events/<name>`. Every endpoint
|
|
129
129
|
* declares its action's errors, the binding's `error`, and the built-in `InvalidInput`,
|
|
130
|
-
* `Unauthenticated` and `
|
|
130
|
+
* `Unauthenticated`, `Forbidden` and `Unavailable`, so clients decode each as a typed failure; a protected one
|
|
131
131
|
* also declares what its descriptor's verifier fails with.
|
|
132
132
|
* Guide: `docs/ActionHttp.md` in this package; in an application: `examples/notes-service/src/Api.ts`.
|
|
133
133
|
*
|
|
@@ -192,7 +192,7 @@ export declare function layer<const H extends AnyHttp, const Apps extends Served
|
|
|
192
192
|
* - An input that does not encode fails with `InvalidInput`, and nothing is sent; undeclared input fields, which TypeScript lets through on a wider value, are dropped as it encodes, since the server would refuse them.
|
|
193
193
|
* - It interprets no status and retries nothing: a failed write may have happened, and only a declared error says what the server did.
|
|
194
194
|
* - `watch(event, input, options)` holds the event's SSE stream open, or polls its pages with `mode: "poll"`, as `Action.client`'s; a watch of an event the server does not serve, its route a 404, fails with `Event.SubscriptionError`, reason `NotServed`.
|
|
195
|
-
* - A watch reconnects after the transport fails, a status such as
|
|
195
|
+
* - A watch reconnects after the transport fails, a status such as 502, `Action.Unavailable`, or 60 seconds without an answer or a frame, a second later and doubling to 30 seconds, each reconnect logged as a warning; another declared error, a refusal included, ends it.
|
|
196
196
|
* - A watch's stream ends at an SSE `retry:` field, which `ActionHttp.layer` never sends, as Effect's client decodes it, and the watch connects again: a server or proxy sending one as each stream starts delivers nothing.
|
|
197
197
|
* - A call of an action declaring `progress` reads the route's event stream, as every request accepts it, and its answer from the `final` event; the server sends the values whether or not the call gave `onProgress`, and without one they are dropped.
|
|
198
198
|
* - A call of an action answering a stream returns a `Stream` of its elements, failing as the route's stream fails, with `Sse.SseError` or `Sse.Retry` too; its `onProgress` gets each `progress` event, which the server sends whether or not the call gave one.
|
package/dist/ActionHttp.mjs
CHANGED
|
@@ -13,6 +13,7 @@ import { answering, eventEndpointOf, servedSent, webhookEndpointsOf } from "./ht
|
|
|
13
13
|
import { credentialNames } from "./http/redacted.mjs";
|
|
14
14
|
import { SchemaErrors, schemaErrors } from "./http/schema-errors.mjs";
|
|
15
15
|
import { answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf } from "./http/streamed.mjs";
|
|
16
|
+
import { RetryAfter, retryAfter } from "./http/unavailable.mjs";
|
|
16
17
|
import { Context, Effect, Layer, Scope } from "effect";
|
|
17
18
|
import { FetchHttpClient, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
18
19
|
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/http-api";
|
|
@@ -84,7 +85,7 @@ function layer(binding, served, options = {}) {
|
|
|
84
85
|
const name = groupName(mount);
|
|
85
86
|
const routed = (endpoint, { caller }) => {
|
|
86
87
|
const within = withinLayerMiddleware(endpoint.middleware(JsonContentType).middleware(SchemaErrors), options.middleware);
|
|
87
|
-
return caller === Anyone || authentication === void 0 ? within : within.middleware(StepUp).middleware(authentication["~middleware"]);
|
|
88
|
+
return (caller === Anyone || authentication === void 0 ? within : within.middleware(StepUp).middleware(authentication["~middleware"])).middleware(RetryAfter);
|
|
88
89
|
};
|
|
89
90
|
const api = apiOf(name, [...actions.map((action) => routed(endpointOf(action, absolutePath([...mount, action.name]), projectedErrors(action, binding.error)), action)), ...eventTypes.flatMap((event) => {
|
|
90
91
|
const path = absolutePath([
|
|
@@ -112,6 +113,7 @@ function layer(binding, served, options = {}) {
|
|
|
112
113
|
};
|
|
113
114
|
return HttpApiBuilder.group(api, name, (builder) => builder.handleAll(byName)).pipe(Layer.provide([
|
|
114
115
|
schemaErrors,
|
|
116
|
+
retryAfter,
|
|
115
117
|
jsonContentType(),
|
|
116
118
|
security,
|
|
117
119
|
...hostProvidedMiddleware
|
package/dist/ActionRpc.d.mts
CHANGED
|
@@ -121,7 +121,7 @@ type RpcsOf<O> = O extends {
|
|
|
121
121
|
* Bind actions once, for servers and clients alike, each as an rpc named after it, taking
|
|
122
122
|
* its action's input and answering its success, and event types, each a stream rpc named after
|
|
123
123
|
* it, taking `{ input, cursor }`, which `layer` serves by poll too, as its `pollTag` and `releaseTag` rpcs. Every rpc declares its action's errors, the binding's `error`,
|
|
124
|
-
* and the built-in `InvalidInput`, `Unauthenticated` and `
|
|
124
|
+
* and the built-in `InvalidInput`, `Unauthenticated`, `Forbidden` and `Unavailable`, so clients decode each as
|
|
125
125
|
* a typed failure; a protected one also declares what its descriptor's verifier fails with.
|
|
126
126
|
* `rpcs` adds native ones beside them. Browser-safe, as an HTTP binding is.
|
|
127
127
|
* Guide: `docs/ActionRpc.md` in this package; in an application: `examples/live-rpc/`.
|
|
@@ -260,7 +260,7 @@ export declare const pollResentAfter: Duration.Duration;
|
|
|
260
260
|
* - `watch(event, input, options)` with no `mode` holds the event's stream rpc open, as `Action.client`'s does, and polls instead, for that watch, where the server answers the stream rpc `Unknown request tag`, as an `ActionEntity` and the Cloudflare package's socket host do: one round trip more per watch, which `mode: "poll"` skips.
|
|
261
261
|
* - `mode: "poll"` calls the event's `<event>/poll` for each page, a poll unanswered for `pollResentAfter` sent again from the same cursor, the first interrupted, so a server that holds a poll until something changes, as the Cloudflare package's socket host does, reads it again at least that often.
|
|
262
262
|
* - A watch of an event the server does not serve fails with `Event.SubscriptionError`, reason `NotServed`, as over HTTP, whatever its `mode`; a webhook `mode` fails with reason `Unsupported`.
|
|
263
|
-
* - A watch reconnects after the protocol's socket or HTTP transport fails, a response ends before its stream does, as a server's restart ends it, a status a server sends while it recovers, or, over Effect's HTTP protocol, 60 seconds without an element, a socket's own pings telling a dead one, a second later and doubling to 30 seconds, each reconnect logged as a warning
|
|
263
|
+
* - A watch reconnects after the protocol's socket or HTTP transport fails, a response ends before its stream does, as a server's restart ends it, a status a server sends while it recovers, or, over Effect's HTTP protocol, 60 seconds without an element, a socket's own pings telling a dead one, a second later and doubling to 30 seconds, each reconnect logged as a warning, and after `Action.Unavailable`; another declared error, a refusal included, or a socket's close with an application's code, 4000 to 4999, ends it.
|
|
264
264
|
* - 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
265
|
*/
|
|
266
266
|
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"]>>>;
|
|
@@ -87,6 +87,33 @@ declare const Forbidden_base: Schema.Class<Forbidden, Schema.TaggedStruct<"Forbi
|
|
|
87
87
|
export declare class Forbidden extends Forbidden_base {
|
|
88
88
|
private readonly "~declared in the action's error, or built in";
|
|
89
89
|
}
|
|
90
|
+
declare const Unavailable_base: Schema.Class<Unavailable, Schema.TaggedStruct<"Unavailable", {
|
|
91
|
+
readonly message: Schema.withConstructorDefault<Schema.String>;
|
|
92
|
+
}>, import("effect/Cause").YieldableError & {
|
|
93
|
+
readonly brand: unique symbol;
|
|
94
|
+
}>;
|
|
95
|
+
/**
|
|
96
|
+
* The server could not answer now, and the call's outcome is unknown: a caller may try again
|
|
97
|
+
* later. `ActionEntity.reaching` fails with it when the entity a call names could not be reached
|
|
98
|
+
* or did not answer within its `timeout`, its message saying the entity may still run the call;
|
|
99
|
+
* a handler fails with it, a message of its own, for a dependency it could not reach, instead of
|
|
100
|
+
* declaring a second error for that.
|
|
101
|
+
*
|
|
102
|
+
* **Gotchas**
|
|
103
|
+
*
|
|
104
|
+
* - Over HTTP its JSON with a 503 and `Retry-After: 1`; over MCP an `isError: true` tool result in a 200; over RPC the typed failure; on a Toolkit and in a CLI as a declared error.
|
|
105
|
+
* - The call may have run, or may still run: retry only a call safe to repeat, such as a read or one carrying an idempotency key.
|
|
106
|
+
* - A watch, on every surface's client, takes it as a transient failure, asking again a second later and doubling to 30 seconds, where another declared error ends it.
|
|
107
|
+
* - An answer `Action.Idempotency` keeps is never this error, as for any 5xx: a repeat runs the call again.
|
|
108
|
+
*/
|
|
109
|
+
export declare class Unavailable extends Unavailable_base {
|
|
110
|
+
private readonly "~declared in the action's error, or built in";
|
|
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;
|
|
90
117
|
/**
|
|
91
118
|
* What authentication or an implementation's `authorize` refuses a caller with, instead of
|
|
92
119
|
* running a handler. As a schema, it tells a refusal apart: `Schema.is(Action.Refusal)(error)`.
|
|
@@ -94,11 +121,11 @@ export declare class Forbidden extends Forbidden_base {
|
|
|
94
121
|
export declare const Refusal: Schema.Union<readonly [typeof Unauthenticated, typeof Forbidden]>;
|
|
95
122
|
/** A refusal: `Unauthenticated | Forbidden`. */
|
|
96
123
|
export type Refusal = (typeof Refusal)["Type"];
|
|
97
|
-
export declare const builtIns: readonly [typeof InvalidInput, typeof Unauthenticated, typeof Forbidden];
|
|
124
|
+
export declare const builtIns: readonly [typeof InvalidInput, typeof Unauthenticated, typeof Forbidden, typeof Unavailable];
|
|
98
125
|
/** The built-in failures' schemas. */
|
|
99
126
|
export type BuiltIns = (typeof builtIns)[number];
|
|
100
127
|
/** The built-in failures as one schema: `Schema.is(Action.BuiltIn)(error)`. */
|
|
101
|
-
export declare const BuiltIn: Schema.Union<readonly [typeof InvalidInput, typeof Unauthenticated, typeof Forbidden]>;
|
|
102
|
-
/** A built-in failure: `InvalidInput | Refusal`. */
|
|
128
|
+
export declare const BuiltIn: Schema.Union<readonly [typeof InvalidInput, typeof Unauthenticated, typeof Forbidden, typeof Unavailable]>;
|
|
129
|
+
/** A built-in failure: `InvalidInput | Refusal | Unavailable`. */
|
|
103
130
|
export type BuiltIn = (typeof BuiltIn)["Type"];
|
|
104
131
|
export { Issue };
|
package/dist/contract/errors.mjs
CHANGED
|
@@ -76,13 +76,37 @@ var Forbidden = class extends Schema.TaggedError()("Forbidden", {
|
|
|
76
76
|
message: defaultedMessage("Not allowed."),
|
|
77
77
|
scopes: Schema.optionalKey(Schema.NonEmptyArray(ScopeToken))
|
|
78
78
|
}, { httpApiStatus: 403 }) {};
|
|
79
|
+
/**
|
|
80
|
+
* The server could not answer now, and the call's outcome is unknown: a caller may try again
|
|
81
|
+
* later. `ActionEntity.reaching` fails with it when the entity a call names could not be reached
|
|
82
|
+
* or did not answer within its `timeout`, its message saying the entity may still run the call;
|
|
83
|
+
* a handler fails with it, a message of its own, for a dependency it could not reach, instead of
|
|
84
|
+
* declaring a second error for that.
|
|
85
|
+
*
|
|
86
|
+
* **Gotchas**
|
|
87
|
+
*
|
|
88
|
+
* - Over HTTP its JSON with a 503 and `Retry-After: 1`; over MCP an `isError: true` tool result in a 200; over RPC the typed failure; on a Toolkit and in a CLI as a declared error.
|
|
89
|
+
* - The call may have run, or may still run: retry only a call safe to repeat, such as a read or one carrying an idempotency key.
|
|
90
|
+
* - A watch, on every surface's client, takes it as a transient failure, asking again a second later and doubling to 30 seconds, where another declared error ends it.
|
|
91
|
+
* - An answer `Action.Idempotency` keeps is never this error, as for any 5xx: a repeat runs the call again.
|
|
92
|
+
*/
|
|
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);
|
|
79
99
|
const refusals = [Unauthenticated, Forbidden];
|
|
80
100
|
/**
|
|
81
101
|
* What authentication or an implementation's `authorize` refuses a caller with, instead of
|
|
82
102
|
* running a handler. As a schema, it tells a refusal apart: `Schema.is(Action.Refusal)(error)`.
|
|
83
103
|
*/
|
|
84
104
|
const Refusal = Schema.Union(refusals);
|
|
85
|
-
const builtIns = [
|
|
105
|
+
const builtIns = [
|
|
106
|
+
InvalidInput,
|
|
107
|
+
...refusals,
|
|
108
|
+
Unavailable
|
|
109
|
+
];
|
|
86
110
|
/** The built-in failures as one schema: `Schema.is(Action.BuiltIn)(error)`. */
|
|
87
111
|
const BuiltIn = Schema.Union(builtIns);
|
|
88
|
-
export { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, builtIns, scopeToken };
|
|
112
|
+
export { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, Unavailable, builtIns, isUnavailable, scopeToken };
|
package/dist/contract/watch.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CallbackUrl } from "./callback.mjs";
|
|
2
|
+
import { isUnavailable } from "./errors.mjs";
|
|
2
3
|
import { SubscriptionError } from "../Event.mjs";
|
|
3
4
|
import { Checked, Gap } from "./occurrence.mjs";
|
|
4
5
|
import { paged } from "./pages.mjs";
|
|
@@ -17,7 +18,7 @@ const reconnecting = (transient, open, cursor, polled) => {
|
|
|
17
18
|
const once = Stream.suspend(() => open(at)).pipe(Stream.tap((fed) => Effect.sync(() => {
|
|
18
19
|
at = fed.cursor ?? at;
|
|
19
20
|
})));
|
|
20
|
-
const reopened = transient === void 0 ? once : once.pipe(Stream.repeat(Schedule.spaced(reconnectDelay)), Stream.retry(afterFailures(transient)));
|
|
21
|
+
const reopened = transient === void 0 ? once.pipe(Stream.retry(afterFailures(isUnavailable))) : once.pipe(Stream.repeat(Schedule.spaced(reconnectDelay)), Stream.retry(afterFailures(Predicate.or(transient, isUnavailable))));
|
|
21
22
|
return polled === void 0 ? reopened : reopened.pipe(Stream.catchIf(pushRefused, () => Stream.suspend(() => polled(at))));
|
|
22
23
|
};
|
|
23
24
|
const closeTimeout = Duration.seconds(5);
|
package/dist/http/client.d.mts
CHANGED
|
@@ -46,7 +46,7 @@ type SseError = Extract<SseFailure, {
|
|
|
46
46
|
}>;
|
|
47
47
|
/**
|
|
48
48
|
* What one call of `A` fails with: a declared error value (the action's own, one `E` of the
|
|
49
|
-
* binding's, or a built-in `InvalidInput`, `Unauthenticated` or `
|
|
49
|
+
* binding's, or a built-in `InvalidInput`, `Unauthenticated`, `Forbidden` or `Unavailable`), a native
|
|
50
50
|
* `HttpClientError` for a failed request or an undeclared answer, or a `SchemaError` when
|
|
51
51
|
* the success does not decode. A call reading an event stream, of an action answering a stream or
|
|
52
52
|
* declaring `progress`, also fails with Effect's `Sse.SseError` or `Sse.Retry`.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Unavailable, isUnavailable } from "../contract/errors.mjs";
|
|
2
|
+
import { Cause, Effect, ErrorReporter, Layer, Schema } from "effect";
|
|
3
|
+
import { HttpServerResponse } from "effect/http";
|
|
4
|
+
import { HttpApiMiddleware } from "effect/http-api";
|
|
5
|
+
// src/http/unavailable.ts
|
|
6
|
+
const encode = Schema.encodeUnknownSync(Schema.toCodecJson(Unavailable));
|
|
7
|
+
var RetryAfter = class extends HttpApiMiddleware.Service()("effect-actions/http/RetryAfter") {};
|
|
8
|
+
const retryAfter = Layer.succeed(RetryAfter, (route) => Effect.catchIf(route, isUnavailable, (error) => Effect.as(ErrorReporter.report(Cause.fail(error)), HttpServerResponse.jsonUnsafe(encode(error), {
|
|
9
|
+
status: 503,
|
|
10
|
+
headers: { "retry-after": "1" }
|
|
11
|
+
}))));
|
|
12
|
+
export { RetryAfter, retryAfter };
|
package/dist/mcp/client.d.mts
CHANGED
|
@@ -62,7 +62,7 @@ type Watching<Listed extends Any$2, D, E, R> = [Listed] extends [never] ? unknow
|
|
|
62
62
|
* - It drops undeclared input fields as it encodes, and fails with `InvalidInput`, sending nothing, for an input that does not encode.
|
|
63
63
|
* - A call of an action answering a stream returns a `Stream` of the elements its tool collected, the first arriving once the whole stream has ended on the server.
|
|
64
64
|
* - A watch of an event the endpoint does not serve fails with `Event.SubscriptionError`, reason `NotServed`, as an endpoint serving events answers its first request; one serving none answers `events/*` with a 404, failing with `McpCallError`'s `StatusError`.
|
|
65
|
-
* - A watch reconnects after the transport fails, a status such as 503, or 60 seconds without an answer or a frame, a second later and doubling to 30 seconds, each reconnect logged as a warning; any other failure ends it.
|
|
65
|
+
* - A watch reconnects after the transport fails, a status such as 503, `Action.Unavailable`, or 60 seconds without an answer or a frame, a second later and doubling to 30 seconds, each reconnect logged as a warning; any other failure ends it.
|
|
66
66
|
* - A call given `onProgress` sends a `progressToken` and reads each `notifications/progress` as its frame arrives; a call without one sends none, so the endpoint sends no progress.
|
|
67
67
|
*/
|
|
68
68
|
export declare function client<const Contracts extends ReadonlyArray<Any$1 | Any$2>, D extends Any | undefined = undefined>(contracts: Contracts, options?: ClientOptions<D>): Effect.Effect<Client<Contracts, D>, never, HttpClient.HttpClient>;
|
package/docs/Action-failures.md
CHANGED
|
@@ -16,7 +16,7 @@ What you see when something is wrong, and the fix. Search for a fragment of the
|
|
|
16
16
|
- `Parameter 'action' implicitly has an 'any' type`, or an `Effect.fn` authorizer whose `action` is `any`: an authorizer defined apart from `implement` annotates its parameter, `(action: Action.Any)`.
|
|
17
17
|
- `Type 'X' is not assignable to type 'Forbidden | Unauthenticated'`, ending `Property '"~declared in the action's error, or built in"' is missing in type 'X'`: an authorizer fails only with `Action.Unauthenticated` or `Action.Forbidden`, and this one fails with `X`. A limit, or another failure callers should see, is the handler's: declare `X` in the action's `error` and fail with it there.
|
|
18
18
|
- `Argument of type ... is not assignable to parameter of type ...`, or `Type 'Effect<...>' is not assignable to type 'Effect<...>'` at a handler of a record written in place, ending `Property '"~declared in the action's error, or built in"' is missing in type 'X'`: the handler fails with `X`, which its action does not declare. Add `X` to the action's `error`, or handle it.
|
|
19
|
-
- `Type 'X' is not assignable to type 'Forbidden | InvalidInput | Unauthenticated'`, or a longer union, under a handler's error: a handler fails only with the errors its action declares and the library's built-in ones, and `X` may be Effect's `HttpApiError.Forbidden` or a `Forbidden` of your own. Add `X` to the action's `error`, or handle it.
|
|
19
|
+
- `Type 'X' is not assignable to type 'Forbidden | InvalidInput | Unauthenticated | Unavailable'`, or a longer union, under a handler's error: a handler fails only with the errors its action declares and the library's built-in ones, and `X` may be Effect's `HttpApiError.Forbidden` or a `Forbidden` of your own. Add `X` to the action's `error`, or handle it.
|
|
20
20
|
- `The types returned by '<handler>(...)'` at a builder: that handler fails with an error its action does not declare, and the error names one handler at a time; add the error to the action's `error` or handle it, and the next handler's shows.
|
|
21
21
|
- `Binding element '<field>' implicitly has an 'any' type` (TS7031), or `Parameter 'input' implicitly has an 'any' type`, at every handler of a builder: the builder is wrapped, as in `Effect.gen(…).pipe(Effect.provide(layer))`, and its record is no longer typed from the contracts. Give `implement` the builder itself, and provide the layer to the surface's layer or to the server.
|
|
22
22
|
- `'<name>' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer` (TS7022), or, with the types bypassed, an acquisition that never completes: a builder acquires an `Action.client` of its own implementation, directly or through another builder. Call the services both use instead.
|
package/docs/Action.md
CHANGED
|
@@ -120,9 +120,9 @@ 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
|
|
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
|
-
- **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([
|
|
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.
|
|
127
127
|
- **Internal failures are never sent** over HTTP, MCP and RPC: what reaches the log and the call's `ErrorReporter`s is on `ActionHttp.layer`, `ActionMcp.layerHttp` and `ActionRpc.layer`; a Toolkit and a CLI make a defect the call's.
|
|
128
128
|
|
package/docs/ActionEntity.md
CHANGED
|
@@ -66,7 +66,7 @@ A protected action authenticates each call from the headers its envelope carries
|
|
|
66
66
|
|
|
67
67
|
## Call it
|
|
68
68
|
|
|
69
|
-
`ActionEntity.client(entity)` is Effect's `Entity.client` with one typed method per action, each call sent to the entity its input's key names: `(yield* ActionEntity.client(Room)).postMessage({ room: "lobby", text })`. Send credentials by setting headers with `RpcClient.withHeaders` around a call. The entity's native rpcs
|
|
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 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
70
|
|
|
71
71
|
## Reach it from any surface
|
|
72
72
|
|
|
@@ -74,6 +74,8 @@ A protected action authenticates each call from the headers its envelope carries
|
|
|
74
74
|
|
|
75
75
|
The surface authenticates a protected call with its own binding's descriptor and the entity authenticates it again, so provide the authentication provider to both.
|
|
76
76
|
|
|
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.EntityCallOptions`, the options `client` and `nativeClient` take too.
|
|
78
|
+
|
|
77
79
|
An event is followed through the entity's poll rpc, so no watcher holds an entity open; a stream polls it from the surface. What crosses the two hops, and what does not, is on `ActionEntity.reaching`.
|
|
78
80
|
|
|
79
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.
|
package/package.json
CHANGED