@gjermundgaraba/effect-actions 0.33.0 → 0.34.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 +28 -10
- package/dist/ActionEntity.mjs +34 -18
- 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 +25 -3
- package/dist/contract/errors.mjs +21 -2
- package/dist/contract/watch.mjs +3 -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 +2 -0
- 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 } 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, 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 } 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, layer, layerIdempotency, make, withErrors };
|
package/dist/ActionEntity.d.mts
CHANGED
|
@@ -10,7 +10,7 @@ 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, Schema, Scope, Stream } from "effect";
|
|
13
|
+
import { Duration, Effect, Layer, Schema, Scope, Stream } from "effect";
|
|
14
14
|
import { ClusterError, Entity as Entity$1, Sharding } from "effect/cluster";
|
|
15
15
|
import { HttpServerRequest } from "effect/http";
|
|
16
16
|
import { Rpc, RpcGroup } from "effect/rpc";
|
|
@@ -165,9 +165,10 @@ type ClusterFailure = typeof ClusterFailures.Type;
|
|
|
165
165
|
/**
|
|
166
166
|
* Whether a failure is one of those Effect's entity client fails with when the entity could not
|
|
167
167
|
* be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
|
|
168
|
-
* `EntityNotAssignedToRunner`, which `client`'s `MethodError` holds and `reaching`
|
|
169
|
-
*
|
|
170
|
-
* does, makes them
|
|
168
|
+
* `EntityNotAssignedToRunner`, which `client`'s `MethodError` holds and `reaching` answers as
|
|
169
|
+
* `Action.Unavailable`: a server forwarding calls into an entity, as the Cloudflare package's
|
|
170
|
+
* socket host does, makes them a defect, and a Worker calling `client` itself answers them, as
|
|
171
|
+
* the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
|
|
171
172
|
*/
|
|
172
173
|
export declare const isClusterFailure: <I>(input: I) => input is I & (ClusterError.AlreadyProcessingMessage | ClusterError.EntityNotAssignedToRunner | ClusterError.MailboxFull | ClusterError.PersistenceError);
|
|
173
174
|
/**
|
|
@@ -206,16 +207,33 @@ export type Client<B extends Any$3> = { readonly [A in B["actions"][number] as A
|
|
|
206
207
|
* - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
|
|
207
208
|
* - 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 polls, its only `mode` `"poll"`, at the page's `nextPollMs`, 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.
|
|
209
|
-
* - A watch asks the entity again after `MailboxFull` or `
|
|
210
|
+
* - A watch asks the entity again after `MailboxFull`, `PersistenceError` or `Action.Unavailable`, from where it reached, a second later and doubling to 30 seconds; another declared error, a refusal included, ends it.
|
|
210
211
|
*/
|
|
211
212
|
export declare const client: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(entity: Entity<Type, B, N>) => Effect.Effect<Client<B>, never, Sharding.Sharding>;
|
|
212
213
|
type Nothing<C extends Any$1 | Any$2> = { readonly [K in C["name"]]: never; };
|
|
214
|
+
/** `reaching`'s options. */
|
|
215
|
+
export interface ReachingOptions {
|
|
216
|
+
/**
|
|
217
|
+
* How long one call to the entity waits for its answer before failing with
|
|
218
|
+
* `Action.Unavailable`: an action's call, a poll, and a webhook subscribe or unsubscribe.
|
|
219
|
+
* 20 seconds by default.
|
|
220
|
+
*
|
|
221
|
+
* **Gotchas**
|
|
222
|
+
*
|
|
223
|
+
* - 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.
|
|
224
|
+
* - A streaming action, one declaring `progress` or answering `Action.Stream`, has no deadline, as it may answer for longer: bound it with the host's request timeout.
|
|
225
|
+
* - 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.
|
|
226
|
+
*/
|
|
227
|
+
readonly timeout?: Duration.Input | undefined;
|
|
228
|
+
}
|
|
213
229
|
/**
|
|
214
230
|
* The implementations of `entity`'s actions and event types that any surface serves beside its
|
|
215
231
|
* own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
|
|
216
232
|
* `Entity.client` to the entity its contract's key names for its input, with the caller's
|
|
217
233
|
* headers, and its answer, declared errors and progress passed back; each event followed through
|
|
218
|
-
* the entity's poll rpc.
|
|
234
|
+
* the entity's poll rpc. A call the entity could not be reached for, or that did not answer
|
|
235
|
+
* within `timeout`, fails with the built-in `Action.Unavailable`, whose message says the entity
|
|
236
|
+
* may still run it.
|
|
219
237
|
*
|
|
220
238
|
* **Gotchas**
|
|
221
239
|
*
|
|
@@ -224,14 +242,14 @@ type Nothing<C extends Any$1 | Any$2> = { readonly [K in C["name"]]: never; };
|
|
|
224
242
|
* - 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
243
|
* - 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
244
|
* - 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
|
-
* -
|
|
245
|
+
* - 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.
|
|
246
|
+
* - 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
247
|
* - 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
|
|
248
|
+
* - 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
249
|
* - 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
250
|
* - 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
251
|
* - 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
252
|
* - 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
253
|
*/
|
|
236
|
-
export declare const reaching: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(entity: Entity<Type, B, N
|
|
254
|
+
export declare const reaching: <const Type extends string, const B extends Any$3, N extends Rpc.Any = never>(entity: Entity<Type, B, N>, options?: ReachingOptions) => ReadonlyArray<Implementation<B["actions"][number], Nothing<B["actions"][number]>, never, Sharding.Sharding> | EventImplementation<B["events"][number], Nothing<B["events"][number]>, never, Sharding.Sharding>>;
|
|
237
255
|
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, 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
|
|
@@ -116,15 +116,13 @@ const ClusterFailures = Schema.Union([
|
|
|
116
116
|
/**
|
|
117
117
|
* Whether a failure is one of those Effect's entity client fails with when the entity could not
|
|
118
118
|
* be reached, `MailboxFull`, `PersistenceError`, `AlreadyProcessingMessage` and
|
|
119
|
-
* `EntityNotAssignedToRunner`, which `client`'s `MethodError` holds and `reaching`
|
|
120
|
-
*
|
|
121
|
-
* does, makes them
|
|
119
|
+
* `EntityNotAssignedToRunner`, which `client`'s `MethodError` holds and `reaching` answers as
|
|
120
|
+
* `Action.Unavailable`: a server forwarding calls into an entity, as the Cloudflare package's
|
|
121
|
+
* socket host does, makes them a defect, and a Worker calling `client` itself answers them, as
|
|
122
|
+
* the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
|
|
122
123
|
*/
|
|
123
124
|
const isClusterFailure = Schema.is(ClusterFailures);
|
|
124
125
|
const isTransient = Schema.is(Transients);
|
|
125
|
-
function clusterFailuresAsDefects(answer) {
|
|
126
|
-
return Effect.isEffect(answer) ? Effect.catchIf(answer, isClusterFailure, Effect.die) : Stream.catchIf(answer, isClusterFailure, Stream.die);
|
|
127
|
-
}
|
|
128
126
|
const entityCallOf = (rpcs, headers) => erasedCallOf((tag, payload) => {
|
|
129
127
|
const method = rpcs[tag];
|
|
130
128
|
return method === void 0 ? Effect.die(/* @__PURE__ */ new Error(`ActionEntity: no rpc ${tag}`)) : method(payload, headers === void 0 ? void 0 : { headers });
|
|
@@ -148,19 +146,22 @@ const reachOf = (entity, headers) => (clientFor) => {
|
|
|
148
146
|
* - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
|
|
149
147
|
* - 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
148
|
* - A watch polls, its only `mode` `"poll"`, at the page's `nextPollMs`, 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.
|
|
151
|
-
* - A watch asks the entity again after `MailboxFull` or `
|
|
149
|
+
* - A watch asks the entity again after `MailboxFull`, `PersistenceError` or `Action.Unavailable`, from where it reached, a second later and doubling to 30 seconds; another declared error, a refusal included, ends it.
|
|
152
150
|
*/
|
|
153
151
|
const client = (entity) => {
|
|
154
152
|
const methods = methodsOf(entity.binding, polledTransport(isTransient));
|
|
155
153
|
const reach = reachOf(entity, Effect.undefined);
|
|
156
154
|
return Effect.map(entity.client, (clientFor) => methods(reach(clientFor)));
|
|
157
155
|
};
|
|
156
|
+
const defaultTimeout = Duration.seconds(20);
|
|
158
157
|
/**
|
|
159
158
|
* The implementations of `entity`'s actions and event types that any surface serves beside its
|
|
160
159
|
* own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
|
|
161
160
|
* `Entity.client` to the entity its contract's key names for its input, with the caller's
|
|
162
161
|
* headers, and its answer, declared errors and progress passed back; each event followed through
|
|
163
|
-
* the entity's poll rpc.
|
|
162
|
+
* the entity's poll rpc. A call the entity could not be reached for, or that did not answer
|
|
163
|
+
* within `timeout`, fails with the built-in `Action.Unavailable`, whose message says the entity
|
|
164
|
+
* may still run it.
|
|
164
165
|
*
|
|
165
166
|
* **Gotchas**
|
|
166
167
|
*
|
|
@@ -169,21 +170,33 @@ const client = (entity) => {
|
|
|
169
170
|
* - 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
171
|
* - 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
172
|
* - 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
|
-
* -
|
|
173
|
+
* - 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.
|
|
174
|
+
* - 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
175
|
* - 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
|
|
176
|
+
* - 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
177
|
* - 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
178
|
* - 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
179
|
* - 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
180
|
* - 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
181
|
*/
|
|
181
|
-
const reaching = (entity) => {
|
|
182
|
+
const reaching = (entity, options = {}) => {
|
|
182
183
|
const { binding } = entity;
|
|
183
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
|
+
});
|
|
184
193
|
const handlerOf = (action, reach) => {
|
|
185
194
|
const method = actionMethodOf(action, binding)(reach);
|
|
186
|
-
return (input, reporting) =>
|
|
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
|
+
};
|
|
187
200
|
};
|
|
188
201
|
const runOf = (event, reach) => {
|
|
189
202
|
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(event.input));
|
|
@@ -191,19 +204,22 @@ const reaching = (entity) => {
|
|
|
191
204
|
const watched = watchedOf(event, binding);
|
|
192
205
|
const webhookCalls = webhookCallsOf(event, binding);
|
|
193
206
|
const reached = (input) => Effect.all([reach(event, input), Effect.orDie(encode(input))]);
|
|
194
|
-
const inEntity = (input, sent) =>
|
|
207
|
+
const inEntity = (input, sent) => Effect.flatMap(reach(event, input), (call) => bounded(event, input, sent(webhookCalls(call))));
|
|
195
208
|
return {
|
|
196
209
|
polls: true,
|
|
197
210
|
webhook: offersWebhook(event) ? {
|
|
198
211
|
subscribe: (subscribing) => inEntity(subscribing.input, (held) => held.subscribe(subscribing)),
|
|
199
212
|
unsubscribe: (subscription) => inEntity(subscription.input, (held) => held.unsubscribe(subscription))
|
|
200
213
|
} : void 0,
|
|
201
|
-
poll: (input, cursor, { maxEvents }) =>
|
|
214
|
+
poll: (input, cursor, { maxEvents }) => Effect.flatMap(reached(input), ([call, json]) => bounded(event, input, poll(call)({
|
|
202
215
|
input: json,
|
|
203
216
|
cursor,
|
|
204
217
|
...maxEvents === void 0 ? {} : { maxEvents }
|
|
205
218
|
}))),
|
|
206
|
-
stream: (input, cursor) =>
|
|
219
|
+
stream: (input, cursor) => Stream.unwrap(Effect.map(reached(input), ([call, json]) => {
|
|
220
|
+
const transport = watched(call)(json);
|
|
221
|
+
return polling({ poll: (from, watch) => bounded(event, input, transport.poll(from, watch)) }, isTransient)(cursor);
|
|
222
|
+
}))
|
|
207
223
|
};
|
|
208
224
|
};
|
|
209
225
|
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)))]];
|
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,28 @@ 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
|
+
}
|
|
90
112
|
/**
|
|
91
113
|
* What authentication or an implementation's `authorize` refuses a caller with, instead of
|
|
92
114
|
* running a handler. As a schema, it tells a refusal apart: `Schema.is(Action.Refusal)(error)`.
|
|
@@ -94,11 +116,11 @@ export declare class Forbidden extends Forbidden_base {
|
|
|
94
116
|
export declare const Refusal: Schema.Union<readonly [typeof Unauthenticated, typeof Forbidden]>;
|
|
95
117
|
/** A refusal: `Unauthenticated | Forbidden`. */
|
|
96
118
|
export type Refusal = (typeof Refusal)["Type"];
|
|
97
|
-
export declare const builtIns: readonly [typeof InvalidInput, typeof Unauthenticated, typeof Forbidden];
|
|
119
|
+
export declare const builtIns: readonly [typeof InvalidInput, typeof Unauthenticated, typeof Forbidden, typeof Unavailable];
|
|
98
120
|
/** The built-in failures' schemas. */
|
|
99
121
|
export type BuiltIns = (typeof builtIns)[number];
|
|
100
122
|
/** 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`. */
|
|
123
|
+
export declare const BuiltIn: Schema.Union<readonly [typeof InvalidInput, typeof Unauthenticated, typeof Forbidden, typeof Unavailable]>;
|
|
124
|
+
/** A built-in failure: `InvalidInput | Refusal | Unavailable`. */
|
|
103
125
|
export type BuiltIn = (typeof BuiltIn)["Type"];
|
|
104
126
|
export { Issue };
|
package/dist/contract/errors.mjs
CHANGED
|
@@ -76,13 +76,32 @@ 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 }) {};
|
|
79
94
|
const refusals = [Unauthenticated, Forbidden];
|
|
80
95
|
/**
|
|
81
96
|
* What authentication or an implementation's `authorize` refuses a caller with, instead of
|
|
82
97
|
* running a handler. As a schema, it tells a refusal apart: `Schema.is(Action.Refusal)(error)`.
|
|
83
98
|
*/
|
|
84
99
|
const Refusal = Schema.Union(refusals);
|
|
85
|
-
const builtIns = [
|
|
100
|
+
const builtIns = [
|
|
101
|
+
InvalidInput,
|
|
102
|
+
...refusals,
|
|
103
|
+
Unavailable
|
|
104
|
+
];
|
|
86
105
|
/** The built-in failures as one schema: `Schema.is(Action.BuiltIn)(error)`. */
|
|
87
106
|
const BuiltIn = Schema.Union(builtIns);
|
|
88
|
-
export { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, builtIns, scopeToken };
|
|
107
|
+
export { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, Unavailable, builtIns, scopeToken };
|
package/dist/contract/watch.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CallbackUrl } from "./callback.mjs";
|
|
2
|
+
import { Unavailable } 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";
|
|
@@ -10,6 +11,7 @@ import { Cause, Clock, Duration, Effect, Predicate, Queue, Schedule, Schema, Str
|
|
|
10
11
|
const reconnectDelay = Duration.seconds(1);
|
|
11
12
|
const maxReconnectDelay = Duration.seconds(30);
|
|
12
13
|
const afterFailures = (transient) => Schedule.min([Schedule.exponential(reconnectDelay), Schedule.spaced(maxReconnectDelay)]).pipe(Schedule.setInputType(), Schedule.while(({ input }) => transient(input)), Schedule.tap(({ input, duration }) => Effect.logWarning(`A watch reconnects in ${Duration.format(duration)} after a failure`, input)));
|
|
14
|
+
const isUnavailable = Schema.is(Unavailable);
|
|
13
15
|
const isSubscriptionError = Schema.is(SubscriptionError);
|
|
14
16
|
const pushRefused = Predicate.compose(isSubscriptionError, ({ reason }) => Predicate.isTagged(reason, "Unsupported") && reason.feature === "deliveryMode" && reason.value === "push");
|
|
15
17
|
const reconnecting = (transient, open, cursor, polled) => {
|
|
@@ -17,7 +19,7 @@ const reconnecting = (transient, open, cursor, polled) => {
|
|
|
17
19
|
const once = Stream.suspend(() => open(at)).pipe(Stream.tap((fed) => Effect.sync(() => {
|
|
18
20
|
at = fed.cursor ?? at;
|
|
19
21
|
})));
|
|
20
|
-
const reopened = transient === void 0 ? once : once.pipe(Stream.repeat(Schedule.spaced(reconnectDelay)), Stream.retry(afterFailures(transient)));
|
|
22
|
+
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
23
|
return polled === void 0 ? reopened : reopened.pipe(Stream.catchIf(pushRefused, () => Stream.suspend(() => polled(at))));
|
|
22
24
|
};
|
|
23
25
|
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 } 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, Schema.is(Unavailable), (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`; 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
|
@@ -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.ReachingOptions`.
|
|
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