@gjermundgaraba/effect-actions 0.34.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 +2 -2
- package/dist/Action.mjs +2 -2
- package/dist/ActionEntity.d.mts +58 -36
- package/dist/ActionEntity.mjs +64 -42
- package/dist/contract/errors.d.mts +5 -0
- package/dist/contract/errors.mjs +6 -1
- package/dist/contract/watch.mjs +1 -2
- package/dist/http/unavailable.mjs +2 -2
- package/docs/Action.md +1 -1
- package/docs/ActionEntity.md +2 -2
- 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, Unavailable } 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";
|
|
@@ -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, Unavailable, 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, Unavailable } 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
|
|
@@ -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, Unavailable, 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 { Duration, 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,30 +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
|
|
166
|
+
* `EntityNotAssignedToRunner`, which `client`, `nativeClient` and `reaching` answer as
|
|
169
167
|
* `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
|
|
171
|
-
* the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
|
|
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.
|
|
172
170
|
*/
|
|
173
171
|
export declare const isClusterFailure: <I>(input: I) => input is I & (ClusterError.AlreadyProcessingMessage | ClusterError.EntityNotAssignedToRunner | ClusterError.MailboxFull | ClusterError.PersistenceError);
|
|
174
172
|
/**
|
|
175
173
|
* What one call of an action `A` fails with, beside the binding's errors `E`: its declared and
|
|
176
|
-
* built-in errors,
|
|
177
|
-
*
|
|
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.
|
|
178
176
|
*/
|
|
179
|
-
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"];
|
|
180
178
|
type Method<A extends Any$1, E extends Errors[number]> = Call<A, Answer<A["success"], MethodError<A, E>, never>>;
|
|
181
179
|
/**
|
|
182
180
|
* What a watch of `W` over the binding `B` may fail with: a refusal, `InvalidInput`, the
|
|
183
|
-
* binding's errors
|
|
184
|
-
* serve)
|
|
181
|
+
* binding's errors or an `Event.SubscriptionError` (`NotServed` for an event the entity does not
|
|
182
|
+
* serve).
|
|
185
183
|
*/
|
|
186
|
-
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"];
|
|
187
185
|
type Watching<B extends Any$3> = [B["events"][number]] extends [never] ? unknown : {
|
|
188
186
|
readonly watch: <W extends B["events"][number], SE = never>(event: W, ...args: WatchArgs<W, SE, {
|
|
189
187
|
readonly mode?: "poll" | undefined;
|
|
@@ -195,37 +193,61 @@ type Watching<B extends Any$3> = [B["events"][number]] extends [never] ? unknown
|
|
|
195
193
|
* options)` follows one by polling.
|
|
196
194
|
*/
|
|
197
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>;
|
|
198
|
-
/**
|
|
199
|
-
|
|
200
|
-
* input, `rooms.postMessage({ room: "lobby", text })`, and `watch(event, input, options)`, which
|
|
201
|
-
* polls the event's rpc, each call and watch sent to the entity its input's key names. Requires
|
|
202
|
-
* `Sharding`, as `Entity.client` does: `TestRunner.layer` in a test. The entity's native rpcs are
|
|
203
|
-
* Effect's own client's methods: `(yield* Room.client)("lobby").expire()`.
|
|
204
|
-
*
|
|
205
|
-
* **Gotchas**
|
|
206
|
-
*
|
|
207
|
-
* - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
|
|
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`.
|
|
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.
|
|
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.
|
|
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>;
|
|
213
|
-
type Nothing<C extends Any$1 | Any$2> = { readonly [K in C["name"]]: never; };
|
|
214
|
-
/** `reaching`'s options. */
|
|
215
|
-
export interface ReachingOptions {
|
|
196
|
+
/** `client`'s, `nativeClient`'s and `reaching`'s options. */
|
|
197
|
+
export interface EntityCallOptions {
|
|
216
198
|
/**
|
|
217
199
|
* 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
|
|
219
|
-
* 20 seconds by default.
|
|
200
|
+
* `Action.Unavailable`: an action's call, a native rpc's, a poll, and a webhook subscribe or
|
|
201
|
+
* unsubscribe. 20 seconds by default.
|
|
220
202
|
*
|
|
221
203
|
* **Gotchas**
|
|
222
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.
|
|
223
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.
|
|
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.
|
|
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.
|
|
225
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.
|
|
226
209
|
*/
|
|
227
210
|
readonly timeout?: Duration.Input | undefined;
|
|
228
211
|
}
|
|
212
|
+
/**
|
|
213
|
+
* The client of `entity` over Effect's own `Entity.client`: one method per action taking its
|
|
214
|
+
* input, `rooms.postMessage({ room: "lobby", text })`, and `watch(event, input, options)`, which
|
|
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.
|
|
220
|
+
*
|
|
221
|
+
* **Gotchas**
|
|
222
|
+
*
|
|
223
|
+
* - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
|
|
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`.
|
|
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.
|
|
248
|
+
*/
|
|
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>;
|
|
250
|
+
type Nothing<C extends Any$1 | Any$2> = { readonly [K in C["name"]]: never; };
|
|
229
251
|
/**
|
|
230
252
|
* The implementations of `entity`'s actions and event types that any surface serves beside its
|
|
231
253
|
* own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
|
|
@@ -251,5 +273,5 @@ export interface ReachingOptions {
|
|
|
251
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.
|
|
252
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.
|
|
253
275
|
*/
|
|
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?:
|
|
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>>;
|
|
255
277
|
export { forwardedHeaders };
|
package/dist/ActionEntity.mjs
CHANGED
|
@@ -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 { Duration, 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,53 +108,86 @@ 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
|
+
* `EntityNotAssignedToRunner`, which `client`, `nativeClient` and `reaching` answer as
|
|
120
121
|
* `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
|
|
122
|
-
* the Cloudflare package's `ActionCluster.failureResponse` does, with a 503.
|
|
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.
|
|
123
124
|
*/
|
|
124
125
|
const isClusterFailure = Schema.is(ClusterFailures);
|
|
125
|
-
const
|
|
126
|
-
const
|
|
127
|
-
const
|
|
128
|
-
return
|
|
129
|
-
});
|
|
130
|
-
const
|
|
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) => {
|
|
131
147
|
const named = namedBy(entity.key);
|
|
148
|
+
const sending = sendingWithin(entity.type, options);
|
|
132
149
|
return (contract, input) => {
|
|
133
150
|
const entityId = named(input);
|
|
134
|
-
return entityId === void 0 ? Effect.fail(new Forbidden({ message: `The input of ${contract.name} names no entity of ${entity.type}` })) : Effect.map(headers, (sent) =>
|
|
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
|
+
});
|
|
135
155
|
};
|
|
136
156
|
};
|
|
137
157
|
/**
|
|
138
158
|
* The client of `entity` over Effect's own `Entity.client`: one method per action taking its
|
|
139
159
|
* input, `rooms.postMessage({ room: "lobby", text })`, and `watch(event, input, options)`, which
|
|
140
|
-
* polls the event's rpc, each call and watch sent to the entity its input's key names.
|
|
141
|
-
*
|
|
142
|
-
*
|
|
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.
|
|
143
165
|
*
|
|
144
166
|
* **Gotchas**
|
|
145
167
|
*
|
|
146
168
|
* - An input whose key names no entity, such as one missing the key's field, fails with `Forbidden`, sending nothing.
|
|
147
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`.
|
|
148
|
-
* -
|
|
149
|
-
* - 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.
|
|
150
173
|
*/
|
|
151
|
-
const client = (entity) => {
|
|
152
|
-
const methods = methodsOf(entity.binding, polledTransport(
|
|
153
|
-
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);
|
|
154
177
|
return Effect.map(entity.client, (clientFor) => methods(reach(clientFor)));
|
|
155
178
|
};
|
|
156
|
-
|
|
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
|
+
}
|
|
157
191
|
/**
|
|
158
192
|
* The implementations of `entity`'s actions and event types that any surface serves beside its
|
|
159
193
|
* own, `ActionHttp.layer`, `ActionRpc.layer` or `ActionMcp.layerHttp`: each call sent through
|
|
@@ -181,22 +215,10 @@ const defaultTimeout = Duration.seconds(20);
|
|
|
181
215
|
*/
|
|
182
216
|
const reaching = (entity, options = {}) => {
|
|
183
217
|
const { binding } = entity;
|
|
184
|
-
const reaches = Effect.map(entity.client, reachOf(entity, forwarded));
|
|
185
|
-
const named = namedBy(entity.key);
|
|
186
|
-
const timeout = Duration.fromInputUnsafe(options.timeout ?? defaultTimeout);
|
|
187
|
-
const unavailable = (contract, input) => (outcome) => new Unavailable({ message: `${contract.name}: the entity ${entity.type}/${named(input) ?? "none"} ${outcome}; the call's outcome is unknown, as the entity may still run it` });
|
|
188
|
-
const unreached = (contract, input, answer) => Effect.catchIf(answer, isClusterFailure, (failure) => Effect.fail(unavailable(contract, input)(`could not be reached (${failure._tag})`)));
|
|
189
|
-
const bounded = (contract, input, answer) => Effect.timeoutOrElse(unreached(contract, input, answer), {
|
|
190
|
-
duration: timeout,
|
|
191
|
-
orElse: () => Effect.fail(unavailable(contract, input)(`did not answer within ${Duration.format(timeout)}`))
|
|
192
|
-
});
|
|
218
|
+
const reaches = Effect.map(entity.client, reachOf(entity, forwarded, options));
|
|
193
219
|
const handlerOf = (action, reach) => {
|
|
194
220
|
const method = actionMethodOf(action, binding)(reach);
|
|
195
|
-
return (input, reporting) => {
|
|
196
|
-
const answer = method(input, ...reporting === void 0 ? [] : [{ onProgress: reporting.progress }]);
|
|
197
|
-
if (!Effect.isEffect(answer)) return Stream.catchIf(answer, isClusterFailure, (failure) => Stream.fail(unavailable(action, input)(`could not be reached (${failure._tag})`)));
|
|
198
|
-
return action.progress === void 0 ? bounded(action, input, answer) : unreached(action, input, answer);
|
|
199
|
-
};
|
|
221
|
+
return (input, reporting) => method(input, ...reporting === void 0 ? [] : [{ onProgress: reporting.progress }]);
|
|
200
222
|
};
|
|
201
223
|
const runOf = (event, reach) => {
|
|
202
224
|
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(event.input));
|
|
@@ -204,24 +226,24 @@ const reaching = (entity, options = {}) => {
|
|
|
204
226
|
const watched = watchedOf(event, binding);
|
|
205
227
|
const webhookCalls = webhookCallsOf(event, binding);
|
|
206
228
|
const reached = (input) => Effect.all([reach(event, input), Effect.orDie(encode(input))]);
|
|
207
|
-
const inEntity = (input, sent) => Effect.flatMap(reach(event, input), (call) =>
|
|
229
|
+
const inEntity = (input, sent) => Effect.flatMap(reach(event, input), (call) => sent(webhookCalls(call)));
|
|
208
230
|
return {
|
|
209
231
|
polls: true,
|
|
210
232
|
webhook: offersWebhook(event) ? {
|
|
211
233
|
subscribe: (subscribing) => inEntity(subscribing.input, (held) => held.subscribe(subscribing)),
|
|
212
234
|
unsubscribe: (subscription) => inEntity(subscription.input, (held) => held.unsubscribe(subscription))
|
|
213
235
|
} : void 0,
|
|
214
|
-
poll: (input, cursor, { maxEvents }) => Effect.flatMap(reached(input), ([call, json]) =>
|
|
236
|
+
poll: (input, cursor, { maxEvents }) => Effect.flatMap(reached(input), ([call, json]) => poll(call)({
|
|
215
237
|
input: json,
|
|
216
238
|
cursor,
|
|
217
239
|
...maxEvents === void 0 ? {} : { maxEvents }
|
|
218
|
-
}))
|
|
240
|
+
})),
|
|
219
241
|
stream: (input, cursor) => Stream.unwrap(Effect.map(reached(input), ([call, json]) => {
|
|
220
242
|
const transport = watched(call)(json);
|
|
221
|
-
return polling(
|
|
243
|
+
return polling(transport, Function.constFalse)(cursor);
|
|
222
244
|
}))
|
|
223
245
|
};
|
|
224
246
|
};
|
|
225
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)))]];
|
|
226
248
|
};
|
|
227
|
-
export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, reaching };
|
|
249
|
+
export { bindingRpcs, client, forwardedHeaders, isClusterFailure, layer, make, nativeClient, reaching };
|
|
@@ -109,6 +109,11 @@ declare const Unavailable_base: Schema.Class<Unavailable, Schema.TaggedStruct<"U
|
|
|
109
109
|
export declare class Unavailable extends Unavailable_base {
|
|
110
110
|
private readonly "~declared in the action's error, or built in";
|
|
111
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* Whether a value is `Unavailable`, the built-in error a caller may try again later, such as one
|
|
114
|
+
* `ActionEntity.client` failed with: `Effect.catchIf(call, Action.isUnavailable, retryLater)`.
|
|
115
|
+
*/
|
|
116
|
+
export declare const isUnavailable: <I>(input: I) => input is I & Unavailable;
|
|
112
117
|
/**
|
|
113
118
|
* What authentication or an implementation's `authorize` refuses a caller with, instead of
|
|
114
119
|
* running a handler. As a schema, it tells a refusal apart: `Schema.is(Action.Refusal)(error)`.
|
package/dist/contract/errors.mjs
CHANGED
|
@@ -91,6 +91,11 @@ var Forbidden = class extends Schema.TaggedError()("Forbidden", {
|
|
|
91
91
|
* - An answer `Action.Idempotency` keeps is never this error, as for any 5xx: a repeat runs the call again.
|
|
92
92
|
*/
|
|
93
93
|
var Unavailable = class extends Schema.TaggedError()("Unavailable", { message: defaultedMessage("The service is unavailable: try again later.") }, { httpApiStatus: 503 }) {};
|
|
94
|
+
/**
|
|
95
|
+
* Whether a value is `Unavailable`, the built-in error a caller may try again later, such as one
|
|
96
|
+
* `ActionEntity.client` failed with: `Effect.catchIf(call, Action.isUnavailable, retryLater)`.
|
|
97
|
+
*/
|
|
98
|
+
const isUnavailable = Schema.is(Unavailable);
|
|
94
99
|
const refusals = [Unauthenticated, Forbidden];
|
|
95
100
|
/**
|
|
96
101
|
* What authentication or an implementation's `authorize` refuses a caller with, instead of
|
|
@@ -104,4 +109,4 @@ const builtIns = [
|
|
|
104
109
|
];
|
|
105
110
|
/** The built-in failures as one schema: `Schema.is(Action.BuiltIn)(error)`. */
|
|
106
111
|
const BuiltIn = Schema.Union(builtIns);
|
|
107
|
-
export { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, Unavailable, builtIns, scopeToken };
|
|
112
|
+
export { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated, Unavailable, builtIns, isUnavailable, scopeToken };
|
package/dist/contract/watch.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CallbackUrl } from "./callback.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { isUnavailable } from "./errors.mjs";
|
|
3
3
|
import { SubscriptionError } from "../Event.mjs";
|
|
4
4
|
import { Checked, Gap } from "./occurrence.mjs";
|
|
5
5
|
import { paged } from "./pages.mjs";
|
|
@@ -11,7 +11,6 @@ import { Cause, Clock, Duration, Effect, Predicate, Queue, Schedule, Schema, Str
|
|
|
11
11
|
const reconnectDelay = Duration.seconds(1);
|
|
12
12
|
const maxReconnectDelay = Duration.seconds(30);
|
|
13
13
|
const afterFailures = (transient) => Schedule.min([Schedule.exponential(reconnectDelay), Schedule.spaced(maxReconnectDelay)]).pipe(Schedule.setInputType(), Schedule.while(({ input }) => transient(input)), Schedule.tap(({ input, duration }) => Effect.logWarning(`A watch reconnects in ${Duration.format(duration)} after a failure`, input)));
|
|
14
|
-
const isUnavailable = Schema.is(Unavailable);
|
|
15
14
|
const isSubscriptionError = Schema.is(SubscriptionError);
|
|
16
15
|
const pushRefused = Predicate.compose(isSubscriptionError, ({ reason }) => Predicate.isTagged(reason, "Unsupported") && reason.feature === "deliveryMode" && reason.value === "push");
|
|
17
16
|
const reconnecting = (transient, open, cursor, polled) => {
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { Unavailable } from "../contract/errors.mjs";
|
|
1
|
+
import { Unavailable, isUnavailable } from "../contract/errors.mjs";
|
|
2
2
|
import { Cause, Effect, ErrorReporter, Layer, Schema } from "effect";
|
|
3
3
|
import { HttpServerResponse } from "effect/http";
|
|
4
4
|
import { HttpApiMiddleware } from "effect/http-api";
|
|
5
5
|
// src/http/unavailable.ts
|
|
6
6
|
const encode = Schema.encodeUnknownSync(Schema.toCodecJson(Unavailable));
|
|
7
7
|
var RetryAfter = class extends HttpApiMiddleware.Service()("effect-actions/http/RetryAfter") {};
|
|
8
|
-
const retryAfter = Layer.succeed(RetryAfter, (route) => Effect.catchIf(route,
|
|
8
|
+
const retryAfter = Layer.succeed(RetryAfter, (route) => Effect.catchIf(route, isUnavailable, (error) => Effect.as(ErrorReporter.report(Cause.fail(error)), HttpServerResponse.jsonUnsafe(encode(error), {
|
|
9
9
|
status: 503,
|
|
10
10
|
headers: { "retry-after": "1" }
|
|
11
11
|
}))));
|
package/docs/Action.md
CHANGED
|
@@ -120,7 +120,7 @@ Actions under another rule go in another `Action.implement` with its own `author
|
|
|
120
120
|
|
|
121
121
|
## Fail with declared and built-in errors
|
|
122
122
|
|
|
123
|
-
A handler fails with the errors its action lists in `error`, and with the four built-in errors, `InvalidInput`, `Unauthenticated`, `Forbidden` and `Unavailable`. What a refusal answers on each surface is on `Action.Unauthenticated` and `Action.Forbidden`, and what `Unavailable`, the answer when the call could not be served now and its outcome is unknown, answers is on `Action.Unavailable`; what a declared error and bad input answer, on each surface's `layer`, `layerHttp`, `runStdio`, `make` or `command`; when to fail with `InvalidInput` yourself, on that class, as [kitchen-sink/src/attachments/handlers.ts](../examples/kitchen-sink/src/attachments/handlers.ts) does.
|
|
123
|
+
A handler fails with the errors its action lists in `error`, and with the four built-in errors, `InvalidInput`, `Unauthenticated`, `Forbidden` and `Unavailable`. What a refusal answers on each surface is on `Action.Unauthenticated` and `Action.Forbidden`, and what `Unavailable`, the answer when the call could not be served now and its outcome is unknown, answers is on `Action.Unavailable`, which a caller tells apart with `Action.isUnavailable`, `Effect.catchIf(call, Action.isUnavailable, retryLater)`; what a declared error and bad input answer, on each surface's `layer`, `layerHttp`, `runStdio`, `make` or `command`; when to fail with `InvalidInput` yourself, on that class, as [kitchen-sink/src/attachments/handlers.ts](../examples/kitchen-sink/src/attachments/handlers.ts) does.
|
|
124
124
|
|
|
125
125
|
- **Add the errors a module adds to every action it serves, a proxy's or a store's, to contracts written elsewhere with `Action.withErrors`**, `pipe(action, Action.withErrors([Throttled]))`, rather than restating each contract. It returns a new contract, which the module then implements and lists; its rules are on `Action.withErrors`.
|
|
126
126
|
- **Map a client's `HttpClientError` and `SchemaError` to one declared error a caller can act on** ([mcp-tools/src/platform/print-farm.ts](../examples/mcp-tools/src/platform/print-farm.ts)). As defects, a model reads only a generic text.
|
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,7 +74,7 @@ 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.
|
|
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
78
|
|
|
79
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`.
|
|
80
80
|
|
package/package.json
CHANGED