liminal 0.17.10 → 0.17.12

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.
Files changed (63) hide show
  1. package/Accumulator.ts +2 -2
  2. package/Actor.ts +2 -2
  3. package/Audition.ts +2 -2
  4. package/CHANGELOG.md +17 -1
  5. package/Client.ts +2 -2
  6. package/ClientDirectory.ts +2 -2
  7. package/Method.ts +6 -6
  8. package/_diagnostic.ts +3 -0
  9. package/_util/socket.ts +20 -0
  10. package/browser/BrowserActorNamespace.ts +213 -0
  11. package/browser/index.ts +1 -0
  12. package/dist/Accumulator.js +2 -2
  13. package/dist/Accumulator.js.map +1 -1
  14. package/dist/Actor.js +2 -2
  15. package/dist/Actor.js.map +1 -1
  16. package/dist/Audition.js +2 -2
  17. package/dist/Audition.js.map +1 -1
  18. package/dist/Client.js +2 -2
  19. package/dist/Client.js.map +1 -1
  20. package/dist/ClientDirectory.js +2 -2
  21. package/dist/ClientDirectory.js.map +1 -1
  22. package/dist/Method.d.ts +4 -4
  23. package/dist/Method.js.map +1 -1
  24. package/dist/_diagnostic.d.ts +4 -0
  25. package/dist/_diagnostic.js +3 -0
  26. package/dist/_diagnostic.js.map +1 -0
  27. package/dist/_util/socket.d.ts +4 -0
  28. package/dist/_util/socket.js +18 -0
  29. package/dist/_util/socket.js.map +1 -0
  30. package/dist/browser/BrowserActorNamespace.d.ts +16 -0
  31. package/dist/browser/BrowserActorNamespace.js +112 -0
  32. package/dist/browser/BrowserActorNamespace.js.map +1 -0
  33. package/dist/browser/index.d.ts +1 -0
  34. package/dist/browser/index.js +2 -0
  35. package/dist/browser/index.js.map +1 -0
  36. package/dist/package.json +47 -0
  37. package/dist/tsconfig.tsbuildinfo +1 -1
  38. package/dist/workerd/WorkerdActorNamespace.d.ts +23 -0
  39. package/dist/workerd/WorkerdActorNamespace.js +152 -0
  40. package/dist/workerd/WorkerdActorNamespace.js.map +1 -0
  41. package/dist/workerd/index.d.ts +1 -0
  42. package/dist/workerd/index.js +2 -0
  43. package/dist/workerd/index.js.map +1 -0
  44. package/package.json +20 -3
  45. package/tsconfig.json +5 -3
  46. package/workerd/WorkerdActorNamespace.ts +361 -0
  47. package/workerd/index.ts +1 -0
  48. package/_constants.ts +0 -1
  49. package/_util/Diagnostic.ts +0 -16
  50. package/_util/boundLayer.ts +0 -11
  51. package/_util/logCause.ts +0 -8
  52. package/dist/_constants.d.ts +0 -1
  53. package/dist/_constants.js +0 -2
  54. package/dist/_constants.js.map +0 -1
  55. package/dist/_util/Diagnostic.d.ts +0 -5
  56. package/dist/_util/Diagnostic.js +0 -10
  57. package/dist/_util/Diagnostic.js.map +0 -1
  58. package/dist/_util/boundLayer.d.ts +0 -2
  59. package/dist/_util/boundLayer.js +0 -4
  60. package/dist/_util/boundLayer.js.map +0 -1
  61. package/dist/_util/logCause.d.ts +0 -2
  62. package/dist/_util/logCause.js +0 -7
  63. package/dist/_util/logCause.js.map +0 -1
