@gjermundgaraba/effect-actions 0.30.0 → 0.32.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 +12 -14
- package/dist/ActionEntity.d.mts +237 -0
- package/dist/ActionEntity.mjs +211 -0
- package/dist/ActionHttp.d.mts +5 -5
- package/dist/ActionHttp.mjs +24 -28
- package/dist/ActionMcp.d.mts +2 -3
- package/dist/ActionMcp.mjs +7 -10
- package/dist/ActionRpc.d.mts +25 -57
- package/dist/ActionRpc.mjs +45 -274
- package/dist/ActionToolkit.mjs +4 -3
- package/dist/Authentication.d.mts +8 -9
- package/dist/Authentication.mjs +49 -51
- package/dist/Event.d.mts +26 -6
- package/dist/Event.mjs +2 -2
- package/dist/Stored.d.mts +49 -0
- package/dist/Stored.mjs +78 -0
- package/dist/Webhook.d.mts +5 -4
- package/dist/Webhook.mjs +11 -4
- package/dist/authentication/provider.d.mts +2 -2
- package/dist/authentication/refusal.mjs +11 -4
- package/dist/cli/commands.mjs +8 -8
- package/dist/contract/call.mjs +6 -2
- package/dist/contract/callback.mjs +6 -1
- package/dist/contract/caller.d.mts +2 -6
- package/dist/contract/caller.mjs +3 -3
- package/dist/contract/digest.mjs +3 -2
- package/dist/contract/event-tables.mjs +90 -0
- package/dist/contract/feed.d.mts +15 -3
- package/dist/contract/feed.mjs +27 -16
- 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 +10 -21
- 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/push.mjs +3 -5
- package/dist/contract/recent.mjs +3 -2
- package/dist/contract/serving.mjs +17 -17
- package/dist/contract/stream.d.mts +1 -1
- package/dist/contract/stream.mjs +14 -2
- package/dist/contract/subscribe.mjs +7 -2
- package/dist/contract/wake.mjs +9 -0
- package/dist/contract/watch.mjs +24 -22
- package/dist/contract/webhooks.d.mts +8 -4
- package/dist/contract/webhooks.mjs +50 -28
- 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 +8 -6
- package/dist/http/events.d.mts +1 -12
- package/dist/http/events.mjs +5 -25
- package/dist/http/redacted.mjs +9 -0
- package/dist/http/streamed.d.mts +1 -0
- package/dist/http/streamed.mjs +10 -5
- package/dist/mcp/bridge.mjs +14 -24
- package/dist/mcp/client.mjs +3 -12
- package/dist/mcp/events.mjs +1 -1
- package/dist/mcp/progress.mjs +11 -1
- package/dist/rpc/erased.d.mts +62 -0
- package/dist/rpc/erased.mjs +356 -0
- package/dist/rpc/watch.mjs +12 -13
- package/dist/webhook/health.mjs +25 -28
- package/dist/webhook/receiver.mjs +4 -7
- package/dist/webhook/stored.mjs +6 -4
- package/dist/webhook/subscriptions.mjs +65 -48
- 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 +12 -9
- 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.d.mts
CHANGED
|
@@ -7,11 +7,11 @@ import { Any as Any$2 } from "./Event.mjs";
|
|
|
7
7
|
import { EventBuildError, EventBuildServices, EventServedRequest, HoldingEvents, ServingEvents } from "./contract/feed.mjs";
|
|
8
8
|
import { BuildError, Holding, Known, Member, MiddlewareOf, Selected, SelectedEvents, Served } from "./contract/implementation.mjs";
|
|
9
9
|
import { Only } from "./contract/listed.mjs";
|
|
10
|
+
import { pageOf } from "./contract/pages.mjs";
|
|
10
11
|
import { SubscriptionOf } from "./contract/push.mjs";
|
|
11
12
|
import { AnyHttp, Client, MethodError, Options, WatchError } from "./http/client.mjs";
|
|
12
|
-
import {
|
|
13
|
+
import { sentOf } from "./http/events.mjs";
|
|
13
14
|
import { SuccessOf } from "./http/streamed.mjs";
|
|
14
|
-
import { Placed, placed } from "./http/placed.mjs";
|
|
15
15
|
import { Context, Effect, FileSystem, Layer, Path, Schema, Types } from "effect";
|
|
16
16
|
import { Etag, HttpClient, HttpClientError, HttpPlatform, HttpRouter } from "effect/http";
|
|
17
17
|
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware } from "effect/http-api";
|
|
@@ -134,7 +134,7 @@ export interface Binding<Actions extends readonly Any$1[], E extends Errors = []
|
|
|
134
134
|
* **Gotchas**
|
|
135
135
|
*
|
|
136
136
|
* - An action and an event type of one name, or an event type listed twice, throw when `make` is called: they would share a client's method.
|
|
137
|
-
* - A protected event type
|
|
137
|
+
* - A protected event type is bound at `POST <prefix>/events/<name>/subscribe` and `/unsubscribe` too, for `Webhook.layer`'s delivery, and OpenAPI lists both: a binding cannot know whether its server provides that layer, and without it they answer a 409 `Event.SubscriptionError`, reason `Unsupported`.
|
|
138
138
|
*/
|
|
139
139
|
export declare function make<const Contracts extends ReadonlyArray<(Any$1 | Any$2) & {
|
|
140
140
|
readonly caller: typeof Anyone;
|
|
@@ -162,6 +162,7 @@ export declare function make<const Contracts extends ReadonlyArray<Any$1 | Any$2
|
|
|
162
162
|
* - An action declaring `progress` answers a request whose `Accept` names `text/event-stream`, whatever else it names, with an SSE stream, listed in OpenAPI: a `progress` event for each value, its data the value's JSON, then one `final` event holding the answer's JSON, `null` for none; without that `Accept` it answers as any action, its progress dropped.
|
|
163
163
|
* - An action answering a stream, `Action.Stream`, answers an SSE stream alone, whatever `Accept` says: an `element` event for each element, its data the element's JSON, and a `progress` event for each value where it declares `progress`; a stream of none answers a 200 with no event. A failure before the first event answers its status; one after ends the stream as Effect's stream failure event, a defect as `Internal server error`.
|
|
164
164
|
* - The stream starts with the call's first event, so a failure before it, a refusal included, answers as it would without the stream; a declared failure after it ends the stream with Effect's `effect/http-api/stream/failure` event, reported as `Info` as without the stream, and a defect or an answer that does not encode with one saying `Internal server error`, its cause logged and reported.
|
|
165
|
+
* - An action's SSE stream writes a `: keepalive` comment every 15 seconds from its first event until it ends, events or not, which SSE clients skip, so a proxy closing a silent response keeps it open through a slow step; before the first event no response has started, so a proxy timing out a response's start still ends a call silent that long.
|
|
165
166
|
* - A body that is not JSON is a 400 `InvalidInput`; a request with no `Content-Type` a 415 `Unsupported content-type: none`, one with another type Effect's own 415; each after authentication on a protected route.
|
|
166
167
|
* - A defect, an undeclared failure, or a success or an error that does not encode answers an empty 500: the cause goes to the log and to the call's `ErrorReporter`s, never to the body.
|
|
167
168
|
* - A path no layer serves, or a method other than `POST` on a route, is a 404.
|
|
@@ -174,7 +175,6 @@ export declare function make<const Contracts extends ReadonlyArray<Any$1 | Any$2
|
|
|
174
175
|
* - A subscription is refused as an action's call is, before its stream starts, with the route's 401 or 403; a refusal later ends the stream with Effect's `effect/http-api/stream/failure` event.
|
|
175
176
|
* - 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, before the stream's first `Checked` too; a poll's is a 500, which `client`'s `watch` reconnects after.
|
|
176
177
|
* - 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`.
|
|
177
|
-
* - A protected event with a `subscription` hook needs `principal` on its descriptor to key poll subscribers: without it the layer fails to build with a message naming the event.
|
|
178
178
|
* - On a host with no lasting process, such as `HttpRouter.toWebHandler` on a serverless platform, serve check sources alone, without a `subscription` hook or `Webhook.layer`: 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 and webhook subscriptions, lost as it ends.
|
|
179
179
|
*/
|
|
180
180
|
export declare function layer<const H extends AnyHttp, const Apps extends Served>(binding: H, implementations: Apps): HttpLayer<H, Apps, []>;
|
|
@@ -207,4 +207,4 @@ export declare function client<const H extends AnyHttp, E, R>(binding: H, option
|
|
|
207
207
|
*/
|
|
208
208
|
export declare function fetchClient<const H extends AnyHttp>(binding: H, options?: FetchClientOptions): Client<H>;
|
|
209
209
|
export declare function fetchClient<const H extends AnyHttp, E, R>(binding: H, options: FetchClientOptions<E, R>): Client<H, E, R>;
|
|
210
|
-
export { type AnyHttp as Any, type Client, type Options as ClientOptions, type MethodError, Options$1 as Options, type
|
|
210
|
+
export { type AnyHttp as Any, type Client, type Options as ClientOptions, type MethodError, Options$1 as Options, type WatchError };
|
package/dist/ActionHttp.mjs
CHANGED
|
@@ -2,18 +2,17 @@ import { providerOf } from "./authentication/provider.mjs";
|
|
|
2
2
|
import { inputParseOptions } from "./contract/call.mjs";
|
|
3
3
|
import { Anyone } from "./contract/caller.mjs";
|
|
4
4
|
import { bindingErrors, bindingOf, eventErrors, projectedErrors } from "./contract/declared.mjs";
|
|
5
|
-
import { acquireFeeds, unkeyedHook } from "./contract/feed.mjs";
|
|
6
5
|
import { acquire } from "./contract/implementation.mjs";
|
|
7
6
|
import { listed } from "./contract/listed.mjs";
|
|
8
7
|
import { provideServed, servingOf } from "./contract/serving.mjs";
|
|
9
8
|
import { declared } from "./contract/status.mjs";
|
|
10
|
-
import {
|
|
11
|
-
import { offersWebhook,
|
|
9
|
+
import { Answering, answeringOf } from "./contract/stream.mjs";
|
|
10
|
+
import { offersWebhook, servingFeeds, webhookAnswers } from "./contract/webhooks.mjs";
|
|
12
11
|
import { methods } from "./http/client.mjs";
|
|
13
|
-
import { answering, eventEndpointOf, servedSent,
|
|
12
|
+
import { answering, eventEndpointOf, servedSent, webhookEndpointsOf } from "./http/events.mjs";
|
|
13
|
+
import { credentialNames } from "./http/redacted.mjs";
|
|
14
14
|
import { SchemaErrors, schemaErrors } from "./http/schema-errors.mjs";
|
|
15
15
|
import { answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf } from "./http/streamed.mjs";
|
|
16
|
-
import { placed } from "./http/placed.mjs";
|
|
17
16
|
import { Context, Effect, Layer, Scope } from "effect";
|
|
18
17
|
import { FetchHttpClient, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
19
18
|
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/http-api";
|
|
@@ -26,21 +25,21 @@ const apiOf = (group, endpoints) => {
|
|
|
26
25
|
const [first, ...rest] = endpoints;
|
|
27
26
|
return HttpApi.make("actions").annotate(HttpApi.ParseOptions, { errors: "all" }).add(first === void 0 ? empty : empty.add(first, ...rest));
|
|
28
27
|
};
|
|
29
|
-
const successOf = (action, errors) => {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
};
|
|
28
|
+
const successOf = (action, errors) => Answering.$match(answeringOf(action), {
|
|
29
|
+
Value: ({ success }) => success,
|
|
30
|
+
Progressed: ({ success, progress }) => [answeredWithProgress(success), progressStreamOf(progress, success, errors)],
|
|
31
|
+
Elements: ({ element, progress }) => elementStreamOf(element, progress, errors)
|
|
32
|
+
});
|
|
34
33
|
const endpointOf = (action, path, errors) => HttpApiEndpoint.post(action.name, path, {
|
|
35
34
|
payload: action.input.pipe(HttpApiSchema.asJson()),
|
|
36
35
|
success: successOf(action, errors),
|
|
37
36
|
error: errors.map(declared)
|
|
38
37
|
});
|
|
39
|
-
const answerOf = (action, run) => {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
};
|
|
38
|
+
const answerOf = (action, run) => Answering.$match(answeringOf(action), {
|
|
39
|
+
Value: () => run,
|
|
40
|
+
Progressed: ({ success }) => answeringWithProgress(success, run),
|
|
41
|
+
Elements: ({ element }) => answeringElements(element, run)
|
|
42
|
+
});
|
|
44
43
|
const withinLayerMiddleware = (endpoint, middleware = []) => {
|
|
45
44
|
let within = endpoint;
|
|
46
45
|
for (const key of middleware) within = within.middleware(key);
|
|
@@ -59,9 +58,9 @@ function make(contracts, options = {}) {
|
|
|
59
58
|
event.name
|
|
60
59
|
]);
|
|
61
60
|
const errors = eventErrors(event, bound);
|
|
62
|
-
return [eventEndpointOf(event, path, errors), ...offersWebhook(event
|
|
61
|
+
return [eventEndpointOf(event, path, errors), ...offersWebhook(event) ? webhookEndpointsOf(event, path, errors) : []].map((endpoint) => secured(endpoint, event));
|
|
63
62
|
})];
|
|
64
|
-
const api = apiOf(groupName(mount), endpoints);
|
|
63
|
+
const api = apiOf(groupName(mount), endpoints).annotate(HttpApi.RedactedNames, credentialNames(bound.authentication));
|
|
65
64
|
return {
|
|
66
65
|
actions,
|
|
67
66
|
events,
|
|
@@ -94,25 +93,22 @@ function layer(binding, served, options = {}) {
|
|
|
94
93
|
event.name
|
|
95
94
|
]);
|
|
96
95
|
const errors = eventErrors(event, { error: binding.error });
|
|
97
|
-
return [eventEndpointOf(event, path, errors, servedSent), ...offersWebhook(event
|
|
98
|
-
})]).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);
|
|
99
98
|
const handlers = Layer.unwrap(Effect.gen(function* () {
|
|
100
99
|
const bound = yield* acquire(apps, authentication);
|
|
101
|
-
const feeds = yield*
|
|
102
|
-
const refusal = unkeyedHook("ActionHttp", feeds, authentication?.principal !== void 0);
|
|
103
|
-
if (refusal !== void 0) return yield* Effect.die(new Error(refusal));
|
|
104
|
-
const { webhooks, offered } = yield* servedWebhooks(feeds, authentication);
|
|
100
|
+
const { feeds, webhooks } = yield* servingFeeds(events, authentication);
|
|
105
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)));
|
|
106
102
|
const hostProvidedMiddleware = yield* Effect.forEach(options.middleware ?? [], (key) => Effect.map(Effect.service(key), (service) => Layer.succeed(key, service)));
|
|
107
|
-
const webhookAnswered =
|
|
103
|
+
const webhookAnswered = feeds.filter(({ event }) => offersWebhook(event)).map((feed) => [feed.event.name, webhookAnswers(feed, authentication, webhooks)]);
|
|
108
104
|
const byName = {
|
|
109
105
|
...Object.fromEntries(bound.map(([action, run]) => {
|
|
110
106
|
const answer = answerOf(action, run);
|
|
111
107
|
return [action.name, (request) => answer(request.payload)];
|
|
112
108
|
})),
|
|
113
109
|
...Object.fromEntries(feeds.map((feed) => [feed.event.name, answering(feed, authentication)])),
|
|
114
|
-
...Object.fromEntries(webhookAnswered.map(([eventName, { subscribe }]) => [`${eventName}/subscribe`, subscribe])),
|
|
115
|
-
...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)]))
|
|
116
112
|
};
|
|
117
113
|
return HttpApiBuilder.group(api, name, (builder) => builder.handleAll(byName)).pipe(Layer.provide([
|
|
118
114
|
schemaErrors,
|
|
@@ -120,7 +116,7 @@ function layer(binding, served, options = {}) {
|
|
|
120
116
|
security,
|
|
121
117
|
...hostProvidedMiddleware
|
|
122
118
|
]), buildInEmptyContext);
|
|
123
|
-
})).pipe(provideServed(selected));
|
|
119
|
+
})).pipe(provideServed(selected.apps, selected.events));
|
|
124
120
|
return HttpApiBuilder.layer(api).pipe(Layer.provide(handlers), Layer.provide(startupBeneathRequest()));
|
|
125
121
|
}
|
|
126
122
|
function client(binding, options) {
|
|
@@ -129,4 +125,4 @@ function client(binding, options) {
|
|
|
129
125
|
function fetchClient(binding, { fetch, ...options } = {}) {
|
|
130
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);
|
|
131
127
|
}
|
|
132
|
-
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
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { providerOf } from "./authentication/provider.mjs";
|
|
2
|
+
import { asCaller } from "./authentication/refusal.mjs";
|
|
3
3
|
import { inputParseOptions } from "./contract/call.mjs";
|
|
4
4
|
import { Anyone, assertAuthentication } from "./contract/caller.mjs";
|
|
5
5
|
import { projectedErrors } from "./contract/declared.mjs";
|
|
@@ -9,8 +9,9 @@ import { liftOf, liftedFrom } from "./contract/lift.mjs";
|
|
|
9
9
|
import { assertOnce, heldOnce } from "./contract/names.mjs";
|
|
10
10
|
import { provideServed, selectFrom } from "./contract/serving.mjs";
|
|
11
11
|
import { toolSuccessOf } from "./contract/stream.mjs";
|
|
12
|
+
import { servingFeeds } from "./contract/webhooks.mjs";
|
|
12
13
|
import { withStderrConsole } from "./stdio/console.mjs";
|
|
13
|
-
import { eventSchemasOf,
|
|
14
|
+
import { eventSchemasOf, withEvents } from "./mcp/bridge.mjs";
|
|
14
15
|
import { progressNotifier } from "./mcp/progress.mjs";
|
|
15
16
|
import { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, protocols, toolJsonSchema } from "./mcp/protocol.mjs";
|
|
16
17
|
import { client } from "./mcp/client.mjs";
|
|
@@ -78,7 +79,7 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
|
|
|
78
79
|
const encodeSuccess = encoder(toolSuccess);
|
|
79
80
|
const encodeFailure = encoder(Schema.Union(projectedErrors(action)));
|
|
80
81
|
const reported = (input) => action.progress === void 0 ? run(input) : Effect.flatMap(progressNotifier(registry.notifications, action.progress), (sink) => run(input, sink));
|
|
81
|
-
const call =
|
|
82
|
+
const call = (input) => asCaller(authentication, action, reported(input));
|
|
82
83
|
const liftedFieldNames = new Set(media?.fields.map(({ name }) => name));
|
|
83
84
|
const resultOf = (encoded, success) => {
|
|
84
85
|
if (media === void 0) return new McpSchema.CallToolResult({
|
|
@@ -131,14 +132,10 @@ const server = (apps, serving, transport, features = Layer.empty) => {
|
|
|
131
132
|
const register = Effect.gen(function* () {
|
|
132
133
|
const namesClaimedByFeatures = (yield* McpServer.McpServer).tools.flatMap(({ tool }) => names.has(tool.name) ? [tool.name] : []);
|
|
133
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)`));
|
|
134
|
-
yield*
|
|
135
|
-
yield* serveWebhooks(serving);
|
|
135
|
+
yield* servingFeeds(serving.events, serving.authentication);
|
|
136
136
|
yield* registerTools(apps, authentication);
|
|
137
137
|
});
|
|
138
|
-
return Layer.empty.pipe(Layer.provide(transport(Layer.effectDiscard(register).pipe(Layer.provide(features)))), Layer.fresh, provideServed(
|
|
139
|
-
apps,
|
|
140
|
-
events
|
|
141
|
-
}));
|
|
138
|
+
return Layer.empty.pipe(Layer.provide(transport(Layer.effectDiscard(register).pipe(Layer.provide(features)))), Layer.fresh, provideServed(apps, events));
|
|
142
139
|
};
|
|
143
140
|
const anonymousMethods = /* @__PURE__ */ new Set([
|
|
144
141
|
"server/discover",
|
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,43 +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.
|
|
200
|
-
*/
|
|
201
|
-
readonly resumeFrom: (values: RpcMessage.ResponseChunkEncoded["values"]) => Schema.Json | undefined;
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* What a protocol keeping event subscriptions across restarts of its server offers under
|
|
205
|
-
* `subscriptionKeeper`, as the Cloudflare package's `layerWebSocket` does: `layer` hands it each
|
|
206
|
-
* subscription once admitted, and sends every position the subscription reaches, with no
|
|
207
|
-
* 30-second heartbeat, whose timer would keep such a host awake.
|
|
208
|
-
*/
|
|
209
|
-
export interface SubscriptionKeeper {
|
|
210
|
-
readonly keep: (subscription: KeptSubscription) => Effect.Effect<void>;
|
|
211
|
-
}
|
|
212
|
-
/** The key a protocol sets to its `SubscriptionKeeper` on its `RpcServer.Protocol` service. */
|
|
213
|
-
export declare const subscriptionKeeper: unique symbol;
|
|
214
|
-
/**
|
|
215
|
-
* The key a protocol answering each call once sets to `true` on its `RpcServer.Protocol`
|
|
216
|
-
* service, as the Cloudflare package's stub protocol does, since Effect's protocol has no flag of
|
|
217
|
-
* its own for it: `layer` refuses to serve a streaming action, an event type or a native stream
|
|
218
|
-
* rpc on it, where a stream is answered with a defect at its first element and one with none
|
|
219
|
-
* waits for good.
|
|
220
|
-
*/
|
|
221
|
-
export declare const unaryProtocol: unique symbol;
|
|
222
184
|
/**
|
|
223
185
|
* Serve the binding's actions and event types among `implementations` with Effect's own
|
|
224
186
|
* `RpcServer`, or those its `actions` lists, as `ActionHttp.layer` selects them, under the
|
|
@@ -237,15 +199,14 @@ export declare const unaryProtocol: unique symbol;
|
|
|
237
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.
|
|
238
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.
|
|
239
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.
|
|
240
|
-
* - An rpc's credential is read from its headers alone: an API key `in: "query"` never reaches authentication.
|
|
241
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.
|
|
242
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.
|
|
243
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.
|
|
244
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`.
|
|
245
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.
|
|
246
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`.
|
|
247
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.
|
|
248
|
-
* - 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.
|
|
249
210
|
*/
|
|
250
211
|
export declare function layer<const B extends Any, const Apps extends Served>(binding: B, implementations: Apps): RpcLayer<B, Apps, []>;
|
|
251
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]>>;
|
|
@@ -258,8 +219,8 @@ export type MethodError<A extends Any$2, E extends BindingError = never> = A["er
|
|
|
258
219
|
type Method<A extends Any$2, E extends BindingError> = Call<A, Answer<A["success"], MethodError<A, E>, never>>;
|
|
259
220
|
/**
|
|
260
221
|
* What a watch of `W` over the binding `B` may fail with: a refusal, when it starts or later,
|
|
261
|
-
* `InvalidInput`, the binding's errors, an `Event.SubscriptionError` (`Unsupported` for
|
|
262
|
-
* `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
|
|
263
224
|
* Effect's own `RpcClientError` that no reconnect outlasts. An element that does not decode is a defect, as for a call.
|
|
264
225
|
*/
|
|
265
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;
|
|
@@ -273,11 +234,16 @@ type Watching<B extends Any> = [B["events"][number]] extends [never] ? unknown :
|
|
|
273
234
|
*/
|
|
274
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>;
|
|
275
236
|
/**
|
|
276
|
-
*
|
|
237
|
+
* `client`'s options: the native `RpcClient.make` options, `spanPrefix`, `spanAttributes`,
|
|
277
238
|
* `generateRequestId` and `disableTracing`. `flatten` changes the client's shape, which the
|
|
278
239
|
* method types cannot follow.
|
|
279
240
|
*/
|
|
280
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;
|
|
281
247
|
/**
|
|
282
248
|
* Effect's native `RpcClient` for a binding, one method per action taking the action's input
|
|
283
249
|
* directly: `client.greet({ name })`, as `ActionHttp.client`'s, the argument omitted when `{}`
|
|
@@ -291,7 +257,9 @@ export type ClientOptions = Omit<NonNullable<Parameters<typeof RpcClient.make>[1
|
|
|
291
257
|
* - It drops undeclared input fields as it encodes, and fails with `InvalidInput`, sending nothing, for an input that does not encode.
|
|
292
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`.
|
|
293
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.
|
|
294
|
-
* - `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`.
|
|
295
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.
|
|
296
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.
|
|
297
265
|
*/
|
|
@@ -316,5 +284,5 @@ export interface ReconnectReason {
|
|
|
316
284
|
* - A client without it connects again after a refusal as after any close, every five seconds for good.
|
|
317
285
|
* - Any other socket error, a drop included, is retried as Effect's default retries it.
|
|
318
286
|
*/
|
|
319
|
-
export declare const reconnectUntil: (...codes: readonly number[]) => Schedule.Schedule<
|
|
320
|
-
export {};
|
|
287
|
+
export declare const reconnectUntil: (...codes: readonly number[]) => Schedule.Schedule<Duration.Duration, ReconnectReason, never, never>;
|
|
288
|
+
export { AnyPage as Page, Poll, pollTag };
|