@gjermundgaraba/effect-actions 0.24.0 → 0.25.1
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 +2 -2
- package/dist/Action.mjs +2 -2
- package/dist/ActionMcp.d.mts +3 -1
- package/dist/ActionMcp.mjs +7 -4
- package/dist/ActionRpc.mjs +5 -2
- package/dist/ActionToolkit.d.mts +3 -0
- package/dist/ActionToolkit.mjs +13 -2
- package/dist/Webhook.d.mts +3 -1
- package/dist/authentication/provider.d.mts +4 -3
- package/dist/contract/callback.mjs +0 -4
- package/dist/contract/feed.mjs +1 -1
- package/dist/contract/implementation.d.mts +5 -15
- package/dist/contract/lift.mjs +80 -0
- package/dist/contract/log.mjs +1 -1
- package/dist/contract/media.d.mts +3 -2
- package/dist/contract/media.mjs +3 -2
- package/dist/contract/push.mjs +6 -10
- package/dist/contract/status.mjs +13 -2
- package/dist/contract/subscribe.mjs +0 -4
- package/dist/http/events.d.mts +2 -2
- package/dist/http/events.mjs +5 -2
- package/dist/mcp/bridge.mjs +8 -4
- package/dist/mcp/client.mjs +2 -1
- package/dist/mcp/protocol.mjs +2 -79
- package/dist/webhook/attempt.mjs +2 -2
- package/dist/webhook/health.mjs +99 -0
- package/dist/webhook/receiver.mjs +2 -2
- package/dist/webhook/signing.mjs +4 -11
- package/dist/webhook/stored.mjs +23 -13
- package/dist/webhook/subscriptions.mjs +34 -46
- package/docs/Action-failures.md +1 -1
- package/docs/ActionCli.md +1 -1
- package/docs/ActionHttp.md +1 -1
- package/docs/ActionMcp.md +2 -2
- package/docs/ActionRpc.md +0 -4
- package/docs/ActionToolkit.md +1 -0
- package/docs/Authentication-advanced.md +16 -19
- package/docs/Authentication-failures.md +1 -1
- package/docs/Authentication.md +0 -4
- package/docs/README.md +1 -1
- package/docs/Webhook.md +3 -6
- package/docs/setup.md +5 -5
- package/examples/build-events/src/notifier/routes.ts +3 -6
- package/examples/build-events/src/notifier.ts +4 -2
- package/examples/build-events/test/notifier.test.ts +1 -1
- package/examples/kitchen-sink/README.md +3 -3
- package/examples/kitchen-sink/src/identity/authenticate.ts +2 -2
- package/examples/kitchen-sink/src/identity/workspace-header.ts +19 -0
- package/examples/kitchen-sink/src/routes.ts +2 -2
- package/examples/live-rpc/src/chat/room.ts +0 -4
- package/examples/notes-service/src/identity/Identity.ts +0 -4
- package/package.json +2 -2
- package/examples/kitchen-sink/src/workspaces/tenant.ts +0 -22
package/dist/mcp/protocol.mjs
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Media, isMarked, kindOf } from "../contract/media.mjs";
|
|
1
|
+
import { isMarked } from "../contract/media.mjs";
|
|
3
2
|
import { JsonPointer, Predicate, Schema, SchemaAST } from "effect";
|
|
4
3
|
import { Base64 } from "effect/encoding";
|
|
5
4
|
import { McpProtocol, McpSchema } from "effect/ai";
|
|
@@ -34,72 +33,7 @@ const toolJsonSchema = (schema, strict) => {
|
|
|
34
33
|
$defs: definitions
|
|
35
34
|
};
|
|
36
35
|
};
|
|
37
|
-
const routingFormsOf = (name) => [name, `=?base64?${Base64.encode(name)}?=`];
|
|
38
36
|
const fieldKey = "effect-actions/field";
|
|
39
|
-
const isMedia = Schema.is(Media);
|
|
40
|
-
const isMediaArray = Schema.is(Schema.Array(Media));
|
|
41
|
-
const kindOfUnsuspended = (ast) => kindOf(unsuspended(ast));
|
|
42
|
-
const wholeSuccessMediaOf = (suspended) => {
|
|
43
|
-
const ast = unsuspended(suspended);
|
|
44
|
-
const one = kindOf(ast);
|
|
45
|
-
if (one !== void 0) return {
|
|
46
|
-
kind: one,
|
|
47
|
-
many: false
|
|
48
|
-
};
|
|
49
|
-
if (!SchemaAST.isArrays(ast) || ast.encoding !== void 0) return;
|
|
50
|
-
const [kind, ...others] = new Set([...ast.elements, ...ast.rest].map(kindOfUnsuspended));
|
|
51
|
-
return kind === void 0 || others.length > 0 ? void 0 : {
|
|
52
|
-
kind,
|
|
53
|
-
many: true
|
|
54
|
-
};
|
|
55
|
-
};
|
|
56
|
-
const mediaFieldOf = (field) => {
|
|
57
|
-
const optional = field.context?.isOptional === true;
|
|
58
|
-
const ast = unsuspended(field);
|
|
59
|
-
if (optional && SchemaAST.isUnion(ast) && ast.types.length === 2) {
|
|
60
|
-
const [definedMember, ...otherDefinedMembers] = ast.types.filter((member) => !SchemaAST.isUndefined(member));
|
|
61
|
-
const kind = definedMember === void 0 || otherDefinedMembers.length > 0 ? void 0 : kindOfUnsuspended(definedMember);
|
|
62
|
-
return kind === void 0 ? void 0 : {
|
|
63
|
-
kind,
|
|
64
|
-
many: false
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
const whole = wholeSuccessMediaOf(ast);
|
|
68
|
-
return whole === void 0 || optional && whole.many ? void 0 : whole;
|
|
69
|
-
};
|
|
70
|
-
const liftOf = (success) => {
|
|
71
|
-
const ast = unsuspended(success.ast);
|
|
72
|
-
const whole = wholeSuccessMediaOf(ast);
|
|
73
|
-
if (whole !== void 0) return {
|
|
74
|
-
fields: [{
|
|
75
|
-
name: void 0,
|
|
76
|
-
...whole
|
|
77
|
-
}],
|
|
78
|
-
rest: void 0
|
|
79
|
-
};
|
|
80
|
-
if (!SchemaAST.isObjects(ast) || ast.encoding !== void 0) return {
|
|
81
|
-
fields: [],
|
|
82
|
-
rest: success
|
|
83
|
-
};
|
|
84
|
-
const fields = ast.propertySignatures.flatMap(({ name, type }) => {
|
|
85
|
-
const field = mediaFieldOf(type);
|
|
86
|
-
return field === void 0 ? [] : [{
|
|
87
|
-
name: String(name),
|
|
88
|
-
...field
|
|
89
|
-
}];
|
|
90
|
-
});
|
|
91
|
-
if (fields.length === 0) return {
|
|
92
|
-
fields,
|
|
93
|
-
rest: success
|
|
94
|
-
};
|
|
95
|
-
const names = new Set(fields.map(({ name }) => name));
|
|
96
|
-
const rest = ast.propertySignatures.filter(({ name }) => !names.has(name));
|
|
97
|
-
const { identifier: _identifierOfWholeSuccess, ...annotationsOfRest } = ast.annotations ?? {};
|
|
98
|
-
return {
|
|
99
|
-
fields,
|
|
100
|
-
rest: rest.length === 0 && ast.indexSignatures.length === 0 ? void 0 : Schema.make(new SchemaAST.Objects(rest, ast.indexSignatures, annotationsOfRest))
|
|
101
|
-
};
|
|
102
|
-
};
|
|
103
37
|
const partsAndEncodedSideOf = (ast) => [
|
|
104
38
|
...SchemaAST.isDeclaration(ast) ? ast.typeParameters : [],
|
|
105
39
|
...SchemaAST.isArrays(ast) ? [...ast.elements, ...ast.rest] : [],
|
|
@@ -124,17 +58,6 @@ const isMisplaced = (action, { rest }) => [
|
|
|
124
58
|
...action.error,
|
|
125
59
|
...rest === void 0 ? [] : [rest]
|
|
126
60
|
].some(({ ast }) => holdsMediaAnywhere(ast));
|
|
127
|
-
const liftedFrom = (lift, success) => lift.fields.flatMap(({ name, kind, many }) => {
|
|
128
|
-
const field = name !== void 0 && Predicate.hasProperty(success, name) ? success[name] : void 0;
|
|
129
|
-
const value = name === void 0 ? success : field;
|
|
130
|
-
const listed = isMediaArray(value) ? value : [];
|
|
131
|
-
const single = isMedia(value) ? [value] : [];
|
|
132
|
-
return (many ? listed : single).map((media) => ({
|
|
133
|
-
kind,
|
|
134
|
-
field: name,
|
|
135
|
-
value: media
|
|
136
|
-
}));
|
|
137
|
-
});
|
|
138
61
|
const mediaOf = ({ name, kind, many }, result) => {
|
|
139
62
|
const values = result.content.flatMap((block) => block.type === kind && block._meta?.["effect-actions/field"] === name ? [{
|
|
140
63
|
data: Base64.encode(block.data),
|
|
@@ -153,4 +76,4 @@ const unliftedFrom = (lift, result) => {
|
|
|
153
76
|
return field.name === void 0 || value === void 0 ? [] : [[field.name, value]];
|
|
154
77
|
})]);
|
|
155
78
|
};
|
|
156
|
-
export { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema,
|
|
79
|
+
export { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, protocols, toolJsonSchema, unliftedFrom };
|
package/dist/webhook/attempt.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { standardWebhooksSignature } from "./signing.mjs";
|
|
2
2
|
import { Clock, Data, Duration, Effect, Option, Schema, Stream } from "effect";
|
|
3
3
|
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
|
|
4
4
|
// src/webhook/attempt.ts
|
|
@@ -15,7 +15,7 @@ const sent = ({ url, subscriptionId, webhookId, body, keys }, checked, answer) =
|
|
|
15
15
|
final: false
|
|
16
16
|
});
|
|
17
17
|
const timestamp = Math.floor((yield* Clock.currentTimeMillis) / 1e3);
|
|
18
|
-
const signed = yield*
|
|
18
|
+
const signed = yield* standardWebhooksSignature(keys, webhookId, timestamp, body);
|
|
19
19
|
const client = HttpClient.withScope(yield* HttpClient.HttpClient);
|
|
20
20
|
const request = HttpClientRequest.post(url).pipe(HttpClientRequest.setHeaders({
|
|
21
21
|
"webhook-id": webhookId,
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { DateTime, Option } from "effect";
|
|
2
|
+
// src/webhook/health.ts
|
|
3
|
+
const deliveryHealth = (retryForMs) => {
|
|
4
|
+
const spent = (failedSince, at) => at - failedSince >= retryForMs;
|
|
5
|
+
const transition = (health, event) => {
|
|
6
|
+
const { lastDeliveryAt } = health;
|
|
7
|
+
switch (health.value) {
|
|
8
|
+
case "Delivering":
|
|
9
|
+
if (event.type === "Refreshed") return health;
|
|
10
|
+
if (event.type === "Delivered") return {
|
|
11
|
+
value: "Delivering",
|
|
12
|
+
lastDeliveryAt: event.at,
|
|
13
|
+
lastError: null
|
|
14
|
+
};
|
|
15
|
+
if (event.final) return event.category === health.lastError ? health : {
|
|
16
|
+
...health,
|
|
17
|
+
lastError: event.category
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
value: spent(event.at, event.at) ? "Suspended" : "Failing",
|
|
21
|
+
lastDeliveryAt,
|
|
22
|
+
lastError: event.category,
|
|
23
|
+
failedSince: event.at
|
|
24
|
+
};
|
|
25
|
+
case "Failing":
|
|
26
|
+
if (event.type === "Refreshed") return health;
|
|
27
|
+
if (event.type === "Delivered") return {
|
|
28
|
+
value: "Delivering",
|
|
29
|
+
lastDeliveryAt: event.at,
|
|
30
|
+
lastError: null
|
|
31
|
+
};
|
|
32
|
+
if (event.final) return {
|
|
33
|
+
value: "Delivering",
|
|
34
|
+
lastDeliveryAt,
|
|
35
|
+
lastError: event.category
|
|
36
|
+
};
|
|
37
|
+
if (spent(health.failedSince, event.at)) return {
|
|
38
|
+
...health,
|
|
39
|
+
value: "Suspended",
|
|
40
|
+
lastError: event.category
|
|
41
|
+
};
|
|
42
|
+
return event.category === health.lastError ? health : {
|
|
43
|
+
...health,
|
|
44
|
+
lastError: event.category
|
|
45
|
+
};
|
|
46
|
+
case "Suspended": return event.type === "Refreshed" ? {
|
|
47
|
+
value: "Delivering",
|
|
48
|
+
lastDeliveryAt,
|
|
49
|
+
lastError: health.lastError
|
|
50
|
+
} : health;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
initialState: {
|
|
55
|
+
value: "Delivering",
|
|
56
|
+
lastDeliveryAt: null,
|
|
57
|
+
lastError: null
|
|
58
|
+
},
|
|
59
|
+
transition
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
const iso = (millis) => DateTime.formatIso(DateTime.makeUnsafe(millis));
|
|
63
|
+
const millisOf = (text) => {
|
|
64
|
+
const millis = Date.parse(text);
|
|
65
|
+
return Number.isNaN(millis) ? Option.none() : Option.some(millis);
|
|
66
|
+
};
|
|
67
|
+
const statusOf = (health) => {
|
|
68
|
+
const lastDeliveryAt = health.lastDeliveryAt === null ? null : iso(health.lastDeliveryAt);
|
|
69
|
+
if (health.value === "Delivering") return {
|
|
70
|
+
active: true,
|
|
71
|
+
lastDeliveryAt,
|
|
72
|
+
lastError: health.lastError
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
active: health.value === "Failing",
|
|
76
|
+
lastDeliveryAt,
|
|
77
|
+
lastError: health.lastError,
|
|
78
|
+
failedSince: iso(health.failedSince)
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
const healthOf = (status) => Option.gen(function* () {
|
|
82
|
+
const lastDeliveryAt = status.lastDeliveryAt === null ? null : yield* millisOf(status.lastDeliveryAt);
|
|
83
|
+
if (status.failedSince === void 0) {
|
|
84
|
+
if (!status.active) return yield* Option.none();
|
|
85
|
+
return {
|
|
86
|
+
value: "Delivering",
|
|
87
|
+
lastDeliveryAt,
|
|
88
|
+
lastError: status.lastError
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
value: status.active ? "Failing" : "Suspended",
|
|
93
|
+
lastDeliveryAt,
|
|
94
|
+
lastError: yield* Option.fromNullOr(status.lastError),
|
|
95
|
+
failedSince: yield* millisOf(status.failedSince)
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
const failingForMs = (health, now) => health.value === "Failing" ? now - health.failedSince : 0;
|
|
99
|
+
export { deliveryHealth, failingForMs, healthOf, statusOf };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { watchParameter } from "../contract/receiving.mjs";
|
|
2
2
|
import { makeRecent } from "../contract/recent.mjs";
|
|
3
|
-
import { constantTimeEqual,
|
|
3
|
+
import { constantTimeEqual, standardWebhooksSignature } from "./signing.mjs";
|
|
4
4
|
import { Clock, Effect, Option, Predicate, Schema } from "effect";
|
|
5
5
|
import { HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
6
6
|
import { Base64, Base64Url } from "effect/encoding";
|
|
@@ -40,7 +40,7 @@ const makeReceiver = (path) => Effect.sync(() => {
|
|
|
40
40
|
const now = Math.floor((yield* Clock.currentTimeMillis) / 1e3);
|
|
41
41
|
if (id === void 0 || !Number.isInteger(timestamp) || Math.abs(now - timestamp) > timestampToleranceSeconds) return unauthorized;
|
|
42
42
|
const text = yield* Effect.orElseSucceed(request.text, () => "");
|
|
43
|
-
const expected = yield*
|
|
43
|
+
const expected = yield* standardWebhooksSignature([place.key], id, timestamp, text);
|
|
44
44
|
if (!signatures.some((each) => constantTimeEqual(each, expected))) return unauthorized;
|
|
45
45
|
const body = decodeBody(text);
|
|
46
46
|
if (Option.isNone(body)) return HttpServerResponse.empty({ status: 400 });
|
package/dist/webhook/signing.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { sha256Hex } from "../contract/digest.mjs";
|
|
2
2
|
import { Effect } from "effect";
|
|
3
3
|
import { Base64, Hex } from "effect/encoding";
|
|
4
|
+
import { Mac } from "effect/crypto";
|
|
4
5
|
// src/webhook/signing.ts
|
|
5
6
|
const encoder = new TextEncoder();
|
|
6
7
|
const hmac = (key, content) => Effect.promise(async () => {
|
|
@@ -10,16 +11,8 @@ const hmac = (key, content) => Effect.promise(async () => {
|
|
|
10
11
|
}, false, ["sign"]);
|
|
11
12
|
return new Uint8Array(await crypto.subtle.sign("HMAC", imported, encoder.encode(content)));
|
|
12
13
|
});
|
|
13
|
-
|
|
14
|
-
* A delivery's `webhook-signature`: Standard Webhooks' `v1,` HMAC-SHA256 of `id.timestamp.body`
|
|
15
|
-
* under each key, space apart, so a receiver mid-rotation verifies under either.
|
|
16
|
-
*/
|
|
17
|
-
const signature = (keys, id, timestamp, body) => Effect.map(Effect.forEach(keys, (key) => hmac(key, `${id}.${timestamp}.${body}`)), (signed) => signed.map((bytes) => `v1,${Base64.encode(bytes)}`).join(" "));
|
|
14
|
+
const standardWebhooksSignature = (keys, id, timestamp, body) => Effect.map(Effect.forEach(keys, (key) => hmac(key, `${id}.${timestamp}.${body}`)), (signed) => signed.map((bytes) => `v1,${Base64.encode(bytes)}`).join(" "));
|
|
18
15
|
const subscriptionId = (key) => Effect.map(sha256Hex(key), (hex) => `sub_${hex.slice(0, 32)}`);
|
|
19
16
|
const randomToken = Effect.sync(() => Hex.encode(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
|
|
20
|
-
const constantTimeEqual = (a, b) =>
|
|
21
|
-
|
|
22
|
-
const right = encoder.encode(b);
|
|
23
|
-
return left.length === right.length && left.reduce((differs, byte, index) => differs | byte ^ (right[index] ?? 0), 0) === 0;
|
|
24
|
-
};
|
|
25
|
-
export { constantTimeEqual, randomToken, signature, subscriptionId };
|
|
17
|
+
const constantTimeEqual = (a, b) => Mac.timingSafeEqual(encoder.encode(a), encoder.encode(b));
|
|
18
|
+
export { constantTimeEqual, randomToken, standardWebhooksSignature, subscriptionId };
|
package/dist/webhook/stored.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { reported } from "../contract/reported.mjs";
|
|
2
2
|
import { CallbackUrl, WebhookSecret } from "../contract/callback.mjs";
|
|
3
3
|
import { DeliveryStatus } from "../contract/subscribe.mjs";
|
|
4
|
-
import { Duration, Effect, Option, Queue, Schema, Semaphore } from "effect";
|
|
4
|
+
import { Cause, Duration, Effect, Option, Queue, Schema, Semaphore } from "effect";
|
|
5
5
|
import { KeyValueStore } from "effect/persistence";
|
|
6
6
|
// src/webhook/stored.ts
|
|
7
7
|
const Stored = Schema.Struct({
|
|
@@ -14,34 +14,44 @@ const Stored = Schema.Struct({
|
|
|
14
14
|
watermark: Schema.NullOr(Schema.String),
|
|
15
15
|
status: DeliveryStatus
|
|
16
16
|
});
|
|
17
|
-
const prefix = "effect-actions/webhook";
|
|
18
|
-
const Index = Schema.Array(Schema.String);
|
|
17
|
+
const prefix = "effect-actions/webhook/";
|
|
19
18
|
const flushTimeout = Duration.seconds(5);
|
|
19
|
+
var UnfinishedWrites = class UnfinishedWrites extends Schema.TaggedError()("UnfinishedWrites", {
|
|
20
|
+
ids: Schema.Array(Schema.String),
|
|
21
|
+
message: Schema.String
|
|
22
|
+
}) {
|
|
23
|
+
static of(ids) {
|
|
24
|
+
return new UnfinishedWrites({
|
|
25
|
+
ids,
|
|
26
|
+
message: `Webhook.layer closed with subscriptions ${ids.join(", ")} unwritten after ${Duration.format(flushTimeout)}: the store keeps each one's last write`
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
};
|
|
20
30
|
const makeWriteBehindStorage = (store) => Effect.gen(function* () {
|
|
21
|
-
const records = KeyValueStore.toSchemaStore(KeyValueStore.prefix(store,
|
|
22
|
-
const
|
|
23
|
-
let indexed = new Set(yield* Effect.orDie(Effect.map(index.get(prefix), Option.getOrElse(() => []))));
|
|
31
|
+
const records = KeyValueStore.toSchemaStore(KeyValueStore.prefix(store, prefix), Stored);
|
|
32
|
+
const kept = new Set(yield* Effect.orDie(records.keys));
|
|
24
33
|
const pending = /* @__PURE__ */ new Map();
|
|
25
34
|
const marked = yield* Queue.sliding(1);
|
|
26
35
|
const writing = Semaphore.makeUnsafe(1);
|
|
27
|
-
const
|
|
28
|
-
|
|
36
|
+
const written = (id, record) => Effect.andThen(record === void 0 ? records.remove(id) : records.set(id, record), Effect.sync(() => {
|
|
37
|
+
if (record === void 0) kept.delete(id);
|
|
38
|
+
else kept.add(id);
|
|
29
39
|
}));
|
|
30
|
-
const removedThenUnlisted = (id) => Effect.andThen(records.remove(id), Effect.suspend(() => indexed.has(id) ? listed(new Set([...indexed].filter((each) => each !== id))) : Effect.void));
|
|
31
|
-
const listedThenKept = (id, record) => Effect.andThen(Effect.suspend(() => indexed.has(id) ? Effect.void : listed(/* @__PURE__ */ new Set([...indexed, id]))), records.set(id, record));
|
|
32
|
-
const written = (id, record) => record === void 0 ? removedThenUnlisted(id) : listedThenKept(id, record);
|
|
33
40
|
const clearedUnlessRemarked = (id, record) => Effect.sync(() => {
|
|
34
41
|
if (pending.get(id) === record) pending.delete(id);
|
|
35
42
|
});
|
|
36
43
|
const flushed = writing.withPermits(1)(Effect.suspend(() => Effect.forEach([...pending], ([id, record]) => written(id, record).pipe(Effect.andThen(clearedUnlessRemarked(id, record)), Effect.catchCause(reported)), { discard: true })));
|
|
37
44
|
yield* Effect.forkScoped(Effect.forever(Effect.andThen(Queue.take(marked), flushed)));
|
|
38
|
-
yield* Effect.addFinalizer(() =>
|
|
45
|
+
yield* Effect.addFinalizer(() => Effect.timeoutOrElse(flushed, {
|
|
46
|
+
duration: flushTimeout,
|
|
47
|
+
orElse: () => reported(Cause.fail(UnfinishedWrites.of([...pending.keys()])))
|
|
48
|
+
}));
|
|
39
49
|
return {
|
|
40
50
|
mark: (id, record) => {
|
|
41
51
|
pending.set(id, record);
|
|
42
52
|
Queue.offerUnsafe(marked, void 0);
|
|
43
53
|
},
|
|
44
|
-
ids: () => [.../* @__PURE__ */ new Set([...
|
|
54
|
+
ids: () => [.../* @__PURE__ */ new Set([...kept, ...pending.keys()])],
|
|
45
55
|
get: (id) => pending.has(id) ? Effect.succeed(Option.fromUndefinedOr(pending.get(id))) : records.get(id)
|
|
46
56
|
};
|
|
47
57
|
});
|
|
@@ -7,7 +7,8 @@ import { randomToken, subscriptionId } from "./signing.mjs";
|
|
|
7
7
|
import { pushed, refusalIn } from "../contract/push.mjs";
|
|
8
8
|
import { checkedHost } from "./address.mjs";
|
|
9
9
|
import { attempt, challenged } from "./attempt.mjs";
|
|
10
|
-
import {
|
|
10
|
+
import { deliveryHealth, failingForMs, healthOf, statusOf } from "./health.mjs";
|
|
11
|
+
import { Cause, Clock, Context, DateTime, Deferred, Duration, Effect, Exit, Fiber, FiberMap, Match, Option, RcMap, Schedule, Schema, Scope, Semaphore, Stream } from "effect";
|
|
11
12
|
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
12
13
|
// src/webhook/subscriptions.ts
|
|
13
14
|
const minTtl = Duration.minutes(1);
|
|
@@ -16,10 +17,6 @@ const maxBody = 262144;
|
|
|
16
17
|
const encoder = new TextEncoder();
|
|
17
18
|
const terminatedEnvelopeRetries = Schedule.exponential(Duration.seconds(1)).pipe(Schedule.upTo({ times: 3 }));
|
|
18
19
|
const iso = (millis) => DateTime.formatIso(DateTime.makeUnsafe(millis));
|
|
19
|
-
const resumedWithFreshBudget = (status) => status.active ? status : {
|
|
20
|
-
...Struct.omit(status, ["failedSince"]),
|
|
21
|
-
active: true
|
|
22
|
-
};
|
|
23
20
|
const grantOf = (ttlMs, policy) => Duration.clamp(ttlMs === null || ttlMs === void 0 ? policy.maxTtl : Duration.millis(ttlMs), {
|
|
24
21
|
minimum: minTtl,
|
|
25
22
|
maximum: policy.maxTtl
|
|
@@ -49,21 +46,26 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
49
46
|
secret: subscription.secret,
|
|
50
47
|
expiresAt: subscription.expiresAt,
|
|
51
48
|
watermark: subscription.watermark,
|
|
52
|
-
status: subscription.
|
|
49
|
+
status: statusOf(subscription.health)
|
|
53
50
|
});
|
|
54
51
|
});
|
|
55
52
|
const dropped = (id) => Effect.sync(() => storage?.mark(id, void 0));
|
|
56
53
|
const verified = /* @__PURE__ */ new Map();
|
|
57
54
|
const locks = yield* RcMap.make({ lookup: (_id) => Semaphore.make(1) });
|
|
58
|
-
const
|
|
59
|
-
const
|
|
60
|
-
|
|
55
|
+
const health = deliveryHealth(Duration.toMillis(policy.retryFor));
|
|
56
|
+
const transitioned = (subscription, event) => Effect.suspend(() => {
|
|
57
|
+
const next = health.transition(subscription.health, event);
|
|
58
|
+
if (next === subscription.health) return Effect.void;
|
|
59
|
+
subscription.health = next;
|
|
60
|
+
return kept(subscription);
|
|
61
|
+
});
|
|
62
|
+
const waitingAsLongAsFailing = (subscription) => Schedule.modifyDelay(Schedule.forever, () => Effect.map(Clock.currentTimeMillis, (now) => Duration.clamp(Duration.millis(failingForMs(subscription.health, now)), {
|
|
61
63
|
minimum: Duration.seconds(1),
|
|
62
64
|
maximum: Duration.minutes(5)
|
|
63
65
|
})));
|
|
64
66
|
const retrying = (subscription) => ({
|
|
65
67
|
schedule: waitingAsLongAsFailing(subscription),
|
|
66
|
-
while: (
|
|
68
|
+
while: () => subscription.health.value === "Failing"
|
|
67
69
|
});
|
|
68
70
|
const locked = (id) => (effect) => Effect.scoped(Effect.flatMap(RcMap.get(locks, id), (lock) => lock.withPermits(1)(effect)));
|
|
69
71
|
const asSubscriber = (subscription, effect) => Effect.updateContext(effect, () => subscription.context);
|
|
@@ -74,31 +76,17 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
74
76
|
body,
|
|
75
77
|
keys: subscription.previous !== void 0 && now < subscription.previous.until ? [subscription.secret.key, subscription.previous.key] : [subscription.secret.key]
|
|
76
78
|
}, trusted(subscription.url, policy.allowedCallbacks) ? Effect.void : checkedHost(subscription.url, policy.dns)), built));
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
return failure !== void 0 && status.lastError === failure.category && status.failedSince !== void 0 ? Effect.void : kept(subscription);
|
|
89
|
-
}));
|
|
90
|
-
const suspended = (subscription) => Effect.andThen(Effect.andThen(Effect.sync(() => {
|
|
91
|
-
subscription.status = {
|
|
92
|
-
...subscription.status,
|
|
93
|
-
active: false
|
|
94
|
-
};
|
|
95
|
-
}), kept(subscription)), Effect.never);
|
|
96
|
-
const abandonedResettingBudget = (subscription) => Effect.andThen(Effect.sync(() => {
|
|
97
|
-
subscription.status = Struct.omit(subscription.status, ["failedSince"]);
|
|
98
|
-
}), kept(subscription));
|
|
99
|
-
const delivered = (subscription, webhookId, body) => post(subscription, webhookId, body).pipe(Effect.tapError((failure) => recorded(subscription, failure)), Effect.retry(retrying(subscription)), Effect.matchEffect({
|
|
100
|
-
onSuccess: () => Effect.as(recorded(subscription, void 0), true),
|
|
101
|
-
onFailure: (failure) => failure.final ? Effect.as(abandonedResettingBudget(subscription), false) : suspended(subscription)
|
|
79
|
+
const delivered = (subscription, webhookId, body) => post(subscription, webhookId, body).pipe(Effect.tapError(({ category, final }) => Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
|
|
80
|
+
type: "AttemptFailed",
|
|
81
|
+
category,
|
|
82
|
+
final,
|
|
83
|
+
at
|
|
84
|
+
}))), Effect.retry(retrying(subscription)), Effect.matchEffect({
|
|
85
|
+
onSuccess: () => Effect.as(Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
|
|
86
|
+
type: "Delivered",
|
|
87
|
+
at
|
|
88
|
+
})), true),
|
|
89
|
+
onFailure: () => subscription.health.value === "Suspended" ? Effect.never : Effect.succeed(false)
|
|
102
90
|
}));
|
|
103
91
|
const gapped = (subscription, cursor) => Effect.flatMap(randomToken, (token) => delivered(subscription, `msg_gap_${token}`, JSON.stringify({
|
|
104
92
|
type: "gap",
|
|
@@ -146,7 +134,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
146
134
|
});
|
|
147
135
|
const finished = (subscription) => Effect.suspend(() => holds(subscription) ? Effect.andThen(ended(subscription), dropped(subscription.id)) : Effect.void);
|
|
148
136
|
const workerOf = (subscription, input, cursor, confirmation) => Effect.raceFirst(pushed((from) => Stream.unwrap(Effect.map(subscription.feed.stream(input), (read) => read(from))), cursor, deliverTo(subscription, input, confirmation), {
|
|
149
|
-
|
|
137
|
+
positions: "watermark",
|
|
150
138
|
resumesUnconfirmed: Deferred.isDoneUnsafe(confirmation)
|
|
151
139
|
}), expired(subscription)).pipe(Effect.exit, Effect.tap(() => finished(subscription)), Effect.flatMap((exit) => {
|
|
152
140
|
if (Deferred.isDoneUnsafe(confirmation)) return Exit.isFailure(exit) ? terminated(subscription, exit.cause) : Effect.void;
|
|
@@ -185,7 +173,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
185
173
|
}));
|
|
186
174
|
}));
|
|
187
175
|
const refreshed = (subscription, granted, input, now) => Effect.gen(function* () {
|
|
188
|
-
const {
|
|
176
|
+
const { health: before, watermark } = subscription;
|
|
189
177
|
const renewed = {
|
|
190
178
|
...subscription,
|
|
191
179
|
...granted,
|
|
@@ -193,7 +181,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
193
181
|
key: subscription.secret.key,
|
|
194
182
|
until: now + Duration.toMillis(rotationGrace)
|
|
195
183
|
} },
|
|
196
|
-
|
|
184
|
+
health: health.transition(before, { type: "Refreshed" })
|
|
197
185
|
};
|
|
198
186
|
const confirmation = yield* confirmedAt(watermark);
|
|
199
187
|
yield* swapHeldWorker(renewed.id, renewed, workerOf(renewed, input, watermark, confirmation));
|
|
@@ -204,7 +192,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
204
192
|
refreshBefore: iso(renewed.expiresAt),
|
|
205
193
|
cursor: watermark,
|
|
206
194
|
truncated: false,
|
|
207
|
-
deliveryStatus:
|
|
195
|
+
deliveryStatus: statusOf(before)
|
|
208
196
|
};
|
|
209
197
|
});
|
|
210
198
|
const heldOf = (fields) => ({
|
|
@@ -233,6 +221,10 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
233
221
|
if (expiresAt <= (yield* Clock.currentTimeMillis)) return yield* dropped(id);
|
|
234
222
|
const input = yield* Schema.decodeEffect(Schema.toCodecJson(feed.event.input))(record.input);
|
|
235
223
|
const identity = yield* Schema.decodeEffect(Schema.toCodecJson(schema))(record.identity);
|
|
224
|
+
const restoredHealth = yield* Option.match(healthOf(record.status), {
|
|
225
|
+
onNone: () => Effect.die(/* @__PURE__ */ new Error(`The kept webhook subscription ${id} has a delivery status no subscription reaches, ${JSON.stringify(record.status)} (unsubscribe it to remove the record, then subscribe again)`)),
|
|
226
|
+
onSome: Effect.succeed
|
|
227
|
+
});
|
|
236
228
|
const principal = keyed.principal(identity);
|
|
237
229
|
const current = yield* idOf({
|
|
238
230
|
feed,
|
|
@@ -254,11 +246,11 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
254
246
|
secret,
|
|
255
247
|
context: Context.add(built, feed.event.caller, identity),
|
|
256
248
|
expiresAt,
|
|
257
|
-
|
|
249
|
+
health: restoredHealth,
|
|
258
250
|
watermark: record.watermark
|
|
259
251
|
});
|
|
260
252
|
const confirmation = yield* confirmedAt(record.watermark);
|
|
261
|
-
yield* swapHeldWorker(current, subscription,
|
|
253
|
+
yield* swapHeldWorker(current, subscription, restoredHealth.value === "Suspended" ? Effect.andThen(expired(subscription), finished(subscription)) : workerOf(subscription, input, record.watermark, confirmation));
|
|
262
254
|
if (current !== id) yield* kept(subscription);
|
|
263
255
|
}).pipe(Effect.catchCause(reported));
|
|
264
256
|
const serve = (feeds, keyed) => Effect.gen(function* () {
|
|
@@ -303,11 +295,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
303
295
|
url,
|
|
304
296
|
feed,
|
|
305
297
|
principal,
|
|
306
|
-
|
|
307
|
-
active: true,
|
|
308
|
-
lastDeliveryAt: null,
|
|
309
|
-
lastError: null
|
|
310
|
-
},
|
|
298
|
+
health: health.initialState,
|
|
311
299
|
watermark: cursor
|
|
312
300
|
});
|
|
313
301
|
yield* verify(subscription, now);
|
package/docs/Action-failures.md
CHANGED
|
@@ -23,7 +23,7 @@ What you see when something is wrong, and the fix. Search for a fragment of the
|
|
|
23
23
|
|
|
24
24
|
## Where an implementation is served
|
|
25
25
|
|
|
26
|
-
- `Type 'CurrentUser' is not assignable to type 'never'`, or `Request<"Requires", CurrentUser>` still owed,
|
|
26
|
+
- `Type 'CurrentUser' is not assignable to type 'never'`, or `Request<"Requires", CurrentUser>` still owed, where a public action's handler reads one, alone on its layer or beside protected actions: authentication provides the identity to protected requests only. Make the action protected.
|
|
27
27
|
- `Type '{ readonly "A builder yields the caller, which a server has per request: yield it in a handler or an authorizer": { readonly caller: CurrentUser; readonly builderOf: "createNote" | ...; }; }' is not assignable to type 'never'` where a server is launched: the builder of the `implement` call whose actions `builderOf` names, or the Effect building its authorizer, yields the caller, which a builder would resolve once at startup. Move the `yield*` into the handler or the authorizer.
|
|
28
28
|
- `is missing the following properties from type 'Scope'` at each `it.effect` that runs the routes: a builder, or the Effect building an authorizer, yields the caller or another per-request service, which a builder would resolve once at startup. Move the `yield*` into the handler or the authorizer.
|
|
29
29
|
- `HttpRouter.Request<"Requires", X>` still owed, or `Type 'X' is not assignable to type 'never'` at `runMain`, although `X`, a store the authorizer reads, is provided at startup: what a plain authorizer yields is a request-time requirement, and this one yields `X` on every call. Make `authorize` an Effect that yields `X` once and returns the function ([Authorize calls](Action.md#authorize-calls)).
|
package/docs/ActionCli.md
CHANGED
|
@@ -42,7 +42,7 @@ The aggregate is [assistant/src/commands.ts](../examples/assistant/src/commands.
|
|
|
42
42
|
|
|
43
43
|
## Call a server from commands
|
|
44
44
|
|
|
45
|
-
Pass the HTTP binding to `remote`. The program imports the binding alone, never a handler. The connection is the `client` option, an `ActionHttp.client` ([ActionHttp.md](ActionHttp.md#call-the-api-from-effect)), its rules on `ActionCli.Calling`'s `client`, shared by `remote` and `remoteCommand`: [notes-service/src/commands.ts](../examples/notes-service/src/commands.ts) requires a token, mapping its absence to an error that says what to do, and [kitchen-sink/src/cli.ts](../examples/kitchen-sink/src/cli.ts) adds
|
|
45
|
+
Pass the HTTP binding to `remote`. The program imports the binding alone, never a handler. The connection is the `client` option, an `ActionHttp.client` ([ActionHttp.md](ActionHttp.md#call-the-api-from-effect)), its rules on `ActionCli.Calling`'s `client`, shared by `remote` and `remoteCommand`: [notes-service/src/commands.ts](../examples/notes-service/src/commands.ts) requires a token, mapping its absence to an error that says what to do, and [kitchen-sink/src/cli.ts](../examples/kitchen-sink/src/cli.ts) adds the `X-Workspace` header, reads an optional token for a public command. The host provides `HttpClient` (`NodeHttpClient.layerUndici`) in [notes-service/src/cli.ts](../examples/notes-service/src/cli.ts).
|
|
46
46
|
|
|
47
47
|
- **Split one binding into groups of commands**, one `remote` per group with its own `actions`; what each group's `client` needs is on `ActionCli.Calling`'s `client`.
|
|
48
48
|
- **Test a remote command the same way** as a local one, with `Testing.layer(routes)` provided as its `HttpClient` ([Testing.md](Testing.md#test-routes-in-memory)). Export the command from a module apart from the entrypoint that runs it ([notes-service/test/commands.test.ts](../examples/notes-service/test/commands.test.ts)).
|
package/docs/ActionHttp.md
CHANGED
|
@@ -108,7 +108,7 @@ const server = Layer.unwrap(
|
|
|
108
108
|
Layer.launch(server).pipe(NodeRuntime.runMain());
|
|
109
109
|
```
|
|
110
110
|
|
|
111
|
-
- A service a verifier, handler or authorizer reads per request is provided by router middleware around the layer ([kitchen-sink/src/
|
|
111
|
+
- A service a verifier, handler or authorizer reads per request is provided by router middleware around the layer ([kitchen-sink/src/identity/workspace-header.ts](../examples/kitchen-sink/src/identity/workspace-header.ts), read by the verifier, provided in [kitchen-sink/src/routes.ts](../examples/kitchen-sink/src/routes.ts)), or, for a handler or authorizer, by `ActionHttp.LayerOptions.middleware`; declaring it, and why not `HttpRouter.provideRequest`, are on `ActionHttp.layer`.
|
|
112
112
|
|
|
113
113
|
### Split a binding across layers, and add middleware
|
|
114
114
|
|
package/docs/ActionMcp.md
CHANGED
|
@@ -27,7 +27,7 @@ export const routes = Layer.mergeAll(
|
|
|
27
27
|
- Claude Code 2.1 and Codex CLI 0.162 connect: `claude mcp add --transport http <name> <url>/mcp --header "Authorization: Bearer <token>"`, `codex mcp add <name> --url <url>/mcp --bearer-token-env-var <VAR>`; [mcp-tools](../examples/mcp-tools/README.md#connect-a-client) has stdio and Claude Desktop.
|
|
28
28
|
- Where an endpoint without `authentication` listens, and its body limit: [mcp-tools/src/server.ts](../examples/mcp-tools/src/server.ts).
|
|
29
29
|
- **On a serverless host**, such as Cloudflare Workers, pass `requestScoped: true`: [notes-service/src/worker.ts](../examples/notes-service/src/worker.ts). For an endpoint in a Cloudflare Durable Object: the `@gjermundgaraba/effect-actions-cloudflare` package's docs.
|
|
30
|
-
-
|
|
30
|
+
- `McpServer.middleware` and `McpServer.visibility` provided around the endpoint run for its tools and its native features alike. A limit that must hold on every surface goes in the handlers: [kitchen-sink/src/issues/write-limit.ts](../examples/kitchen-sink/src/issues/write-limit.ts).
|
|
31
31
|
|
|
32
32
|
## Serve tools over stdio
|
|
33
33
|
|
|
@@ -77,7 +77,7 @@ Give the success an `Action.Image` field and return its bytes and MIME type from
|
|
|
77
77
|
|
|
78
78
|
Name the protected actions' authentication descriptor as `authentication` and provide its provider to the routes: [notes-service/src/routes.ts](../examples/notes-service/src/routes.ts). Write the [descriptor](Authentication.md#declare-how-callers-sign-in) and its [provider](Authentication.md#verify-credentials) once for every surface, and [publish discovery](Authentication.md#publish-oauth-discovery) so an MCP client finds where to sign in. What a signed-in caller may do is each implementation's [`authorize`](Action.md#authorize-calls), which runs on every call of a protected tool.
|
|
79
79
|
|
|
80
|
-
- **One endpoint or two.** What a mixed endpoint, serving public and protected tools, shows and runs signed out is on `ActionMcp.LayerHttpOptions`'s `authentication`.
|
|
80
|
+
- **One endpoint or two.** What a mixed endpoint, serving public and protected tools, shows and runs signed out, and how to hide its protected tools then, is on `ActionMcp.LayerHttpOptions`'s `authentication`.
|
|
81
81
|
- Test as a signed-in caller ([Testing.md](Testing.md#test-as-a-signed-in-caller)): [notes-service/test/routes.test.ts](../examples/notes-service/test/routes.test.ts).
|
|
82
82
|
|
|
83
83
|
## Serve events
|
package/docs/ActionRpc.md
CHANGED
|
@@ -185,10 +185,6 @@ import { RpcMiddleware } from "effect/rpc";
|
|
|
185
185
|
|
|
186
186
|
import { defaultRoom, roomHeader } from "./Chat.js";
|
|
187
187
|
|
|
188
|
-
/**
|
|
189
|
-
* The room a message is about. A request-time service: handlers and `authorize` read it per
|
|
190
|
-
* call, and it has no Layer, because no one value of it is right for a whole server.
|
|
191
|
-
*/
|
|
192
188
|
export class CurrentRoom extends Context.Service<CurrentRoom, string>()(
|
|
193
189
|
"live-rpc/CurrentRoom"
|
|
194
190
|
) {}
|
package/docs/ActionToolkit.md
CHANGED
|
@@ -45,6 +45,7 @@ export const actingFor = (member: Member) =>
|
|
|
45
45
|
[assistant/src/agent.ts](../examples/assistant/src/agent.ts) runs the turns and provides `layer` with its startup services, with a scripted model in [assistant/src/scripted.ts](../examples/assistant/src/scripted.ts). What a call returns, a refusal and arguments that do not decode included, is on `ActionToolkit.make`; the options' rules are on `ActionToolkit.Options`.
|
|
46
46
|
|
|
47
47
|
- **Let the model read its tools' results** by asking again: [kitchen-sink/src/assistant/handlers.ts](../examples/kitchen-sink/src/assistant/handlers.ts).
|
|
48
|
+
- **Show the model an image** by giving the success an `Action.Image` field, as `get_camera_snapshot` does in [mcp-tools/src/printers/Printers.ts](../examples/mcp-tools/src/printers/Printers.ts): the model reads the image as a file and the other fields as JSON. Where an image is lifted is on `Action.Image`; what a provider that takes only text reads is on `ActionToolkit.make`.
|
|
48
49
|
- Where a model must not get every action, list the tools ([Action.md](Action.md#define-a-contract)): [kitchen-sink/src/issues/assistant.ts](../examples/kitchen-sink/src/issues/assistant.ts).
|
|
49
50
|
- A turn's tool calls, the approved calls of an answering turn included, run concurrently unless `generateText` is given a `concurrency`: [assistant/src/tasks/store.ts](../examples/assistant/src/tasks/store.ts) locks each change.
|
|
50
51
|
- **A model loop behind a route.** Yield `toolkit` and the model in the implementation's builder, and provide `layer` to the route's layer, `ActionHttp.layer(Http, ask).pipe(Layer.provide(layer))`, so the tools share the routes' build ([Action.md](Action.md#share-one-build-across-servers)): [kitchen-sink/src/assistant/handlers.ts](../examples/kitchen-sink/src/assistant/handlers.ts), keeping each caller's `Chat` in [conversations.ts](../examples/kitchen-sink/src/assistant/conversations.ts), with a scripted model in [demo-model.ts](../examples/kitchen-sink/src/assistant/demo-model.ts) that the entrypoint provides through [kitchen-sink/src/memory.ts](../examples/kitchen-sink/src/memory.ts), tested over HTTP in [kitchen-sink/test/assistant/assistant.test.ts](../examples/kitchen-sink/test/assistant/assistant.test.ts). Name the files as it does, the route's contract `Assistant.ts` and the loop `handlers.ts`, from the first one written.
|
|
@@ -6,30 +6,27 @@ A message the library throws says its fix; for a compiler diagnostic or Effect's
|
|
|
6
6
|
|
|
7
7
|
## Read request context in a verifier
|
|
8
8
|
|
|
9
|
-
A verifier may read per-request services: the request, or one of your own, such as the
|
|
9
|
+
A verifier may read per-request services: the request, or one of your own, such as the workspace a request's header names, which native router middleware provides:
|
|
10
10
|
|
|
11
|
-
```ts example=kitchen-sink/src/
|
|
11
|
+
```ts example=kitchen-sink/src/identity/workspace-header.ts
|
|
12
12
|
import { Context, Effect, Option } from "effect";
|
|
13
13
|
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
export
|
|
21
|
-
|
|
22
|
-
)
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
route,
|
|
29
|
-
Tenant,
|
|
30
|
-
Option.fromNullishOr(request.headers["x-workspace"])
|
|
31
|
-
)
|
|
15
|
+
export class WorkspaceHeader extends Context.Service<
|
|
16
|
+
WorkspaceHeader,
|
|
17
|
+
Option.Option<string>
|
|
18
|
+
>()("tracker/WorkspaceHeader") {}
|
|
19
|
+
|
|
20
|
+
export const readWorkspaceHeader = HttpRouter.middleware<{
|
|
21
|
+
provides: WorkspaceHeader;
|
|
22
|
+
}>()((route) =>
|
|
23
|
+
Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) =>
|
|
24
|
+
Effect.provideService(
|
|
25
|
+
route,
|
|
26
|
+
WorkspaceHeader,
|
|
27
|
+
Option.fromNullishOr(request.headers["x-workspace"])
|
|
32
28
|
)
|
|
29
|
+
)
|
|
33
30
|
);
|
|
34
31
|
```
|
|
35
32
|
|
|
@@ -8,7 +8,7 @@ What you see when something is wrong, and the fix: compiler diagnostics and erro
|
|
|
8
8
|
- `Property 'authentication' is missing`, or `No overload matches this call` with `"Protected actions take options naming their authentication"` or `"Authentication descriptor does not cover every protected action"`, at `ActionHttp.make`, `ActionRpc.make` or `ActionMcp.layerHttp`: a protected action is served and no descriptor is named. Give `{ authentication: Login }` ([Declare how callers sign in](Authentication.md#declare-how-callers-sign-in)).
|
|
9
9
|
- `Type 'Other' is not assignable to type 'CurrentUser'` under `Descriptor<…>`, at `authentication`: the descriptor authenticates another identity than the action's `caller`. Name the descriptor made for the caller's identity service.
|
|
10
10
|
- `is not assignable to type 'Forbidden | Unauthenticated'`, or `Property '…' is missing in type`, at `layer`'s verifier: it fails with an error that is neither a refusal nor one its descriptor declares, or succeeds with a value that is not the identity. Declare the error in the descriptor's `error`, or map it to a refusal where it is the caller's.
|
|
11
|
-
- `Request<"Requires",
|
|
11
|
+
- `Request<"Requires", WorkspaceHeader>` still owed although its middleware's layer is provided: it is in one `Layer.provide([...])` array with the provider, and an array's layers provide to the routes, not to one another. Provide it in a later `Layer.provide` of its own ([Read request context in a verifier](Authentication-advanced.md#read-request-context-in-a-verifier)).
|
|
12
12
|
|
|
13
13
|
## Signing in
|
|
14
14
|
|