@@ -0,0 +1,152 @@
1
+ import { Layer, Effect, Scope, Schema as S, Context, ManagedRuntime, ConfigProvider, Duration, flow, String, Array, Encoding, Option, } from "effect";
2
+ import { Binding, DoState, NativeRequest } from "effect-workerd";
3
+ import { SecWebSocketProtocol, close } from "effect-workerd/socket_util";
4
+ import { HttpServerResponse, HttpClient, FetchHttpClient } from "effect/unstable/http";
5
+ import { boundLayer } from "liminal-util/boundLayer";
6
+ import { logCause } from "liminal-util/logCause";
7
+ import { diagnostic } from "../_diagnostic.js";
8
+ import * as Mutex from "../_util/Mutex.js";
9
+ import { encodeJsonString, decodeJsonString } from "../_util/schema.js";
10
+ import * as ClientDirectory from "../ClientDirectory.js";
11
+ import * as Method from "../Method.js";
12
+ const { debug, span } = diagnostic("workerd.WorkerdActorNamespace");
13
+ export const Service = () => (id, definition) => {
14
+ const { hibernation, actor, prelude, handlers, layer: runLayer, onConnect } = definition;
15
+ const { definition: { name: Name, client: { key: clientId, protocol: P }, attachments: AttachmentFields, }, } = actor;
16
+ const encodeName = S.encodeEffect(Name);
17
+ const decodeName = S.decodeUnknownEffect(Name);
18
+ const Attachments = S.Struct(AttachmentFields);
19
+ const encodeAttachments = S.encodeEffect(S.toCodecJson(Attachments));
20
+ const decodeAttachments = S.decodeUnknownEffect(S.toCodecJson(Attachments));
21
+ const encodeAttachmentsString = encodeJsonString(Attachments);
22
+ const decodeAttachmentsString = decodeJsonString(Attachments);
23
+ const encodeAuditionSuccess = encodeJsonString(P.Audition.Success);
24
+ const encodeAuditionFailure = encodeJsonString(P.Audition.Failure);
25
+ const decodeClientM = decodeJsonString(P.Client);
26
+ const encodeFSuccess = encodeJsonString(P.F.Success);
27
+ const encodeFFailure = encodeJsonString(P.F.Failure);
28
+ const encodeEvent = encodeJsonString(P.Event);
29
+ const transport = {
30
+ send: (socket, event) => encodeEvent(event).pipe(Effect.andThen((v) => Effect.sync(() => socket.send(v)))),
31
+ close: (socket) => Effect.sync(() => socket.close(1000)),
32
+ snapshot: (socket, attachments) => encodeAttachments(attachments).pipe(Effect.andThen((v) => Effect.sync(() => socket.serializeAttachment(v)))),
33
+ };
34
+ const tag = class tag extends Context.Service()(id) {
35
+ runtime;
36
+ directory = ClientDirectory.make(actor, transport);
37
+ constructor(...args) {
38
+ super(...args);
39
+ const [state, env] = args;
40
+ if (hibernation) {
41
+ Option.andThen(Duration.fromInput(hibernation), flow(Duration.toMillis, state.setHibernatableWebSocketEventTimeout));
42
+ }
43
+ const baseLayer = Layer.mergeAll(prelude.pipe(Layer.provideMerge(ConfigProvider.layer(ConfigProvider.fromUnknown(env)))), FetchHttpClient.layer, Layer.succeed(DoState.DoState, state), Mutex.layer);
44
+ this.runtime = Effect.gen({ self: this }, function* () {
45
+ this.#name = yield* Effect.tryPromise(() => state.storage.get("__liminal_name")).pipe(Effect.flatMap((v) => (typeof v === "string" ? decodeName(v) : Effect.succeed(undefined))));
46
+ for (const socket of state.getWebSockets()) {
47
+ const attachments = yield* decodeAttachments(socket.deserializeAttachment());
48
+ yield* this.directory.register(socket, attachments);
49
+ }
50
+ }).pipe(Effect.tapCause(logCause), span("make_runtime"), Layer.effectDiscard, Layer.provideMerge(baseLayer), boundLayer("actor"), ManagedRuntime.make);
51
+ }
52
+ #name;
53
+ fetch(request) {
54
+ return Effect.gen({ self: this }, function* () {
55
+ const url = new URL(request.url);
56
+ const name = yield* decodeName(url.searchParams.get("__liminal_name"));
57
+ const attachments = yield* decodeAttachmentsString(url.searchParams.get("__liminal_attachments"));
58
+ if (!this.#name) {
59
+ this.#name = name;
60
+ const state = yield* DoState.DoState;
61
+ const encoded = yield* S.encodeEffect(Name)(name);
62
+ yield* Effect.promise(() => state.storage.put("__liminal_name", encoded));
63
+ }
64
+ const { 0: webSocket, 1: server } = new WebSocketPair();
65
+ const state = yield* DoState.DoState;
66
+ state.acceptWebSocket(server);
67
+ server.send(yield* encodeAuditionSuccess({ _tag: "Audition.Success" }));
68
+ const currentClient = yield* this.directory.register(server, attachments);
69
+ const ActorLive = Layer.succeed(actor, {
70
+ name,
71
+ clients: this.directory.handles,
72
+ currentClient,
73
+ });
74
+ yield* onConnect.pipe(Effect.scoped, span("onConnect"), Effect.scoped, Effect.provide(Layer.provideMerge(runLayer, ActorLive)));
75
+ yield* debug("ClientRegistered");
76
+ return new Response(null, {
77
+ status: 101,
78
+ webSocket,
79
+ headers: { [SecWebSocketProtocol]: "liminal" },
80
+ });
81
+ }).pipe(Effect.tapCause(logCause), span("fetch"), this.runtime.runPromise);
82
+ }
83
+ webSocketMessage(socket, raw) {
84
+ Effect.gen({ self: this }, function* () {
85
+ const currentClient = yield* this.directory.get(socket);
86
+ const name = yield* Effect.fromNullishOr(this.#name);
87
+ const ActorLive = Layer.succeed(actor, {
88
+ name,
89
+ clients: this.directory.handles,
90
+ currentClient,
91
+ });
92
+ const message = yield* decodeClientM(raw instanceof ArrayBuffer ? new TextDecoder().decode(raw) : raw);
93
+ yield* debug("MessageReceived", { message });
94
+ if (message._tag === "Audition.Payload") {
95
+ return yield* Effect.die(undefined);
96
+ }
97
+ if (message._tag === "Disconnect") {
98
+ return yield* currentClient.disconnect;
99
+ }
100
+ const { id, payload } = message;
101
+ const { _tag, value } = payload;
102
+ yield* handlers[_tag](value).pipe(Effect.matchEffect({
103
+ onSuccess: (value) => encodeFSuccess({
104
+ _tag: "F.Success",
105
+ id,
106
+ success: { _tag, value },
107
+ }),
108
+ onFailure: (value) => encodeFFailure({
109
+ _tag: "F.Failure",
110
+ id,
111
+ failure: { _tag, value },
112
+ }),
113
+ }), span("handler", { attributes: { _tag } }), Effect.andThen((v) => Effect.sync(() => socket.send(v))), Effect.scoped, Effect.provide(Layer.provideMerge(runLayer, ActorLive)));
114
+ }).pipe(Effect.scoped, Mutex.task, Effect.tapCause(logCause), span("webSocketMessage"), this.runtime.runFork);
115
+ }
116
+ webSocketClose(socket, _code, _reason, _wasClean) {
117
+ this.directory
118
+ .unregister(socket)
119
+ .pipe(Effect.tap(debug("SocketClosed")), Effect.tapCause(logCause), this.runtime.runFork);
120
+ }
121
+ webSocketError(socket, cause) {
122
+ Effect.gen({ self: this }, function* () {
123
+ yield* debug("SocketErrored", { cause });
124
+ yield* this.directory.unregister(socket);
125
+ }).pipe(Effect.tapCause(logCause), span("SocketErrored", { attributes: { cause } }), this.runtime.runFork);
126
+ }
127
+ };
128
+ const upgrade = Effect.fnUntraced(function* (name, attachments) {
129
+ yield* debug("UpgradeInitiated", { attachments });
130
+ const namespace = yield* tag;
131
+ const nameEncoded = yield* encodeName(name);
132
+ const stub = namespace.getByName(nameEncoded);
133
+ const request = yield* NativeRequest.NativeRequest;
134
+ const protocols = yield* Effect.fromNullishOr(request.headers.get(SecWebSocketProtocol)).pipe(Effect.map(flow(String.split(","), Array.map(String.trim))));
135
+ const liminalTokenI = yield* Array.findFirstIndex(protocols, (v) => v === "liminal");
136
+ const requestClientId = yield* Effect.fromNullishOr(protocols[liminalTokenI + 1]).pipe(Effect.flatMap((v) => Encoding.decodeBase64UrlString(v).asEffect()));
137
+ if (requestClientId !== clientId) {
138
+ return close(yield* encodeAuditionFailure({
139
+ _tag: "Audition.Failure",
140
+ expected: clientId,
141
+ actual: requestClientId,
142
+ }));
143
+ }
144
+ const url = new URL(request.url);
145
+ url.searchParams.set("__liminal_name", nameEncoded);
146
+ url.searchParams.set("__liminal_attachments", yield* encodeAttachmentsString(attachments));
147
+ return yield* Effect.promise(() => stub.fetch(new Request(url, request))).pipe(Effect.map(HttpServerResponse.raw));
148
+ }, span("upgrade"));
149
+ const layer = Binding.layer(tag, ["getByName"]);
150
+ return Object.assign(tag, { definition, upgrade, layer });
151
+ };
152
+ //# sourceMappingURL=WorkerdActorNamespace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkerdActorNamespace.js","sourceRoot":"","sources":["../../workerd/WorkerdActorNamespace.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,MAAM,EACN,KAAK,EACL,MAAM,IAAI,CAAC,EACX,OAAO,EACP,cAAc,EACd,cAAc,EACd,QAAQ,EACR,IAAI,EACJ,MAAM,EACN,KAAK,EACL,QAAQ,EACR,MAAM,GACP,MAAM,QAAQ,CAAA;AACf,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAChE,OAAO,EAAE,oBAAoB,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAA;AACxE,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AACtF,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAA;AAMhD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAC9C,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAA;AAC1C,OAAO,EAAsB,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAC3F,OAAO,KAAK,eAAe,MAAM,uBAAuB,CAAA;AACxD,OAAO,K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espace from "./WorkerdActorNamespace.ts";
@@ -0,0 +1,2 @@
1
+ export * as WorkerdActorNamespace from "./WorkerdActorNamespace.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../workerd/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,qBAAqB,MAAM,4BAA4B,CAAA"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "liminal",
3
- "version": "0.17.10",
4
- "description": "Actors x Effects",
3
+ "version": "0.17.12",
4
+ "description": "Effect x Actors",
5
5
  "bugs": {
6
6
  "url": "https://github.com/crosshatch/liminal/issues"
7
7
  },
@@ -22,9 +22,26 @@
22
22
  "types": "./*.ts",
23
23
  "default": "./dist/*.js"
24
24
  },
