@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/http/streamed.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { elementsOf } from "../contract/implementation.mjs";
|
|
2
2
|
import { Progressed, answerFrom, elementsFrom } from "../contract/progress.mjs";
|
|
3
3
|
import { concealed } from "../contract/reported.mjs";
|
|
4
|
-
import { Cause, Effect, ErrorReporter, Queue, Schema, Stream } from "effect";
|
|
4
|
+
import { Cause, Duration, Effect, ErrorReporter, Queue, Schema, Stream } from "effect";
|
|
5
5
|
import { HttpServerRequest } from "effect/http";
|
|
6
6
|
import { HttpApiSchema } from "effect/http-api";
|
|
7
7
|
// src/http/streamed.ts
|
|
@@ -10,14 +10,17 @@ const eventOf = (event, data) => Schema.Struct({
|
|
|
10
10
|
event: Schema.Literal(event),
|
|
11
11
|
data: Schema.fromJsonString(Schema.toCodecJson(data))
|
|
12
12
|
});
|
|
13
|
+
const keepAliveEvery = Duration.seconds(15);
|
|
13
14
|
const answeredWithProgress = (success) => HttpApiSchema.isNoContent(success.ast) ? HttpApiSchema.NoContent : success;
|
|
14
15
|
const progressStreamOf = (progress, success, errors) => HttpApiSchema.StreamSse({
|
|
15
16
|
events: Schema.Union([eventOf("progress", progress), eventOf("final", success)]),
|
|
16
|
-
error: Schema.Union(errors)
|
|
17
|
+
error: Schema.Union(errors),
|
|
18
|
+
keepAlive: keepAliveEvery
|
|
17
19
|
});
|
|
18
20
|
const elementStreamOf = (element, progress, errors) => HttpApiSchema.StreamSse({
|
|
19
21
|
events: Schema.Union(progress === void 0 ? [eventOf("element", element)] : [eventOf("element", element), eventOf("progress", progress)]),
|
|
20
|
-
error: Schema.Union(errors)
|
|
22
|
+
error: Schema.Union(errors),
|
|
23
|
+
keepAlive: keepAliveEvery
|
|
21
24
|
});
|
|
22
25
|
const gatedOnFirst = (sent) => Effect.map(Effect.catchIf(Queue.take(sent), Cause.isDone, () => Effect.undefined), (first) => first === void 0 ? Stream.empty : Stream.concat(Stream.make(first), Stream.fromQueue(sent)));
|
|
23
26
|
const streamed = (answer) => Effect.gen(function* () {
|
|
@@ -41,9 +44,11 @@ const checkedBy = (schema) => {
|
|
|
41
44
|
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(schema));
|
|
42
45
|
return (data) => Effect.orDie(encode(data));
|
|
43
46
|
};
|
|
47
|
+
/** Whether `request` asks for an SSE stream, `text/event-stream` among whatever else it accepts. */
|
|
48
|
+
const acceptsEventStream = (request) => (request.headers["accept"] ?? "").includes("text/event-stream");
|
|
44
49
|
const answeringWithProgress = (success, run) => {
|
|
45
50
|
const check = checkedBy(success);
|
|
46
|
-
return (payload) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => (request
|
|
51
|
+
return (payload) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => acceptsEventStream(request) ? streamed((reporting, send) => run(payload, reporting).pipe(Effect.tap(check), Effect.flatMap((data) => send({
|
|
47
52
|
event: "final",
|
|
48
53
|
data
|
|
49
54
|
})))) : run(payload));
|
|
@@ -63,4 +68,4 @@ const answeredWithout = /* @__PURE__ */ new Error("A route of an action declarin
|
|
|
63
68
|
const sentFrom = (answer) => Stream.isStream(answer) ? Stream.map(answer, progressedOf) : Stream.die(answeredWithout);
|
|
64
69
|
const readWithProgress = (answer, onProgress) => answerFrom(sentFrom(answer), onProgress);
|
|
65
70
|
const readElements = (answer, onProgress) => elementsFrom(sentFrom(answer), onProgress);
|
|
66
|
-
export { answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf, readElements, readWithProgress };
|
|
71
|
+
export { acceptsEventStream, answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf, readElements, readWithProgress };
|
package/dist/mcp/bridge.mjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { recordStepUp } from "../authentication/refusal.mjs";
|
|
1
|
+
import { asCaller } from "../authentication/refusal.mjs";
|
|
3
2
|
import { inputParseOptions } from "../contract/call.mjs";
|
|
4
|
-
import {
|
|
3
|
+
import { principalOf } from "../contract/caller.mjs";
|
|
5
4
|
import { sentError } from "../contract/codes.mjs";
|
|
6
|
-
import { NotServed, SubscriptionError
|
|
7
|
-
import { acquireFeeds
|
|
5
|
+
import { NotServed, SubscriptionError } from "../Event.mjs";
|
|
6
|
+
import { acquireFeeds } from "../contract/feed.mjs";
|
|
8
7
|
import { encodeUntaggedOf } from "../contract/occurrence.mjs";
|
|
9
8
|
import { pushed, refusalIn } from "../contract/push.mjs";
|
|
10
9
|
import { reported } from "../contract/reported.mjs";
|
|
11
|
-
import {
|
|
10
|
+
import { deliveryUnsupported } from "../contract/subscribe.mjs";
|
|
11
|
+
import { Webhooks, subscriberOf, webhookSubscriber } from "../contract/webhooks.mjs";
|
|
12
12
|
import { Active, EventsError, Failed, Heartbeat, Notifications, Occurred, Requests, Terminated, codes, extension, subscriptionIdKey } from "./events.mjs";
|
|
13
13
|
import { isObjectSchema, toolJsonSchema } from "./protocol.mjs";
|
|
14
14
|
import { Cause, Context, Duration, Effect, Exit, Match, Option, Predicate, Result, Schema } from "effect";
|
|
@@ -70,11 +70,6 @@ const servedOf = (feed, delivery) => {
|
|
|
70
70
|
}
|
|
71
71
|
};
|
|
72
72
|
};
|
|
73
|
-
const refuseUnservable = ({ events, authentication }) => authentication === void 0 ? Effect.void : Effect.flatMap(acquireFeeds(events), (feeds) => {
|
|
74
|
-
const refusal = unkeyedHook("MCP", feeds, authentication.principal !== void 0);
|
|
75
|
-
return refusal === void 0 ? Effect.void : Effect.die(new Error(refusal));
|
|
76
|
-
});
|
|
77
|
-
const serveWebhooks = (serving) => Effect.asVoid(Effect.flatMap(acquireFeeds(serving.events), (feeds) => servedWebhooks(feeds, serving.authentication)));
|
|
78
73
|
const delivered = ({ send, clientId, requestId, wire, _meta: resultMeta }, run) => {
|
|
79
74
|
const notify = (rpc, payload) => send("2026-07-28", clientId, {
|
|
80
75
|
tag: rpc._tag,
|
|
@@ -135,25 +130,23 @@ const delivered = ({ send, clientId, requestId, wire, _meta: resultMeta }, run)
|
|
|
135
130
|
};
|
|
136
131
|
const withEvents = (base, serving) => {
|
|
137
132
|
const { authentication } = serving;
|
|
138
|
-
const asSubscriber = (event, run) => authentication === void 0 || event.caller === Anyone ? run : recordStepUp(promote(authentication, run));
|
|
139
133
|
const installHandlers = (core, lifecycle, target) => Effect.gen(function* () {
|
|
140
134
|
const feeds = yield* acquireFeeds(serving.events);
|
|
141
135
|
const built = yield* Effect.context();
|
|
142
136
|
const send = target.context.sendNotification;
|
|
143
137
|
const meta = Effect.map(Effect.orDie(encodeServerInfo(target.context.serverInfo)), (serverInfo) => ({ "io.modelcontextprotocol/serverInfo": serverInfo }));
|
|
144
138
|
const webhooks = Context.getOption(built, Webhooks);
|
|
145
|
-
const
|
|
146
|
-
const deliveryOf = (event) => [
|
|
139
|
+
const deliveryOf = (feed) => [
|
|
147
140
|
"poll",
|
|
148
141
|
...send === void 0 ? [] : ["push"],
|
|
149
|
-
...
|
|
142
|
+
...Option.isSome(webhookSubscriber(feed, authentication, webhooks)) ? ["webhook"] : []
|
|
150
143
|
];
|
|
151
|
-
const served = new Map(feeds.map((feed) => [feed.event.name, servedOf(feed, deliveryOf(feed
|
|
144
|
+
const served = new Map(feeds.map((feed) => [feed.event.name, servedOf(feed, deliveryOf(feed))]));
|
|
152
145
|
const servedNamed = (name) => {
|
|
153
146
|
const found = served.get(name);
|
|
154
147
|
return found === void 0 ? Effect.fail(new EventsError(sentError(SubscriptionError.of(name, new NotServed())))) : Effect.succeed(found);
|
|
155
148
|
};
|
|
156
|
-
const asWebhook = (feed, run) => Effect.catchCause(
|
|
149
|
+
const asWebhook = (feed, run) => Effect.catchCause(asCaller(authentication, feed.event, Effect.flatMap(subscriberOf(feed, authentication, webhooks), run)), (cause) => Effect.flatMap(wireErrorOf(cause), Effect.fail));
|
|
157
150
|
const fromBuilt = (handled) => Effect.updateContext(handled, (request) => Context.merge(built, request));
|
|
158
151
|
const handlers = Requests.of({
|
|
159
152
|
"events/list": () => Effect.map(meta, (_meta) => ({
|
|
@@ -166,7 +159,7 @@ const withEvents = (base, serving) => {
|
|
|
166
159
|
const { feed, decode, wire } = yield* servedNamed(name);
|
|
167
160
|
const input = yield* decode(args);
|
|
168
161
|
const { page, events } = yield* Effect.gen(function* () {
|
|
169
|
-
const polled = yield*
|
|
162
|
+
const polled = yield* asCaller(authentication, feed.event, Effect.flatMap(principalOf(feed.event, authentication), (subscriber) => feed.poll(input, cursor ?? null, {
|
|
170
163
|
subscriber,
|
|
171
164
|
maxEvents
|
|
172
165
|
})));
|
|
@@ -189,17 +182,14 @@ const withEvents = (base, serving) => {
|
|
|
189
182
|
yield* routedTo(name);
|
|
190
183
|
const { feed, decode, wire } = yield* servedNamed(name);
|
|
191
184
|
const input = yield* decode(args);
|
|
192
|
-
if (send === void 0) return yield* new EventsError(sentError(
|
|
193
|
-
feature: "deliveryMode",
|
|
194
|
-
value: "push"
|
|
195
|
-
}))));
|
|
185
|
+
if (send === void 0) return yield* new EventsError(sentError(deliveryUnsupported(name, "push")));
|
|
196
186
|
return yield* delivered({
|
|
197
187
|
send,
|
|
198
188
|
clientId: client.id,
|
|
199
189
|
requestId,
|
|
200
190
|
wire,
|
|
201
191
|
_meta: yield* meta
|
|
202
|
-
}, (deliver) =>
|
|
192
|
+
}, (deliver) => asCaller(authentication, feed.event, Effect.flatMap(feed.stream(input), (open) => pushed(open, cursor ?? null, deliver, { positions: "heartbeat" }))));
|
|
203
193
|
}).pipe(fromBuilt),
|
|
204
194
|
"events/subscribe": ({ name, arguments: args, delivery: { url, secret }, cursor, ttlMs }) => Effect.gen(function* () {
|
|
205
195
|
yield* routedTo(name);
|
|
@@ -259,4 +249,4 @@ const withEvents = (base, serving) => {
|
|
|
259
249
|
installHandlers
|
|
260
250
|
};
|
|
261
251
|
};
|
|
262
|
-
export { eventSchemasOf,
|
|
252
|
+
export { eventSchemasOf, withEvents };
|
package/dist/mcp/client.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { checked, checkedStream, sendingJson,
|
|
1
|
+
import { checked, checkedStream, sendingJson, sentInput } from "../contract/call.mjs";
|
|
2
2
|
import { Anyone } from "../contract/caller.mjs";
|
|
3
3
|
import { projectedErrors } from "../contract/declared.mjs";
|
|
4
4
|
import { Refusal } from "../contract/errors.mjs";
|
|
5
5
|
import { liftOf } from "../contract/lift.mjs";
|
|
6
6
|
import { split } from "../contract/listed.mjs";
|
|
7
7
|
import { assertOnce } from "../contract/names.mjs";
|
|
8
|
-
import { progressSink } from "../contract/progress.mjs";
|
|
9
8
|
import { elementOf } from "../contract/stream.mjs";
|
|
10
9
|
import { watching } from "../contract/watch.mjs";
|
|
10
|
+
import { decodedSink } from "./progress.mjs";
|
|
11
11
|
import { defaultPath, unliftedFrom } from "./protocol.mjs";
|
|
12
12
|
import { NoReply, NoStructuredContent, ProtocolError, StatusError, UndeclaredError, bodyOf, callError, failWith } from "./reply.mjs";
|
|
13
13
|
import { request } from "./request.mjs";
|
|
@@ -22,15 +22,6 @@ const ToolCallReply = Schema.Union([Schema.Struct({ result: McpSchema.CallToolRe
|
|
|
22
22
|
message: Schema.String
|
|
23
23
|
}) })]);
|
|
24
24
|
const decodeReply = Schema.decodeUnknownOption(Schema.fromJsonString(ToolCallReply));
|
|
25
|
-
const decodedSink = (progress, onProgress) => {
|
|
26
|
-
const sink = progressSink(onProgress);
|
|
27
|
-
if (progress === void 0 || sink === void 0) return;
|
|
28
|
-
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(progress));
|
|
29
|
-
return { progress: (json) => Effect.matchEffect(decode(json), {
|
|
30
|
-
onFailure: (error) => Effect.logWarning("A progress value did not decode", error),
|
|
31
|
-
onSuccess: sink.progress
|
|
32
|
-
}) };
|
|
33
|
-
};
|
|
34
25
|
const callTool = (client, url, action, success, refusedWith, input, sink) => {
|
|
35
26
|
const { name } = action;
|
|
36
27
|
const lift = liftOf(success);
|
|
@@ -66,7 +57,7 @@ function client(contracts, { url = defaultPath, transformClient, authentication
|
|
|
66
57
|
const refusedWith = (contract) => [...Refusal.members, ...contract.caller === Anyone ? [] : authentication?.error ?? []];
|
|
67
58
|
return Effect.map(HttpClient.HttpClient, (native) => {
|
|
68
59
|
const http = transformClient === void 0 ? native : transformClient(native);
|
|
69
|
-
const watch = (event, input, options) => Stream.unwrap(Effect.map(
|
|
60
|
+
const watch = (event, input, options) => Stream.unwrap(Effect.map(sentInput(event, input), ({ json }) => watching(transportOf({
|
|
70
61
|
http,
|
|
71
62
|
url,
|
|
72
63
|
event,
|
package/dist/mcp/events.mjs
CHANGED
|
@@ -133,4 +133,4 @@ const Terminated = Rpc.make("notifications/events/terminated", { payload: {
|
|
|
133
133
|
} });
|
|
134
134
|
const Requests = RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents);
|
|
135
135
|
const Notifications = RpcGroup.make(Active, Occurred, Heartbeat, Failed, Terminated);
|
|
136
|
-
export { Active, EventDescriptor, EventsError, Failed, Heartbeat,
|
|
136
|
+
export { Active, EventDescriptor, EventsError, Failed, Heartbeat, Notifications, Occurred, PollEvents, Requests, SubscribeEvents, Terminated, UnsubscribeEvents, WireError, WireOccurrence, codes, extension, subscriptionIdKey };
|
package/dist/mcp/progress.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { progressSink } from "../contract/progress.mjs";
|
|
1
2
|
import { Effect, Option, Schema } from "effect";
|
|
2
3
|
import { McpSchema } from "effect/ai";
|
|
3
4
|
// src/mcp/progress.ts
|
|
@@ -24,4 +25,13 @@ const Notified = Schema.fromJsonString(Schema.Struct({
|
|
|
24
25
|
}));
|
|
25
26
|
const notifiedOf = Schema.decodeUnknownOption(Notified);
|
|
26
27
|
const progressOf = (data) => Option.map(notifiedOf(data), (notified) => notified.params._meta[progressKey]);
|
|
27
|
-
|
|
28
|
+
const decodedSink = (progress, onProgress) => {
|
|
29
|
+
const sink = progressSink(onProgress);
|
|
30
|
+
if (progress === void 0 || sink === void 0) return;
|
|
31
|
+
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(progress));
|
|
32
|
+
return { progress: (json) => Effect.matchEffect(decode(json), {
|
|
33
|
+
onFailure: (error) => Effect.logWarning("A progress value did not decode", error),
|
|
34
|
+
onSuccess: sink.progress
|
|
35
|
+
}) };
|
|
36
|
+
};
|
|
37
|
+
export { decodedSink, progressNotifier, progressOf };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import "../authentication/provider.mjs";
|
|
2
|
+
import { Forbidden } from "../contract/errors.mjs";
|
|
3
|
+
import { Any } from "../Action.mjs";
|
|
4
|
+
import "../contract/call.mjs";
|
|
5
|
+
import { Codec } from "../contract/codec.mjs";
|
|
6
|
+
import "../contract/declared.mjs";
|
|
7
|
+
import { Any as Any$1 } from "../Event.mjs";
|
|
8
|
+
import "../contract/feed.mjs";
|
|
9
|
+
import { ErasedValue } from "../contract/implementation.mjs";
|
|
10
|
+
import "../contract/progress.mjs";
|
|
11
|
+
import "../contract/watch.mjs";
|
|
12
|
+
import "../contract/webhooks.mjs";
|
|
13
|
+
import { Cause, Duration, Effect, ErrorReporter, Queue, Schema, Stream } from "effect";
|
|
14
|
+
import { Rpc, RpcGroup, RpcMiddleware } from "effect/rpc";
|
|
15
|
+
export declare class DeclaredFailure {
|
|
16
|
+
readonly [ErrorReporter.ignore] = true;
|
|
17
|
+
readonly json: Schema.Json;
|
|
18
|
+
constructor(json: Schema.Json);
|
|
19
|
+
toString(): string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* What serves a binding's erased rpcs: `ActionRpc.layer`, which streams each event type beside
|
|
23
|
+
* polling it, through its `middleware`, or an entity, which only polls them, holds their webhooks
|
|
24
|
+
* and runs `check` on each input.
|
|
25
|
+
*/
|
|
26
|
+
export type Server = {
|
|
27
|
+
readonly _tag: "ActionRpc.layer";
|
|
28
|
+
readonly middleware: readonly RpcMiddleware.AnyService[];
|
|
29
|
+
} | {
|
|
30
|
+
readonly _tag: "ActionEntity.layer";
|
|
31
|
+
readonly check: InputCheck;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* The tag of the unary rpc polling the event type `name`, `<name>/poll`, taking `Poll` beside
|
|
35
|
+
* its `input` and answering a `Page`, which `ActionRpc.layer` and an `ActionEntity` serve and
|
|
36
|
+
* `ActionRpc.client`'s polling watch calls.
|
|
37
|
+
*/
|
|
38
|
+
export declare const pollTag: (name: string) => string;
|
|
39
|
+
/** The rpcs `server` serves for `actions` and `events`, and its clients call. */
|
|
40
|
+
export declare const erasedOf: (actions: readonly Any[], events: readonly Any$1[], server: Server["_tag"]) => RpcGroup.RpcGroup<Rpc.Rpc<string, Schema.Codec<Schema.Json, Schema.Json, never, never>, Schema.Codec<Schema.Json, Schema.Json, never, never>, Schema.instanceOf<DeclaredFailure, DeclaredFailure>, never, never> | Rpc.Rpc<string, Schema.Codec<Schema.Json, Schema.Json, never, never>, import("effect/rpc/RpcSchema").Stream<Schema.Codec<Schema.Json, Schema.Json, never, never>, Schema.instanceOf<DeclaredFailure, DeclaredFailure>>, Schema.Never, never, never>>;
|
|
41
|
+
/**
|
|
42
|
+
* The payload of an event type's poll rpc, `<event>/poll`, past its `input`, as a client sends
|
|
43
|
+
* it: the `cursor` to read after, `null` reading from now, at most `maxEvents` occurrences, and
|
|
44
|
+
* the `watch`, a UUID one watch sends with each of its polls, which tells a page's watches apart
|
|
45
|
+
* on a socket and holds nothing on the server: a poll's subscription hook is its caller's.
|
|
46
|
+
*/
|
|
47
|
+
export declare const Poll: Schema.Struct<{
|
|
48
|
+
readonly cursor: Schema.NullOr<Schema.String>;
|
|
49
|
+
readonly maxEvents: Schema.optionalKey<Schema.Finite>;
|
|
50
|
+
readonly watch: Schema.optionalKey<Schema.String>;
|
|
51
|
+
}>;
|
|
52
|
+
export declare const ProgressedOf: <P extends Codec, S extends Codec>(progress: P, success: S) => Schema.Union<readonly [Schema.TaggedStruct<"Progress", {
|
|
53
|
+
readonly value: P;
|
|
54
|
+
}>, Schema.TaggedStruct<"Final", {
|
|
55
|
+
readonly value: S;
|
|
56
|
+
}>]>;
|
|
57
|
+
/**
|
|
58
|
+
* What a server checks of each call's and subscription's decoded input, once it has verified its
|
|
59
|
+
* caller and before the implementation's authorizer: an entity refuses an input whose key names
|
|
60
|
+
* another entity.
|
|
61
|
+
*/
|
|
62
|
+
export type InputCheck = (contract: Any | Any$1, input: ErasedValue) => Effect.Effect<void, Forbidden>;
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import { providerOf } from "../authentication/provider.mjs";
|
|
2
|
+
import { checked, checkedStream, decodeInput, sendingJson, sentInput } from "../contract/call.mjs";
|
|
3
|
+
import { Anyone, principalOf } from "../contract/caller.mjs";
|
|
4
|
+
import { bindingErrors, eventErrors } from "../contract/declared.mjs";
|
|
5
|
+
import { SubscriptionError } from "../Event.mjs";
|
|
6
|
+
import { acquireFeeds } from "../contract/feed.mjs";
|
|
7
|
+
import { acquire, answered, elementsOf } from "../contract/implementation.mjs";
|
|
8
|
+
import { pageOf, rpcPageOf } from "../contract/pages.mjs";
|
|
9
|
+
import { answerFrom, elementsFrom } from "../contract/progress.mjs";
|
|
10
|
+
import { PushedOf, SubscriptionOf, queuedPush } from "../contract/push.mjs";
|
|
11
|
+
import { concealed } from "../contract/reported.mjs";
|
|
12
|
+
import { Answering, answeringOf, elementOf } from "../contract/stream.mjs";
|
|
13
|
+
import { Subscribed, WebhookCancellationOf, WebhookSubscriptionOf, deliveryUnsupported } from "../contract/subscribe.mjs";
|
|
14
|
+
import { watching } from "../contract/watch.mjs";
|
|
15
|
+
import { offersWebhook, servingFeeds, webhookAnswers } from "../contract/webhooks.mjs";
|
|
16
|
+
import { isUnknownTag, polledTransportOf, streamingOf } from "./watch.mjs";
|
|
17
|
+
import { Cause, Effect, ErrorReporter, Option, Predicate, Queue, Result, Schema, SchemaTransformation, Stream } from "effect";
|
|
18
|
+
import { HttpClientRequest, HttpServerRequest } from "effect/http";
|
|
19
|
+
import { Rpc, RpcGroup } from "effect/rpc";
|
|
20
|
+
import { HttpApiBuilder } from "effect/http-api";
|
|
21
|
+
// src/rpc/erased.ts
|
|
22
|
+
const streams = (action) => !Answering.$is("Value")(answeringOf(action));
|
|
23
|
+
const withSyntheticRequestFromHeaders = (headers) => (effect) => effect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromClientRequest(HttpClientRequest.get("/", { headers }))), Effect.provideService(HttpServerRequest.ParsedSearchParams, {}));
|
|
24
|
+
const throughSteps = (steps, call, options) => {
|
|
25
|
+
let wrapped = call;
|
|
26
|
+
for (const step of steps) {
|
|
27
|
+
const inner = wrapped;
|
|
28
|
+
wrapped = Effect.suspend(() => step(inner, options));
|
|
29
|
+
}
|
|
30
|
+
return wrapped;
|
|
31
|
+
};
|
|
32
|
+
const authenticatingOf = (authentication) => Effect.map(providerOf(authentication), (provider) => {
|
|
33
|
+
const verify = Effect.flatMap(HttpApiBuilder.securityDecode(authentication.security), provider.authenticate);
|
|
34
|
+
return (verifying) => (effect, options) => Effect.flatMap(verifying(verify, options), (actor) => Effect.provideService(effect, authentication.identity, actor));
|
|
35
|
+
});
|
|
36
|
+
var DeclaredFailure = class {
|
|
37
|
+
[ErrorReporter.ignore] = true;
|
|
38
|
+
json;
|
|
39
|
+
constructor(json) {
|
|
40
|
+
this.json = json;
|
|
41
|
+
}
|
|
42
|
+
toString() {
|
|
43
|
+
return Predicate.isString(this.json) ? this.json : JSON.stringify(this.json);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const asJson = () => Schema.link()(Schema.Json, SchemaTransformation.transform({
|
|
47
|
+
decode: (json) => new DeclaredFailure(json),
|
|
48
|
+
encode: (failure) => failure.json
|
|
49
|
+
}));
|
|
50
|
+
const Declared = Schema.instanceOf(DeclaredFailure, {
|
|
51
|
+
toCodecJson: asJson,
|
|
52
|
+
toCodecIso: asJson
|
|
53
|
+
});
|
|
54
|
+
const streamOf = (name) => Rpc.make(name, {
|
|
55
|
+
payload: Schema.Json,
|
|
56
|
+
success: Schema.Json,
|
|
57
|
+
error: Declared,
|
|
58
|
+
stream: true
|
|
59
|
+
});
|
|
60
|
+
const unaryOf = (name) => Rpc.make(name, {
|
|
61
|
+
payload: Schema.Json,
|
|
62
|
+
success: Schema.Json,
|
|
63
|
+
error: Declared
|
|
64
|
+
});
|
|
65
|
+
const streamsEvents = (server) => server === "ActionRpc.layer";
|
|
66
|
+
/**
|
|
67
|
+
* The tag of the unary rpc polling the event type `name`, `<name>/poll`, taking `Poll` beside
|
|
68
|
+
* its `input` and answering a `Page`, which `ActionRpc.layer` and an `ActionEntity` serve and
|
|
69
|
+
* `ActionRpc.client`'s polling watch calls.
|
|
70
|
+
*/
|
|
71
|
+
const pollTag = (name) => `${name}/poll`;
|
|
72
|
+
const subscribeTag = (name) => `${name}/subscribe`;
|
|
73
|
+
const unsubscribeTag = (name) => `${name}/unsubscribe`;
|
|
74
|
+
const webhookRpcsOf = (events) => RpcGroup.make(...events.filter(offersWebhook).flatMap((event) => [unaryOf(subscribeTag(event.name)), unaryOf(unsubscribeTag(event.name))]));
|
|
75
|
+
const webhookErrors = (event, binding) => Schema.Union([...eventErrors(event, binding), SubscriptionError]);
|
|
76
|
+
/** The rpcs `server` serves for `actions` and `events`, and its clients call. */
|
|
77
|
+
const erasedOf = (actions, events, server) => RpcGroup.make(...actions.map((action) => streams(action) ? streamOf(action.name) : unaryOf(action.name)), ...events.flatMap((event) => [...streamsEvents(server) ? [streamOf(event.name)] : [], unaryOf(pollTag(event.name))]));
|
|
78
|
+
const Watch = Schema.String.check(Schema.isUUID());
|
|
79
|
+
/**
|
|
80
|
+
* The payload of an event type's poll rpc, `<event>/poll`, past its `input`, as a client sends
|
|
81
|
+
* it: the `cursor` to read after, `null` reading from now, at most `maxEvents` occurrences, and
|
|
82
|
+
* the `watch`, a UUID one watch sends with each of its polls, which tells a page's watches apart
|
|
83
|
+
* on a socket and holds nothing on the server: a poll's subscription hook is its caller's.
|
|
84
|
+
*/
|
|
85
|
+
const Poll = Schema.Struct({
|
|
86
|
+
cursor: Schema.NullOr(Schema.String),
|
|
87
|
+
maxEvents: Schema.optionalKey(Schema.Finite),
|
|
88
|
+
watch: Schema.optionalKey(Watch)
|
|
89
|
+
});
|
|
90
|
+
const PollOf = (event) => Schema.Struct({
|
|
91
|
+
...Poll.fields,
|
|
92
|
+
...SubscriptionOf(event).fields
|
|
93
|
+
});
|
|
94
|
+
const erasedCallOf = (send) => ({
|
|
95
|
+
unary: (tag, payload) => {
|
|
96
|
+
const answer = send(tag, payload);
|
|
97
|
+
return Effect.isEffect(answer) ? answer : Effect.die(/* @__PURE__ */ new Error(`The rpc ${tag} streams, called as unary`));
|
|
98
|
+
},
|
|
99
|
+
stream: (tag, payload) => {
|
|
100
|
+
const answer = send(tag, payload);
|
|
101
|
+
return Stream.isStream(answer) ? answer : Stream.die(/* @__PURE__ */ new Error(`The rpc ${tag} is unary, called as a stream`));
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
const ProgressedOf = (progress, success) => Schema.Union([Schema.TaggedStruct("Progress", { value: progress }), Schema.TaggedStruct("Final", { value: success })]);
|
|
105
|
+
const elementedOf = (element, progress) => Schema.Union([Schema.TaggedStruct("Element", { value: element }), ...progress === void 0 ? [] : [Schema.TaggedStruct("Progress", { value: progress })]]);
|
|
106
|
+
const streamedOf = (action) => Answering.$match(answeringOf(action), {
|
|
107
|
+
Value: () => void 0,
|
|
108
|
+
Progressed: ({ success, progress }) => ProgressedOf(progress, success),
|
|
109
|
+
Elements: ({ element, progress }) => elementedOf(element, progress)
|
|
110
|
+
});
|
|
111
|
+
const nativeOf = (group) => group;
|
|
112
|
+
const isDeclared = (failure) => failure instanceof DeclaredFailure;
|
|
113
|
+
const failedOf = (error) => {
|
|
114
|
+
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(error));
|
|
115
|
+
return (failure) => Effect.flatMap(Effect.orDie(decode(failure.json)), Effect.fail);
|
|
116
|
+
};
|
|
117
|
+
const calledMethodOf = (action, binding) => {
|
|
118
|
+
const failed = failedOf(Schema.Union(bindingErrors(action, binding)));
|
|
119
|
+
const streamed = streamedOf(action);
|
|
120
|
+
const encode = sendingJson(action);
|
|
121
|
+
const sending = () => encode;
|
|
122
|
+
if (streamed === void 0) {
|
|
123
|
+
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(action.success));
|
|
124
|
+
return (call) => checked(action, sending, (json) => call.unary(action.name, json).pipe(Effect.catchIf(isDeclared, failed), Effect.flatMap((sent) => Effect.orDie(decode(sent)))));
|
|
125
|
+
}
|
|
126
|
+
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(streamed));
|
|
127
|
+
const progressed = (call, json) => call.stream(action.name, json).pipe(Stream.catchIf(isDeclared, (failure) => Stream.fromEffect(failed(failure))), Stream.mapEffect((sent) => Effect.orDie(decode(sent))));
|
|
128
|
+
return elementOf(action.success) === void 0 ? (call) => checked(action, sending, (json, onProgress) => answerFrom(progressed(call, json), onProgress)) : (call) => checkedStream(action, sending, (json, onProgress) => elementsFrom(progressed(call, json), onProgress));
|
|
129
|
+
};
|
|
130
|
+
const streamedTransport = (silenceEnds, polled) => (event, binding) => {
|
|
131
|
+
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(PushedOf(event)));
|
|
132
|
+
const failed = failedOf(Schema.Union(eventErrors(event, binding)));
|
|
133
|
+
const polledThrough = polled(event, binding);
|
|
134
|
+
return (call) => {
|
|
135
|
+
const polling = polledThrough(call);
|
|
136
|
+
return (input, streamOnly) => ({
|
|
137
|
+
...polling(input, streamOnly),
|
|
138
|
+
stream: streamingOf(event, (cursor) => call.stream(event.name, {
|
|
139
|
+
input,
|
|
140
|
+
cursor
|
|
141
|
+
}).pipe(Stream.catchIf(isDeclared, (failure) => Stream.fromEffect(failed(failure))), Stream.mapEffect((json) => Effect.orDie(decode(json)))), silenceEnds, streamOnly)
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
const pollOf = (event, binding) => {
|
|
146
|
+
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(pageOf(event)));
|
|
147
|
+
const failed = failedOf(Schema.Union(eventErrors(event, binding)));
|
|
148
|
+
return (call) => (payload) => call.unary(pollTag(event.name), payload).pipe(Effect.catchIf(isDeclared, failed), Effect.flatMap((json) => Effect.orDie(decode(json))));
|
|
149
|
+
};
|
|
150
|
+
const watchedOf = (event, binding) => {
|
|
151
|
+
const pollThrough = pollOf(event, binding);
|
|
152
|
+
return (call) => {
|
|
153
|
+
const poll = pollThrough(call);
|
|
154
|
+
return (input) => ({ poll: (cursor, watch) => poll({
|
|
155
|
+
input,
|
|
156
|
+
cursor,
|
|
157
|
+
...watch === void 0 ? {} : { watch }
|
|
158
|
+
}) });
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
const webhookCallsOf = (event, binding) => {
|
|
162
|
+
const failed = failedOf(webhookErrors(event, binding));
|
|
163
|
+
const encodeSubscription = Schema.encodeUnknownEffect(Schema.toCodecJson(WebhookSubscriptionOf(event)));
|
|
164
|
+
const encodeCancellation = Schema.encodeUnknownEffect(Schema.toCodecJson(WebhookCancellationOf(event)));
|
|
165
|
+
const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(Subscribed));
|
|
166
|
+
return (call) => ({
|
|
167
|
+
subscribe: ({ input, delivery, cursor, ttlMs }) => Effect.orDie(encodeSubscription({
|
|
168
|
+
input,
|
|
169
|
+
delivery,
|
|
170
|
+
cursor,
|
|
171
|
+
ttlMs
|
|
172
|
+
})).pipe(Effect.flatMap((json) => call.unary(subscribeTag(event.name), json)), Effect.catchIf(isDeclared, failed), Effect.flatMap((json) => Effect.orDie(decode(json)))),
|
|
173
|
+
unsubscribe: ({ input, delivery: { url } }) => Effect.orDie(encodeCancellation({
|
|
174
|
+
input,
|
|
175
|
+
delivery: { url }
|
|
176
|
+
})).pipe(Effect.flatMap((json) => call.unary(unsubscribeTag(event.name), json)), Effect.catchIf(isDeclared, failed), Effect.asVoid)
|
|
177
|
+
});
|
|
178
|
+
};
|
|
179
|
+
const resending = (poll, after) => (cursor, watch) => Effect.timeoutOrElse(poll(cursor, watch), {
|
|
180
|
+
duration: after,
|
|
181
|
+
orElse: () => resending(poll, after)(cursor, watch)
|
|
182
|
+
});
|
|
183
|
+
const polledTransport = (transient, resendAfter) => (event, binding) => {
|
|
184
|
+
const watchedThrough = watchedOf(event, binding);
|
|
185
|
+
const pollUnserved = isUnknownTag(pollTag(event.name));
|
|
186
|
+
return (call) => {
|
|
187
|
+
const watched = watchedThrough(call);
|
|
188
|
+
return (input) => {
|
|
189
|
+
const { poll } = watched(input);
|
|
190
|
+
return polledTransportOf(event, { poll: resendAfter === void 0 ? poll : resending(poll, resendAfter) }, transient, pollUnserved);
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* An action's client method over `reach`: its call goes where its input, decoded as the server
|
|
196
|
+
* will decode it, a decoding default included, says.
|
|
197
|
+
*/
|
|
198
|
+
const actionMethodOf = (action, binding) => {
|
|
199
|
+
const method = calledMethodOf(action, binding);
|
|
200
|
+
const answer = (reach, [input, ...rest]) => Effect.flatMap(sentInput(action, input), ({ value }) => Effect.map(reach(action, value), (call) => method(call)(value, ...rest)));
|
|
201
|
+
return elementOf(action.success) === void 0 ? (reach) => (...args) => Effect.flatMap(answer(reach, args), answered) : (reach) => (...args) => elementsOf(answer(reach, args));
|
|
202
|
+
};
|
|
203
|
+
const methodsOf = (binding, transport) => {
|
|
204
|
+
const actions = binding.actions.map((action) => [action.name, actionMethodOf(action, binding)]);
|
|
205
|
+
const transports = new Map(binding.events.map((event) => [event.name, transport(event, binding)]));
|
|
206
|
+
return (reach) => {
|
|
207
|
+
const methods = Object.fromEntries(actions.map(([name, method]) => [name, method(reach)]));
|
|
208
|
+
if (transports.size === 0) return methods;
|
|
209
|
+
const watch = (event, input, watchOptions) => {
|
|
210
|
+
const feed = transports.get(event.name);
|
|
211
|
+
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)`));
|
|
212
|
+
return Stream.unwrap(Effect.flatMap(sentInput(event, input), ({ json, value }) => Effect.map(reach(event, value), (call) => watching(feed(call)(json, watchOptions?.mode === "stream"), watchOptions))));
|
|
213
|
+
};
|
|
214
|
+
return {
|
|
215
|
+
...methods,
|
|
216
|
+
watch
|
|
217
|
+
};
|
|
218
|
+
};
|
|
219
|
+
};
|
|
220
|
+
const callBoundaryOf = (error) => {
|
|
221
|
+
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(error));
|
|
222
|
+
return (effect) => Effect.catchCause(effect, (cause) => {
|
|
223
|
+
if (Cause.hasDies(cause)) return concealed(cause);
|
|
224
|
+
const failure = Cause.findFail(cause);
|
|
225
|
+
return Result.isSuccess(failure) ? encode(failure.success.error).pipe(Effect.matchCauseEffect({
|
|
226
|
+
onFailure: (unencoded) => concealed(Cause.combine(cause, unencoded)),
|
|
227
|
+
onSuccess: (encoded) => Effect.fail(new DeclaredFailure(encoded))
|
|
228
|
+
})) : Effect.failCause(failure.failure);
|
|
229
|
+
});
|
|
230
|
+
};
|
|
231
|
+
const servedCall = (steps, boundary, call) => (payload, options) => boundary(throughSteps(steps, call(payload, options), {
|
|
232
|
+
...options,
|
|
233
|
+
payload
|
|
234
|
+
}));
|
|
235
|
+
const handlerOf = (action, run, steps, error) => {
|
|
236
|
+
const decode = decodeInput(action);
|
|
237
|
+
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(action.success));
|
|
238
|
+
return servedCall(steps, callBoundaryOf(error), (payload) => Effect.suspend(() => decode(payload)).pipe(Effect.flatMap(run), Effect.flatMap(encode)));
|
|
239
|
+
};
|
|
240
|
+
const streamingHandlerOf = (action, sending, steps, error) => {
|
|
241
|
+
const decode = decodeInput(action);
|
|
242
|
+
const boundary = callBoundaryOf(error);
|
|
243
|
+
const encodeProgress = Schema.encodeUnknownEffect(Schema.toCodecJson(action.progress ?? Schema.Never));
|
|
244
|
+
return servedCall(steps, boundary, (payload) => Effect.gen(function* () {
|
|
245
|
+
const input = yield* decode(payload);
|
|
246
|
+
const sent = yield* Queue.bounded(1);
|
|
247
|
+
const send = (each) => Effect.asVoid(Queue.offer(sent, each));
|
|
248
|
+
yield* sending(input, { progress: (value) => Effect.flatMap(Effect.orDie(encodeProgress(value)), (json) => send({
|
|
249
|
+
_tag: "Progress",
|
|
250
|
+
value: json
|
|
251
|
+
})) }, send).pipe(boundary, Queue.into(sent), Effect.forkScoped({ startImmediately: true }));
|
|
252
|
+
return sent;
|
|
253
|
+
}));
|
|
254
|
+
};
|
|
255
|
+
const sendingAnswer = (success, run) => {
|
|
256
|
+
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(success));
|
|
257
|
+
return (input, reporting, send) => run(input, reporting).pipe(Effect.flatMap(encode), Effect.flatMap((value) => send({
|
|
258
|
+
_tag: "Final",
|
|
259
|
+
value
|
|
260
|
+
})));
|
|
261
|
+
};
|
|
262
|
+
const sendingElements = (element, run) => {
|
|
263
|
+
const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(element));
|
|
264
|
+
return (input, reporting, send) => Stream.runForEach(elementsOf(run(input, reporting)), (each) => Effect.flatMap(encode(each), (value) => send({
|
|
265
|
+
_tag: "Element",
|
|
266
|
+
value
|
|
267
|
+
})));
|
|
268
|
+
};
|
|
269
|
+
const subscriptionHandlerOf = (feed, steps, error) => {
|
|
270
|
+
const decode = decodeInput({ input: SubscriptionOf(feed.event) });
|
|
271
|
+
const encode = Schema.encodeEffect(Schema.toCodecJson(PushedOf(feed.event)));
|
|
272
|
+
const boundary = callBoundaryOf(error);
|
|
273
|
+
return servedCall(steps, boundary, (payload) => Effect.gen(function* () {
|
|
274
|
+
const { input, cursor } = yield* decode(payload);
|
|
275
|
+
const open = yield* feed.stream(input);
|
|
276
|
+
return yield* queuedPush(open, cursor, encode, {
|
|
277
|
+
ending: boundary,
|
|
278
|
+
positions: "heartbeat"
|
|
279
|
+
});
|
|
280
|
+
}));
|
|
281
|
+
};
|
|
282
|
+
const pollHandlerOf = (feed, steps, error, authentication, check) => {
|
|
283
|
+
const decode = decodeInput({ input: PollOf(feed.event) });
|
|
284
|
+
const encode = Schema.encodeEffect(Schema.toCodecJson(rpcPageOf(feed.event)));
|
|
285
|
+
return servedCall(steps, callBoundaryOf(error), (payload) => Effect.gen(function* () {
|
|
286
|
+
const { input, cursor, maxEvents } = yield* decode(payload);
|
|
287
|
+
yield* check(input);
|
|
288
|
+
const subscriber = yield* principalOf(feed.event, authentication);
|
|
289
|
+
const page = yield* feed.poll(input, cursor, {
|
|
290
|
+
subscriber,
|
|
291
|
+
maxEvents
|
|
292
|
+
});
|
|
293
|
+
return yield* encode({
|
|
294
|
+
...page,
|
|
295
|
+
notified: !feed.polls
|
|
296
|
+
});
|
|
297
|
+
}));
|
|
298
|
+
};
|
|
299
|
+
const pollingRefused = ({ event }) => Effect.logWarning(`An entity refused a webhook subscription to "${event.name}", whose check source is not notified: its timer would be cut by Effect's entity reaper and keep a Durable Object awake (mark the source notified, notifying after each write, or serve the event's webhooks from a surface outside the entity)`);
|
|
300
|
+
const webhookHandlersOf = (feed, steps, error, answers, check) => {
|
|
301
|
+
const subscribing = decodeInput({ input: WebhookSubscriptionOf(feed.event) });
|
|
302
|
+
const cancelling = decodeInput({ input: WebhookCancellationOf(feed.event) });
|
|
303
|
+
const encode = Schema.encodeEffect(Schema.toCodecJson(Subscribed));
|
|
304
|
+
const boundary = callBoundaryOf(error);
|
|
305
|
+
return [[subscribeTag(feed.event.name), servedCall(steps, boundary, (payload) => Effect.suspend(() => subscribing(payload)).pipe(Effect.tap(({ input }) => check(input)), Effect.flatMap(answers.subscribe), Effect.flatMap(encode)))], [unsubscribeTag(feed.event.name), servedCall(steps, boundary, (payload) => Effect.suspend(() => cancelling(payload)).pipe(Effect.tap(({ input }) => check(input)), Effect.flatMap(answers.unsubscribe), Effect.as(null)))]];
|
|
306
|
+
};
|
|
307
|
+
const verifyingNative = (verify, { headers }) => withSyntheticRequestFromHeaders(headers)(verify).pipe(Effect.catchCauseIf(Cause.hasDies, concealed));
|
|
308
|
+
const requested = (effect, { headers }) => withSyntheticRequestFromHeaders(headers)(effect);
|
|
309
|
+
const handlersOf = Effect.fnUntraced(function* (binding, { apps, events, authentication, server }) {
|
|
310
|
+
const holdsWebhooks = server._tag === "ActionEntity.layer";
|
|
311
|
+
const check = server._tag === "ActionEntity.layer" ? server.check : () => Effect.void;
|
|
312
|
+
const listedMiddleware = server._tag === "ActionRpc.layer" ? yield* Effect.forEach(server.middleware, (key) => Effect.service(key)) : [];
|
|
313
|
+
const authenticating = authentication === void 0 ? void 0 : yield* authenticatingOf(authentication);
|
|
314
|
+
const bound = yield* acquire(apps, authentication);
|
|
315
|
+
const { feeds, webhooks } = holdsWebhooks ? yield* servingFeeds(events, authentication, ({ polls }) => !polls) : {
|
|
316
|
+
feeds: yield* acquireFeeds(events),
|
|
317
|
+
webhooks: Option.none()
|
|
318
|
+
};
|
|
319
|
+
const heldAnswers = (feed) => {
|
|
320
|
+
const answers = webhookAnswers(feed, authentication, webhooks);
|
|
321
|
+
if (!feed.polls || Option.isNone(webhooks)) return answers;
|
|
322
|
+
return {
|
|
323
|
+
...answers,
|
|
324
|
+
subscribe: () => Effect.andThen(pollingRefused(feed), Effect.fail(deliveryUnsupported(feed.event.name, "webhook")))
|
|
325
|
+
};
|
|
326
|
+
};
|
|
327
|
+
const stepsOf = (caller) => caller === Anyone || authenticating === void 0 ? [...listedMiddleware, requested] : [
|
|
328
|
+
...listedMiddleware,
|
|
329
|
+
authenticating((verify) => verify),
|
|
330
|
+
requested
|
|
331
|
+
];
|
|
332
|
+
const handlerFor = (action, unchecked, steps, error) => {
|
|
333
|
+
const run = (input, reporting) => Effect.andThen(check(action, input), () => unchecked(input, reporting));
|
|
334
|
+
const streaming = (sending) => streamingHandlerOf(action, sending, steps, error);
|
|
335
|
+
return Answering.$match(answeringOf(action), {
|
|
336
|
+
Value: () => handlerOf(action, run, steps, error),
|
|
337
|
+
Progressed: ({ success }) => streaming(sendingAnswer(success, run)),
|
|
338
|
+
Elements: ({ element }) => streaming(sendingElements(element, run))
|
|
339
|
+
});
|
|
340
|
+
};
|
|
341
|
+
return {
|
|
342
|
+
handlers: {
|
|
343
|
+
...Object.fromEntries(bound.map(([action, run]) => [action.name, handlerFor(action, run, stepsOf(action.caller), Schema.Union(bindingErrors(action, binding)))])),
|
|
344
|
+
...Object.fromEntries(streamsEvents(server._tag) ? feeds.map((feed) => [feed.event.name, subscriptionHandlerOf(feed, stepsOf(feed.event.caller), Schema.Union(eventErrors(feed.event, binding)))]) : []),
|
|
345
|
+
...Object.fromEntries(feeds.flatMap((feed) => {
|
|
346
|
+
const steps = stepsOf(feed.event.caller);
|
|
347
|
+
const error = Schema.Union(eventErrors(feed.event, binding));
|
|
348
|
+
const checking = (input) => check(feed.event, input);
|
|
349
|
+
return [[pollTag(feed.event.name), pollHandlerOf(feed, steps, error, authentication, checking)]];
|
|
350
|
+
})),
|
|
351
|
+
...Object.fromEntries(holdsWebhooks ? feeds.filter(({ event }) => offersWebhook(event)).flatMap((feed) => webhookHandlersOf(feed, stepsOf(feed.event.caller), webhookErrors(feed.event, binding), heldAnswers(feed), (input) => check(feed.event, input))) : [])
|
|
352
|
+
},
|
|
353
|
+
authenticating
|
|
354
|
+
};
|
|
355
|
+
});
|
|
356
|
+
export { DeclaredFailure, Poll, ProgressedOf, actionMethodOf, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollOf, pollTag, polledTransport, streamedOf, streamedTransport, verifyingNative, watchedOf, webhookCallsOf, webhookRpcsOf };
|