@orpc/experimental-publisher-durable-object 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 oRPC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/experimental-publisher-durable-object">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fexperimental-publisher-durable-object?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ <a href="https://deepwiki.com/unnoq/orpc">
21
+ <img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki">
22
+ </a>
23
+ </div>
24
+
25
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
26
+
27
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards
28
+
29
+ ---
30
+
31
+ ## Highlights
32
+
33
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
34
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
35
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
36
+ - **🔍 First-Class OpenTelemetry**: Seamlessly integrate with OpenTelemetry for observability.
37
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), SWR, Pinia Colada, and more.
38
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
39
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
40
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
41
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
42
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
43
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
44
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
45
+
46
+ ## Documentation
47
+
48
+ You can find the full documentation [here](https://orpc.unnoq.com).
49
+
50
+ ## Packages
51
+
52
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
53
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
54
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
55
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
56
+ - [@orpc/otel](https://www.npmjs.com/package/@orpc/otel): [OpenTelemetry](https://opentelemetry.io/) integration for observability.
57
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
58
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
59
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
60
+ - [@orpc/experimental-react-swr](https://www.npmjs.com/package/@orpc/experimental-react-swr): [SWR](https://swr.vercel.app/) integration.
61
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
63
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
64
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
65
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
66
+
67
+ ## `@orpc/experimental-publisher-durable-object`
68
+
69
+ Publisher adapter for [Durable Objects](https://developers.cloudflare.com/durable-objects/)
70
+
71
+ ## Sponsors
72
+
73
+ <p align="center">
74
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
75
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
76
+ </a>
77
+ </p>
78
+
79
+ ## License
80
+
81
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,108 @@
1
+ import { DurableObject } from 'cloudflare:workers';
2
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
3
+ import { PublisherOptions, Publisher, PublisherSubscribeListenerOptions } from '@orpc/experimental-publisher';
4
+ import { EventMeta } from '@orpc/standard-server';
5
+
6
+ interface ResumeStorageOptions {
7
+ /**
8
+ * How long (in seconds) to retain events for replay.
9
+ *
10
+ * When a client reconnects, stored events within this window can be replayed
11
+ * to ensure no data is lost. Outside this window, missed events are dropped.
12
+ *
13
+ * @remarks
14
+ * - Use 0, negative or infinite numbers to disable resume functionality
15
+ * - Event cleanup is deferred for performance reasons — expired events may
16
+ * remain briefly beyond their retention time
17
+ *
18
+ * @default 0 (disabled)
19
+ */
20
+ retentionSeconds?: number;
21
+ /**
22
+ * How long (in seconds) of inactivity before auto-deleting the durable object's data.
23
+ * Inactivity means no active WebSocket connections and no events within the retention period.
24
+ *
25
+ * The alarm is scheduled at `retentionSeconds + inactiveDataRetentionTime`.
26
+ *
27
+ * @default 6 * 60 * 60 (6 hours)
28
+ */
29
+ inactiveDataRetentionTime?: number;
30
+ /**
31
+ * Prefix for the resume storage table schema.
32
+ * Used to avoid naming conflicts with other tables in the same Durable Object.
33
+ *
34
+ * @default 'orpc:publisher:resume:'
35
+ */
36
+ schemaPrefix?: string;
37
+ }
38
+ declare class ResumeStorage {
39
+ private readonly ctx;
40
+ private readonly retentionSeconds;
41
+ private readonly inactiveDataRetentionTime;
42
+ private readonly schemaPrefix;
43
+ private isInitedSchema;
44
+ private isInitedAlarm;
45
+ private lastCleanupTime;
46
+ get isEnabled(): boolean;
47
+ constructor(ctx: DurableObjectState, options?: ResumeStorageOptions);
48
+ /**
49
+ * Store an event and return the updated serialized message with an assigned ID.
50
+ */
51
+ store(stringified: string): Promise<string>;
52
+ /**
53
+ * Get all events after the specified lastEventId, ordered by ID ascending.
54
+ */
55
+ getEventsAfter(lastEventId: string): Promise<string[]>;
56
+ /**
57
+ * Auto-delete durable object data if inactive for extended period.
58
+ * Inactivity means: no active connections AND no active events.
59
+ */
60
+ alarm(): Promise<void>;
61
+ private ensureReady;
62
+ private resetData;
63
+ private scheduleAlarm;
64
+ }
65
+
66
+ interface PublisherDurableObjectOptions {
67
+ resume?: ResumeStorageOptions;
68
+ }
69
+ declare class PublisherDurableObject<Env = Cloudflare.Env, Props = {}> extends DurableObject<Env, Props> {
70
+ private readonly resumeStorage;
71
+ constructor(ctx: DurableObjectState<Props>, env: Env, options?: PublisherDurableObjectOptions);
72
+ fetch(request: Request): Promise<Response>;
73
+ private handlePublish;
74
+ private handleSubscribe;
75
+ alarm(): Promise<void>;
76
+ }
77
+
78
+ interface DurablePublisherOptions extends PublisherOptions, StandardRPCJsonSerializerOptions {
79
+ /**
80
+ * Prefix for events, to avoid naming conflicts with other publishers in the same Durable Object.
81
+ *
82
+ * @default ''
83
+ */
84
+ prefix?: string;
85
+ /**
86
+ * Custom function to get the Durable Object stub for publishing.
87
+ *
88
+ * @default ((namespace, event) => namespace.getByName(event))
89
+ */
90
+ getStubByName?: (namespace: DurableObjectNamespace, event: string) => DurableObjectStub;
91
+ }
92
+ declare class DurablePublisher<T extends Record<string, object>> extends Publisher<T> {
93
+ private readonly namespace;
94
+ private readonly prefix;
95
+ private readonly serializer;
96
+ private readonly getStubByName;
97
+ constructor(namespace: DurableObjectNamespace, { prefix, getStubByName, ...options }?: DurablePublisherOptions);
98
+ publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
99
+ protected subscribeListener<K extends keyof T & string>(event: K, listener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
100
+ }
101
+
102
+ interface SerializedMessage {
103
+ data: unknown;
104
+ meta?: EventMeta;
105
+ }
106
+
107
+ export { DurablePublisher, PublisherDurableObject, ResumeStorage };
108
+ export type { DurablePublisherOptions, PublisherDurableObjectOptions, ResumeStorageOptions, SerializedMessage };
@@ -0,0 +1,108 @@
1
+ import { DurableObject } from 'cloudflare:workers';
2
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
3
+ import { PublisherOptions, Publisher, PublisherSubscribeListenerOptions } from '@orpc/experimental-publisher';
4
+ import { EventMeta } from '@orpc/standard-server';
5
+
6
+ interface ResumeStorageOptions {
7
+ /**
8
+ * How long (in seconds) to retain events for replay.
9
+ *
10
+ * When a client reconnects, stored events within this window can be replayed
11
+ * to ensure no data is lost. Outside this window, missed events are dropped.
12
+ *
13
+ * @remarks
14
+ * - Use 0, negative or infinite numbers to disable resume functionality
15
+ * - Event cleanup is deferred for performance reasons — expired events may
16
+ * remain briefly beyond their retention time
17
+ *
18
+ * @default 0 (disabled)
19
+ */
20
+ retentionSeconds?: number;
21
+ /**
22
+ * How long (in seconds) of inactivity before auto-deleting the durable object's data.
23
+ * Inactivity means no active WebSocket connections and no events within the retention period.
24
+ *
25
+ * The alarm is scheduled at `retentionSeconds + inactiveDataRetentionTime`.
26
+ *
27
+ * @default 6 * 60 * 60 (6 hours)
28
+ */
29
+ inactiveDataRetentionTime?: number;
30
+ /**
31
+ * Prefix for the resume storage table schema.
32
+ * Used to avoid naming conflicts with other tables in the same Durable Object.
33
+ *
34
+ * @default 'orpc:publisher:resume:'
35
+ */
36
+ schemaPrefix?: string;
37
+ }
38
+ declare class ResumeStorage {
39
+ private readonly ctx;
40
+ private readonly retentionSeconds;
41
+ private readonly inactiveDataRetentionTime;
42
+ private readonly schemaPrefix;
43
+ private isInitedSchema;
44
+ private isInitedAlarm;
45
+ private lastCleanupTime;
46
+ get isEnabled(): boolean;
47
+ constructor(ctx: DurableObjectState, options?: ResumeStorageOptions);
48
+ /**
49
+ * Store an event and return the updated serialized message with an assigned ID.
50
+ */
51
+ store(stringified: string): Promise<string>;
52
+ /**
53
+ * Get all events after the specified lastEventId, ordered by ID ascending.
54
+ */
55
+ getEventsAfter(lastEventId: string): Promise<string[]>;
56
+ /**
57
+ * Auto-delete durable object data if inactive for extended period.
58
+ * Inactivity means: no active connections AND no active events.
59
+ */
60
+ alarm(): Promise<void>;
61
+ private ensureReady;
62
+ private resetData;
63
+ private scheduleAlarm;
64
+ }
65
+
66
+ interface PublisherDurableObjectOptions {
67
+ resume?: ResumeStorageOptions;
68
+ }
69
+ declare class PublisherDurableObject<Env = Cloudflare.Env, Props = {}> extends DurableObject<Env, Props> {
70
+ private readonly resumeStorage;
71
+ constructor(ctx: DurableObjectState<Props>, env: Env, options?: PublisherDurableObjectOptions);
72
+ fetch(request: Request): Promise<Response>;
73
+ private handlePublish;
74
+ private handleSubscribe;
75
+ alarm(): Promise<void>;
76
+ }
77
+
78
+ interface DurablePublisherOptions extends PublisherOptions, StandardRPCJsonSerializerOptions {
79
+ /**
80
+ * Prefix for events, to avoid naming conflicts with other publishers in the same Durable Object.
81
+ *
82
+ * @default ''
83
+ */
84
+ prefix?: string;
85
+ /**
86
+ * Custom function to get the Durable Object stub for publishing.
87
+ *
88
+ * @default ((namespace, event) => namespace.getByName(event))
89
+ */
90
+ getStubByName?: (namespace: DurableObjectNamespace, event: string) => DurableObjectStub;
91
+ }
92
+ declare class DurablePublisher<T extends Record<string, object>> extends Publisher<T> {
93
+ private readonly namespace;
94
+ private readonly prefix;
95
+ private readonly serializer;
96
+ private readonly getStubByName;
97
+ constructor(namespace: DurableObjectNamespace, { prefix, getStubByName, ...options }?: DurablePublisherOptions);
98
+ publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
99
+ protected subscribeListener<K extends keyof T & string>(event: K, listener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
100
+ }
101
+
102
+ interface SerializedMessage {
103
+ data: unknown;
104
+ meta?: EventMeta;
105
+ }
106
+
107
+ export { DurablePublisher, PublisherDurableObject, ResumeStorage };
108
+ export type { DurablePublisherOptions, PublisherDurableObjectOptions, ResumeStorageOptions, SerializedMessage };
package/dist/index.mjs ADDED
@@ -0,0 +1,278 @@
1
+ import { DurableObject } from 'cloudflare:workers';
2
+ import { stringifyJSON, isTypescriptObject } from '@orpc/shared';
3
+ import { StandardRPCJsonSerializer } from '@orpc/client/standard';
4
+ import { Publisher } from '@orpc/experimental-publisher';
5
+ import { getEventMeta, withEventMeta } from '@orpc/standard-server';
6
+
7
+ class ResumeStorage {
8
+ constructor(ctx, options = {}) {
9
+ this.ctx = ctx;
10
+ this.retentionSeconds = options.retentionSeconds ?? 0;
11
+ this.inactiveDataRetentionTime = options.inactiveDataRetentionTime ?? 6 * 60 * 60;
12
+ this.schemaPrefix = options.schemaPrefix ?? "orpc:publisher:resume:";
13
+ }
14
+ retentionSeconds;
15
+ inactiveDataRetentionTime;
16
+ schemaPrefix;
17
+ isInitedSchema = false;
18
+ isInitedAlarm = false;
19
+ lastCleanupTime;
20
+ get isEnabled() {
21
+ return Number.isFinite(this.retentionSeconds) && this.retentionSeconds > 0;
22
+ }
23
+ /**
24
+ * Store an event and return the updated serialized message with an assigned ID.
25
+ */
26
+ async store(stringified) {
27
+ if (!this.isEnabled) {
28
+ return stringified;
29
+ }
30
+ await this.ensureReady();
31
+ const message = JSON.parse(stringified);
32
+ const insertEvent = () => {
33
+ const result = this.ctx.storage.sql.exec(
34
+ `INSERT INTO "${this.schemaPrefix}events" (payload) VALUES (?) RETURNING CAST(id AS TEXT) as id`,
35
+ stringified
36
+ );
37
+ const id = result.one()?.id;
38
+ const updatedIdMessage = {
39
+ ...message,
40
+ meta: { ...message.meta, id }
41
+ };
42
+ return stringifyJSON(updatedIdMessage);
43
+ };
44
+ try {
45
+ return insertEvent();
46
+ } catch {
47
+ await this.resetData();
48
+ return insertEvent();
49
+ }
50
+ }
51
+ /**
52
+ * Get all events after the specified lastEventId, ordered by ID ascending.
53
+ */
54
+ async getEventsAfter(lastEventId) {
55
+ if (!this.isEnabled) {
56
+ return [];
57
+ }
58
+ await this.ensureReady();
59
+ const result = this.ctx.storage.sql.exec(`
60
+ SELECT CAST(id AS TEXT) as id, payload
61
+ FROM "${this.schemaPrefix}events"
62
+ WHERE id > ?
63
+ ORDER BY id ASC
64
+ `, lastEventId);
65
+ const events = [];
66
+ for (const record of result.toArray()) {
67
+ const message = JSON.parse(record.payload);
68
+ const updatedIdMessage = {
69
+ ...message,
70
+ meta: { ...message.meta, id: record.id }
71
+ };
72
+ events.push(stringifyJSON(updatedIdMessage));
73
+ }
74
+ return events;
75
+ }
76
+ /**
77
+ * Auto-delete durable object data if inactive for extended period.
78
+ * Inactivity means: no active connections AND no active events.
79
+ */
80
+ async alarm() {
81
+ this.isInitedAlarm = true;
82
+ await this.ensureReady();
83
+ const hasActiveWebSockets = this.ctx.getWebSockets().length > 0;
84
+ if (hasActiveWebSockets) {
85
+ await this.scheduleAlarm();
86
+ return;
87
+ }
88
+ const activeEventsCount = this.ctx.storage.sql.exec(`
89
+ SELECT COUNT(*) as count
90
+ FROM "${this.schemaPrefix}events"
91
+ `);
92
+ const hasActiveEvents = activeEventsCount.one()?.count > 0;
93
+ if (hasActiveEvents) {
94
+ await this.scheduleAlarm();
95
+ return;
96
+ }
97
+ await this.ctx.blockConcurrencyWhile(async () => {
98
+ this.isInitedSchema = false;
99
+ this.isInitedAlarm = false;
100
+ await this.ctx.storage.deleteAll();
101
+ });
102
+ }
103
+ async ensureReady() {
104
+ if (this.isInitedSchema) {
105
+ const now = Date.now();
106
+ if (this.lastCleanupTime && this.lastCleanupTime + this.retentionSeconds * 1e3 > now) {
107
+ return;
108
+ }
109
+ this.lastCleanupTime = now;
110
+ this.ctx.storage.sql.exec(`
111
+ DELETE FROM "${this.schemaPrefix}events" WHERE stored_at < unixepoch() - ?
112
+ `, this.retentionSeconds);
113
+ return;
114
+ }
115
+ const result = this.ctx.storage.sql.exec(`
116
+ CREATE TABLE IF NOT EXISTS "${this.schemaPrefix}events" (
117
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
118
+ payload TEXT NOT NULL,
119
+ stored_at INTEGER NOT NULL DEFAULT (unixepoch())
120
+ )
121
+ `);
122
+ this.ctx.storage.sql.exec(`
123
+ CREATE INDEX IF NOT EXISTS "${this.schemaPrefix}idx_events_id" ON "${this.schemaPrefix}events" (id)
124
+ `);
125
+ this.ctx.storage.sql.exec(`
126
+ CREATE INDEX IF NOT EXISTS "${this.schemaPrefix}idx_events_stored_at" ON "${this.schemaPrefix}events" (stored_at)
127
+ `);
128
+ this.isInitedSchema = true;
129
+ if (!this.isInitedAlarm || result.rowsWritten > 0) {
130
+ await this.scheduleAlarm();
131
+ this.isInitedAlarm = true;
132
+ }
133
+ }
134
+ async resetData() {
135
+ this.ctx.storage.sql.exec(`DROP TABLE IF EXISTS "${this.schemaPrefix}events"`);
136
+ this.isInitedSchema = false;
137
+ await this.ensureReady();
138
+ }
139
+ scheduleAlarm() {
140
+ return this.ctx.storage.setAlarm(Date.now() + (this.retentionSeconds + this.inactiveDataRetentionTime) * 1e3);
141
+ }
142
+ }
143
+
144
+ class PublisherDurableObject extends DurableObject {
145
+ resumeStorage;
146
+ constructor(ctx, env, options = {}) {
147
+ super(ctx, env);
148
+ this.resumeStorage = new ResumeStorage(ctx, options.resume);
149
+ }
150
+ fetch(request) {
151
+ if (request.url.includes("/publish")) {
152
+ return this.handlePublish(request);
153
+ }
154
+ return this.handleSubscribe(request);
155
+ }
156
+ async handlePublish(request) {
157
+ const message = await this.resumeStorage.store(
158
+ await request.text()
159
+ );
160
+ for (const ws of this.ctx.getWebSockets()) {
161
+ try {
162
+ ws.send(message);
163
+ } catch (e) {
164
+ console.error("Failed to send message to websocket:", e);
165
+ }
166
+ }
167
+ return new Response(null, { status: 204 });
168
+ }
169
+ async handleSubscribe(request) {
170
+ const { "0": client, "1": server } = new WebSocketPair();
171
+ this.ctx.acceptWebSocket(server);
172
+ const lastEventId = request.headers.get("last-event-id");
173
+ if (lastEventId !== null) {
174
+ const events = await this.resumeStorage.getEventsAfter(lastEventId);
175
+ for (const event of events) {
176
+ try {
177
+ server.send(event);
178
+ } catch (e) {
179
+ console.error("Failed to replay event to websocket:", e);
180
+ }
181
+ }
182
+ }
183
+ return new Response(null, { status: 101, webSocket: client });
184
+ }
185
+ async alarm() {
186
+ await this.resumeStorage.alarm();
187
+ }
188
+ }
189
+
190
+ class DurablePublisher extends Publisher {
191
+ constructor(namespace, { prefix, getStubByName, ...options } = {}) {
192
+ super(options);
193
+ this.namespace = namespace;
194
+ this.prefix = prefix ?? "";
195
+ this.serializer = new StandardRPCJsonSerializer(options);
196
+ this.getStubByName = getStubByName ?? ((namespace2, event) => namespace2.getByName(event));
197
+ }
198
+ prefix;
199
+ serializer;
200
+ getStubByName;
201
+ async publish(event, payload) {
202
+ const stub = this.getStubByName(this.namespace, this.prefix + event);
203
+ const [json_, meta_] = this.serializer.serialize(payload);
204
+ const serialized = {
205
+ data: { json: json_, meta: meta_ },
206
+ meta: getEventMeta(payload)
207
+ };
208
+ const response = await stub.fetch(new Request("http://localhost/publish", {
209
+ method: "POST",
210
+ body: stringifyJSON(serialized)
211
+ }));
212
+ if (!response.ok) {
213
+ throw new Error(`Failed to publish event: ${response.status} ${response.statusText}`, {
214
+ cause: response
215
+ });
216
+ }
217
+ }
218
+ async subscribeListener(event, listener, options) {
219
+ const stub = this.getStubByName(this.namespace, this.prefix + event);
220
+ const headers = new Headers({ upgrade: "websocket" });
221
+ if (options?.lastEventId !== void 0) {
222
+ headers.set("last-event-id", options.lastEventId);
223
+ }
224
+ const response = await stub.fetch("http://localhost/subscribe", {
225
+ headers
226
+ });
227
+ const websocket = response.webSocket;
228
+ if (!websocket) {
229
+ throw new Error("Failed to open subscription websocket to publisher durable object", {
230
+ cause: response
231
+ });
232
+ }
233
+ websocket.addEventListener("message", async (event2) => {
234
+ try {
235
+ let data;
236
+ if (event2.data instanceof Blob) {
237
+ data = await event2.data.text();
238
+ } else if (typeof event2.data === "string") {
239
+ data = event2.data;
240
+ } else {
241
+ data = new TextDecoder().decode(event2.data);
242
+ }
243
+ const serialized = JSON.parse(data);
244
+ const payload = this.serializer.deserialize(serialized.data.json, serialized.data.meta);
245
+ const payloadWithMeta = isTypescriptObject(payload) && serialized.meta ? withEventMeta(payload, serialized.meta) : payload;
246
+ listener(payloadWithMeta);
247
+ } catch (error) {
248
+ options?.onError?.(
249
+ new Error("Failed to deserialize message from publisher durable object", {
250
+ cause: error
251
+ })
252
+ );
253
+ }
254
+ });
255
+ websocket.addEventListener("close", (event2) => {
256
+ if (event2.code !== 1e3 && event2.code !== 1001) {
257
+ options?.onError?.(
258
+ new Error(`WebSocket closed unexpectedly: ${event2.code} ${event2.reason}`, {
259
+ cause: event2
260
+ })
261
+ );
262
+ }
263
+ });
264
+ websocket.addEventListener("error", (event2) => {
265
+ options?.onError?.(
266
+ new Error(`Subscription websocket error`, {
267
+ cause: event2
268
+ })
269
+ );
270
+ });
271
+ websocket.accept();
272
+ return async () => {
273
+ websocket.close();
274
+ };
275
+ }
276
+ }
277
+
278
+ export { DurablePublisher, PublisherDurableObject, ResumeStorage };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@orpc/experimental-publisher-durable-object",
3
+ "type": "module",
4
+ "version": "0.0.0",
5
+ "license": "MIT",
6
+ "homepage": "https://orpc.unnoq.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/unnoq/orpc.git",
10
+ "directory": "packages/publisher-durable-object"
11
+ },
12
+ "keywords": [
13
+ "unnoq",
14
+ "orpc"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "dependencies": {
27
+ "@orpc/client": "1.11.3",
28
+ "@orpc/experimental-publisher": "1.11.3",
29
+ "@orpc/shared": "1.11.3",
30
+ "@orpc/standard-server": "1.11.3"
31
+ },
32
+ "devDependencies": {
33
+ "@cloudflare/workers-types": "^4.20251118.0",
34
+ "@types/node": "^22.15.30",
35
+ "@orpc/standard-server-peer": "1.11.3"
36
+ },
37
+ "scripts": {
38
+ "build": "unbuild",
39
+ "build:watch": "pnpm run build --watch",
40
+ "type:check": "tsc -b",
41
+ "type:check:test": "tsc -p tsconfig.test.json --noEmit"
42
+ }
43
+ }