25
+ "./browser": {
26
+ "types": "./browser/index.ts",
27
+ "default": "./dist/browser/index.js"
28
+ },
29
+ "./experimental": {
30
+ "types": "./experimental/index.ts",
31
+ "default": "./dist/experimental/index.js"
32
+ },
33
+ "./workerd": {
34
+ "types": "./workerd/index.ts",
35
+ "default": "./dist/workerd/index.js"
36
+ },
25
37
  "./package.json": "./package.json"
26
38
  },
27
39
  "peerDependencies": {
28
- "effect": "4.0.0-beta.50"
40
+ "@cloudflare/workers-types": "^4.20260414.1",
41
+ "@effect/platform-browser": "4.0.0-beta.50",
42
+ "@effect/sql-d1": "4.0.0-beta.50",
43
+ "effect": "4.0.0-beta.50",
44
+ "effect-workerd": "0.0.2",
45
+ "liminal-util": "0.0.2"
29
46
  }
30
47
  }
package/tsconfig.json CHANGED
@@ -2,8 +2,10 @@
2
2
  "extends": "../konfik/tsconfig.base",
3
3
  "compilerOptions": {
4
4
  "noEmit": false,
5
- "outDir": "dist"
5
+ "outDir": "dist",
6
+ "types": ["@cloudflare/workers-types"]
6
7
  },
