@gjermundgaraba/effect-actions 0.31.0 → 0.33.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/README.md +4 -3
- package/dist/Action.d.mts +6 -6
- package/dist/Action.mjs +3 -4
- package/dist/ActionEntity.d.mts +237 -0
- package/dist/ActionEntity.mjs +211 -0
- package/dist/ActionHttp.d.mts +4 -5
- package/dist/ActionHttp.mjs +12 -12
- package/dist/ActionMcp.d.mts +2 -3
- package/dist/ActionMcp.mjs +1 -1
- package/dist/ActionRpc.d.mts +25 -58
- package/dist/ActionRpc.mjs +34 -249
- package/dist/Authentication.d.mts +8 -9
- package/dist/Authentication.mjs +6 -6
- package/dist/Event.d.mts +26 -6
- package/dist/Event.mjs +2 -2
- package/dist/Stored.d.mts +64 -0
- package/dist/Stored.mjs +102 -0
- package/dist/Webhook.d.mts +5 -4
- package/dist/Webhook.mjs +11 -4
- package/dist/authentication/provider.d.mts +2 -2
- package/dist/contract/call.mjs +6 -2
- package/dist/contract/caller.d.mts +2 -6
- package/dist/contract/caller.mjs +3 -3
- package/dist/contract/event-tables.mjs +90 -0
- package/dist/contract/feed.d.mts +15 -3
- package/dist/contract/feed.mjs +20 -11
- package/dist/contract/hub.d.mts +4 -57
- package/dist/contract/hub.mjs +12 -15
- package/dist/contract/idempotency.d.mts +6 -18
- package/dist/contract/idempotency.mjs +6 -14
- package/dist/contract/implementation.mjs +3 -4
- package/dist/contract/log.d.mts +0 -26
- package/dist/contract/log.mjs +16 -8
- package/dist/contract/pages.d.mts +30 -2
- package/dist/contract/pages.mjs +27 -3
- package/dist/contract/wake.mjs +9 -0
- package/dist/contract/watch.mjs +20 -15
- package/dist/contract/webhooks.d.mts +8 -4
- package/dist/contract/webhooks.mjs +42 -31
- package/dist/entity/forwarded.d.mts +11 -0
- package/dist/entity/forwarded.mjs +32 -0
- package/dist/entity/wakes.mjs +39 -0
- package/dist/http/client.mjs +2 -2
- package/dist/http/events.d.mts +1 -12
- package/dist/http/events.mjs +2 -24
- package/dist/http/redacted.mjs +9 -0
- package/dist/mcp/bridge.mjs +5 -6
- package/dist/mcp/client.mjs +2 -2
- package/dist/rpc/erased.d.mts +62 -0
- package/dist/rpc/erased.mjs +356 -0
- package/dist/rpc/watch.mjs +10 -9
- package/dist/webhook/stored.mjs +6 -4
- package/dist/webhook/subscriptions.mjs +58 -40
- package/docs/Action-streams.md +2 -2
- package/docs/Action.md +3 -3
- package/docs/ActionEntity-failures.md +10 -0
- package/docs/ActionEntity.md +165 -0
- package/docs/ActionHttp.md +0 -4
- package/docs/ActionMcp.md +2 -2
- package/docs/ActionRpc-events.md +2 -2
- package/docs/ActionRpc.md +1 -1
- package/docs/Authentication-failures.md +1 -0
- package/docs/Authentication.md +4 -2
- package/docs/Event.md +5 -5
- package/docs/README.md +5 -2
- package/docs/Webhook.md +1 -1
- package/docs/setup-failures.md +1 -1
- package/docs/setup.md +6 -5
- package/examples/README.md +1 -1
- package/examples/kitchen-sink/src/admin/Admin.ts +1 -0
- package/examples/kitchen-sink/src/identity/Identity.ts +5 -1
- package/examples/live-rpc/src/identity/Identity.ts +3 -1
- package/examples/notes-service/src/identity/Identity.ts +3 -1
- package/examples/shopping-carts/README.md +46 -0
- package/examples/shopping-carts/src/Api.ts +9 -0
- package/examples/shopping-carts/src/Rpc.ts +6 -0
- package/examples/shopping-carts/src/cart/Cart.ts +47 -0
- package/examples/shopping-carts/src/cart/handlers.ts +42 -0
- package/examples/shopping-carts/src/cart/held.ts +5 -0
- package/examples/shopping-carts/src/cart/store.ts +10 -0
- package/examples/shopping-carts/src/entities.ts +7 -0
- package/examples/shopping-carts/src/identity/Identity.ts +16 -0
- package/examples/shopping-carts/src/identity/shoppers.ts +6 -0
- package/examples/shopping-carts/src/identity/verifier.ts +21 -0
- package/examples/shopping-carts/src/platform/cluster.ts +7 -0
- package/examples/shopping-carts/src/platform/sql-carts.ts +30 -0
- package/examples/shopping-carts/src/routes.ts +23 -0
- package/examples/shopping-carts/src/server.ts +23 -0
- package/examples/shopping-carts/test/routes.test.ts +69 -0
- package/package.json +9 -6
- package/dist/contract/input-check.d.mts +0 -15
- package/dist/contract/input-check.mjs +0 -15
- package/dist/http/placed.d.mts +0 -34
- package/dist/http/placed.mjs +0 -71
package/dist/ActionHttp.mjs
CHANGED
|
@@ -7,12 +7,12 @@ import { listed } from "./contract/listed.mjs";
|
|
|
7
7
|
import { provideServed, servingOf } from "./contract/serving.mjs";
|
|
8
8
|
import { declared } from "./contract/status.mjs";
|
|
9
9
|
import { Answering, answeringOf } from "./contract/stream.mjs";
|
|
10
|
-
import { offersWebhook, servingFeeds } from "./contract/webhooks.mjs";
|
|
10
|
+
import { offersWebhook, servingFeeds, webhookAnswers } from "./contract/webhooks.mjs";
|
|
11
11
|
import { methods } from "./http/client.mjs";
|
|
12
|
-
import { answering, eventEndpointOf, servedSent,
|
|
12
|
+
import { answering, eventEndpointOf, servedSent, webhookEndpointsOf } from "./http/events.mjs";
|
|
13
|
+
import { credentialNames } from "./http/redacted.mjs";
|
|
13
14
|
import { SchemaErrors, schemaErrors } from "./http/schema-errors.mjs";
|
|
14
15
|
import { answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf } from "./http/streamed.mjs";
|
|
15
|
-
import { placed } from "./http/placed.mjs";
|
|
16
16
|
import { Context, Effect, Layer, Scope } from "effect";
|
|
17
17
|
import { FetchHttpClient, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
18
18
|
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/http-api";
|
|
@@ -58,9 +58,9 @@ function make(contracts, options = {}) {
|
|
|
58
58
|
event.name
|
|
59
59
|
]);
|
|
60
60
|
const errors = eventErrors(event, bound);
|
|
61
|
-
return [eventEndpointOf(event, path, errors), ...offersWebhook(event
|
|
61
|
+
return [eventEndpointOf(event, path, errors), ...offersWebhook(event) ? webhookEndpointsOf(event, path, errors) : []].map((endpoint) => secured(endpoint, event));
|
|
62
62
|
})];
|
|
63
|
-
const api = apiOf(groupName(mount), endpoints);
|
|
63
|
+
const api = apiOf(groupName(mount), endpoints).annotate(HttpApi.RedactedNames, credentialNames(bound.authentication));
|
|
64
64
|
return {
|
|
65
65
|
actions,
|
|
66
66
|
events,
|
|
@@ -93,22 +93,22 @@ function layer(binding, served, options = {}) {
|
|
|
93
93
|
event.name
|
|
94
94
|
]);
|
|
95
95
|
const errors = eventErrors(event, { error: binding.error });
|
|
96
|
-
return [eventEndpointOf(event, path, errors, servedSent), ...offersWebhook(event
|
|
97
|
-
})]).annotate(HttpApi.PayloadParseOptions, inputParseOptions);
|
|
96
|
+
return [eventEndpointOf(event, path, errors, servedSent), ...offersWebhook(event) ? webhookEndpointsOf(event, path, errors) : []].map((endpoint) => routed(endpoint, event));
|
|
97
|
+
})]).annotate(HttpApi.RedactedNames, credentialNames(binding.authentication)).annotate(HttpApi.PayloadParseOptions, inputParseOptions);
|
|
98
98
|
const handlers = Layer.unwrap(Effect.gen(function* () {
|
|
99
99
|
const bound = yield* acquire(apps, authentication);
|
|
100
|
-
const { feeds, webhooks
|
|
100
|
+
const { feeds, webhooks } = yield* servingFeeds(events, authentication);
|
|
101
101
|
const security = authentication === void 0 ? Layer.empty : yield* Effect.map(providerOf(authentication), (provider) => Layer.mergeAll(Layer.succeed(authentication["~middleware"], provider.middleware), Layer.succeed(StepUp, provider.stepUp)));
|
|
102
102
|
const hostProvidedMiddleware = yield* Effect.forEach(options.middleware ?? [], (key) => Effect.map(Effect.service(key), (service) => Layer.succeed(key, service)));
|
|
103
|
-
const webhookAnswered =
|
|
103
|
+
const webhookAnswered = feeds.filter(({ event }) => offersWebhook(event)).map((feed) => [feed.event.name, webhookAnswers(feed, authentication, webhooks)]);
|
|
104
104
|
const byName = {
|
|
105
105
|
...Object.fromEntries(bound.map(([action, run]) => {
|
|
106
106
|
const answer = answerOf(action, run);
|
|
107
107
|
return [action.name, (request) => answer(request.payload)];
|
|
108
108
|
})),
|
|
109
109
|
...Object.fromEntries(feeds.map((feed) => [feed.event.name, answering(feed, authentication)])),
|
|
110
|
-
...Object.fromEntries(webhookAnswered.map(([eventName, { subscribe }]) => [`${eventName}/subscribe`, subscribe])),
|
|
111
|
-
...Object.fromEntries(webhookAnswered.map(([eventName, { unsubscribe }]) => [`${eventName}/unsubscribe`, unsubscribe]))
|
|
110
|
+
...Object.fromEntries(webhookAnswered.map(([eventName, { subscribe }]) => [`${eventName}/subscribe`, ({ payload }) => subscribe(payload)])),
|
|
111
|
+
...Object.fromEntries(webhookAnswered.map(([eventName, { unsubscribe }]) => [`${eventName}/unsubscribe`, ({ payload }) => unsubscribe(payload)]))
|
|
112
112
|
};
|
|
113
113
|
return HttpApiBuilder.group(api, name, (builder) => builder.handleAll(byName)).pipe(Layer.provide([
|
|
114
114
|
schemaErrors,
|
|
@@ -125,4 +125,4 @@ function client(binding, options) {
|
|
|
125
125
|
function fetchClient(binding, { fetch, ...options } = {}) {
|
|
126
126
|
return methods(binding, options).pipe(Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.Fetch, fetch ?? (async (input, init) => await globalThis.fetch(input, init))), Effect.runSync);
|
|
127
127
|
}
|
|
128
|
-
export { client, fetchClient, layer, make
|
|
128
|
+
export { client, fetchClient, layer, make };
|
package/dist/ActionMcp.d.mts
CHANGED
|
@@ -108,7 +108,7 @@ type Inferring<D, A extends Pick<Any$1, "caller">> = [D] extends [undefined] ? [
|
|
|
108
108
|
* tools need `authentication`; for a serverless host, see `requestScoped`. In a tool call, what
|
|
109
109
|
* middleware provides per request wins over what the endpoint was built with. The event
|
|
110
110
|
* types among `implementations`, or those `actions` lists, are served as SEP-3415 events,
|
|
111
|
-
* `events/list`, `events/poll` and `events/stream`, and, where `Webhook.layer` is provided, `events/subscribe`
|
|
111
|
+
* `events/list`, `events/poll` and `events/stream`, and, where `Webhook.layer` is provided or for a protected event `ActionEntity.reaching` serves, `events/subscribe`
|
|
112
112
|
* and `events/unsubscribe`: experimental, as that extension is a draft, pinned to its PR head
|
|
113
113
|
* 2ec39b9c49c583411b73cb460dea5f52b5c541a6.
|
|
114
114
|
* Guide: `docs/ActionMcp.md` in this package; in an application: `examples/mcp-tools/`, and
|
|
@@ -128,9 +128,8 @@ type Inferring<D, A extends Pick<Any$1, "caller">> = [D] extends [undefined] ? [
|
|
|
128
128
|
* - A request body is read whole, however large, and a 2025 session holds what its `initialize` sent until it ends, so an oversized `initialize` costs memory for that long: limit bodies as `ActionHttp.layer` says.
|
|
129
129
|
* - An event type named starting with `mcp.`, a prefix MCP keeps for its own events, is refused as the endpoint is made, with `MCP event name starts with "mcp."`.
|
|
130
130
|
* - Events are 2026-07-28's alone: a 2025 session gets `-32601` for `events/*`, and its `initialize` advertises no events extension.
|
|
131
|
-
* - With `requestScoped`, `events/stream` answers `-32026`, no server outliving a request to push, so events are served by poll, and by webhook where `Webhook.layer` is provided; their sources, logs, `subscription` hooks' leases and webhook subscriptions are built once with the endpoint, as without it.
|
|
131
|
+
* - With `requestScoped`, `events/stream` answers `-32026`, no server outliving a request to push, so events are served by poll, and by webhook where `Webhook.layer` is provided or the event is a protected one `ActionEntity.reaching` serves; their sources, logs, `subscription` hooks' leases and webhook subscriptions are built once with the endpoint, as without it.
|
|
132
132
|
* - On a host with no lasting process, such as a serverless platform, serve check sources alone, without a `subscription` hook: nothing refuses the others, and under `Event.layerMemory` each instance keeps its own log of a log source, whose cursors another reads as a gap, and its own leases, lost as it ends.
|
|
133
|
-
* - A protected event with a `subscription` hook needs `principal` on `authentication`, or the endpoint is refused at startup: a poll's hook is held per principal between requests.
|
|
134
133
|
* - A push stream holds its request open while it is read, a heartbeat every 30 seconds: a host's request timeout ends it, and `client`'s `watch` reconnects from its cursor.
|
|
135
134
|
* - A poll's `maxEvents` caps a log source's page, at most 100, and is not honored for a check source, whose page is answered whole since only its last cursor resumes; `maxAgeMs` is accepted and not honored, a log source keeping what its `log.maxAge` and `log.maxEvents` say.
|
|
136
135
|
* - A push stream's failure that no refusal explains, such as an upstream's outage, is `notifications/events/error`, its cause logged and reported, and the stream resumes from where it reached after 5 seconds; a refusal ends it with `notifications/events/terminated`. One before `active`, or a poll's, is a JSON-RPC `-32603`, which `client`'s `watch` reconnects after, as after a 5xx.
|
package/dist/ActionMcp.mjs
CHANGED
|
@@ -132,7 +132,7 @@ const server = (apps, serving, transport, features = Layer.empty) => {
|
|
|
132
132
|
const register = Effect.gen(function* () {
|
|
133
133
|
const namesClaimedByFeatures = (yield* McpServer.McpServer).tools.flatMap(({ tool }) => names.has(tool.name) ? [tool.name] : []);
|
|
134
134
|
if (namesClaimedByFeatures.length > 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Duplicate MCP tool: ${namesClaimedByFeatures.join(", ")}, claimed by an action and a native feature (rename the native tool, or leave the action out of actions)`));
|
|
135
|
-
yield* servingFeeds(
|
|
135
|
+
yield* servingFeeds(serving.events, serving.authentication);
|
|
136
136
|
yield* registerTools(apps, authentication);
|
|
137
137
|
});
|
|
138
138
|
return Layer.empty.pipe(Layer.provide(transport(Layer.effectDiscard(register).pipe(Layer.provide(features)))), Layer.fresh, provideServed(apps, events));
|
package/dist/ActionRpc.d.mts
CHANGED
|
@@ -12,16 +12,13 @@ import { Only } from "./contract/listed.mjs";
|
|
|
12
12
|
import { PushedOf, SubscriptionOf } from "./contract/push.mjs";
|
|
13
13
|
import { Answer, StreamOf } from "./contract/stream.mjs";
|
|
14
14
|
import { WatchArgs } from "./contract/watch.mjs";
|
|
15
|
-
import {
|
|
15
|
+
import { Poll, ProgressedOf, pollTag } from "./rpc/erased.mjs";
|
|
16
|
+
import { AnyPage } from "./contract/pages.mjs";
|
|
17
|
+
import { Context, Duration, Effect, Layer, Schedule, Schema, Scope, Stream, Types } from "effect";
|
|
16
18
|
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
17
|
-
import { Rpc, RpcClient, RpcClientError, RpcGroup,
|
|
19
|
+
import { Rpc, RpcClient, RpcClientError, RpcGroup, RpcMiddleware, RpcSchema, RpcServer } from "effect/rpc";
|
|
18
20
|
type BindingError = Errors[number];
|
|
19
21
|
type ErrorOf<A extends Any$2, E extends Errors, D> = Schema.Union<ReadonlyArray<A["error"][number] | E[number] | VerifierError<A, D> | BuiltIns>>;
|
|
20
|
-
declare const ProgressedOf: <P extends Codec, S extends Codec>(progress: P, success: S) => Schema.Union<readonly [Schema.TaggedStruct<"Progress", {
|
|
21
|
-
readonly value: P;
|
|
22
|
-
}>, Schema.TaggedStruct<"Final", {
|
|
23
|
-
readonly value: S;
|
|
24
|
-
}>]>;
|
|
25
22
|
type ElementedOf<Element extends Schema.Constraint, P> = Schema.Union<readonly [Schema.TaggedStruct<"Element", {
|
|
26
23
|
readonly value: Element;
|
|
27
24
|
}>, ...(P extends Codec ? [Schema.TaggedStruct<"Progress", {
|
|
@@ -65,12 +62,13 @@ export interface Binding<Actions extends readonly Any$2[], E extends Errors = []
|
|
|
65
62
|
*/
|
|
66
63
|
readonly rpcs: RpcGroup.RpcGroup<NativeOf<N, D>>;
|
|
67
64
|
/**
|
|
68
|
-
* The native group of one rpc per action, named after it, one stream rpc per event
|
|
69
|
-
* taking `{ input, cursor }`, `cursor: null` reading from now, and `rpcs
|
|
70
|
-
* `RpcClient.make(Rpc.group)` is
|
|
65
|
+
* The typed native group of one rpc per action, named after it, one stream rpc per event
|
|
66
|
+
* type, taking `{ input, cursor }`, `cursor: null` reading from now, and `rpcs`:
|
|
67
|
+
* `RpcClient.make(Rpc.group)` is a native client of them.
|
|
71
68
|
*
|
|
72
69
|
* **Gotchas**
|
|
73
70
|
*
|
|
71
|
+
* - It holds no event's `<event>/poll`, which `layer` serves beside its stream rpc: a native client of it watches by stream alone; poll through `client`, whose watch takes `mode: "poll"`.
|
|
74
72
|
* - `layer` hands the protocol an action's and an event type's values as their JSON, the native `rpcs`' as they are: under a codec other than a JSON serialization's, such as schema-binary's or a protocol passing values, `RpcClient.make(Rpc.group)` decodes an action's answer or an event's occurrence by its own schema and fails; call actions and watch events through `client`, which hands them over as JSON too.
|
|
75
73
|
*/
|
|
76
74
|
readonly group: RpcGroup.RpcGroup<RpcOf<Actions[number], E, D> | EventRpcOf<Events[number], E, D> | NativeOf<N, D>>;
|
|
@@ -112,7 +110,7 @@ export interface Options<E extends Errors = Errors> {
|
|
|
112
110
|
* - The layer's `middleware` runs on actions and event types alone: a native rpc runs the native middleware its group adds, inside its authentication.
|
|
113
111
|
* - Native middleware added to the binding's `rpcs` after `make` runs outside the authentication, before the identity exists; added to the group given here, inside it.
|
|
114
112
|
* - `layer` refuses a protected binding holding a native rpc without its authentication, such as one added with `rpcs.add` after `make`: add rpcs to the group given here.
|
|
115
|
-
* - A native rpc named after an action, an event type or a name the client keeps, `then` or `watch`, its method of events, is refused as the binding is made.
|
|
113
|
+
* - A native rpc named after an action, an event type, an event's `<event>/poll`, or a name the client keeps, `then` or `watch`, its method of events, is refused as the binding is made.
|
|
116
114
|
*/
|
|
117
115
|
readonly rpcs?: RpcGroup.Any;
|
|
118
116
|
}
|
|
@@ -122,7 +120,7 @@ type RpcsOf<O> = O extends {
|
|
|
122
120
|
/**
|
|
123
121
|
* Bind actions once, for servers and clients alike, each as an rpc named after it, taking
|
|
124
122
|
* its action's input and answering its success, and event types, each a stream rpc named after
|
|
125
|
-
* it, taking `{ input, cursor }
|
|
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`,
|
|
126
124
|
* and the built-in `InvalidInput`, `Unauthenticated` and `Forbidden`, so clients decode each as
|
|
127
125
|
* a typed failure; a protected one also declares what its descriptor's verifier fails with.
|
|
128
126
|
* `rpcs` adds native ones beside them. Browser-safe, as an HTTP binding is.
|
|
@@ -131,6 +129,7 @@ type RpcsOf<O> = O extends {
|
|
|
131
129
|
* **Gotchas**
|
|
132
130
|
*
|
|
133
131
|
* - An action, an event type and a native rpc of one name throw when `make` is called: they would share a client's method.
|
|
132
|
+
* - An authentication reading an API key `in: "query"` throws when `make` is called: an rpc carries headers alone, on every protocol and in an entity's envelope.
|
|
134
133
|
* - An action declaring `progress` is a stream rpc taking its input, streaming `{ _tag: "Progress", value }` for each value its handler reports, then one `{ _tag: "Final", value }` holding its answer: the native client's method of it returns a `Stream`.
|
|
135
134
|
* - An action answering a stream, `Action.Stream`, is a stream rpc taking its input, streaming `{ _tag: "Element", value }` for each element, beside `{ _tag: "Progress", value }` for each value where it declares `progress`; `client`'s method returns a `Stream` of the elements.
|
|
136
135
|
*/
|
|
@@ -182,44 +181,6 @@ export interface LayerOptions<M extends Middleware = [], C extends Any$2 | Any$3
|
|
|
182
181
|
*/
|
|
183
182
|
readonly middleware?: M;
|
|
184
183
|
}
|
|
185
|
-
/**
|
|
186
|
-
* One event subscription a `SubscriptionKeeper` keeps, as it arrived: the request a keeper writes
|
|
187
|
-
* to the server again, once restarted, with the payload `resumeFrom` gave for the last value sent.
|
|
188
|
-
*/
|
|
189
|
-
export interface KeptSubscription {
|
|
190
|
-
readonly clientId: number;
|
|
191
|
-
readonly requestId: string | number;
|
|
192
|
-
readonly tag: string;
|
|
193
|
-
/** The subscription's payload, an object of its `input` and the `cursor` it resumes from. */
|
|
194
|
-
readonly payload: Schema.Json;
|
|
195
|
-
/** The headers the request was authenticated with, which a resumed one is authenticated with again. */
|
|
196
|
-
readonly headers: ReadonlyArray<readonly [string, string]>;
|
|
197
|
-
/**
|
|
198
|
-
* The payload that resumes the subscription after `values`, a chunk sent for it, or
|
|
199
|
-
* `undefined` where they reach no position. It never throws, being called as the protocol
|
|
200
|
-
* sends: an input that does not encode fails its subscription as it is admitted instead.
|
|
201
|
-
*/
|
|
202
|
-
readonly resumeFrom: (values: RpcMessage.ResponseChunkEncoded["values"]) => Schema.Json | undefined;
|
|
203
|
-
}
|
|
204
|
-
/**
|
|
205
|
-
* What a protocol keeping event subscriptions across restarts of its server offers under
|
|
206
|
-
* `subscriptionKeeper`, as the Cloudflare package's `layerWebSocket` does: `layer` hands it each
|
|
207
|
-
* subscription once admitted, and sends every position the subscription reaches, with no
|
|
208
|
-
* 30-second heartbeat, whose timer would keep such a host awake.
|
|
209
|
-
*/
|
|
210
|
-
export interface SubscriptionKeeper {
|
|
211
|
-
readonly keep: (subscription: KeptSubscription) => Effect.Effect<void>;
|
|
212
|
-
}
|
|
213
|
-
/** The key a protocol sets to its `SubscriptionKeeper` on its `RpcServer.Protocol` service. */
|
|
214
|
-
export declare const subscriptionKeeper: unique symbol;
|
|
215
|
-
/**
|
|
216
|
-
* The key a protocol answering each call once sets to `true` on its `RpcServer.Protocol`
|
|
217
|
-
* service, as the Cloudflare package's stub protocol does, since Effect's protocol has no flag of
|
|
218
|
-
* its own for it: `layer` refuses to serve a streaming action, an event type or a native stream
|
|
219
|
-
* rpc on it, where a stream is answered with a defect at its first element and one with none
|
|
220
|
-
* waits for good.
|
|
221
|
-
*/
|
|
222
|
-
export declare const unaryProtocol: unique symbol;
|
|
223
184
|
/**
|
|
224
185
|
* Serve the binding's actions and event types among `implementations` with Effect's own
|
|
225
186
|
* `RpcServer`, or those its `actions` lists, as `ActionHttp.layer` selects them, under the
|
|
@@ -238,15 +199,14 @@ export declare const unaryProtocol: unique symbol;
|
|
|
238
199
|
* - A declared error, or `InvalidInput` for input that does not decode, is the call's typed failure; a refusal is answered as `Action.Unauthenticated` and `Action.Forbidden` say; the socket stays open, so a token may expire under it and a client handles `Unauthenticated` itself.
|
|
239
200
|
* - A defect, an undeclared failure, a middleware that throws, or a success or an error that does not encode ends that call with an `Error` whose message is `Internal server error`, its cause logged and reported to the call's `ErrorReporter`s; the connection's other calls go on.
|
|
240
201
|
* - An `ErrorReporter` is given only what ends a call with `Internal server error`, never a declared failure, a refusal or `InvalidInput`, unlike `ActionHttp.layer`'s `Info`: an alert counting declared failures counts none from rpcs.
|
|
241
|
-
* - An rpc's credential is read from its headers alone: an API key `in: "query"` never reaches authentication.
|
|
242
202
|
* - Over a protocol with no router, such as `RpcServer.layerProtocolSocketServer` or `layerProtocolStdio`, there is no route: a provider publishing a `protectedResource` leaves `HttpRouter` owed; the request a handler or a verifier reads is, on every protocol, one holding the message's headers, at `/`, with no query or body.
|
|
243
203
|
* - An event's stream rpc takes `{ input, cursor }`, a `cursor` omitted or `null` reading from now, and streams `Checked`, `Occurrence`, `Gap` and `Failed`, a `Checked` every 30 seconds; over `RpcServer.layerProtocolHttp` serialize with `RpcSerialization.layerNdjson`: under `layerJson` a response is sent once its streams end, so a watch never answers.
|
|
204
|
+
* - Beside it, an event's `<event>/poll` answers a `Page`, its subscription hook held for the caller's principal, as an `ActionEntity`'s is, so a `client`'s watch in either `mode` watches the layer.
|
|
244
205
|
* - A subscription refused when it starts or later ends its stream rpc with the refusal as the typed failure; a source's failure no refusal explains is logged and reported once, sent as a bare `Failed`, and read again from where it reached after 5 seconds.
|
|
245
206
|
* - A stream is read only as fast as its client reads it: a slow reader of a log source falls behind its log, and receives a `Gap`.
|
|
246
207
|
* - An action declaring `progress` streams it to every call, a client's call without `onProgress` too, its values handed on one at a time, so a slow reader drops the oldest; under `RpcSerialization.layerJson` over HTTP they arrive with the answer, at the end.
|
|
247
208
|
* - A failure after an action's progress or its first element ends its stream rpc as it ends any call: a declared failure as the typed failure, a defect as `Internal server error`.
|
|
248
209
|
* - The binding's native `rpcs` are served on the same protocol with their own schemas, every one, whatever `actions` lists, and their handlers are owed until provided: `Rpc.rpcs.toLayer(handlers)`; a native rpc's defect or undeclared failure is answered as Effect's server answers it, never `Internal server error`, and only its verifier's defect is.
|
|
249
|
-
* - On a protocol answering each call once, one setting `unaryProtocol`, such as a Durable Object stub's, the build fails while it would serve a streaming action, an event type or a native stream rpc.
|
|
250
210
|
*/
|
|
251
211
|
export declare function layer<const B extends Any, const Apps extends Served>(binding: B, implementations: Apps): RpcLayer<B, Apps, []>;
|
|
252
212
|
export declare function layer<const B extends Any, const Apps extends Served, const O extends LayerOptions<Middleware, B["actions"][number] | B["events"][number]>>(binding: B, implementations: Apps, options: O & ServerOnly<MiddlewareOf<O, Middleware>, B["error"]> & NoInfer<Known<O, LayerOptions<Middleware>>>): RpcLayer<B, Apps, MiddlewareOf<O, Middleware>, Selected<O, B["actions"][number]>, SelectedEvents<O, B["events"][number]>>;
|
|
@@ -259,8 +219,8 @@ export type MethodError<A extends Any$2, E extends BindingError = never> = A["er
|
|
|
259
219
|
type Method<A extends Any$2, E extends BindingError> = Call<A, Answer<A["success"], MethodError<A, E>, never>>;
|
|
260
220
|
/**
|
|
261
221
|
* What a watch of `W` over the binding `B` may fail with: a refusal, when it starts or later,
|
|
262
|
-
* `InvalidInput`, the binding's errors, an `Event.SubscriptionError` (`Unsupported` for
|
|
263
|
-
* `mode
|
|
222
|
+
* `InvalidInput`, the binding's errors, an `Event.SubscriptionError` (`Unsupported` for a
|
|
223
|
+
* webhook `mode`, `NotServed` for an event the server does not serve), or
|
|
264
224
|
* Effect's own `RpcClientError` that no reconnect outlasts. An element that does not decode is a defect, as for a call.
|
|
265
225
|
*/
|
|
266
226
|
export type WatchError<W extends Any$3, B extends Any> = SubscriptionError | BuiltIns["Type"] | B["error"][number]["Type"] | VerifierError<W, B["authentication"]>["Type"] | RpcClientError.RpcClientError;
|
|
@@ -274,11 +234,16 @@ type Watching<B extends Any> = [B["events"][number]] extends [never] ? unknown :
|
|
|
274
234
|
*/
|
|
275
235
|
export type Client<B extends Any> = { readonly [A in B["actions"][number] as A["name"]]: Method<A, B["error"][number] | VerifierError<A, B["authentication"]>>; } & Watching<B> & RpcClient.RpcClient<RpcGroup.Rpcs<B["rpcs"]>, RpcClientError.RpcClientError>;
|
|
276
236
|
/**
|
|
277
|
-
*
|
|
237
|
+
* `client`'s options: the native `RpcClient.make` options, `spanPrefix`, `spanAttributes`,
|
|
278
238
|
* `generateRequestId` and `disableTracing`. `flatten` changes the client's shape, which the
|
|
279
239
|
* method types cannot follow.
|
|
280
240
|
*/
|
|
281
241
|
export type ClientOptions = Omit<NonNullable<Parameters<typeof RpcClient.make>[1]>, "flatten">;
|
|
242
|
+
/**
|
|
243
|
+
* How long a polling watch waits for a poll's answer, 4 minutes, before it sends the poll again
|
|
244
|
+
* from the same cursor and interrupts the first.
|
|
245
|
+
*/
|
|
246
|
+
export declare const pollResentAfter: Duration.Duration;
|
|
282
247
|
/**
|
|
283
248
|
* Effect's native `RpcClient` for a binding, one method per action taking the action's input
|
|
284
249
|
* directly: `client.greet({ name })`, as `ActionHttp.client`'s, the argument omitted when `{}`
|
|
@@ -292,7 +257,9 @@ export type ClientOptions = Omit<NonNullable<Parameters<typeof RpcClient.make>[1
|
|
|
292
257
|
* - It drops undeclared input fields as it encodes, and fails with `InvalidInput`, sending nothing, for an input that does not encode.
|
|
293
258
|
* - A browser WebSocket cannot set an `Authorization` header on its upgrade, so under Bearer a protected call without its own token fails with `Unauthenticated`, `A bearer token is required.`: send the token on each call with `RpcClient.withHeaders`.
|
|
294
259
|
* - The socket belongs to the Layer providing the protocol, not to the `Scope` around the client: provided around one call, it opens a socket for that call alone.
|
|
295
|
-
* - `watch(event, input, options)` holds the event's stream rpc open, as `Action.client`'s does
|
|
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
|
+
* - `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
|
+
* - 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`.
|
|
296
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; a declared error, a refusal included, or a socket's close with an application's code, 4000 to 4999, ends it.
|
|
297
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.
|
|
298
265
|
*/
|
|
@@ -317,5 +284,5 @@ export interface ReconnectReason {
|
|
|
317
284
|
* - A client without it connects again after a refusal as after any close, every five seconds for good.
|
|
318
285
|
* - Any other socket error, a drop included, is retried as Effect's default retries it.
|
|
319
286
|
*/
|
|
320
|
-
export declare const reconnectUntil: (...codes: readonly number[]) => Schedule.Schedule<
|
|
321
|
-
export {};
|
|
287
|
+
export declare const reconnectUntil: (...codes: readonly number[]) => Schedule.Schedule<Duration.Duration, ReconnectReason, never, never>;
|
|
288
|
+
export { AnyPage as Page, Poll, pollTag };
|
package/dist/ActionRpc.mjs
CHANGED
|
@@ -1,39 +1,23 @@
|
|
|
1
|
-
import { providerOf } from "./authentication/provider.mjs";
|
|
2
|
-
import { checked, checkedStream, decodeInput, sendingJson, watchInput } from "./contract/call.mjs";
|
|
3
|
-
import { Anyone } from "./contract/caller.mjs";
|
|
4
1
|
import { bindingErrors, bindingOf, eventErrors } from "./contract/declared.mjs";
|
|
5
2
|
import { Unauthenticated } from "./contract/errors.mjs";
|
|
6
|
-
import { acquireFeeds } from "./contract/feed.mjs";
|
|
7
|
-
import { acquire, elementsOf } from "./contract/implementation.mjs";
|
|
8
3
|
import { listed } from "./contract/listed.mjs";
|
|
9
4
|
import { reservedList, reservedNames } from "./contract/names.mjs";
|
|
10
|
-
import {
|
|
11
|
-
import { PushedOf, SubscriptionOf, queuedPush } from "./contract/push.mjs";
|
|
12
|
-
import { concealed } from "./contract/reported.mjs";
|
|
5
|
+
import { PushedOf, SubscriptionOf } from "./contract/push.mjs";
|
|
13
6
|
import { provideServed, servingOf } from "./contract/serving.mjs";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import { HttpApiBuilder } from "effect/http-api";
|
|
20
|
-
import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcSchema, RpcServer } from "effect/rpc";
|
|
7
|
+
import { Poll, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollTag, polledTransport, streamedOf, streamedTransport, verifyingNative } from "./rpc/erased.mjs";
|
|
8
|
+
import { isRpcTransient } from "./rpc/watch.mjs";
|
|
9
|
+
import { AnyPage } from "./contract/pages.mjs";
|
|
10
|
+
import { Duration, Effect, Function, Layer, Predicate, Schedule, Schema } from "effect";
|
|
11
|
+
import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcServer } from "effect/rpc";
|
|
21
12
|
// src/rpc/ActionRpc.ts
|
|
22
|
-
const ProgressedOf = (progress, success) => Schema.Union([Schema.TaggedStruct("Progress", { value: progress }), Schema.TaggedStruct("Final", { value: success })]);
|
|
23
|
-
const elementedOf = (element, progress) => Schema.Union([Schema.TaggedStruct("Element", { value: element }), ...progress === void 0 ? [] : [Schema.TaggedStruct("Progress", { value: progress })]]);
|
|
24
|
-
const streams = (action) => !Answering.$is("Value")(answeringOf(action));
|
|
25
|
-
const streamedOf = (action) => Answering.$match(answeringOf(action), {
|
|
26
|
-
Value: () => void 0,
|
|
27
|
-
Progressed: ({ success, progress }) => ProgressedOf(progress, success),
|
|
28
|
-
Elements: ({ element, progress }) => elementedOf(element, progress)
|
|
29
|
-
});
|
|
30
13
|
const authenticatedKey = "effect-actions/ActionRpc/Authenticated";
|
|
31
|
-
const nativeOf = (group) => group;
|
|
32
14
|
const authenticatedOf = (authentication) => RpcMiddleware.Service()(authenticatedKey, { error: Schema.Union([Unauthenticated, ...authentication.error]) });
|
|
33
15
|
const authenticatedIn = (rpc) => [...rpc.middlewares].find(({ key }) => key === authenticatedKey);
|
|
34
16
|
function make(contracts, options = {}) {
|
|
35
17
|
const { actions, events } = listed(contracts);
|
|
36
18
|
const bound = bindingOf("ActionRpc binding", actions, events, options);
|
|
19
|
+
const security = bound.authentication?.security;
|
|
20
|
+
if (Predicate.isTagged(security, "ApiKey") && security.in === "query") throw new Error(`ActionRpc binding: its authentication reads its API key ${security.key} from the query, which no rpc carries (read it from a header: HttpApiSecurity.apiKey({ in: "header", key }))`);
|
|
37
21
|
const rpcOf = (action) => {
|
|
38
22
|
const streamed = streamedOf(action);
|
|
39
23
|
return Rpc.make(action.name, {
|
|
@@ -44,7 +28,8 @@ function make(contracts, options = {}) {
|
|
|
44
28
|
});
|
|
45
29
|
};
|
|
46
30
|
const given = options.rpcs === void 0 ? RpcGroup.make() : nativeOf(options.rpcs);
|
|
47
|
-
|
|
31
|
+
const served = erasedOf(actions, events, "ActionRpc.layer").requests;
|
|
32
|
+
for (const tag of given.requests.keys()) if (reservedNames.includes(tag) || served.has(tag)) throw new Error(`ActionRpc binding: the rpc "${tag}" of rpcs is named after an action, an event type, an event's poll, or a name the client keeps, ${reservedList} (rename it)`);
|
|
48
33
|
const rpcs = bound.authentication === void 0 ? given : given.middleware(authenticatedOf(bound.authentication));
|
|
49
34
|
const group = RpcGroup.make(...actions.map(rpcOf), ...events.map((event) => Rpc.make(event.name, {
|
|
50
35
|
payload: SubscriptionOf(event),
|
|
@@ -60,186 +45,25 @@ function make(contracts, options = {}) {
|
|
|
60
45
|
group
|
|
61
46
|
};
|
|
62
47
|
}
|
|
63
|
-
const withSyntheticRequestFromHeaders = (headers) => (effect) => effect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromClientRequest(HttpClientRequest.get("/", { headers }))), Effect.provideService(HttpServerRequest.ParsedSearchParams, {}));
|
|
64
|
-
const throughSteps = (steps, call, options) => {
|
|
65
|
-
let wrapped = call;
|
|
66
|
-
for (const step of steps) {
|
|
67
|
-
const inner = wrapped;
|
|
68
|
-
wrapped = Effect.suspend(() => step(inner, options));
|
|
69
|
-
}
|
|
70
|
-
return wrapped;
|
|
71
|
-
};
|
|
72
|
-
const authenticatingOf = (authentication) => Effect.map(providerOf(authentication), (provider) => {
|
|
73
|
-
const verify = Effect.flatMap(HttpApiBuilder.securityDecode(authentication.security), provider.authenticate);
|
|
74
|
-
return (verifying) => (effect, options) => Effect.flatMap(verifying(verify, options), (actor) => Effect.provideService(effect, authentication.identity, actor));
|
|
75
|
-
});
|
|
76
|
-
var DeclaredFailure = class {
|
|
77
|
-
[ErrorReporter.ignore] = true;
|
|
78
|
-
json;
|
|
79
|
-
constructor(json) {
|
|
80
|
-
this.json = json;
|
|
81
|
-
}
|
|
82
|
-
toString() {
|
|
83
|
-
return Predicate.isString(this.json) ? this.json : JSON.stringify(this.json);
|
|
84
|
-
}
|
|
85
|
-
};
|
|
86
|
-
const asJson = () => Schema.link()(Schema.Json, SchemaTransformation.transform({
|
|
87
|
-
decode: (json) => new DeclaredFailure(json),
|
|
88
|
-
encode: (failure) => failure.json
|
|
89
|
-
}));
|
|
90
|
-
const Declared = Schema.instanceOf(DeclaredFailure, {
|
|
91
|
-
toCodecJson: asJson,
|
|
92
|
-
toCodecIso: asJson
|
|
93
|
-
});
|
|
94
|
-
const streamOf = (name) => Rpc.make(name, {
|
|
95
|
-
payload: Schema.Json,
|
|
96
|
-
success: Schema.Json,
|
|
97
|
-
error: Declared,
|
|
98
|
-
stream: true
|
|
99
|
-
});
|
|
100
|
-
const erasedOf = (actions, events) => RpcGroup.make(...actions.map((action) => streams(action) ? streamOf(action.name) : Rpc.make(action.name, {
|
|
101
|
-
payload: Schema.Json,
|
|
102
|
-
success: Schema.Json,
|
|
103
|
-
error: Declared
|
|
104
|
-
})), ...events.map((event) => streamOf(event.name)));
|
|
105
|
-
const callBoundaryOf = (error) => {
|
|
106
|
-
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(error));
|
|
107
|
-
return (effect) => Effect.catchCause(effect, (cause) => {
|
|
108
|
-
if (Cause.hasDies(cause)) return concealed(cause);
|
|
109
|
-
const failure = Cause.findFail(cause);
|
|
110
|
-
return Result.isSuccess(failure) ? encode(failure.success.error).pipe(Effect.matchCauseEffect({
|
|
111
|
-
onFailure: (unencoded) => concealed(Cause.combine(cause, unencoded)),
|
|
112
|
-
onSuccess: (encoded) => Effect.fail(new DeclaredFailure(encoded))
|
|
113
|
-
})) : Effect.failCause(failure.failure);
|
|
114
|
-
});
|
|
115
|
-
};
|
|
116
|
-
const servedCall = (steps, boundary, call) => (payload, options) => boundary(throughSteps(steps, call(payload, options), {
|
|
117
|
-
...options,
|
|
118
|
-
payload
|
|
119
|
-
}));
|
|
120
|
-
const handlerOf = (action, run, steps, error) => {
|
|
121
|
-
const decode = decodeInput(action);
|
|
122
|
-
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(action.success));
|
|
123
|
-
return servedCall(steps, callBoundaryOf(error), (payload) => Effect.suspend(() => decode(payload)).pipe(Effect.flatMap(run), Effect.flatMap(encode)));
|
|
124
|
-
};
|
|
125
|
-
const streamingHandlerOf = (action, sending, steps, error) => {
|
|
126
|
-
const decode = decodeInput(action);
|
|
127
|
-
const boundary = callBoundaryOf(error);
|
|
128
|
-
const encodeProgress = Schema.encodeUnknownEffect(Schema.toCodecJson(action.progress ?? Schema.Never));
|
|
129
|
-
return servedCall(steps, boundary, (payload) => Effect.gen(function* () {
|
|
130
|
-
const input = yield* decode(payload);
|
|
131
|
-
const sent = yield* Queue.bounded(1);
|
|
132
|
-
const send = (each) => Effect.asVoid(Queue.offer(sent, each));
|
|
133
|
-
yield* sending(input, { progress: (value) => Effect.flatMap(Effect.orDie(encodeProgress(value)), (json) => send({
|
|
134
|
-
_tag: "Progress",
|
|
135
|
-
value: json
|
|
136
|
-
})) }, send).pipe(boundary, Queue.into(sent), Effect.forkScoped({ startImmediately: true }));
|
|
137
|
-
return sent;
|
|
138
|
-
}));
|
|
139
|
-
};
|
|
140
|
-
const sendingAnswer = (success, run) => {
|
|
141
|
-
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(success));
|
|
142
|
-
return (input, reporting, send) => run(input, reporting).pipe(Effect.flatMap(encode), Effect.flatMap((value) => send({
|
|
143
|
-
_tag: "Final",
|
|
144
|
-
value
|
|
145
|
-
})));
|
|
146
|
-
};
|
|
147
|
-
const sendingElements = (element, run) => {
|
|
148
|
-
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(element));
|
|
149
|
-
return (input, reporting, send) => Stream.runForEach(elementsOf(run(input, reporting)), (each) => Effect.flatMap(encode(each), (value) => send({
|
|
150
|
-
_tag: "Element",
|
|
151
|
-
value
|
|
152
|
-
})));
|
|
153
|
-
};
|
|
154
|
-
/** The key a protocol sets to its `SubscriptionKeeper` on its `RpcServer.Protocol` service. */
|
|
155
|
-
const subscriptionKeeper = Symbol.for("effect-actions/ActionRpc/subscriptionKeeper");
|
|
156
|
-
const isSubscriptionKeeper = (kept) => Predicate.hasProperty(kept, "keep") && Predicate.isFunction(kept.keep);
|
|
157
|
-
const keeperOf = (protocol) => {
|
|
158
|
-
const kept = Predicate.hasProperty(protocol, subscriptionKeeper) ? protocol[subscriptionKeeper] : void 0;
|
|
159
|
-
return isSubscriptionKeeper(kept) ? kept : void 0;
|
|
160
|
-
};
|
|
161
|
-
const subscriptionHandlerOf = (feed, steps, error, keeper) => {
|
|
162
|
-
const decode = decodeInput({ input: SubscriptionOf(feed.event) });
|
|
163
|
-
const encodeInput = Schema.encodeEffect(Schema.toCodecJson(feed.event.input));
|
|
164
|
-
const sent = Schema.toCodecJson(PushedOf(feed.event));
|
|
165
|
-
const encode = Schema.encodeEffect(sent);
|
|
166
|
-
const decodeSent = Schema.decodeUnknownOption(sent);
|
|
167
|
-
const boundary = callBoundaryOf(error);
|
|
168
|
-
return servedCall(steps, boundary, (payload, options) => Effect.gen(function* () {
|
|
169
|
-
const { input, cursor } = yield* decode(payload);
|
|
170
|
-
const open = yield* feed.stream(input);
|
|
171
|
-
if (keeper !== void 0) {
|
|
172
|
-
const resumed = yield* Effect.orDie(encodeInput(input));
|
|
173
|
-
yield* keeper.keep({
|
|
174
|
-
clientId: options.client.id,
|
|
175
|
-
requestId: options.requestId,
|
|
176
|
-
tag: feed.event.name,
|
|
177
|
-
payload,
|
|
178
|
-
headers: Object.entries(options.headers),
|
|
179
|
-
resumeFrom: (values) => {
|
|
180
|
-
const reached = values.flatMap((value) => Option.toArray(decodeSent(value))).map((pushed) => Match.value(pushed).pipe(Match.tag("Failed", () => null), Match.orElse((positioned) => positioned.cursor))).findLast(Predicate.isNotNull);
|
|
181
|
-
return reached === void 0 ? void 0 : {
|
|
182
|
-
input: resumed,
|
|
183
|
-
cursor: reached
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
});
|
|
187
|
-
}
|
|
188
|
-
return yield* queuedPush(open, cursor, encode, {
|
|
189
|
-
ending: boundary,
|
|
190
|
-
positions: keeper === void 0 ? "heartbeat" : "watermark"
|
|
191
|
-
});
|
|
192
|
-
}));
|
|
193
|
-
};
|
|
194
|
-
/**
|
|
195
|
-
* The key a protocol answering each call once sets to `true` on its `RpcServer.Protocol`
|
|
196
|
-
* service, as the Cloudflare package's stub protocol does, since Effect's protocol has no flag of
|
|
197
|
-
* its own for it: `layer` refuses to serve a streaming action, an event type or a native stream
|
|
198
|
-
* rpc on it, where a stream is answered with a defect at its first element and one with none
|
|
199
|
-
* waits for good.
|
|
200
|
-
*/
|
|
201
|
-
const unaryProtocol = Symbol.for("effect-actions/ActionRpc/unary");
|
|
202
|
-
const verifyingNative = (verify, { headers }) => withSyntheticRequestFromHeaders(headers)(verify).pipe(Effect.catchCauseIf(Cause.hasDies, concealed));
|
|
203
|
-
const requested = (effect, { headers }) => withSyntheticRequestFromHeaders(headers)(effect);
|
|
204
|
-
const isUnary = (protocol) => Predicate.hasProperty(protocol, unaryProtocol) && protocol[unaryProtocol] === true;
|
|
205
48
|
function layer(binding, served, options = {}) {
|
|
206
49
|
const selected = servingOf("RPC binding", binding, served, options);
|
|
207
50
|
const { apps, actions, events, eventTypes } = selected;
|
|
208
51
|
const middleware = options.middleware ?? [];
|
|
209
|
-
const jsonGroup = erasedOf(actions, eventTypes);
|
|
52
|
+
const jsonGroup = erasedOf(actions, eventTypes, "ActionRpc.layer");
|
|
210
53
|
const natives = [...nativeOf(binding.rpcs).requests.values()];
|
|
211
54
|
const authentication = natives.length === 0 ? selected.authentication : binding.authentication;
|
|
212
55
|
const handlers = Layer.unwrap(Effect.gen(function* () {
|
|
213
56
|
const unauthenticated = authentication === void 0 ? void 0 : natives.find((rpc) => authenticatedIn(rpc) === void 0);
|
|
214
57
|
if (unauthenticated !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`ActionRpc.layer: the native rpc ${unauthenticated._tag} of a protected binding runs without its authentication: add it to the group ActionRpc.make is given as its rpcs, not to the binding's rpcs after`));
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
const bound = yield* acquire(apps, authentication);
|
|
225
|
-
const feeds = yield* acquireFeeds(events);
|
|
226
|
-
const stepsOf = (caller) => caller === Anyone || authenticating === void 0 ? [...listedMiddleware, requested] : [
|
|
227
|
-
...listedMiddleware,
|
|
228
|
-
authenticating((verify) => verify),
|
|
229
|
-
requested
|
|
230
|
-
];
|
|
231
|
-
const handlerFor = (action, run, steps, error) => {
|
|
232
|
-
const streaming = (sending) => streamingHandlerOf(action, sending, steps, error);
|
|
233
|
-
return Answering.$match(answeringOf(action), {
|
|
234
|
-
Value: () => handlerOf(action, run, steps, error),
|
|
235
|
-
Progressed: ({ success }) => streaming(sendingAnswer(success, run)),
|
|
236
|
-
Elements: ({ element }) => streaming(sendingElements(element, run))
|
|
237
|
-
});
|
|
238
|
-
};
|
|
239
|
-
const byName = {
|
|
240
|
-
...Object.fromEntries(bound.map(([action, run]) => [action.name, handlerFor(action, run, stepsOf(action.caller), Schema.Union(bindingErrors(action, binding)))])),
|
|
241
|
-
...Object.fromEntries(feeds.map((feed) => [feed.event.name, subscriptionHandlerOf(feed, stepsOf(feed.event.caller), Schema.Union(eventErrors(feed.event, binding)), keeper)]))
|
|
242
|
-
};
|
|
58
|
+
const { handlers: byName, authenticating } = yield* handlersOf(binding, {
|
|
59
|
+
apps,
|
|
60
|
+
events,
|
|
61
|
+
authentication,
|
|
62
|
+
server: {
|
|
63
|
+
_tag: "ActionRpc.layer",
|
|
64
|
+
middleware
|
|
65
|
+
}
|
|
66
|
+
});
|
|
243
67
|
const servedActions = jsonGroup.toLayer(byName);
|
|
244
68
|
const authenticated = natives.map(authenticatedIn).find(Predicate.isNotUndefined);
|
|
245
69
|
if (authenticated === void 0 || authenticating === void 0) return servedActions;
|
|
@@ -248,58 +72,19 @@ function layer(binding, served, options = {}) {
|
|
|
248
72
|
})).pipe(provideServed(selected.apps, selected.events));
|
|
249
73
|
return RpcServer.layer(jsonGroup.merge(binding.rpcs), { disableFatalDefects: true }).pipe(Layer.provide(handlers));
|
|
250
74
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
}
|
|
264
|
-
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(streamed));
|
|
265
|
-
const call = method;
|
|
266
|
-
const progressed = (json) => call(json).pipe(Stream.catchIf(isDeclared, (failure) => Stream.fromEffect(failed(failure))), Stream.mapEffect((sent) => Effect.orDie(decode(sent))));
|
|
267
|
-
return elementOf(action.success) === void 0 ? checked(action, sendingJson, (json, onProgress) => answerFrom(progressed(json), onProgress)) : checkedStream(action, sendingJson, (json, onProgress) => elementsFrom(progressed(json), onProgress));
|
|
268
|
-
};
|
|
269
|
-
const eventMethodOf = (event, binding, method) => {
|
|
270
|
-
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(PushedOf(event)));
|
|
271
|
-
const failed = failedOf(Schema.Union(eventErrors(event, binding)));
|
|
272
|
-
const call = method;
|
|
273
|
-
return (input) => (cursor) => call({
|
|
274
|
-
input,
|
|
275
|
-
cursor
|
|
276
|
-
}).pipe(Stream.catchIf(isDeclared, (failure) => Stream.fromEffect(failed(failure))), Stream.mapEffect((json) => Effect.orDie(decode(json))));
|
|
277
|
-
};
|
|
278
|
-
function client(binding, options) {
|
|
279
|
-
const actions = new Map(binding.actions.map((action) => [action.name, action]));
|
|
280
|
-
const events = new Map(binding.events.map((event) => [event.name, event]));
|
|
281
|
-
const clients = Effect.all([RpcClient.make(erasedOf(binding.actions, binding.events).merge(nativeOf(binding.rpcs)), options), Effect.map(Effect.service(RpcClient.Protocol), ({ supportsAck }) => !supportsAck)]);
|
|
282
|
-
return Effect.map(clients, ([native, silenceEnds]) => {
|
|
283
|
-
const rpcs = Object.entries(native);
|
|
284
|
-
const methods = Object.fromEntries(rpcs.filter(([tag]) => !events.has(tag)).map(([tag, method]) => {
|
|
285
|
-
const action = actions.get(tag);
|
|
286
|
-
return [tag, action === void 0 ? method : actionMethodOf(action, binding, method)];
|
|
287
|
-
}));
|
|
288
|
-
if (events.size === 0) return methods;
|
|
289
|
-
const feeds = new Map(rpcs.flatMap(([tag, method]) => {
|
|
290
|
-
const event = events.get(tag);
|
|
291
|
-
return event === void 0 ? [] : [[tag, eventMethodOf(event, binding, method)]];
|
|
292
|
-
}));
|
|
293
|
-
const watch = (event, input, watchOptions) => {
|
|
294
|
-
const feed = feeds.get(event.name);
|
|
295
|
-
if (feed === void 0) return Stream.die(/* @__PURE__ */ new Error(`ActionRpc.client: the binding holds no event type ${event.name} (watch one the binding ActionRpc.make returned lists)`));
|
|
296
|
-
return Stream.unwrap(Effect.map(watchInput(event, input), ({ json }) => watching(transportOf(event, feed(json), silenceEnds), watchOptions)));
|
|
297
|
-
};
|
|
298
|
-
return {
|
|
299
|
-
...methods,
|
|
300
|
-
watch
|
|
301
|
-
};
|
|
302
|
-
});
|
|
75
|
+
/**
|
|
76
|
+
* How long a polling watch waits for a poll's answer, 4 minutes, before it sends the poll again
|
|
77
|
+
* from the same cursor and interrupts the first.
|
|
78
|
+
*/
|
|
79
|
+
const pollResentAfter = Duration.minutes(4);
|
|
80
|
+
function client(binding, options = {}) {
|
|
81
|
+
return Effect.map(Effect.all([RpcClient.make(erasedOf(binding.actions, binding.events, "ActionRpc.layer").merge(nativeOf(binding.rpcs)), {
|
|
82
|
+
...options,
|
|
83
|
+
flatten: true
|
|
84
|
+
}), Effect.map(Effect.service(RpcClient.Protocol), ({ supportsAck }) => !supportsAck)]), ([call, silenceEnds]) => ({
|
|
85
|
+
...methodsOf(binding, streamedTransport(silenceEnds, polledTransport(isRpcTransient, pollResentAfter)))(Function.constant(Effect.succeed(erasedCallOf(call)))),
|
|
86
|
+
...Object.fromEntries([...nativeOf(binding.rpcs).requests.keys()].map((tag) => [tag, (payload, callOptions) => call(tag, payload, callOptions)]))
|
|
87
|
+
}));
|
|
303
88
|
}
|
|
304
89
|
/**
|
|
305
90
|
* A socket client's `retryPolicy`, for `RpcClient.layerProtocolSocket`, that stops connecting
|
|
@@ -315,4 +100,4 @@ function client(binding, options) {
|
|
|
315
100
|
* - Any other socket error, a drop included, is retried as Effect's default retries it.
|
|
316
101
|
*/
|
|
317
102
|
const reconnectUntil = (...codes) => Schedule.min([Schedule.exponential(500, 1.5), Schedule.spaced(5e3)]).pipe(Schedule.setInputType(), Schedule.while(({ input: { reason } }) => !(Predicate.isTagged(reason, "SocketCloseError") && Predicate.hasProperty(reason, "code") && codes.some((code) => code === reason.code))));
|
|
318
|
-
export { client, layer, make,
|
|
103
|
+
export { AnyPage as Page, Poll, client, layer, make, pollResentAfter, pollTag, reconnectUntil };
|