@signe/room 3.1.1 → 3.2.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/CHANGELOG.md +7 -0
- package/dist/cloudflare/index.d.ts +17 -1
- package/dist/cloudflare/index.js +118 -34
- package/dist/cloudflare/index.js.map +1 -1
- package/examples/cloudflare/CHANGELOG.md +8 -0
- package/examples/cloudflare/README.md +4 -0
- package/examples/cloudflare/package.json +1 -1
- package/examples/cloudflare/src/index.ts +1 -0
- package/examples/node/CHANGELOG.md +8 -0
- package/examples/node/package.json +1 -1
- package/examples/node-game/CHANGELOG.md +8 -0
- package/examples/node-game/package.json +1 -1
- package/examples/node-shard/CHANGELOG.md +8 -0
- package/examples/node-shard/package.json +1 -1
- package/package.json +1 -1
- package/src/cloudflare/index.ts +163 -35
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,7 @@ type CloudflareRoomWorkerOptions = {
|
|
|
10
10
|
partiesPath?: string;
|
|
11
11
|
env?: Record<string, unknown>;
|
|
12
12
|
rooms?: Record<string, CloudflareRoomServerConstructor>;
|
|
13
|
+
webSocketMode?: "standard" | "hibernate";
|
|
13
14
|
};
|
|
14
15
|
type CloudflareRoomEnv = Record<string, unknown>;
|
|
15
16
|
declare function createCloudflareRoomWorker<TServer extends Server>(ServerClass: CloudflareRoomServerConstructor<TServer>, options: CloudflareRoomWorkerOptions): {
|
|
@@ -23,8 +24,12 @@ declare class SigneRoomDurableObject {
|
|
|
23
24
|
constructor(ctx: DurableObjectState, env: CloudflareRoomEnv);
|
|
24
25
|
fetch(request: Request): Promise<Response>;
|
|
25
26
|
alarm(): Promise<void>;
|
|
27
|
+
webSocketMessage(webSocket: WebSocket, message: string | ArrayBuffer): Promise<void>;
|
|
28
|
+
webSocketClose(webSocket: WebSocket, _code: number, _reason: string, _wasClean: boolean): Promise<void>;
|
|
29
|
+
webSocketError(webSocket: WebSocket, error: unknown): Promise<void>;
|
|
26
30
|
private acceptWebSocket;
|
|
27
31
|
private getRecord;
|
|
32
|
+
private getStoredRecord;
|
|
28
33
|
private createRecord;
|
|
29
34
|
}
|
|
30
35
|
declare class CloudflareRoom implements Room {
|
|
@@ -37,6 +42,8 @@ declare class CloudflareRoom implements Room {
|
|
|
37
42
|
readonly connections: Map<string, Connection<unknown>>;
|
|
38
43
|
readonly parties: Context["parties"];
|
|
39
44
|
readonly analytics: _cloudflare_workers_types.AnalyticsEngineDataset;
|
|
45
|
+
private readonly hibernating;
|
|
46
|
+
private readonly state;
|
|
40
47
|
constructor(options: {
|
|
41
48
|
id: string;
|
|
42
49
|
name: string;
|
|
@@ -51,6 +58,7 @@ declare class CloudflareRoom implements Room {
|
|
|
51
58
|
getConnections<TState = unknown>(): Iterable<Connection<TState>>;
|
|
52
59
|
addConnection(connection: CloudflareConnection): void;
|
|
53
60
|
deleteConnection(id: string, connection?: CloudflareConnection): void;
|
|
61
|
+
connectionForWebSocket(webSocket: WebSocket): CloudflareConnection;
|
|
54
62
|
}
|
|
55
63
|
declare class CloudflareConnection<TState = unknown> {
|
|
56
64
|
private readonly webSocket;
|
|
@@ -60,12 +68,20 @@ declare class CloudflareConnection<TState = unknown> {
|
|
|
60
68
|
readonly uri: string;
|
|
61
69
|
state: ConnectionState<TState> | TState | null;
|
|
62
70
|
private attachment;
|
|
63
|
-
constructor(webSocket: WebSocket,
|
|
71
|
+
constructor(webSocket: WebSocket, options: {
|
|
72
|
+
id?: string;
|
|
73
|
+
uri: string;
|
|
74
|
+
sessionId?: string;
|
|
75
|
+
state?: ConnectionState<TState> | TState | null;
|
|
76
|
+
attachment?: unknown;
|
|
77
|
+
});
|
|
78
|
+
static restore(webSocket: WebSocket): CloudflareConnection;
|
|
64
79
|
send(data: string | ArrayBuffer | ArrayBufferView): void;
|
|
65
80
|
close(code?: number, reason?: string): void;
|
|
66
81
|
setState(state: TState | ConnectionSetStateFn<TState> | null): { readonly [K in keyof TState]: TState[K] extends infer T ? T extends TState[K] ? T extends string | number | boolean ? T : T extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T extends Set<infer M> ? ReadonlySet<any> : { readonly [K_3 in keyof T]: T[K_3] extends infer T_1 ? T_1 extends T[K_3] ? T_1 extends string | number | boolean ? T_1 : T_1 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_1 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_1 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_4 in keyof T_1]: T_1[K_4] extends infer T_2 ? T_2 extends T_1[K_4] ? T_2 extends string | number | boolean ? T_2 : T_2 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_2 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_2 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_5 in keyof T_2]: T_2[K_5] extends infer T_3 ? T_3 extends T_2[K_5] ? T_3 extends string | number | boolean ? T_3 : T_3 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_3 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_3 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_6 in keyof T_3]: T_3[K_6] extends infer T_4 ? T_4 extends T_3[K_6] ? T_4 extends string | number | boolean ? T_4 : T_4 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_4 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_4 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_7 in keyof T_4]: T_4[K_7] extends infer T_5 ? T_5 extends T_4[K_7] ? T_5 extends string | number | boolean ? T_5 : T_5 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_5 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_5 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_8 in keyof T_5]: T_5[K_8] extends infer T_6 ? T_6 extends T_5[K_8] ? T_6 extends string | number | boolean ? T_6 : T_6 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_6 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_6 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_9 in keyof T_6]: T_6[K_9] extends infer T_7 ? T_7 extends T_6[K_9] ? T_7 extends string | number | boolean ? T_7 : T_7 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_7 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_7 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_10 in keyof T_7]: T_7[K_10] extends infer T_8 ? T_8 extends T_7[K_10] ? T_8 extends string | number | boolean ? T_8 : T_8 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_8 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_8 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_11 in keyof T_8]: T_8[K_11] extends infer T_9 ? T_9 extends T_8[K_11] ? T_9 extends string | number | boolean ? T_9 : T_9 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_9 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_9 extends Set<infer M> ? ReadonlySet<any> : { readonly [K_12 in keyof T_9]: T_9[K_12] extends infer T_10 ? T_10 extends T_9[K_12] ? T_10 extends string | number | boolean ? T_10 : T_10 extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly (U extends string | number | boolean ? U : U extends (infer U)[] ? readonly any[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : U extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : U extends Set<infer M> ? ReadonlySet<any> : { readonly [K_2 in keyof U]: any; })[] : T_10 extends Map<infer K_1, infer V> ? ReadonlyMap<any, any> : T_10 extends Set<infer M> ? ReadonlySet<any> : any : never : never; } : never : never; } : never : never; } : never : never; } : never : never; } : never : never; } : never : never; } : never : never; } : never : never; } : never : never; } : never : never; };
|
|
67
82
|
serializeAttachment<T = unknown>(attachment: T): void;
|
|
68
83
|
deserializeAttachment<T = unknown>(): T | null;
|
|
84
|
+
persistAttachment(): void;
|
|
69
85
|
}
|
|
70
86
|
|
|
71
87
|
export { CloudflareConnection, CloudflareRoom, type CloudflareRoomEnv, type CloudflareRoomServerConstructor, type CloudflareRoomWorkerOptions, SigneRoomDurableObject, createCloudflareRoomWorker, dispatchCloudflareRoomRequest };
|
package/dist/cloudflare/index.js
CHANGED
|
@@ -3,6 +3,7 @@ import "../chunk-EUXUH3YW.js";
|
|
|
3
3
|
// src/cloudflare/index.ts
|
|
4
4
|
var DEFAULT_PARTIES_PATH = "/parties/main";
|
|
5
5
|
var WEBSOCKET_OPEN = 1;
|
|
6
|
+
var ROUTE_STORAGE_KEY = "$signe:cloudflare-route";
|
|
6
7
|
var runtimeConfig;
|
|
7
8
|
function createCloudflareRoomWorker(ServerClass, options) {
|
|
8
9
|
runtimeConfig = createRuntimeConfig(ServerClass, options);
|
|
@@ -19,7 +20,7 @@ async function dispatchCloudflareRoomRequest(request, env, _ctx) {
|
|
|
19
20
|
return new Response("Not Found", { status: 404 });
|
|
20
21
|
}
|
|
21
22
|
const namespace = getNamespace(env, config.binding);
|
|
22
|
-
const stub = namespace.get(namespace.idFromName(parsed
|
|
23
|
+
const stub = namespace.get(namespace.idFromName(getDurableObjectName(parsed)));
|
|
23
24
|
return fetchDurableObjectStub(stub, request);
|
|
24
25
|
}
|
|
25
26
|
var SigneRoomDurableObject = class {
|
|
@@ -40,37 +41,69 @@ var SigneRoomDurableObject = class {
|
|
|
40
41
|
return record.server.onRequest?.(request) ?? new Response("Not Found", { status: 404 });
|
|
41
42
|
}
|
|
42
43
|
async alarm() {
|
|
43
|
-
const record = await this.
|
|
44
|
+
const record = await this.getStoredRecord();
|
|
44
45
|
await record?.server.onAlarm?.();
|
|
45
46
|
}
|
|
47
|
+
async webSocketMessage(webSocket, message) {
|
|
48
|
+
const record = await this.getStoredRecord();
|
|
49
|
+
if (!record) return;
|
|
50
|
+
const connection = record.room.connectionForWebSocket(webSocket);
|
|
51
|
+
await record.server.onMessage?.(
|
|
52
|
+
normalizeWebSocketMessage(message),
|
|
53
|
+
connection
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
async webSocketClose(webSocket, _code, _reason, _wasClean) {
|
|
57
|
+
const record = await this.getStoredRecord();
|
|
58
|
+
if (!record) return;
|
|
59
|
+
const connection = record.room.connectionForWebSocket(webSocket);
|
|
60
|
+
await record.server.onClose?.(connection);
|
|
61
|
+
}
|
|
62
|
+
async webSocketError(webSocket, error) {
|
|
63
|
+
const record = await this.getStoredRecord();
|
|
64
|
+
if (!record) return;
|
|
65
|
+
const connection = record.room.connectionForWebSocket(webSocket);
|
|
66
|
+
const normalizedError = error instanceof Error ? error : new Error(String(error));
|
|
67
|
+
await record.server.onError?.(
|
|
68
|
+
connection,
|
|
69
|
+
normalizedError
|
|
70
|
+
);
|
|
71
|
+
}
|
|
46
72
|
async acceptWebSocket(request, parsed) {
|
|
47
73
|
const pair = new WebSocketPair();
|
|
48
74
|
const [client, server] = Object.values(pair);
|
|
49
75
|
const record = await this.getRecord(parsed);
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
request.url,
|
|
53
|
-
getConnectionIdFromUrl(request.url)
|
|
54
|
-
);
|
|
55
|
-
|
|
76
|
+
const hibernating = getRuntimeConfig().webSocketMode === "hibernate";
|
|
77
|
+
const connection = new CloudflareConnection(server, {
|
|
78
|
+
uri: request.url,
|
|
79
|
+
sessionId: getConnectionIdFromUrl(request.url)
|
|
80
|
+
});
|
|
81
|
+
if (hibernating) {
|
|
82
|
+
this.ctx.acceptWebSocket(server);
|
|
83
|
+
connection.persistAttachment();
|
|
84
|
+
} else {
|
|
85
|
+
server.accept();
|
|
86
|
+
}
|
|
56
87
|
await record.server.onConnect?.(connection, {
|
|
57
88
|
request
|
|
58
89
|
});
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
90
|
+
if (!hibernating) {
|
|
91
|
+
server.addEventListener("message", (event) => {
|
|
92
|
+
void record.server.onMessage?.(
|
|
93
|
+
normalizeWebSocketMessage(event.data),
|
|
94
|
+
connection
|
|
95
|
+
);
|
|
96
|
+
});
|
|
97
|
+
server.addEventListener("close", () => {
|
|
98
|
+
record.room.deleteConnection(connection.id, connection);
|
|
99
|
+
void record.server.onClose?.(connection);
|
|
100
|
+
});
|
|
101
|
+
server.addEventListener("error", (event) => {
|
|
102
|
+
const errorData = event.error;
|
|
103
|
+
const error = errorData instanceof Error ? errorData : new Error(event.message ?? "Cloudflare WebSocket error");
|
|
104
|
+
void record.server.onError?.(connection, error);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
74
107
|
record.room.addConnection(connection);
|
|
75
108
|
return new Response(null, {
|
|
76
109
|
status: 101,
|
|
@@ -79,10 +112,18 @@ var SigneRoomDurableObject = class {
|
|
|
79
112
|
}
|
|
80
113
|
async getRecord(parsed) {
|
|
81
114
|
if (!this.recordPromise) {
|
|
115
|
+
await this.ctx.storage.put(ROUTE_STORAGE_KEY, parsed);
|
|
82
116
|
this.recordPromise = this.createRecord(parsed);
|
|
83
117
|
}
|
|
84
118
|
return this.recordPromise;
|
|
85
119
|
}
|
|
120
|
+
async getStoredRecord() {
|
|
121
|
+
if (this.recordPromise) return this.recordPromise;
|
|
122
|
+
const parsed = await this.ctx.storage.get(ROUTE_STORAGE_KEY);
|
|
123
|
+
if (!parsed) return void 0;
|
|
124
|
+
this.recordPromise = this.createRecord(parsed);
|
|
125
|
+
return this.recordPromise;
|
|
126
|
+
}
|
|
86
127
|
async createRecord(parsed) {
|
|
87
128
|
const config = getRuntimeConfig();
|
|
88
129
|
const ServerClass = config.rooms[parsed.namespace] ?? config.ServerClass;
|
|
@@ -131,9 +172,11 @@ var CloudflareRoom = class {
|
|
|
131
172
|
}
|
|
132
173
|
};
|
|
133
174
|
this.blockConcurrencyWhile = options.state.blockConcurrencyWhile.bind(options.state);
|
|
175
|
+
this.state = options.state;
|
|
176
|
+
this.hibernating = getRuntimeConfig().webSocketMode === "hibernate";
|
|
134
177
|
}
|
|
135
178
|
broadcast(msg, without = []) {
|
|
136
|
-
for (const connection of this.
|
|
179
|
+
for (const connection of this.getConnections()) {
|
|
137
180
|
if (!without.includes(connection.id)) {
|
|
138
181
|
connection.send(msg);
|
|
139
182
|
}
|
|
@@ -141,7 +184,7 @@ var CloudflareRoom = class {
|
|
|
141
184
|
}
|
|
142
185
|
getConnection(id) {
|
|
143
186
|
let connection;
|
|
144
|
-
for (const current of this.
|
|
187
|
+
for (const current of this.getConnections()) {
|
|
145
188
|
if (current.id === id || current.sessionId === id) {
|
|
146
189
|
connection = current;
|
|
147
190
|
}
|
|
@@ -149,12 +192,19 @@ var CloudflareRoom = class {
|
|
|
149
192
|
return connection;
|
|
150
193
|
}
|
|
151
194
|
getConnections() {
|
|
195
|
+
if (this.hibernating) {
|
|
196
|
+
return this.state.getWebSockets().map(
|
|
197
|
+
(webSocket) => this.connectionForWebSocket(webSocket)
|
|
198
|
+
);
|
|
199
|
+
}
|
|
152
200
|
return Array.from(this.connections.values());
|
|
153
201
|
}
|
|
154
202
|
addConnection(connection) {
|
|
203
|
+
if (this.hibernating) return;
|
|
155
204
|
this.connections.set(connection.id, connection);
|
|
156
205
|
}
|
|
157
206
|
deleteConnection(id, connection) {
|
|
207
|
+
if (this.hibernating) return;
|
|
158
208
|
if (connection) {
|
|
159
209
|
this.connections.delete(connection.id);
|
|
160
210
|
return;
|
|
@@ -165,16 +215,32 @@ var CloudflareRoom = class {
|
|
|
165
215
|
}
|
|
166
216
|
}
|
|
167
217
|
}
|
|
218
|
+
connectionForWebSocket(webSocket) {
|
|
219
|
+
return CloudflareConnection.restore(webSocket);
|
|
220
|
+
}
|
|
168
221
|
};
|
|
169
|
-
var CloudflareConnection = class {
|
|
170
|
-
constructor(webSocket,
|
|
222
|
+
var CloudflareConnection = class _CloudflareConnection {
|
|
223
|
+
constructor(webSocket, options) {
|
|
171
224
|
this.webSocket = webSocket;
|
|
172
|
-
this.id = createConnectionId();
|
|
173
225
|
this.socket = this;
|
|
174
|
-
this.
|
|
175
|
-
this.
|
|
176
|
-
this.
|
|
177
|
-
this.
|
|
226
|
+
this.id = options.id ?? createConnectionId();
|
|
227
|
+
this.sessionId = options.sessionId || this.id;
|
|
228
|
+
this.uri = options.uri;
|
|
229
|
+
this.state = options.state ?? null;
|
|
230
|
+
this.attachment = options.attachment ?? null;
|
|
231
|
+
}
|
|
232
|
+
static restore(webSocket) {
|
|
233
|
+
const attachment = webSocket.deserializeAttachment?.();
|
|
234
|
+
if (!attachment) {
|
|
235
|
+
throw new Error("Missing Signe WebSocket attachment");
|
|
236
|
+
}
|
|
237
|
+
return new _CloudflareConnection(webSocket, {
|
|
238
|
+
id: attachment.id,
|
|
239
|
+
sessionId: attachment.sessionId,
|
|
240
|
+
uri: attachment.uri,
|
|
241
|
+
state: attachment.state,
|
|
242
|
+
attachment: attachment.customAttachment
|
|
243
|
+
});
|
|
178
244
|
}
|
|
179
245
|
send(data) {
|
|
180
246
|
if (this.webSocket.readyState === void 0 || this.webSocket.readyState === WEBSOCKET_OPEN) {
|
|
@@ -186,14 +252,25 @@ var CloudflareConnection = class {
|
|
|
186
252
|
}
|
|
187
253
|
setState(state) {
|
|
188
254
|
this.state = typeof state === "function" ? state(this.state) : state;
|
|
255
|
+
this.persistAttachment();
|
|
189
256
|
return this.state;
|
|
190
257
|
}
|
|
191
258
|
serializeAttachment(attachment) {
|
|
192
259
|
this.attachment = attachment;
|
|
260
|
+
this.persistAttachment();
|
|
193
261
|
}
|
|
194
262
|
deserializeAttachment() {
|
|
195
263
|
return this.attachment;
|
|
196
264
|
}
|
|
265
|
+
persistAttachment() {
|
|
266
|
+
this.webSocket.serializeAttachment?.({
|
|
267
|
+
id: this.id,
|
|
268
|
+
sessionId: this.sessionId,
|
|
269
|
+
uri: this.uri,
|
|
270
|
+
state: this.state,
|
|
271
|
+
customAttachment: this.attachment
|
|
272
|
+
});
|
|
273
|
+
}
|
|
197
274
|
};
|
|
198
275
|
function createRuntimeConfig(ServerClass, options) {
|
|
199
276
|
return {
|
|
@@ -204,7 +281,8 @@ function createRuntimeConfig(ServerClass, options) {
|
|
|
204
281
|
rooms: {
|
|
205
282
|
main: ServerClass,
|
|
206
283
|
...options.rooms ?? {}
|
|
207
|
-
}
|
|
284
|
+
},
|
|
285
|
+
webSocketMode: options.webSocketMode ?? "standard"
|
|
208
286
|
};
|
|
209
287
|
}
|
|
210
288
|
function getRuntimeConfig() {
|
|
@@ -229,7 +307,10 @@ function createPartiesContext(env, binding, partiesPath) {
|
|
|
229
307
|
},
|
|
230
308
|
fetch(pathOrInit, init) {
|
|
231
309
|
const namespaceBinding = getNamespace(env, binding);
|
|
232
|
-
const
|
|
310
|
+
const parsed = { namespace, roomId };
|
|
311
|
+
const stub = namespaceBinding.get(
|
|
312
|
+
namespaceBinding.idFromName(getDurableObjectName(parsed))
|
|
313
|
+
);
|
|
233
314
|
if (pathOrInit instanceof Request) {
|
|
234
315
|
return fetchDurableObjectStub(stub, pathOrInit);
|
|
235
316
|
}
|
|
@@ -247,6 +328,9 @@ function createPartiesContext(env, binding, partiesPath) {
|
|
|
247
328
|
}
|
|
248
329
|
});
|
|
249
330
|
}
|
|
331
|
+
function getDurableObjectName(parsed) {
|
|
332
|
+
return `${parsed.namespace}:${parsed.roomId}`;
|
|
333
|
+
}
|
|
250
334
|
function getNamespace(env, binding) {
|
|
251
335
|
const namespace = env[binding];
|
|
252
336
|
if (!namespace) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cloudflare/index.ts"],"sourcesContent":["import type {\n DurableObjectNamespace,\n DurableObjectState,\n WebSocket as CloudflareWebSocket,\n} from \"@cloudflare/workers-types\";\nimport type * as Party from \"../types/party\";\n\nexport type CloudflareRoomServerConstructor<TServer extends Party.Server = Party.Server> = {\n new (room: Party.Room): TServer;\n};\n\nexport type CloudflareRoomWorkerOptions = {\n binding: string;\n partiesPath?: string;\n env?: Record<string, unknown>;\n rooms?: Record<string, CloudflareRoomServerConstructor>;\n};\n\nexport type CloudflareRoomEnv = Record<string, unknown>;\n\ntype ParsedPartyPath = {\n namespace: string;\n roomId: string;\n};\n\ntype CloudflareRoomRecord = {\n room: CloudflareRoom;\n server: Party.Server;\n started: Promise<void>;\n};\n\ntype CloudflareRuntimeConfig = Required<Pick<CloudflareRoomWorkerOptions, \"binding\" | \"partiesPath\">> & {\n ServerClass: CloudflareRoomServerConstructor;\n env: Record<string, unknown>;\n rooms: Record<string, CloudflareRoomServerConstructor>;\n};\n\nconst DEFAULT_PARTIES_PATH = \"/parties/main\";\nconst WEBSOCKET_OPEN = 1;\n\nlet runtimeConfig: CloudflareRuntimeConfig | undefined;\n\nexport function createCloudflareRoomWorker<TServer extends Party.Server>(\n ServerClass: CloudflareRoomServerConstructor<TServer>,\n options: CloudflareRoomWorkerOptions\n) {\n runtimeConfig = createRuntimeConfig(ServerClass, options);\n\n return {\n async fetch(\n request: Request,\n env: CloudflareRoomEnv,\n ctx: unknown\n ): Promise<Response> {\n return dispatchCloudflareRoomRequest(request, env, ctx);\n },\n };\n}\n\nexport async function dispatchCloudflareRoomRequest(\n request: Request,\n env: CloudflareRoomEnv,\n _ctx?: unknown\n): Promise<Response> {\n const config = getRuntimeConfig();\n const parsed = parsePartyRequest(request.url, config.partiesPath);\n\n if (!parsed) {\n return new Response(\"Not Found\", { status: 404 });\n }\n\n const namespace = getNamespace(env, config.binding);\n const stub = namespace.get(namespace.idFromName(parsed.roomId));\n return fetchDurableObjectStub(stub, request);\n}\n\nexport class SigneRoomDurableObject {\n private recordPromise?: Promise<CloudflareRoomRecord>;\n\n constructor(\n private readonly ctx: DurableObjectState,\n private readonly env: CloudflareRoomEnv\n ) {}\n\n async fetch(request: Request): Promise<Response> {\n const config = getRuntimeConfig();\n const parsed = parsePartyRequest(request.url, config.partiesPath);\n\n if (!parsed) {\n return new Response(\"Not Found\", { status: 404 });\n }\n\n if (isWebSocketUpgrade(request)) {\n return this.acceptWebSocket(request, parsed);\n }\n\n const record = await this.getRecord(parsed);\n return record.server.onRequest?.(request as unknown as Party.Request)\n ?? new Response(\"Not Found\", { status: 404 });\n }\n\n async alarm(): Promise<void> {\n const record = await this.recordPromise;\n await record?.server.onAlarm?.();\n }\n\n private async acceptWebSocket(\n request: Request,\n parsed: ParsedPartyPath\n ): Promise<Response> {\n const pair = new WebSocketPair();\n const [client, server] = Object.values(pair) as [\n CloudflareWebSocket,\n CloudflareWebSocket,\n ];\n const record = await this.getRecord(parsed);\n const connection = new CloudflareConnection(\n server,\n request.url,\n getConnectionIdFromUrl(request.url)\n );\n\n server.accept();\n\n await record.server.onConnect?.(connection as unknown as Party.Connection, {\n request: request as unknown as Party.Request,\n });\n\n server.addEventListener(\"message\", (event) => {\n void record.server.onMessage?.(\n normalizeWebSocketMessage(event.data),\n connection as unknown as Party.Connection\n );\n });\n server.addEventListener(\"close\", () => {\n record.room.deleteConnection(connection.id, connection);\n void record.server.onClose?.(connection as unknown as Party.Connection);\n });\n server.addEventListener(\"error\", (event) => {\n const errorData = (event as { error?: unknown; message?: string }).error;\n const error = errorData instanceof Error\n ? errorData\n : new Error((event as { message?: string }).message ?? \"Cloudflare WebSocket error\");\n void record.server.onError?.(connection as unknown as Party.Connection, error);\n });\n record.room.addConnection(connection);\n\n return new Response(null, {\n status: 101,\n webSocket: client,\n } as ResponseInit & { webSocket: CloudflareWebSocket });\n }\n\n private async getRecord(parsed: ParsedPartyPath): Promise<CloudflareRoomRecord> {\n if (!this.recordPromise) {\n this.recordPromise = this.createRecord(parsed);\n }\n\n return this.recordPromise;\n }\n\n private async createRecord(parsed: ParsedPartyPath): Promise<CloudflareRoomRecord> {\n const config = getRuntimeConfig();\n const ServerClass = config.rooms[parsed.namespace] ?? config.ServerClass;\n const room = new CloudflareRoom({\n id: parsed.roomId,\n name: parsed.namespace,\n env: {\n ...config.env,\n ...this.env,\n },\n state: this.ctx,\n binding: config.binding,\n partiesPath: config.partiesPath,\n });\n const server = new ServerClass(room as Party.Room);\n const record: CloudflareRoomRecord = {\n room,\n server,\n started: Promise.resolve(server.onStart?.()).then(() => undefined),\n };\n\n await record.started;\n return record;\n }\n}\n\nexport class CloudflareRoom implements Party.Room {\n readonly id: string;\n readonly internalID: string;\n readonly name: string;\n readonly env: Record<string, unknown>;\n readonly storage: Party.Storage;\n readonly context: Party.Context;\n readonly connections = new Map<string, Party.Connection>();\n readonly parties: Party.Context[\"parties\"];\n readonly analytics = {} as Party.Room[\"analytics\"];\n\n constructor(options: {\n id: string;\n name: string;\n env: Record<string, unknown>;\n state: DurableObjectState;\n binding: string;\n partiesPath: string;\n }) {\n this.id = options.id;\n this.internalID = `${options.name}:${options.id}`;\n this.name = options.name;\n this.env = options.env;\n this.storage = options.state.storage as Party.Storage;\n this.parties = createPartiesContext(options.env, options.binding, options.partiesPath);\n this.context = {\n parties: this.parties,\n ai: {},\n vectorize: {},\n analytics: this.analytics,\n assets: {\n fetch: async () => null,\n },\n bindings: {\n r2: {},\n kv: {},\n },\n } as Party.Context;\n this.blockConcurrencyWhile = options.state.blockConcurrencyWhile.bind(options.state);\n }\n\n blockConcurrencyWhile: Party.Room[\"blockConcurrencyWhile\"];\n\n broadcast(msg: string | ArrayBuffer | ArrayBufferView, without: string[] = []) {\n for (const connection of this.connections.values()) {\n if (!without.includes(connection.id)) {\n connection.send(msg);\n }\n }\n }\n\n getConnection<TState = unknown>(id: string): Party.Connection<TState> | undefined {\n let connection: Party.Connection | undefined;\n for (const current of this.connections.values()) {\n if (current.id === id || current.sessionId === id) {\n connection = current;\n }\n }\n return connection as Party.Connection<TState> | undefined;\n }\n\n getConnections<TState = unknown>(): Iterable<Party.Connection<TState>> {\n return Array.from(this.connections.values()) as Party.Connection<TState>[];\n }\n\n addConnection(connection: CloudflareConnection) {\n this.connections.set(connection.id, connection as unknown as Party.Connection);\n }\n\n deleteConnection(id: string, connection?: CloudflareConnection) {\n if (connection) {\n this.connections.delete(connection.id);\n return;\n }\n\n for (const [connectionKey, current] of this.connections) {\n if (current.id === id || current.sessionId === id) {\n this.connections.delete(connectionKey);\n }\n }\n }\n}\n\nexport class CloudflareConnection<TState = unknown> {\n readonly id = createConnectionId();\n readonly sessionId: string;\n readonly socket: this = this;\n readonly uri: string;\n state: Party.ConnectionState<TState> | TState | null = null;\n private attachment: unknown = null;\n\n constructor(\n private readonly webSocket: CloudflareWebSocket,\n uri: string,\n sessionId?: string\n ) {\n this.sessionId = sessionId || this.id;\n this.uri = uri;\n }\n\n send(data: string | ArrayBuffer | ArrayBufferView) {\n if (\n this.webSocket.readyState === undefined ||\n this.webSocket.readyState === WEBSOCKET_OPEN\n ) {\n this.webSocket.send(data);\n }\n }\n\n close(code?: number, reason?: string) {\n this.webSocket.close(code, reason);\n }\n\n setState(state: TState | Party.ConnectionSetStateFn<TState> | null) {\n this.state = typeof state === \"function\"\n ? (state as Party.ConnectionSetStateFn<TState>)(this.state as Party.ConnectionState<TState>)\n : state;\n return this.state as Party.ConnectionState<TState>;\n }\n\n serializeAttachment<T = unknown>(attachment: T): void {\n this.attachment = attachment;\n }\n\n deserializeAttachment<T = unknown>(): T | null {\n return this.attachment as T | null;\n }\n}\n\nfunction createRuntimeConfig<TServer extends Party.Server>(\n ServerClass: CloudflareRoomServerConstructor<TServer>,\n options: CloudflareRoomWorkerOptions\n): CloudflareRuntimeConfig {\n return {\n ServerClass: ServerClass as CloudflareRoomServerConstructor,\n binding: options.binding,\n partiesPath: normalizePath(options.partiesPath ?? DEFAULT_PARTIES_PATH),\n env: options.env ?? {},\n rooms: {\n main: ServerClass as CloudflareRoomServerConstructor,\n ...(options.rooms ?? {}),\n },\n };\n}\n\nfunction getRuntimeConfig(): CloudflareRuntimeConfig {\n if (!runtimeConfig) {\n throw new Error(\n \"createCloudflareRoomWorker() must be called before using SigneRoomDurableObject.\"\n );\n }\n\n return runtimeConfig;\n}\n\nfunction createPartiesContext(\n env: Record<string, unknown>,\n binding: string,\n partiesPath: string\n): Party.Context[\"parties\"] {\n return new Proxy({}, {\n get(_target, namespace: string) {\n return {\n get(roomId: string) {\n return {\n connect: () => {\n throw new Error(\"Party stub connect() is not implemented by @signe/room/cloudflare\");\n },\n socket: async () => {\n throw new Error(\"Party stub socket() is not implemented by @signe/room/cloudflare\");\n },\n fetch(pathOrInit?: string | RequestInit | Request, init?: RequestInit) {\n const namespaceBinding = getNamespace(env, binding);\n const stub = namespaceBinding.get(namespaceBinding.idFromName(roomId));\n if (pathOrInit instanceof Request) {\n return fetchDurableObjectStub(stub, pathOrInit);\n }\n const path = typeof pathOrInit === \"string\" ? pathOrInit : \"/\";\n const requestInit = typeof pathOrInit === \"string\" ? init : pathOrInit;\n return fetchDurableObjectStub(\n stub,\n toLocalUrl(`${getNamespacePath(partiesPath, namespace, roomId)}${normalizeStubPath(path)}`),\n requestInit as RequestInit | undefined\n );\n },\n };\n },\n };\n },\n }) as Party.Context[\"parties\"];\n}\n\nfunction getNamespace(env: Record<string, unknown>, binding: string) {\n const namespace = env[binding] as DurableObjectNamespace | undefined;\n\n if (!namespace) {\n throw new Error(`Missing Durable Object binding: ${binding}`);\n }\n\n return namespace;\n}\n\nfunction fetchDurableObjectStub(\n stub: unknown,\n input: Request | string | URL,\n init?: RequestInit\n): Promise<Response> {\n return (stub as {\n fetch(request: Request | string | URL, init?: RequestInit): Promise<Response>;\n }).fetch(input, init);\n}\n\nfunction parsePartyRequest(url: string, partiesPath: string): ParsedPartyPath | null {\n const requestUrl = new URL(url);\n const segments = trimSlashes(requestUrl.pathname).split(\"/\");\n const configuredSegments = trimSlashes(partiesPath).split(\"/\");\n const baseSegments = configuredSegments.slice(0, -1);\n\n if (segments.length < baseSegments.length + 2) {\n return null;\n }\n\n for (let index = 0; index < baseSegments.length; index++) {\n if (segments[index] !== baseSegments[index]) {\n return null;\n }\n }\n\n return {\n namespace: decodeURIComponent(segments[baseSegments.length]),\n roomId: decodeURIComponent(segments[baseSegments.length + 1]),\n };\n}\n\nfunction getNamespacePath(partiesPath: string, namespace: string, roomId: string) {\n const baseSegments = trimSlashes(partiesPath).split(\"/\").slice(0, -1);\n return `/${[...baseSegments, namespace, encodeURIComponent(roomId)].join(\"/\")}`;\n}\n\nfunction isWebSocketUpgrade(request: Request) {\n return request.headers.get(\"Upgrade\")?.toLowerCase() === \"websocket\";\n}\n\nfunction normalizeWebSocketMessage(data: unknown): string | ArrayBuffer | ArrayBufferView {\n if (typeof data === \"string\" || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\n return data;\n }\n\n return String(data);\n}\n\nfunction normalizePath(path: string) {\n return `/${trimSlashes(path)}`;\n}\n\nfunction toLocalUrl(path: string) {\n return path.startsWith(\"http://\") || path.startsWith(\"https://\")\n ? path\n : `http://localhost${path.startsWith(\"/\") ? path : `/${path}`}`;\n}\n\nfunction normalizeStubPath(path: string) {\n if (!path || path === \"/\") {\n return \"\";\n }\n return path.startsWith(\"/\") ? path : `/${path}`;\n}\n\nfunction getConnectionIdFromUrl(url: string) {\n const requestedId = new URL(url).searchParams.get(\"id\")?.trim();\n return requestedId || undefined;\n}\n\nfunction trimSlashes(value: string) {\n return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction createConnectionId() {\n return Math.random().toString(36).slice(2, 12);\n}\n\ndeclare const WebSocketPair: {\n new (): {\n 0: CloudflareWebSocket;\n 1: CloudflareWebSocket;\n };\n};\n"],"mappings":";;;AAqCA,IAAM,uBAAuB;AAC7B,IAAM,iBAAiB;AAEvB,IA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AO,IAAI,YAAY,IAAI,CAAC;AAC9B;AAEA,SAAS,WAAW,MAAc;AAChC,SAAO,KAAK,WAAW,SAAS,KAAK,KAAK,WAAW,UAAU,IAC3D,OACA,mBAAmB,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI,EAAE;AACjE;AAEA,SAAS,kBAAkB,MAAc;AACvC,MAAI,CAAC,QAAQ,SAAS,KAAK;AACzB,WAAO;AAAA,EACT;AACA,SAAO,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI;AAC/C;AAEA,SAAS,uBAAuB,KAAa;AAC3C,QAAM,cAAc,IAAI,IAAI,GAAG,EAAE,aAAa,IAAI,IAAI,GAAG,KAAK;AAC9D,SAAO,eAAe;AACxB;AAEA,SAAS,YAAY,OAAe;AAClC,SAAO,MAAM,QAAQ,cAAc,EAAE;AACvC;AAEA,SAAS,qBAAqB;AAC5B,SAAO,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE;AAC/C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/cloudflare/index.ts"],"sourcesContent":["import type {\n DurableObjectNamespace,\n DurableObjectState,\n WebSocket as CloudflareWebSocket,\n} from \"@cloudflare/workers-types\";\nimport type * as Party from \"../types/party\";\n\nexport type CloudflareRoomServerConstructor<TServer extends Party.Server = Party.Server> = {\n new (room: Party.Room): TServer;\n};\n\nexport type CloudflareRoomWorkerOptions = {\n binding: string;\n partiesPath?: string;\n env?: Record<string, unknown>;\n rooms?: Record<string, CloudflareRoomServerConstructor>;\n webSocketMode?: \"standard\" | \"hibernate\";\n};\n\nexport type CloudflareRoomEnv = Record<string, unknown>;\n\ntype ParsedPartyPath = {\n namespace: string;\n roomId: string;\n};\n\ntype CloudflareRoomRecord = {\n room: CloudflareRoom;\n server: Party.Server;\n started: Promise<void>;\n};\n\ntype CloudflareRuntimeConfig = Required<Pick<CloudflareRoomWorkerOptions, \"binding\" | \"partiesPath\">> & {\n ServerClass: CloudflareRoomServerConstructor;\n env: Record<string, unknown>;\n rooms: Record<string, CloudflareRoomServerConstructor>;\n webSocketMode: \"standard\" | \"hibernate\";\n};\n\nconst DEFAULT_PARTIES_PATH = \"/parties/main\";\nconst WEBSOCKET_OPEN = 1;\nconst ROUTE_STORAGE_KEY = \"$signe:cloudflare-route\";\n\ntype CloudflareConnectionAttachment = {\n id: string;\n sessionId: string;\n uri: string;\n state: unknown;\n customAttachment: unknown;\n};\n\nlet runtimeConfig: CloudflareRuntimeConfig | undefined;\n\nexport function createCloudflareRoomWorker<TServer extends Party.Server>(\n ServerClass: CloudflareRoomServerConstructor<TServer>,\n options: CloudflareRoomWorkerOptions\n) {\n runtimeConfig = createRuntimeConfig(ServerClass, options);\n\n return {\n async fetch(\n request: Request,\n env: CloudflareRoomEnv,\n ctx: unknown\n ): Promise<Response> {\n return dispatchCloudflareRoomRequest(request, env, ctx);\n },\n };\n}\n\nexport async function dispatchCloudflareRoomRequest(\n request: Request,\n env: CloudflareRoomEnv,\n _ctx?: unknown\n): Promise<Response> {\n const config = getRuntimeConfig();\n const parsed = parsePartyRequest(request.url, config.partiesPath);\n\n if (!parsed) {\n return new Response(\"Not Found\", { status: 404 });\n }\n\n const namespace = getNamespace(env, config.binding);\n const stub = namespace.get(namespace.idFromName(getDurableObjectName(parsed)));\n return fetchDurableObjectStub(stub, request);\n}\n\nexport class SigneRoomDurableObject {\n private recordPromise?: Promise<CloudflareRoomRecord>;\n\n constructor(\n private readonly ctx: DurableObjectState,\n private readonly env: CloudflareRoomEnv\n ) {}\n\n async fetch(request: Request): Promise<Response> {\n const config = getRuntimeConfig();\n const parsed = parsePartyRequest(request.url, config.partiesPath);\n\n if (!parsed) {\n return new Response(\"Not Found\", { status: 404 });\n }\n\n if (isWebSocketUpgrade(request)) {\n return this.acceptWebSocket(request, parsed);\n }\n\n const record = await this.getRecord(parsed);\n return record.server.onRequest?.(request as unknown as Party.Request)\n ?? new Response(\"Not Found\", { status: 404 });\n }\n\n async alarm(): Promise<void> {\n const record = await this.getStoredRecord();\n await record?.server.onAlarm?.();\n }\n\n async webSocketMessage(\n webSocket: CloudflareWebSocket,\n message: string | ArrayBuffer\n ): Promise<void> {\n const record = await this.getStoredRecord();\n if (!record) return;\n const connection = record.room.connectionForWebSocket(webSocket);\n await record.server.onMessage?.(\n normalizeWebSocketMessage(message),\n connection as unknown as Party.Connection\n );\n }\n\n async webSocketClose(\n webSocket: CloudflareWebSocket,\n _code: number,\n _reason: string,\n _wasClean: boolean\n ): Promise<void> {\n const record = await this.getStoredRecord();\n if (!record) return;\n const connection = record.room.connectionForWebSocket(webSocket);\n await record.server.onClose?.(connection as unknown as Party.Connection);\n }\n\n async webSocketError(\n webSocket: CloudflareWebSocket,\n error: unknown\n ): Promise<void> {\n const record = await this.getStoredRecord();\n if (!record) return;\n const connection = record.room.connectionForWebSocket(webSocket);\n const normalizedError = error instanceof Error\n ? error\n : new Error(String(error));\n await record.server.onError?.(\n connection as unknown as Party.Connection,\n normalizedError\n );\n }\n\n private async acceptWebSocket(\n request: Request,\n parsed: ParsedPartyPath\n ): Promise<Response> {\n const pair = new WebSocketPair();\n const [client, server] = Object.values(pair) as [\n CloudflareWebSocket,\n CloudflareWebSocket,\n ];\n const record = await this.getRecord(parsed);\n const hibernating = getRuntimeConfig().webSocketMode === \"hibernate\";\n const connection = new CloudflareConnection(server, {\n uri: request.url,\n sessionId: getConnectionIdFromUrl(request.url),\n });\n\n if (hibernating) {\n this.ctx.acceptWebSocket(server);\n connection.persistAttachment();\n } else {\n server.accept();\n }\n\n await record.server.onConnect?.(connection as unknown as Party.Connection, {\n request: request as unknown as Party.Request,\n });\n\n if (!hibernating) {\n server.addEventListener(\"message\", (event) => {\n void record.server.onMessage?.(\n normalizeWebSocketMessage(event.data),\n connection as unknown as Party.Connection\n );\n });\n server.addEventListener(\"close\", () => {\n record.room.deleteConnection(connection.id, connection);\n void record.server.onClose?.(connection as unknown as Party.Connection);\n });\n server.addEventListener(\"error\", (event) => {\n const errorData = (event as { error?: unknown; message?: string }).error;\n const error = errorData instanceof Error\n ? errorData\n : new Error((event as { message?: string }).message ?? \"Cloudflare WebSocket error\");\n void record.server.onError?.(connection as unknown as Party.Connection, error);\n });\n }\n record.room.addConnection(connection);\n\n return new Response(null, {\n status: 101,\n webSocket: client,\n } as ResponseInit & { webSocket: CloudflareWebSocket });\n }\n\n private async getRecord(parsed: ParsedPartyPath): Promise<CloudflareRoomRecord> {\n if (!this.recordPromise) {\n await this.ctx.storage.put(ROUTE_STORAGE_KEY, parsed);\n this.recordPromise = this.createRecord(parsed);\n }\n\n return this.recordPromise;\n }\n\n private async getStoredRecord(): Promise<CloudflareRoomRecord | undefined> {\n if (this.recordPromise) return this.recordPromise;\n const parsed = await this.ctx.storage.get<ParsedPartyPath>(ROUTE_STORAGE_KEY);\n if (!parsed) return undefined;\n this.recordPromise = this.createRecord(parsed);\n return this.recordPromise;\n }\n\n private async createRecord(parsed: ParsedPartyPath): Promise<CloudflareRoomRecord> {\n const config = getRuntimeConfig();\n const ServerClass = config.rooms[parsed.namespace] ?? config.ServerClass;\n const room = new CloudflareRoom({\n id: parsed.roomId,\n name: parsed.namespace,\n env: {\n ...config.env,\n ...this.env,\n },\n state: this.ctx,\n binding: config.binding,\n partiesPath: config.partiesPath,\n });\n const server = new ServerClass(room as Party.Room);\n const record: CloudflareRoomRecord = {\n room,\n server,\n started: Promise.resolve(server.onStart?.()).then(() => undefined),\n };\n\n await record.started;\n return record;\n }\n}\n\nexport class CloudflareRoom implements Party.Room {\n readonly id: string;\n readonly internalID: string;\n readonly name: string;\n readonly env: Record<string, unknown>;\n readonly storage: Party.Storage;\n readonly context: Party.Context;\n readonly connections = new Map<string, Party.Connection>();\n readonly parties: Party.Context[\"parties\"];\n readonly analytics = {} as Party.Room[\"analytics\"];\n private readonly hibernating: boolean;\n private readonly state: DurableObjectState;\n\n constructor(options: {\n id: string;\n name: string;\n env: Record<string, unknown>;\n state: DurableObjectState;\n binding: string;\n partiesPath: string;\n }) {\n this.id = options.id;\n this.internalID = `${options.name}:${options.id}`;\n this.name = options.name;\n this.env = options.env;\n this.storage = options.state.storage as Party.Storage;\n this.parties = createPartiesContext(options.env, options.binding, options.partiesPath);\n this.context = {\n parties: this.parties,\n ai: {},\n vectorize: {},\n analytics: this.analytics,\n assets: {\n fetch: async () => null,\n },\n bindings: {\n r2: {},\n kv: {},\n },\n } as Party.Context;\n this.blockConcurrencyWhile = options.state.blockConcurrencyWhile.bind(options.state);\n this.state = options.state;\n this.hibernating = getRuntimeConfig().webSocketMode === \"hibernate\";\n }\n\n blockConcurrencyWhile: Party.Room[\"blockConcurrencyWhile\"];\n\n broadcast(msg: string | ArrayBuffer | ArrayBufferView, without: string[] = []) {\n for (const connection of this.getConnections()) {\n if (!without.includes(connection.id)) {\n connection.send(msg);\n }\n }\n }\n\n getConnection<TState = unknown>(id: string): Party.Connection<TState> | undefined {\n let connection: Party.Connection | undefined;\n for (const current of this.getConnections()) {\n if (current.id === id || current.sessionId === id) {\n connection = current;\n }\n }\n return connection as Party.Connection<TState> | undefined;\n }\n\n getConnections<TState = unknown>(): Iterable<Party.Connection<TState>> {\n if (this.hibernating) {\n return this.state.getWebSockets().map((webSocket) =>\n this.connectionForWebSocket(webSocket as CloudflareWebSocket)\n ) as unknown as Party.Connection<TState>[];\n }\n return Array.from(this.connections.values()) as Party.Connection<TState>[];\n }\n\n addConnection(connection: CloudflareConnection) {\n if (this.hibernating) return;\n this.connections.set(connection.id, connection as unknown as Party.Connection);\n }\n\n deleteConnection(id: string, connection?: CloudflareConnection) {\n if (this.hibernating) return;\n if (connection) {\n this.connections.delete(connection.id);\n return;\n }\n\n for (const [connectionKey, current] of this.connections) {\n if (current.id === id || current.sessionId === id) {\n this.connections.delete(connectionKey);\n }\n }\n }\n\n\n connectionForWebSocket(webSocket: CloudflareWebSocket): CloudflareConnection {\n return CloudflareConnection.restore(webSocket);\n }\n}\n\nexport class CloudflareConnection<TState = unknown> {\n readonly id: string;\n readonly sessionId: string;\n readonly socket: this = this;\n readonly uri: string;\n state: Party.ConnectionState<TState> | TState | null;\n private attachment: unknown;\n\n constructor(\n private readonly webSocket: CloudflareWebSocket,\n options: {\n id?: string;\n uri: string;\n sessionId?: string;\n state?: Party.ConnectionState<TState> | TState | null;\n attachment?: unknown;\n }\n ) {\n this.id = options.id ?? createConnectionId();\n this.sessionId = options.sessionId || this.id;\n this.uri = options.uri;\n this.state = options.state ?? null;\n this.attachment = options.attachment ?? null;\n }\n\n static restore(webSocket: CloudflareWebSocket): CloudflareConnection {\n const attachment = webSocket.deserializeAttachment?.() as\n | CloudflareConnectionAttachment\n | undefined;\n if (!attachment) {\n throw new Error(\"Missing Signe WebSocket attachment\");\n }\n return new CloudflareConnection(webSocket, {\n id: attachment.id,\n sessionId: attachment.sessionId,\n uri: attachment.uri,\n state: attachment.state,\n attachment: attachment.customAttachment,\n });\n }\n\n send(data: string | ArrayBuffer | ArrayBufferView) {\n if (\n this.webSocket.readyState === undefined ||\n this.webSocket.readyState === WEBSOCKET_OPEN\n ) {\n this.webSocket.send(data);\n }\n }\n\n close(code?: number, reason?: string) {\n this.webSocket.close(code, reason);\n }\n\n setState(state: TState | Party.ConnectionSetStateFn<TState> | null) {\n this.state = typeof state === \"function\"\n ? (state as Party.ConnectionSetStateFn<TState>)(this.state as Party.ConnectionState<TState>)\n : state;\n this.persistAttachment();\n return this.state as Party.ConnectionState<TState>;\n }\n\n serializeAttachment<T = unknown>(attachment: T): void {\n this.attachment = attachment;\n this.persistAttachment();\n }\n\n deserializeAttachment<T = unknown>(): T | null {\n return this.attachment as T | null;\n }\n\n persistAttachment(): void {\n this.webSocket.serializeAttachment?.({\n id: this.id,\n sessionId: this.sessionId,\n uri: this.uri,\n state: this.state,\n customAttachment: this.attachment,\n } satisfies CloudflareConnectionAttachment);\n }\n}\n\nfunction createRuntimeConfig<TServer extends Party.Server>(\n ServerClass: CloudflareRoomServerConstructor<TServer>,\n options: CloudflareRoomWorkerOptions\n): CloudflareRuntimeConfig {\n return {\n ServerClass: ServerClass as CloudflareRoomServerConstructor,\n binding: options.binding,\n partiesPath: normalizePath(options.partiesPath ?? DEFAULT_PARTIES_PATH),\n env: options.env ?? {},\n rooms: {\n main: ServerClass as CloudflareRoomServerConstructor,\n ...(options.rooms ?? {}),\n },\n webSocketMode: options.webSocketMode ?? \"standard\",\n };\n}\n\nfunction getRuntimeConfig(): CloudflareRuntimeConfig {\n if (!runtimeConfig) {\n throw new Error(\n \"createCloudflareRoomWorker() must be called before using SigneRoomDurableObject.\"\n );\n }\n\n return runtimeConfig;\n}\n\nfunction createPartiesContext(\n env: Record<string, unknown>,\n binding: string,\n partiesPath: string\n): Party.Context[\"parties\"] {\n return new Proxy({}, {\n get(_target, namespace: string) {\n return {\n get(roomId: string) {\n return {\n connect: () => {\n throw new Error(\"Party stub connect() is not implemented by @signe/room/cloudflare\");\n },\n socket: async () => {\n throw new Error(\"Party stub socket() is not implemented by @signe/room/cloudflare\");\n },\n fetch(pathOrInit?: string | RequestInit | Request, init?: RequestInit) {\n const namespaceBinding = getNamespace(env, binding);\n const parsed = { namespace, roomId };\n const stub = namespaceBinding.get(\n namespaceBinding.idFromName(getDurableObjectName(parsed))\n );\n if (pathOrInit instanceof Request) {\n return fetchDurableObjectStub(stub, pathOrInit);\n }\n const path = typeof pathOrInit === \"string\" ? pathOrInit : \"/\";\n const requestInit = typeof pathOrInit === \"string\" ? init : pathOrInit;\n return fetchDurableObjectStub(\n stub,\n toLocalUrl(`${getNamespacePath(partiesPath, namespace, roomId)}${normalizeStubPath(path)}`),\n requestInit as RequestInit | undefined\n );\n },\n };\n },\n };\n },\n }) as Party.Context[\"parties\"];\n}\n\nfunction getDurableObjectName(parsed: ParsedPartyPath): string {\n return `${parsed.namespace}:${parsed.roomId}`;\n}\n\nfunction getNamespace(env: Record<string, unknown>, binding: string) {\n const namespace = env[binding] as DurableObjectNamespace | undefined;\n\n if (!namespace) {\n throw new Error(`Missing Durable Object binding: ${binding}`);\n }\n\n return namespace;\n}\n\nfunction fetchDurableObjectStub(\n stub: unknown,\n input: Request | string | URL,\n init?: RequestInit\n): Promise<Response> {\n return (stub as {\n fetch(request: Request | string | URL, init?: RequestInit): Promise<Response>;\n }).fetch(input, init);\n}\n\nfunction parsePartyRequest(url: string, partiesPath: string): ParsedPartyPath | null {\n const requestUrl = new URL(url);\n const segments = trimSlashes(requestUrl.pathname).split(\"/\");\n const configuredSegments = trimSlashes(partiesPath).split(\"/\");\n const baseSegments = configuredSegments.slice(0, -1);\n\n if (segments.length < baseSegments.length + 2) {\n return null;\n }\n\n for (let index = 0; index < baseSegments.length; index++) {\n if (segments[index] !== baseSegments[index]) {\n return null;\n }\n }\n\n return {\n namespace: decodeURIComponent(segments[baseSegments.length]),\n roomId: decodeURIComponent(segments[baseSegments.length + 1]),\n };\n}\n\nfunction getNamespacePath(partiesPath: string, namespace: string, roomId: string) {\n const baseSegments = trimSlashes(partiesPath).split(\"/\").slice(0, -1);\n return `/${[...baseSegments, namespace, encodeURIComponent(roomId)].join(\"/\")}`;\n}\n\nfunction isWebSocketUpgrade(request: Request) {\n return request.headers.get(\"Upgrade\")?.toLowerCase() === \"websocket\";\n}\n\nfunction normalizeWebSocketMessage(data: unknown): string | ArrayBuffer | ArrayBufferView {\n if (typeof data === \"string\" || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\n return data;\n }\n\n return String(data);\n}\n\nfunction normalizePath(path: string) {\n return `/${trimSlashes(path)}`;\n}\n\nfunction toLocalUrl(path: string) {\n return path.startsWith(\"http://\") || path.startsWith(\"https://\")\n ? path\n : `http://localhost${path.startsWith(\"/\") ? path : `/${path}`}`;\n}\n\nfunction normalizeStubPath(path: string) {\n if (!path || path === \"/\") {\n return \"\";\n }\n return path.startsWith(\"/\") ? path : `/${path}`;\n}\n\nfunction getConnectionIdFromUrl(url: string) {\n const requestedId = new URL(url).searchParams.get(\"id\")?.trim();\n return requestedId || undefined;\n}\n\nfunction trimSlashes(value: string) {\n return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction createConnectionId() {\n return Math.random().toString(36).slice(2, 12);\n}\n\ndeclare const WebSocketPair: {\n new (): {\n 0: CloudflareWebSocket;\n 1: CloudflareWebSocket;\n };\n};\n"],"mappings":";;;AAuCA,IAAM,uBAAuB;AAC7B,IAAM,iBAAiB;AACvB,IAAM,oBAAoB;AAU1B,IAAI;AAEG,SAAS,2BACd,aACA,SACA;AACA,kBAAgB,oBAAoB,aAAa,OAAO;AAExD,SAAO;AAAA,IACL,MAAM,MACJ,SACA,KACA,KACmB;AACnB,aAAO,8BAA8B,SAAS,KAAK,GAAG;AAAA,IACxD;AAAA,EACF;AACF;AAEA,eAAsB,8BACpB,SACA,KACA,MACmB;AACnB,QAAM,SAAS,iBAAiB;AAChC,QAAM,SAAS,kBAAkB,QAAQ,KAAK,OAAO,WAAW;AAEhE,MAAI,CAAC,QAAQ;AACX,WAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;AAAA,EAClD;AAEA,QAAM,YAAY,aAAa,KAAK,OAAO,OAAO;AAClD,QAAM,OAAO,UAAU,IAAI,UAAU,WAAW,qBAAqB,MAAM,CAAC,CAAC;AAC7E,SAAO,uBAAuB,MAAM,OAAO;AAC7C;AAEO,IAAM,yBAAN,MAA6B;AAAA,EAGlC,YACmB,KACA,KACjB;AAFiB;AACA;AAAA,EAChB;AAAA,EAEH,MAAM,MAAM,SAAqC;AAC/C,UAAM,SAAS,iBAAiB;AAChC,UAAM,SAAS,kBAAkB,QAAQ,KAAK,OAAO,WAAW;AAEhE,QAAI,CAAC,QAAQ;AACX,aAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;AAAA,IAClD;AAEA,QAAI,mBAAmB,OAAO,GAAG;AAC/B,aAAO,KAAK,gBAAgB,SAAS,MAAM;AAAA,IAC7C;AAEA,UAAM,SAAS,MAAM,KAAK,UAAU,MAAM;AAC1C,WAAO,OAAO,OAAO,YAAY,OAAmC,KAC/D,IAAI,SAAS,aA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,EACT;AAEA,SAAO,OAAO,IAAI;AACpB;AAEA,SAAS,cAAc,MAAc;AACnC,SAAO,IAAI,YAAY,IAAI,CAAC;AAC9B;AAEA,SAAS,WAAW,MAAc;AAChC,SAAO,KAAK,WAAW,SAAS,KAAK,KAAK,WAAW,UAAU,IAC3D,OACA,mBAAmB,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI,EAAE;AACjE;AAEA,SAAS,kBAAkB,MAAc;AACvC,MAAI,CAAC,QAAQ,SAAS,KAAK;AACzB,WAAO;AAAA,EACT;AACA,SAAO,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI;AAC/C;AAEA,SAAS,uBAAuB,KAAa;AAC3C,QAAM,cAAc,IAAI,IAAI,GAAG,EAAE,aAAa,IAAI,IAAI,GAAG,KAAK;AAC9D,SAAO,eAAe;AACxB;AAEA,SAAS,YAAY,OAAe;AAClC,SAAO,MAAM,QAAQ,cAAc,EAAE;AACvC;AAEA,SAAS,qBAAqB;AAC5B,SAAO,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE;AAC/C;","names":[]}
|
|
@@ -33,9 +33,13 @@ export { SigneRoomDurableObject };
|
|
|
33
33
|
export default createCloudflareRoomWorker(CounterServer, {
|
|
34
34
|
binding: "ROOMS",
|
|
35
35
|
partiesPath: "/parties/main",
|
|
36
|
+
webSocketMode: "hibernate",
|
|
36
37
|
});
|
|
37
38
|
```
|
|
38
39
|
|
|
40
|
+
`webSocketMode: "hibernate"` lets Cloudflare evict idle Worker isolates while
|
|
41
|
+
Signe restores connection state from Durable Object WebSocket attachments.
|
|
42
|
+
|
|
39
43
|
This example wraps that worker so non-room requests are served by the `ASSETS`
|
|
40
44
|
binding from `public/`.
|
|
41
45
|
|
package/package.json
CHANGED
package/src/cloudflare/index.ts
CHANGED
|
@@ -14,6 +14,7 @@ export type CloudflareRoomWorkerOptions = {
|
|
|
14
14
|
partiesPath?: string;
|
|
15
15
|
env?: Record<string, unknown>;
|
|
16
16
|
rooms?: Record<string, CloudflareRoomServerConstructor>;
|
|
17
|
+
webSocketMode?: "standard" | "hibernate";
|
|
17
18
|
};
|
|
18
19
|
|
|
19
20
|
export type CloudflareRoomEnv = Record<string, unknown>;
|
|
@@ -33,10 +34,20 @@ type CloudflareRuntimeConfig = Required<Pick<CloudflareRoomWorkerOptions, "bindi
|
|
|
33
34
|
ServerClass: CloudflareRoomServerConstructor;
|
|
34
35
|
env: Record<string, unknown>;
|
|
35
36
|
rooms: Record<string, CloudflareRoomServerConstructor>;
|
|
37
|
+
webSocketMode: "standard" | "hibernate";
|
|
36
38
|
};
|
|
37
39
|
|
|
38
40
|
const DEFAULT_PARTIES_PATH = "/parties/main";
|
|
39
41
|
const WEBSOCKET_OPEN = 1;
|
|
42
|
+
const ROUTE_STORAGE_KEY = "$signe:cloudflare-route";
|
|
43
|
+
|
|
44
|
+
type CloudflareConnectionAttachment = {
|
|
45
|
+
id: string;
|
|
46
|
+
sessionId: string;
|
|
47
|
+
uri: string;
|
|
48
|
+
state: unknown;
|
|
49
|
+
customAttachment: unknown;
|
|
50
|
+
};
|
|
40
51
|
|
|
41
52
|
let runtimeConfig: CloudflareRuntimeConfig | undefined;
|
|
42
53
|
|
|
@@ -70,7 +81,7 @@ export async function dispatchCloudflareRoomRequest(
|
|
|
70
81
|
}
|
|
71
82
|
|
|
72
83
|
const namespace = getNamespace(env, config.binding);
|
|
73
|
-
const stub = namespace.get(namespace.idFromName(parsed
|
|
84
|
+
const stub = namespace.get(namespace.idFromName(getDurableObjectName(parsed)));
|
|
74
85
|
return fetchDurableObjectStub(stub, request);
|
|
75
86
|
}
|
|
76
87
|
|
|
@@ -100,10 +111,51 @@ export class SigneRoomDurableObject {
|
|
|
100
111
|
}
|
|
101
112
|
|
|
102
113
|
async alarm(): Promise<void> {
|
|
103
|
-
const record = await this.
|
|
114
|
+
const record = await this.getStoredRecord();
|
|
104
115
|
await record?.server.onAlarm?.();
|
|
105
116
|
}
|
|
106
117
|
|
|
118
|
+
async webSocketMessage(
|
|
119
|
+
webSocket: CloudflareWebSocket,
|
|
120
|
+
message: string | ArrayBuffer
|
|
121
|
+
): Promise<void> {
|
|
122
|
+
const record = await this.getStoredRecord();
|
|
123
|
+
if (!record) return;
|
|
124
|
+
const connection = record.room.connectionForWebSocket(webSocket);
|
|
125
|
+
await record.server.onMessage?.(
|
|
126
|
+
normalizeWebSocketMessage(message),
|
|
127
|
+
connection as unknown as Party.Connection
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async webSocketClose(
|
|
132
|
+
webSocket: CloudflareWebSocket,
|
|
133
|
+
_code: number,
|
|
134
|
+
_reason: string,
|
|
135
|
+
_wasClean: boolean
|
|
136
|
+
): Promise<void> {
|
|
137
|
+
const record = await this.getStoredRecord();
|
|
138
|
+
if (!record) return;
|
|
139
|
+
const connection = record.room.connectionForWebSocket(webSocket);
|
|
140
|
+
await record.server.onClose?.(connection as unknown as Party.Connection);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async webSocketError(
|
|
144
|
+
webSocket: CloudflareWebSocket,
|
|
145
|
+
error: unknown
|
|
146
|
+
): Promise<void> {
|
|
147
|
+
const record = await this.getStoredRecord();
|
|
148
|
+
if (!record) return;
|
|
149
|
+
const connection = record.room.connectionForWebSocket(webSocket);
|
|
150
|
+
const normalizedError = error instanceof Error
|
|
151
|
+
? error
|
|
152
|
+
: new Error(String(error));
|
|
153
|
+
await record.server.onError?.(
|
|
154
|
+
connection as unknown as Party.Connection,
|
|
155
|
+
normalizedError
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
107
159
|
private async acceptWebSocket(
|
|
108
160
|
request: Request,
|
|
109
161
|
parsed: ParsedPartyPath
|
|
@@ -114,35 +166,42 @@ export class SigneRoomDurableObject {
|
|
|
114
166
|
CloudflareWebSocket,
|
|
115
167
|
];
|
|
116
168
|
const record = await this.getRecord(parsed);
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
request.url,
|
|
120
|
-
getConnectionIdFromUrl(request.url)
|
|
121
|
-
);
|
|
169
|
+
const hibernating = getRuntimeConfig().webSocketMode === "hibernate";
|
|
170
|
+
const connection = new CloudflareConnection(server, {
|
|
171
|
+
uri: request.url,
|
|
172
|
+
sessionId: getConnectionIdFromUrl(request.url),
|
|
173
|
+
});
|
|
122
174
|
|
|
123
|
-
|
|
175
|
+
if (hibernating) {
|
|
176
|
+
this.ctx.acceptWebSocket(server);
|
|
177
|
+
connection.persistAttachment();
|
|
178
|
+
} else {
|
|
179
|
+
server.accept();
|
|
180
|
+
}
|
|
124
181
|
|
|
125
182
|
await record.server.onConnect?.(connection as unknown as Party.Connection, {
|
|
126
183
|
request: request as unknown as Party.Request,
|
|
127
184
|
});
|
|
128
185
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
186
|
+
if (!hibernating) {
|
|
187
|
+
server.addEventListener("message", (event) => {
|
|
188
|
+
void record.server.onMessage?.(
|
|
189
|
+
normalizeWebSocketMessage(event.data),
|
|
190
|
+
connection as unknown as Party.Connection
|
|
191
|
+
);
|
|
192
|
+
});
|
|
193
|
+
server.addEventListener("close", () => {
|
|
194
|
+
record.room.deleteConnection(connection.id, connection);
|
|
195
|
+
void record.server.onClose?.(connection as unknown as Party.Connection);
|
|
196
|
+
});
|
|
197
|
+
server.addEventListener("error", (event) => {
|
|
198
|
+
const errorData = (event as { error?: unknown; message?: string }).error;
|
|
199
|
+
const error = errorData instanceof Error
|
|
200
|
+
? errorData
|
|
201
|
+
: new Error((event as { message?: string }).message ?? "Cloudflare WebSocket error");
|
|
202
|
+
void record.server.onError?.(connection as unknown as Party.Connection, error);
|
|
203
|
+
});
|
|
204
|
+
}
|
|
146
205
|
record.room.addConnection(connection);
|
|
147
206
|
|
|
148
207
|
return new Response(null, {
|
|
@@ -153,12 +212,21 @@ export class SigneRoomDurableObject {
|
|
|
153
212
|
|
|
154
213
|
private async getRecord(parsed: ParsedPartyPath): Promise<CloudflareRoomRecord> {
|
|
155
214
|
if (!this.recordPromise) {
|
|
215
|
+
await this.ctx.storage.put(ROUTE_STORAGE_KEY, parsed);
|
|
156
216
|
this.recordPromise = this.createRecord(parsed);
|
|
157
217
|
}
|
|
158
218
|
|
|
159
219
|
return this.recordPromise;
|
|
160
220
|
}
|
|
161
221
|
|
|
222
|
+
private async getStoredRecord(): Promise<CloudflareRoomRecord | undefined> {
|
|
223
|
+
if (this.recordPromise) return this.recordPromise;
|
|
224
|
+
const parsed = await this.ctx.storage.get<ParsedPartyPath>(ROUTE_STORAGE_KEY);
|
|
225
|
+
if (!parsed) return undefined;
|
|
226
|
+
this.recordPromise = this.createRecord(parsed);
|
|
227
|
+
return this.recordPromise;
|
|
228
|
+
}
|
|
229
|
+
|
|
162
230
|
private async createRecord(parsed: ParsedPartyPath): Promise<CloudflareRoomRecord> {
|
|
163
231
|
const config = getRuntimeConfig();
|
|
164
232
|
const ServerClass = config.rooms[parsed.namespace] ?? config.ServerClass;
|
|
@@ -195,6 +263,8 @@ export class CloudflareRoom implements Party.Room {
|
|
|
195
263
|
readonly connections = new Map<string, Party.Connection>();
|
|
196
264
|
readonly parties: Party.Context["parties"];
|
|
197
265
|
readonly analytics = {} as Party.Room["analytics"];
|
|
266
|
+
private readonly hibernating: boolean;
|
|
267
|
+
private readonly state: DurableObjectState;
|
|
198
268
|
|
|
199
269
|
constructor(options: {
|
|
200
270
|
id: string;
|
|
@@ -224,12 +294,14 @@ export class CloudflareRoom implements Party.Room {
|
|
|
224
294
|
},
|
|
225
295
|
} as Party.Context;
|
|
226
296
|
this.blockConcurrencyWhile = options.state.blockConcurrencyWhile.bind(options.state);
|
|
297
|
+
this.state = options.state;
|
|
298
|
+
this.hibernating = getRuntimeConfig().webSocketMode === "hibernate";
|
|
227
299
|
}
|
|
228
300
|
|
|
229
301
|
blockConcurrencyWhile: Party.Room["blockConcurrencyWhile"];
|
|
230
302
|
|
|
231
303
|
broadcast(msg: string | ArrayBuffer | ArrayBufferView, without: string[] = []) {
|
|
232
|
-
for (const connection of this.
|
|
304
|
+
for (const connection of this.getConnections()) {
|
|
233
305
|
if (!without.includes(connection.id)) {
|
|
234
306
|
connection.send(msg);
|
|
235
307
|
}
|
|
@@ -238,7 +310,7 @@ export class CloudflareRoom implements Party.Room {
|
|
|
238
310
|
|
|
239
311
|
getConnection<TState = unknown>(id: string): Party.Connection<TState> | undefined {
|
|
240
312
|
let connection: Party.Connection | undefined;
|
|
241
|
-
for (const current of this.
|
|
313
|
+
for (const current of this.getConnections()) {
|
|
242
314
|
if (current.id === id || current.sessionId === id) {
|
|
243
315
|
connection = current;
|
|
244
316
|
}
|
|
@@ -247,14 +319,21 @@ export class CloudflareRoom implements Party.Room {
|
|
|
247
319
|
}
|
|
248
320
|
|
|
249
321
|
getConnections<TState = unknown>(): Iterable<Party.Connection<TState>> {
|
|
322
|
+
if (this.hibernating) {
|
|
323
|
+
return this.state.getWebSockets().map((webSocket) =>
|
|
324
|
+
this.connectionForWebSocket(webSocket as CloudflareWebSocket)
|
|
325
|
+
) as unknown as Party.Connection<TState>[];
|
|
326
|
+
}
|
|
250
327
|
return Array.from(this.connections.values()) as Party.Connection<TState>[];
|
|
251
328
|
}
|
|
252
329
|
|
|
253
330
|
addConnection(connection: CloudflareConnection) {
|
|
331
|
+
if (this.hibernating) return;
|
|
254
332
|
this.connections.set(connection.id, connection as unknown as Party.Connection);
|
|
255
333
|
}
|
|
256
334
|
|
|
257
335
|
deleteConnection(id: string, connection?: CloudflareConnection) {
|
|
336
|
+
if (this.hibernating) return;
|
|
258
337
|
if (connection) {
|
|
259
338
|
this.connections.delete(connection.id);
|
|
260
339
|
return;
|
|
@@ -266,23 +345,52 @@ export class CloudflareRoom implements Party.Room {
|
|
|
266
345
|
}
|
|
267
346
|
}
|
|
268
347
|
}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
connectionForWebSocket(webSocket: CloudflareWebSocket): CloudflareConnection {
|
|
351
|
+
return CloudflareConnection.restore(webSocket);
|
|
352
|
+
}
|
|
269
353
|
}
|
|
270
354
|
|
|
271
355
|
export class CloudflareConnection<TState = unknown> {
|
|
272
|
-
readonly id
|
|
356
|
+
readonly id: string;
|
|
273
357
|
readonly sessionId: string;
|
|
274
358
|
readonly socket: this = this;
|
|
275
359
|
readonly uri: string;
|
|
276
|
-
state: Party.ConnectionState<TState> | TState | null
|
|
277
|
-
private attachment: unknown
|
|
360
|
+
state: Party.ConnectionState<TState> | TState | null;
|
|
361
|
+
private attachment: unknown;
|
|
278
362
|
|
|
279
363
|
constructor(
|
|
280
364
|
private readonly webSocket: CloudflareWebSocket,
|
|
281
|
-
|
|
282
|
-
|
|
365
|
+
options: {
|
|
366
|
+
id?: string;
|
|
367
|
+
uri: string;
|
|
368
|
+
sessionId?: string;
|
|
369
|
+
state?: Party.ConnectionState<TState> | TState | null;
|
|
370
|
+
attachment?: unknown;
|
|
371
|
+
}
|
|
283
372
|
) {
|
|
284
|
-
this.
|
|
285
|
-
this.
|
|
373
|
+
this.id = options.id ?? createConnectionId();
|
|
374
|
+
this.sessionId = options.sessionId || this.id;
|
|
375
|
+
this.uri = options.uri;
|
|
376
|
+
this.state = options.state ?? null;
|
|
377
|
+
this.attachment = options.attachment ?? null;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
static restore(webSocket: CloudflareWebSocket): CloudflareConnection {
|
|
381
|
+
const attachment = webSocket.deserializeAttachment?.() as
|
|
382
|
+
| CloudflareConnectionAttachment
|
|
383
|
+
| undefined;
|
|
384
|
+
if (!attachment) {
|
|
385
|
+
throw new Error("Missing Signe WebSocket attachment");
|
|
386
|
+
}
|
|
387
|
+
return new CloudflareConnection(webSocket, {
|
|
388
|
+
id: attachment.id,
|
|
389
|
+
sessionId: attachment.sessionId,
|
|
390
|
+
uri: attachment.uri,
|
|
391
|
+
state: attachment.state,
|
|
392
|
+
attachment: attachment.customAttachment,
|
|
393
|
+
});
|
|
286
394
|
}
|
|
287
395
|
|
|
288
396
|
send(data: string | ArrayBuffer | ArrayBufferView) {
|
|
@@ -302,16 +410,28 @@ export class CloudflareConnection<TState = unknown> {
|
|
|
302
410
|
this.state = typeof state === "function"
|
|
303
411
|
? (state as Party.ConnectionSetStateFn<TState>)(this.state as Party.ConnectionState<TState>)
|
|
304
412
|
: state;
|
|
413
|
+
this.persistAttachment();
|
|
305
414
|
return this.state as Party.ConnectionState<TState>;
|
|
306
415
|
}
|
|
307
416
|
|
|
308
417
|
serializeAttachment<T = unknown>(attachment: T): void {
|
|
309
418
|
this.attachment = attachment;
|
|
419
|
+
this.persistAttachment();
|
|
310
420
|
}
|
|
311
421
|
|
|
312
422
|
deserializeAttachment<T = unknown>(): T | null {
|
|
313
423
|
return this.attachment as T | null;
|
|
314
424
|
}
|
|
425
|
+
|
|
426
|
+
persistAttachment(): void {
|
|
427
|
+
this.webSocket.serializeAttachment?.({
|
|
428
|
+
id: this.id,
|
|
429
|
+
sessionId: this.sessionId,
|
|
430
|
+
uri: this.uri,
|
|
431
|
+
state: this.state,
|
|
432
|
+
customAttachment: this.attachment,
|
|
433
|
+
} satisfies CloudflareConnectionAttachment);
|
|
434
|
+
}
|
|
315
435
|
}
|
|
316
436
|
|
|
317
437
|
function createRuntimeConfig<TServer extends Party.Server>(
|
|
@@ -327,6 +447,7 @@ function createRuntimeConfig<TServer extends Party.Server>(
|
|
|
327
447
|
main: ServerClass as CloudflareRoomServerConstructor,
|
|
328
448
|
...(options.rooms ?? {}),
|
|
329
449
|
},
|
|
450
|
+
webSocketMode: options.webSocketMode ?? "standard",
|
|
330
451
|
};
|
|
331
452
|
}
|
|
332
453
|
|
|
@@ -358,7 +479,10 @@ function createPartiesContext(
|
|
|
358
479
|
},
|
|
359
480
|
fetch(pathOrInit?: string | RequestInit | Request, init?: RequestInit) {
|
|
360
481
|
const namespaceBinding = getNamespace(env, binding);
|
|
361
|
-
const
|
|
482
|
+
const parsed = { namespace, roomId };
|
|
483
|
+
const stub = namespaceBinding.get(
|
|
484
|
+
namespaceBinding.idFromName(getDurableObjectName(parsed))
|
|
485
|
+
);
|
|
362
486
|
if (pathOrInit instanceof Request) {
|
|
363
487
|
return fetchDurableObjectStub(stub, pathOrInit);
|
|
364
488
|
}
|
|
@@ -377,6 +501,10 @@ function createPartiesContext(
|
|
|
377
501
|
}) as Party.Context["parties"];
|
|
378
502
|
}
|
|
379
503
|
|
|
504
|
+
function getDurableObjectName(parsed: ParsedPartyPath): string {
|
|
505
|
+
return `${parsed.namespace}:${parsed.roomId}`;
|
|
506
|
+
}
|
|
507
|
+
|
|
380
508
|
function getNamespace(env: Record<string, unknown>, binding: string) {
|
|
381
509
|
const namespace = env[binding] as DurableObjectNamespace | undefined;
|
|
382
510
|
|