7
- "include": ["."],
8
- "exclude": ["dist"]
8
+ "include": [".", "package.json"],
9
+ "exclude": ["dist"],
10
+ "references": [{ "path": "../effect-workerd" }, { "path": "../liminal-util" }]
9
11
  }
@@ -0,0 +1,361 @@
1
+ import {
2
+ Layer,
3
+ Effect,
4
+ Scope,
5
+ Schema as S,
6
+ Context,
7
+ ManagedRuntime,
8
+ ConfigProvider,
9
+ Duration,
10
+ flow,
11
+ String,
12
+ Array,
13
+ Encoding,
14
+ Option,
15
+ } from "effect"
16
+ import { Binding, DoState, NativeRequest } from "effect-workerd"
17
+ import { SecWebSocketProtocol, close } from "effect-workerd/socket_util"
18
+ import { HttpServerResponse, HttpClient, FetchHttpClient } from "effect/unstable/http"
19
+ import { boundLayer } from "liminal-util/boundLayer"
20
+ import { logCause } from "liminal-util/logCause"
21
+
22
+ import type { Actor } from "../Actor.ts"
23
+ import type { ActorTransport } from "../ActorTransport.ts"
24
+ import type { ProtocolDefinition } from "../Protocol.ts"
25
+
26
+ import { diagnostic } from "../_diagnostic.ts"
27
+ import * as Mutex from "../_util/Mutex.ts"
28
+ import { type TopFromString, encodeJsonString, decodeJsonString } from "../_util/schema.ts"
29
+ import * as ClientDirectory from "../ClientDirectory.ts"
30
+ import * as Method from "../Method.ts"
31
+
32
+ const { debug, span } = diagnostic("workerd.WorkerdActorNamespace")
33
+
34
+ export interface ActorNamespaceDefinition<
35
+ ActorSelf,
36
+ ActorId extends string,
37
+ Name extends TopFromString,
38
+ AttachmentFields extends S.Struct.Fields,
39
+ ClientSelf,
40
+ ClientId extends string,
41
+ D extends ProtocolDefinition,
42
+ PreludeROut,
43
+ PreludeE,
44
+ RunROut,
45
+ RunE,
46
+ > {
47
+ readonly ""?: this["actor"]["definition"]["client"]["protocol"]
48
+
49
+ readonly actor: Actor<ActorSelf, ActorId, Name, AttachmentFields, ClientSelf, ClientId, D>
50
+
51
+ readonly prelude: Layer.Layer<
52
+ | PreludeROut
53
+ | NonNullable<this[""]>["F"]["Payload"]["DecodingServices"]
54
+ | NonNullable<this[""]>["F"]["Success"]["EncodingServices"]
55
+ | NonNullable<this[""]>["F"]["Failure"]["EncodingServices"]
56
+ | NonNullable<this[""]>["Event"]["EncodingServices"]
57
+ | S.Struct<AttachmentFields>["DecodingServices"]
58
+ | S.Struct<AttachmentFields>["EncodingServices"]
59
+ | Name["EncodingServices"]
60
+ | Name["DecodingServices"],
61
+ PreludeE
62
+ >
63
+
64
+ readonly layer: Layer.Layer<RunROut, RunE, ActorSelf | HttpClient.HttpClient | PreludeROut>
65
+
66
+ readonly handlers: Method.Handlers<
67
+ D["methods"],
68
+ ActorSelf | HttpClient.HttpClient | PreludeROut | RunROut | Scope.Scope
69
+ >
70
+
71
+ readonly onConnect: Effect.Effect<
72
+ void,
73
+ never,
74
+ ActorSelf | HttpClient.HttpClient | PreludeROut | RunROut | Scope.Scope
75
+ >
76
+
77
+ readonly hibernation?: Duration.Input | undefined
78
+ }
79
+
80
+ export interface ActorNamespace<
81
+ NamespaceSelf,
82
+ NamespaceId extends string,
83
+ ActorSelf,
84
+ ActorId extends string,
85
+ Name extends TopFromString,
86
+ AttachmentFields extends S.Struct.Fields,
87
+ ClientSelf,
88
+ ClientId extends string,
89
+ D extends ProtocolDefinition,
90
+ PreludeROut,
91
+ PreludeE,
92
+ RunROut,
93
+ RunE,
94
+ > extends Context.Service<NamespaceSelf, DurableObjectNamespace> {
95
+ new (state: globalThis.DurableObjectState<{}>): Context.ServiceClass.Shape<NamespaceId, DurableObjectNamespace>
96
+
97
+ readonly definition: ActorNamespaceDefinition<
98
+ ActorSelf,
99
+ ActorId,
100
+ Name,
101
+ AttachmentFields,
102
+ ClientSelf,
103
+ ClientId,
104
+ D,
105
+ PreludeROut,
106
+ PreludeE,
107
+ RunROut,
108
+ RunE
109
+ >
110
+
111
+ readonly upgrade: (
112
+ name: Name["Type"],
113
+ attachments: S.Struct<AttachmentFields>["Type"],
114
+ ) => Effect.Effect<HttpServerResponse.HttpServerResponse, S.SchemaError, NamespaceSelf | NativeRequest.NativeRequest>
115
+
116
+ readonly layer: (binding: string) => Layer.Layer<NamespaceSelf, S.SchemaError, never>
117
+ }
118
+
119
+ export const Service =
120
+ <NamespaceSelf>() =>
121
+ <
122
+ NamespaceId extends string,
123
+ ActorSelf,
124
+ ActorId extends string,
125
+ Name extends TopFromString,
126
+ AttachmentFields extends S.Struct.Fields,
127
+ ClientSelf,
128
+ ClientId extends string,
129
+ D extends ProtocolDefinition,
130
+ PreludeROut,
131
+ PreludeE,
132
+ RunROut,
133
+ RunE,
134
+ >(
135
+ id: NamespaceId,
136
+ definition: ActorNamespaceDefinition<
137
+ ActorSelf,
138
+ ActorId,
139
+ Name,
140
+ AttachmentFields,
141
+ ClientSelf,
142
+ ClientId,
143
+ D,
144
+ PreludeROut,
145
+ PreludeE,
146
+ RunROut,
147
+ RunE
148
+ >,
149
+ ): ActorNamespace<
150
+ NamespaceSelf,
151
+ NamespaceId,
152
+ ActorSelf,
153
+ ActorId,
154
+ Name,
155
+ AttachmentFields,
156
+ ClientSelf,
157
+ ClientId,
158
+ D,
159
+ PreludeROut,
160
+ PreludeE,
161
+ RunROut,
162
+ RunE
163
+ > => {
164
+ const { hibernation, actor, prelude, handlers, layer: runLayer, onConnect } = definition
165
+ const {
166
+ definition: {
167
+ name: Name,
168
+ client: { key: clientId, protocol: P },
169
+ attachments: AttachmentFields,
170
+ },
171
+ } = actor
172
+
173
+ const encodeName = S.encodeEffect(Name)
174
+ const decodeName = S.decodeUnknownEffect(Name)
175
+
176
+ const Attachments = S.Struct(AttachmentFields)
177
+ const encodeAttachments = S.encodeEffect(S.toCodecJson(Attachments))
178
+ const decodeAttachments = S.decodeUnknownEffect(S.toCodecJson(Attachments))
179
+ const encodeAttachmentsString = encodeJsonString(Attachments)
180
+ const decodeAttachmentsString = decodeJsonString(Attachments)
181
+
182
+ const encodeAuditionSuccess = encodeJsonString(P.Audition.Success)
183
+ const encodeAuditionFailure = encodeJsonString(P.Audition.Failure)
184
+ const decodeClientM = decodeJsonString(P.Client)
185
+ const encodeFSuccess = encodeJsonString(P.F.Success)
186
+ const encodeFFailure = encodeJsonString(P.F.Failure)
187
+
188
+ const encodeEvent = encodeJsonString(P.Event)
189
+
190
+ const transport: ActorTransport<WebSocket, AttachmentFields, D> = {
191
+ send: (socket, event) => encodeEvent(event).pipe(Effect.andThen((v) => Effect.sync(() => socket.send(v)))),
192
+ close: (socket) => Effect.sync(() => socket.close(1000)),
193
+ snapshot: (socket, attachments) =>
194
+ encodeAttachments(attachments).pipe(Effect.andThen((v) => Effect.sync(() => socket.serializeAttachment(v)))),
195
+ }
196
+
197
+ const tag = class tag extends Context.Service<NamespaceSelf, DurableObjectNamespace>()(id) {
198
+ readonly runtime
199
+ readonly directory = ClientDirectory.make(actor, transport)
200
+
201
+ constructor(...args: [never]) {
202
+ super(...args)
203
+ const [state, env] = args as never as [state: globalThis.DurableObjectState<{}>, env: unknown]
204
+
205
+ if (hibernation) {
206
+ Option.andThen(
207
+ Duration.fromInput(hibernation),
208
+ flow(Duration.toMillis, state.setHibernatableWebSocketEventTimeout),
209
+ )
210
+ }
211
+
212
+ const baseLayer = Layer.mergeAll(
213
+ prelude.pipe(Layer.provideMerge(ConfigProvider.layer(ConfigProvider.fromUnknown(env)))),
214
+ FetchHttpClient.layer,
215
+ Layer.succeed(DoState.DoState, state),
216
+ Mutex.layer,
217
+ )
218
+
219
+ this.runtime = Effect.gen({ self: this }, function* () {
220
+ this.#name = yield* Effect.tryPromise(() => state.storage.get("__liminal_name")).pipe(
221
+ Effect.flatMap((v) => (typeof v === "string" ? decodeName(v) : Effect.succeed(undefined))),
222
+ )
223
+ for (const socket of state.getWebSockets()) {
224
+ const attachments = yield* decodeAttachments(socket.deserializeAttachment())
225
+ yield* this.directory.register(socket, attachments)
226
+ }
227
+ }).pipe(
228
+ Effect.tapCause(logCause),
229
+ span("make_runtime"),
230
+ Layer.effectDiscard,
231
+ Layer.provideMerge(baseLayer),
232
+ boundLayer("actor"),
233
+ ManagedRuntime.make,
234
+ )
235
+ }
236
+
237
+ #name?: Name["Type"] | undefined
238
+ fetch(request: Request): Promise<Response> {
239
+ return Effect.gen({ self: this }, function* () {
240
+ const url = new URL(request.url)
241
+ const name = yield* decodeName(url.searchParams.get("__liminal_name"))
242
+ const attachments = yield* decodeAttachmentsString(url.searchParams.get("__liminal_attachments"))
243
+ if (!this.#name) {
244
+ this.#name = name
245
+ const state = yield* DoState.DoState
246
+ const encoded = yield* S.encodeEffect(Name)(name)
247
+ yield* Effect.promise(() => state.storage.put("__liminal_name", encoded))
248
+ }
249
+ const { 0: webSocket, 1: server } = new WebSocketPair()
250
+ const state = yield* DoState.DoState
251
+ state.acceptWebSocket(server)
252
+ server.send(yield* encodeAuditionSuccess({ _tag: "Audition.Success" }))
253
+ const currentClient = yield* this.directory.register(server, attachments)
254
+ const ActorLive = Layer.succeed(actor, {
255
+ name,
256
+ clients: this.directory.handles,
257
+ currentClient,
258
+ })
259
+ yield* onConnect.pipe(
260
+ Effect.scoped,
261
+ span("onConnect"),
262
+ Effect.scoped,
263
+ Effect.provide(Layer.provideMerge(runLayer, ActorLive)),
264
+ )
265
+ yield* debug("ClientRegistered")
266
+ return new Response(null, {
267
+ status: 101,
268
+ webSocket,
269
+ headers: { [SecWebSocketProtocol]: "liminal" },
270
+ })
271
+ }).pipe(Effect.tapCause(logCause), span("fetch"), this.runtime.runPromise)
272
+ }
273
+
274
+ webSocketMessage(socket: WebSocket, raw: string | ArrayBuffer) {
275
+ Effect.gen({ self: this }, function* () {
276
+ const currentClient = yield* this.directory.get(socket)
277
+ const name = yield* Effect.fromNullishOr(this.#name)
278
+ const ActorLive = Layer.succeed(actor, {
279
+ name,
280
+ clients: this.directory.handles,
281
+ currentClient,
282
+ })
283
+ const message = yield* decodeClientM(raw instanceof ArrayBuffer ? new TextDecoder().decode(raw) : raw)
284
+ yield* debug("MessageReceived", { message })
285
+ if (message._tag === "Audition.Payload") {
286
+ return yield* Effect.die(undefined)
287
+ }
288
+ if (message._tag === "Disconnect") {
289
+ return yield* currentClient.disconnect
290
+ }
291
+ const { id, payload } = message
292
+ const { _tag, value } = payload as never
293
+ yield* handlers[_tag]!(value).pipe(
294
+ Effect.matchEffect({
295
+ onSuccess: (value) =>
296
+ encodeFSuccess({
297
+ _tag: "F.Success",
298
+ id,
299
+ success: { _tag, value } as never,
300
+ }),
301
+ onFailure: (value) =>
302
+ encodeFFailure({
303
+ _tag: "F.Failure",
304
+ id,
305
+ failure: { _tag, value } as never,
306
+ }),
307
+ }),
308
+ span("handler", { attributes: { _tag } }),
309
+ Effect.andThen((v) => Effect.sync(() => socket.send(v))),
310
+ Effect.scoped,
311
+ Effect.provide(Layer.provideMerge(runLayer, ActorLive)),
312
+ )
313
+ }).pipe(Effect.scoped, Mutex.task, Effect.tapCause(logCause), span("webSocketMessage"), this.runtime.runFork)
314
+ }
315
+
316
+ webSocketClose(socket: WebSocket, _code: number, _reason: string, _wasClean: boolean) {
317
+ this.directory
318
+ .unregister(socket)
319
+ .pipe(Effect.tap(debug("SocketClosed")), Effect.tapCause(logCause), this.runtime.runFork)
320
+ }
321
+
322
+ webSocketError(socket: WebSocket, cause: unknown) {
323
+ Effect.gen({ self: this }, function* () {
324
+ yield* debug("SocketErrored", { cause })
325
+ yield* this.directory.unregister(socket)
326
+ }).pipe(Effect.tapCause(logCause), span("SocketErrored", { attributes: { cause } }), this.runtime.runFork)
327
+ }
328
+ }
329
+
330
+ const upgrade = Effect.fnUntraced(function* (name: Name["Type"], attachments: (typeof Attachments)["Type"]) {
331
+ yield* debug("UpgradeInitiated", { attachments })
332
+ const namespace = yield* tag
333
+ const nameEncoded = yield* encodeName(name)
334
+ const stub = namespace.getByName(nameEncoded)
335
+ const request = yield* NativeRequest.NativeRequest
336
+ const protocols = yield* Effect.fromNullishOr(request.headers.get(SecWebSocketProtocol)).pipe(
337
+ Effect.map(flow(String.split(","), Array.map(String.trim))),
338
+ )
339
+ const liminalTokenI = yield* Array.findFirstIndex(protocols, (v) => v === "liminal")
340
+ const requestClientId = yield* Effect.fromNullishOr(protocols[liminalTokenI + 1]).pipe(
341
+ Effect.flatMap((v) => Encoding.decodeBase64UrlString(v).asEffect()),
342
+ )
343
+ if (requestClientId !== clientId) {
344
+ return close(
345
+ yield* encodeAuditionFailure({
346
+ _tag: "Audition.Failure",
347
+ expected: clientId,
348
+ actual: requestClientId,
349
+ }),
350
+ )
351
+ }
352
+ const url = new URL(request.url)
353
+ url.searchParams.set("__liminal_name", nameEncoded)
354
+ url.searchParams.set("__liminal_attachments", yield* encodeAttachmentsString(attachments))
355
+ return yield* Effect.promise(() => stub.fetch(new Request(url, request))).pipe(Effect.map(HttpServerResponse.raw))
356
+ }, span("upgrade"))
357
+
358
+ const layer = Binding.layer(tag, ["getByName"])
359
+
360
+ return Object.assign(tag, { definition, upgrade, layer }) as never
361
+ }
@@ -0,0 +1 @@
1
+ export * as WorkerdActorNamespace from "./WorkerdActorNamespace.ts"
package/_constants.ts DELETED
@@ -1 +0,0 @@
1
- export const SecWebSocketProtocol = "Sec-WebSocket-Protocol" as const
@@ -1,16 +0,0 @@
1
- import { Effect, Tracer } from "effect"
2
-
3
- export const module = (module: string) => ({
4
- debug: (event: string, annotations?: Record<string, unknown>) =>
5
- Effect.logDebug(event).pipe(
6
- Effect.annotateLogs({
7
- package: "liminal",
8
- module,
9
- ...annotations,
10
- }),
11
- ),
12
- span:
13
- (operation: string, options?: Tracer.SpanOptions | undefined) =>
14
- <A, E, R>(effect: Effect.Effect<A, E, R>) =>
15
- Effect.withSpan(effect, `liminal.${module}.${operation}`, options),
16
- })
@@ -1,11 +0,0 @@
1
- import { References, Effect, Layer } from "effect"
2
-
3
- import { logCause } from "./logCause.ts"
4
-
5
- export const boundLayer = (boundary: string) =>
6
- Layer.provideMerge(
7
- Layer.effect(
8
- References.CurrentLogAnnotations,
9
- Effect.map(References.CurrentLogAnnotations.asEffect(), (existing) => ({ ...existing, _boundary: boundary })),
10
- ).pipe(Layer.tapCause(logCause), Layer.provideMerge(Layer.succeed(References.MinimumLogLevel, "All"))),
11
- )
package/_util/logCause.ts DELETED
@@ -1,8 +0,0 @@
1
- import { Cause, Effect, Schema as S, flow } from "effect"
2
-
3
- const formatReason = <E>(reason: Cause.Reason<E>): unknown => {
4
- const value = Cause.isFailReason(reason) ? reason.error : Cause.isDieReason(reason) ? reason.defect : reason
5
- return S.isSchemaError(value) ? value.toString() : value
6
- }
7
-
8
- export const logCause = <E>(cause: Cause.Cause<E>) => Effect.forEach(cause.reasons, flow(formatReason, Effect.logError))
@@ -1 +0,0 @@
1
- export declare const SecWebSocketProtocol: "Sec-WebSocket-Protocol";
@@ -1,2 +0,0 @@
1
- export const SecWebSocketProtocol = "Sec-WebSocket-Protocol";
2
- //# sourceMappingURL=_constants.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"_constants.js","sourceRoot":"","sources":["../_constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,oBAAoB,GAAG,wBAAiC,CAAA"}
@@ -1,5 +0,0 @@
1
- import { Effect, Tracer } from "effect";
2
- export declare const module: (module: string) => {
3
- debug: (event: string, annotations?: Record<string, unknown>) => Effect.Effect<void, never, never>;
4
- span: (operation: string, options?: Tracer.SpanOptions | undefined) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>>;
5
- };