@fieldnotes/sync-redis 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,152 +1,152 @@
1
- # @fieldnotes/sync-redis
2
-
3
- A `HubBackend` that persists Field Notes relay room state in Redis — state survives relay restarts and is
4
- shared across relay instances.
5
-
6
- ## Install
7
-
8
- ```bash
9
- pnpm add @fieldnotes/sync-redis
10
- # plus your Redis client of choice, e.g.:
11
- pnpm add redis # node-redis v4
12
- # or
13
- pnpm add ioredis
14
- ```
15
-
16
- `@fieldnotes/sync-redis` has **no Redis dependency of its own** — you inject a client that satisfies a
17
- minimal `RedisHashClient` interface (`hGetAll` / `hGet` / `hSet` / `hDel` / `del`).
18
-
19
- ## node-redis v4 (direct)
20
-
21
- node-redis v4's client already matches `RedisHashClient`, so you can pass it straight through:
22
-
23
- ```ts
24
- import { createClient } from 'redis';
25
- import { createSyncServer } from '@fieldnotes/sync-server';
26
- import { RedisHubBackend } from '@fieldnotes/sync-redis';
27
-
28
- const client = createClient({ url: process.env.REDIS_URL });
29
- await client.connect();
30
- createSyncServer({ port: 8080, backend: new RedisHubBackend(client) });
31
- ```
32
-
33
- ## ioredis (shim)
34
-
35
- ioredis uses lowercased method names, so wrap it in a small adapter:
36
-
37
- ```ts
38
- import Redis from 'ioredis';
39
- import { RedisHubBackend } from '@fieldnotes/sync-redis';
40
-
41
- const io = new Redis(process.env.REDIS_URL);
42
- const client = {
43
- hGetAll: (k: string) => io.hgetall(k),
44
- hGet: (k: string, f: string) => io.hget(k, f),
45
- hSet: (k: string, f: string, v: string) => io.hset(k, f, v),
46
- hDel: (k: string, f: string) => io.hdel(k, f),
47
- del: (k: string) => io.del(k),
48
- };
49
- const backend = new RedisHubBackend(client);
50
- ```
51
-
52
- ## Key schema
53
-
54
- Each room is stored as a Redis **HASH** at `{keyPrefix}{room}` (default prefix `fieldnotes:room:`):
55
-
56
- - **field** = element id
57
- - **value** = `JSON.stringify(element)`
58
-
59
- node-redis v4 conforms to `RedisHashClient` directly (it has `hGet`); `RedisHubBackend.get(room, id)`
60
- (via `HGET`) powers the relay's ownership lookups for write authorization (D2).
61
-
62
- The prefix is configurable:
63
-
64
- ```ts
65
- new RedisHubBackend(client, { keyPrefix: 'myapp:room:' });
66
- ```
67
-
68
- ## Single vs. multiple relay instances
69
-
70
- Persistence and shared state work with any number of relay instances — every instance reads and writes the
71
- same Redis, so room state survives restarts and is visible to all of them.
72
-
73
- For clients connected to **different** relay instances to see each other's **live** ops, you also need
74
- cross-instance fan-out (Redis pub/sub) — available via `RedisHubFanout` (below). A **single** relay instance
75
- is fully live on its own.
76
-
77
- ## Cross-instance fan-out (`RedisHubFanout`)
78
-
79
- `RedisHubFanout` is a `HubFanout` (from `@fieldnotes/sync-server`) over Redis pub/sub: each relay instance
80
- publishes its live ops to a single channel and every other instance forwards them to its local connections.
81
- Like the backend, it has **no Redis dependency of its own** — you inject two connections via the
82
- `RedisPublisher` / `RedisSubscriber` seams.
83
-
84
- `publish()` resolves only after Redis acknowledges the command. If Redis rejects it, the fanout
85
- invokes the optional `onError` observer and rethrows so `SyncHub` can surface the failed durable
86
- mutation publication. Do not discard the returned promise when publishing directly.
87
-
88
- > **The subscriber MUST be a dedicated connection.** Redis forbids any other command on a connection that is
89
- > in subscribe mode, so publish and subscribe cannot share one connection — that is why `RedisHubFanout`
90
- > takes two.
91
-
92
- ### node-redis v4
93
-
94
- ```ts
95
- import { createClient } from 'redis';
96
- import { createSyncServer } from '@fieldnotes/sync-server';
97
- import { RedisHubBackend, RedisHubFanout } from '@fieldnotes/sync-redis';
98
-
99
- const hash = createClient({ url: process.env.REDIS_URL });
100
- await hash.connect(); // HASH backend (persistence)
101
-
102
- const publisher = createClient({ url: process.env.REDIS_URL });
103
- await publisher.connect();
104
- const subscriber = publisher.duplicate();
105
- await subscriber.connect(); // DEDICATED subscriber — a subscriber connection cannot also publish
106
-
107
- createSyncServer({
108
- port: 8080,
109
- backend: new RedisHubBackend(hash),
110
- fanout: new RedisHubFanout(publisher, subscriber),
111
- });
112
- ```
113
-
114
- ### ioredis
115
-
116
- ioredis lowercases `publish`/`subscribe` and delivers messages via a `'message'` event, so wrap each client:
117
-
118
- ```ts
119
- import Redis from 'ioredis';
120
- import { RedisHubFanout } from '@fieldnotes/sync-redis';
121
-
122
- const pubIo = new Redis(process.env.REDIS_URL); // publish connection
123
- const subIo = new Redis(process.env.REDIS_URL); // SECOND, dedicated subscriber connection
124
-
125
- const publisher = { publish: (c: string, m: string) => pubIo.publish(c, m) };
126
- const subscriber = {
127
- subscribe: (channel: string, listener: (m: string) => void) => {
128
- subIo.on('message', (ch, msg) => {
129
- if (ch === channel) listener(msg);
130
- });
131
- return subIo.subscribe(channel);
132
- },
133
- };
134
-
135
- const fanout = new RedisHubFanout(publisher, subscriber);
136
- ```
137
-
138
- ### Channel
139
-
140
- All instances must share one channel (default `fieldnotes:fanout`, configurable):
141
-
142
- ```ts
143
- new RedisHubFanout(publisher, subscriber, { channel: 'myapp:fanout' });
144
- ```
145
-
146
- ### Precondition: shared fanout AND shared backend
147
-
148
- Multi-instance **live** sync requires **both** a shared fanout **and** a shared backend (both Redis). The
149
- fanout forwards live ops; the shared backend keeps snapshots consistent. A shared fanout **without** a shared
150
- backend leaves a new joiner's snapshot stale — it would catch up from whichever instance it happened to hit,
151
- missing edits applied elsewhere. Pair `RedisHubFanout` with `RedisHubBackend` for full multi-instance
152
- real-time sync.
1
+ # @fieldnotes/sync-redis
2
+
3
+ A `HubBackend` that persists Field Notes relay room state in Redis — state survives relay restarts and is
4
+ shared across relay instances.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pnpm add @fieldnotes/sync-redis
10
+ # plus your Redis client of choice, e.g.:
11
+ pnpm add redis # node-redis v4
12
+ # or
13
+ pnpm add ioredis
14
+ ```
15
+
16
+ `@fieldnotes/sync-redis` has **no Redis dependency of its own** — you inject a client that satisfies a
17
+ minimal `RedisHashClient` interface (`hGetAll` / `hGet` / `hSet` / `hDel` / `del`).
18
+
19
+ ## node-redis v4 (direct)
20
+
21
+ node-redis v4's client already matches `RedisHashClient`, so you can pass it straight through:
22
+
23
+ ```ts
24
+ import { createClient } from 'redis';
25
+ import { createSyncServer } from '@fieldnotes/sync-server';
26
+ import { RedisHubBackend } from '@fieldnotes/sync-redis';
27
+
28
+ const client = createClient({ url: process.env.REDIS_URL });
29
+ await client.connect();
30
+ createSyncServer({ port: 8080, backend: new RedisHubBackend(client) });
31
+ ```
32
+
33
+ ## ioredis (shim)
34
+
35
+ ioredis uses lowercased method names, so wrap it in a small adapter:
36
+
37
+ ```ts
38
+ import Redis from 'ioredis';
39
+ import { RedisHubBackend } from '@fieldnotes/sync-redis';
40
+
41
+ const io = new Redis(process.env.REDIS_URL);
42
+ const client = {
43
+ hGetAll: (k: string) => io.hgetall(k),
44
+ hGet: (k: string, f: string) => io.hget(k, f),
45
+ hSet: (k: string, f: string, v: string) => io.hset(k, f, v),
46
+ hDel: (k: string, f: string) => io.hdel(k, f),
47
+ del: (k: string) => io.del(k),
48
+ };
49
+ const backend = new RedisHubBackend(client);
50
+ ```
51
+
52
+ ## Key schema
53
+
54
+ Each room is stored as a Redis **HASH** at `{keyPrefix}{room}` (default prefix `fieldnotes:room:`):
55
+
56
+ - **field** = element id
57
+ - **value** = `JSON.stringify(element)`
58
+
59
+ node-redis v4 conforms to `RedisHashClient` directly (it has `hGet`); `RedisHubBackend.get(room, id)`
60
+ (via `HGET`) powers the relay's ownership lookups for write authorization (D2).
61
+
62
+ The prefix is configurable:
63
+
64
+ ```ts
65
+ new RedisHubBackend(client, { keyPrefix: 'myapp:room:' });
66
+ ```
67
+
68
+ ## Single vs. multiple relay instances
69
+
70
+ Persistence and shared state work with any number of relay instances — every instance reads and writes the
71
+ same Redis, so room state survives restarts and is visible to all of them.
72
+
73
+ For clients connected to **different** relay instances to see each other's **live** ops, you also need
74
+ cross-instance fan-out (Redis pub/sub) — available via `RedisHubFanout` (below). A **single** relay instance
75
+ is fully live on its own.
76
+
77
+ ## Cross-instance fan-out (`RedisHubFanout`)
78
+
79
+ `RedisHubFanout` is a `HubFanout` (from `@fieldnotes/sync-server`) over Redis pub/sub: each relay instance
80
+ publishes its live ops to a single channel and every other instance forwards them to its local connections.
81
+ Like the backend, it has **no Redis dependency of its own** — you inject two connections via the
82
+ `RedisPublisher` / `RedisSubscriber` seams.
83
+
84
+ `publish()` resolves only after Redis acknowledges the command. If Redis rejects it, the fanout
85
+ invokes the optional `onError` observer and rethrows so `SyncHub` can surface the failed durable
86
+ mutation publication. Do not discard the returned promise when publishing directly.
87
+
88
+ > **The subscriber MUST be a dedicated connection.** Redis forbids any other command on a connection that is
89
+ > in subscribe mode, so publish and subscribe cannot share one connection — that is why `RedisHubFanout`
90
+ > takes two.
91
+
92
+ ### node-redis v4
93
+
94
+ ```ts
95
+ import { createClient } from 'redis';
96
+ import { createSyncServer } from '@fieldnotes/sync-server';
97
+ import { RedisHubBackend, RedisHubFanout } from '@fieldnotes/sync-redis';
98
+
99
+ const hash = createClient({ url: process.env.REDIS_URL });
100
+ await hash.connect(); // HASH backend (persistence)
101
+
102
+ const publisher = createClient({ url: process.env.REDIS_URL });
103
+ await publisher.connect();
104
+ const subscriber = publisher.duplicate();
105
+ await subscriber.connect(); // DEDICATED subscriber — a subscriber connection cannot also publish
106
+
107
+ createSyncServer({
108
+ port: 8080,
109
+ backend: new RedisHubBackend(hash),
110
+ fanout: new RedisHubFanout(publisher, subscriber),
111
+ });
112
+ ```
113
+
114
+ ### ioredis
115
+
116
+ ioredis lowercases `publish`/`subscribe` and delivers messages via a `'message'` event, so wrap each client:
117
+
118
+ ```ts
119
+ import Redis from 'ioredis';
120
+ import { RedisHubFanout } from '@fieldnotes/sync-redis';
121
+
122
+ const pubIo = new Redis(process.env.REDIS_URL); // publish connection
123
+ const subIo = new Redis(process.env.REDIS_URL); // SECOND, dedicated subscriber connection
124
+
125
+ const publisher = { publish: (c: string, m: string) => pubIo.publish(c, m) };
126
+ const subscriber = {
127
+ subscribe: (channel: string, listener: (m: string) => void) => {
128
+ subIo.on('message', (ch, msg) => {
129
+ if (ch === channel) listener(msg);
130
+ });
131
+ return subIo.subscribe(channel);
132
+ },
133
+ };
134
+
135
+ const fanout = new RedisHubFanout(publisher, subscriber);
136
+ ```
137
+
138
+ ### Channel
139
+
140
+ All instances must share one channel (default `fieldnotes:fanout`, configurable):
141
+
142
+ ```ts
143
+ new RedisHubFanout(publisher, subscriber, { channel: 'myapp:fanout' });
144
+ ```
145
+
146
+ ### Precondition: shared fanout AND shared backend
147
+
148
+ Multi-instance **live** sync requires **both** a shared fanout **and** a shared backend (both Redis). The
149
+ fanout forwards live ops; the shared backend keeps snapshots consistent. A shared fanout **without** a shared
150
+ backend leaves a new joiner's snapshot stale — it would catch up from whichever instance it happened to hit,
151
+ missing edits applied elsewhere. Pair `RedisHubFanout` with `RedisHubBackend` for full multi-instance
152
+ real-time sync.
package/dist/index.cjs CHANGED
@@ -37,6 +37,9 @@ var RedisHubBackend = class {
37
37
  key(room) {
38
38
  return `${this.keyPrefix}${room}`;
39
39
  }
40
+ layersKey(room) {
41
+ return `${this.keyPrefix}${room}:layers`;
42
+ }
40
43
  async snapshot(room) {
41
44
  const map = await this.client.hGetAll(this.key(room));
42
45
  const out = [];
@@ -68,6 +71,33 @@ var RedisHubBackend = class {
68
71
  else if (op.kind === "remove") await this.client.hDel(key, op.id);
69
72
  else if (op.kind === "clear") await this.client.del(key);
70
73
  }
74
+ async layerRecords(room) {
75
+ const map = await this.client.hGetAll(this.layersKey(room));
76
+ const out = [];
77
+ for (const value of Object.values(map)) {
78
+ let parsed;
79
+ try {
80
+ parsed = JSON.parse(value);
81
+ } catch {
82
+ continue;
83
+ }
84
+ if ((0, import_sync.isValidLayerRecord)(parsed)) out.push(parsed);
85
+ }
86
+ return out;
87
+ }
88
+ async getLayerRecord(room, id) {
89
+ const value = await this.client.hGet(this.layersKey(room), id);
90
+ if (value == null) return void 0;
91
+ try {
92
+ const parsed = JSON.parse(value);
93
+ return (0, import_sync.isValidLayerRecord)(parsed) ? parsed : void 0;
94
+ } catch {
95
+ return void 0;
96
+ }
97
+ }
98
+ async applyLayerRecord(room, record) {
99
+ await this.client.hSet(this.layersKey(room), record.id, JSON.stringify(record));
100
+ }
71
101
  };
72
102
 
73
103
  // src/redis-hub-fanout.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/redis-hub-backend.ts","../src/redis-hub-fanout.ts"],"sourcesContent":["export { RedisHubBackend } from './redis-hub-backend';\r\nexport type { RedisHubBackendOptions } from './redis-hub-backend';\r\nexport type { RedisHashClient } from './redis-hash-client';\r\nexport { RedisHubFanout } from './redis-hub-fanout';\r\nexport type { RedisHubFanoutOptions } from './redis-hub-fanout';\r\nexport type { RedisPublisher, RedisSubscriber } from './redis-fanout-client';\r\n","import { isValidElement, type SyncOp } from '@fieldnotes/sync';\r\nimport type { CanvasElement } from '@fieldnotes/core';\r\nimport type { HubBackend } from '@fieldnotes/sync-server';\r\nimport type { RedisHashClient } from './redis-hash-client';\r\n\r\nexport interface RedisHubBackendOptions {\r\n keyPrefix?: string; // default 'fieldnotes:room:'\r\n}\r\n\r\nexport class RedisHubBackend implements HubBackend {\r\n private readonly client: RedisHashClient;\r\n private readonly keyPrefix: string;\r\n\r\n constructor(client: RedisHashClient, options: RedisHubBackendOptions = {}) {\r\n this.client = client;\r\n this.keyPrefix = options.keyPrefix ?? 'fieldnotes:room:';\r\n }\r\n\r\n private key(room: string): string {\r\n return `${this.keyPrefix}${room}`;\r\n }\r\n\r\n async snapshot(room: string): Promise<CanvasElement[]> {\r\n const map = await this.client.hGetAll(this.key(room));\r\n const out: CanvasElement[] = [];\r\n for (const value of Object.values(map)) {\r\n let parsed: unknown;\r\n try {\r\n parsed = JSON.parse(value);\r\n } catch {\r\n continue; // skip a corrupt stored value rather than throwing the whole snapshot\r\n }\r\n if (isValidElement(parsed)) out.push(parsed);\r\n }\r\n return out;\r\n }\r\n\r\n async get(room: string, id: string): Promise<CanvasElement | undefined> {\r\n const value = await this.client.hGet(this.key(room), id);\r\n if (value == null) return undefined;\r\n try {\r\n const parsed: unknown = JSON.parse(value);\r\n return isValidElement(parsed) ? parsed : undefined;\r\n } catch {\r\n return undefined;\r\n }\r\n }\r\n\r\n async apply(room: string, op: SyncOp): Promise<void> {\r\n const key = this.key(room);\r\n if (op.kind === 'upsert')\r\n await this.client.hSet(key, op.element.id, JSON.stringify(op.element));\r\n else if (op.kind === 'remove') await this.client.hDel(key, op.id);\r\n else if (op.kind === 'clear') await this.client.del(key);\r\n // request-snapshot/snapshot never reach apply (the hub only applies data ops)\r\n }\r\n}\r\n","import type { HubFanout } from '@fieldnotes/sync-server';\nimport type { RedisPublisher, RedisSubscriber } from './redis-fanout-client';\n\nexport interface RedisHubFanoutOptions {\n channel?: string;\n onError?: (err: unknown) => void;\n}\n\nexport class RedisHubFanout implements HubFanout {\n private readonly publisher: RedisPublisher;\n private readonly subscriber: RedisSubscriber;\n private readonly channel: string;\n private readonly onError: (err: unknown) => void;\n private readonly handlers = new Set<(payload: string) => void>();\n private subscribed = false;\n\n constructor(\n publisher: RedisPublisher,\n subscriber: RedisSubscriber,\n options: RedisHubFanoutOptions = {},\n ) {\n this.publisher = publisher;\n this.subscriber = subscriber;\n this.channel = options.channel ?? 'fieldnotes:fanout';\n this.onError = options.onError ?? (() => undefined);\n }\n\n async publish(payload: string): Promise<void> {\n try {\n await this.publisher.publish(this.channel, payload);\n } catch (error) {\n try {\n this.onError(error);\n } catch {\n /* preserve the publication failure even when the observer throws */\n }\n throw error;\n }\n }\n\n subscribe(handler: (payload: string) => void): () => void {\n this.handlers.add(handler);\n if (!this.subscribed) {\n this.subscribed = true;\n Promise.resolve(\n this.subscriber.subscribe(this.channel, (message) => {\n for (const h of this.handlers) {\n try {\n h(message);\n } catch {\n /* isolate handlers */\n }\n }\n }),\n ).catch(this.onError);\n }\n return () => this.handlers.delete(handler);\n }\n}\n"],"m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AK,OAAO,IAAI,GAAG;AAAA,EAEzD;AACF;;;AChDO,IAAM,iBAAN,MAA0C;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW,oBAAI,IAA+B;AAAA,EACvD,aAAa;AAAA,EAErB,YACE,WACA,YACA,UAAiC,CAAC,GAClC;AACA,SAAK,YAAY;AACjB,SAAK,aAAa;AAClB,SAAK,UAAU,QAAQ,WAAW;AAClC,SAAK,UAAU,QAAQ,YAAY,MAAM;AAAA,EAC3C;AAAA,EAEA,MAAM,QAAQ,SAAgC;AAC5C,QAAI;AACF,YAAM,KAAK,UAAU,QAAQ,KAAK,SAAS,OAAO;AAAA,IACpD,SAAS,OAAO;AACd,UAAI;AACF,aAAK,QAAQ,KAAK;AAAA,MACpB,QAAQ;AAAA,MAER;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,UAAU,SAAgD;AACxD,SAAK,SAAS,IAAI,OAAO;AACzB,QAAI,CAAC,KAAK,YAAY;AACpB,WAAK,aAAa;AAClB,cAAQ;AAAA,QACN,KAAK,WAAW,UAAU,KAAK,SAAS,CAAC,YAAY;AACnD,qBAAW,KAAK,KAAK,UAAU;AAC7B,gBAAI;AACF,gBAAE,OAAO;AAAA,YACX,QAAQ;AAAA,YAER;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,EAAE,MAAM,KAAK,OAAO;AAAA,IACtB;AACA,WAAO,MAAM,KAAK,SAAS,OAAO,OAAO;AAAA,EAC3C;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/redis-hub-backend.ts","../src/redis-hub-fanout.ts"],"sourcesContent":["export { RedisHubBackend } from './redis-hub-backend';\nexport type { RedisHubBackendOptions } from './redis-hub-backend';\nexport type { RedisHashClient } from './redis-hash-client';\nexport { RedisHubFanout } from './redis-hub-fanout';\nexport type { RedisHubFanoutOptions } from './redis-hub-fanout';\nexport type { RedisPublisher, RedisSubscriber } from './redis-fanout-client';\n","import {\n isValidElement,\n isValidLayerRecord,\n type LayerRecord,\n type SyncOp,\n} from '@fieldnotes/sync';\nimport type { CanvasElement } from '@fieldnotes/core';\nimport type { HubBackend } from '@fieldnotes/sync-server';\nimport type { RedisHashClient } from './redis-hash-client';\n\nexport interface RedisHubBackendOptions {\n keyPrefix?: string; // default 'fieldnotes:room:'\n}\n\nexport class RedisHubBackend implements HubBackend {\n private readonly client: RedisHashClient;\n private readonly keyPrefix: string;\n\n constructor(client: RedisHashClient, options: RedisHubBackendOptions = {}) {\n this.client = client;\n this.keyPrefix = options.keyPrefix ?? 'fieldnotes:room:';\n }\n\n private key(room: string): string {\n return `${this.keyPrefix}${room}`;\n }\n\n private layersKey(room: string): string {\n return `${this.keyPrefix}${room}:layers`;\n }\n\n async snapshot(room: string): Promise<CanvasElement[]> {\n const map = await this.client.hGetAll(this.key(room));\n const out: CanvasElement[] = [];\n for (const value of Object.values(map)) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n continue; // skip a corrupt stored value rather than throwing the whole snapshot\n }\n if (isValidElement(parsed)) out.push(parsed);\n }\n return out;\n }\n\n async get(room: string, id: string): Promise<CanvasElement | undefined> {\n const value = await this.client.hGet(this.key(room), id);\n if (value == null) return undefined;\n try {\n const parsed: unknown = JSON.parse(value);\n return isValidElement(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n }\n\n async apply(room: string, op: SyncOp): Promise<void> {\n const key = this.key(room);\n if (op.kind === 'upsert')\n await this.client.hSet(key, op.element.id, JSON.stringify(op.element));\n else if (op.kind === 'remove') await this.client.hDel(key, op.id);\n // 'clear' deletes elements only; the layer ledger is a separate hash and survives.\n else if (op.kind === 'clear') await this.client.del(key);\n // request-snapshot/snapshot never reach apply (the hub only applies data ops)\n }\n\n async layerRecords(room: string): Promise<LayerRecord[]> {\n const map = await this.client.hGetAll(this.layersKey(room));\n const out: LayerRecord[] = [];\n for (const value of Object.values(map)) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n continue; // skip a corrupt stored value rather than throwing the whole ledger\n }\n if (isValidLayerRecord(parsed)) out.push(parsed);\n }\n return out;\n }\n\n async getLayerRecord(room: string, id: string): Promise<LayerRecord | undefined> {\n const value = await this.client.hGet(this.layersKey(room), id);\n if (value == null) return undefined;\n try {\n const parsed: unknown = JSON.parse(value);\n return isValidLayerRecord(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n }\n\n async applyLayerRecord(room: string, record: LayerRecord): Promise<void> {\n await this.client.hSet(this.layersKey(room), record.id, JSON.stringify(record));\n }\n}\n","import type { HubFanout } from '@fieldnotes/sync-server';\nimport type { RedisPublisher, RedisSubscriber } from './redis-fanout-client';\n\nexport interface RedisHubFanoutOptions {\n channel?: string;\n onError?: (err: unknown) => void;\n}\n\nexport class RedisHubFanout implements HubFanout {\n private readonly publisher: RedisPublisher;\n private readonly subscriber: RedisSubscriber;\n private readonly channel: string;\n private readonly onError: (err: unknown) => void;\n private readonly handlers = new Set<(payload: string) => void>();\n private subscribed = false;\n\n constructor(\n publisher: RedisPublisher,\n subscriber: RedisSubscriber,\n options: RedisHubFanoutOptions = {},\n ) {\n this.publisher = publisher;\n this.subscriber = subscriber;\n this.channel = options.channel ?? 'fieldnotes:fanout';\n this.onError = options.onError ?? (() => undefined);\n }\n\n async publish(payload: string): Promise<void> {\n try {\n await this.publisher.publish(this.channel, payload);\n } catch (error) {\n try {\n this.onError(error);\n } catch {\n /* preserve the publication failure even when the observer throws */\n }\n throw error;\n }\n }\n\n subscribe(handler: (payload: string) => void): () => void {\n this.handlers.add(handler);\n if (!this.subscribed) {\n this.subscribed = true;\n Promise.resolve(\n this.subscriber.subscribe(this.channel, (message) => {\n for (const h of this.handlers) {\n try {\n h(message);\n } catch {\n /* isolate handlers */\n }\n }\n }),\n ).catch(this.onError);\n }\n return () => this.handlers.delete(handler);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,k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ACF,aAAK,QAAQ,KAAK;AAAA,MACpB,QAAQ;AAAA,MAER;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,UAAU,SAAgD;AACxD,SAAK,SAAS,IAAI,OAAO;AACzB,QAAI,CAAC,KAAK,YAAY;AACpB,WAAK,aAAa;AAClB,cAAQ;AAAA,QACN,KAAK,WAAW,UAAU,KAAK,SAAS,CAAC,YAAY;AACnD,qBAAW,KAAK,KAAK,UAAU;AAC7B,gBAAI;AACF,gBAAE,OAAO;AAAA,YACX,QAAQ;AAAA,YAER;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,EAAE,MAAM,KAAK,OAAO;AAAA,IACtB;AACA,WAAO,MAAM,KAAK,SAAS,OAAO,OAAO;AAAA,EAC3C;AACF;","names":[]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { SyncOp } from '@fieldnotes/sync';
1
+ import { SyncOp, LayerRecord } from '@fieldnotes/sync';
2
2
  import { CanvasElement } from '@fieldnotes/core';
3
3
  import { HubBackend, HubFanout } from '@fieldnotes/sync-server';
4
4
 
@@ -18,9 +18,13 @@ declare class RedisHubBackend implements HubBackend {
18
18
  private readonly keyPrefix;
19
19
  constructor(client: RedisHashClient, options?: RedisHubBackendOptions);
20
20
  private key;
21
+ private layersKey;
21
22
  snapshot(room: string): Promise<CanvasElement[]>;
22
23
  get(room: string, id: string): Promise<CanvasElement | undefined>;
23
24
  apply(room: string, op: SyncOp): Promise<void>;
25
+ layerRecords(room: string): Promise<LayerRecord[]>;
26
+ getLayerRecord(room: string, id: string): Promise<LayerRecord | undefined>;
27
+ applyLayerRecord(room: string, record: LayerRecord): Promise<void>;
24
28
  }
25
29
 
26
30
  interface RedisPublisher {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SyncOp } from '@fieldnotes/sync';
1
+ import { SyncOp, LayerRecord } from '@fieldnotes/sync';
2
2
  import { CanvasElement } from '@fieldnotes/core';
3
3
  import { HubBackend, HubFanout } from '@fieldnotes/sync-server';
4
4
 
@@ -18,9 +18,13 @@ declare class RedisHubBackend implements HubBackend {
18
18
  private readonly keyPrefix;
19
19
  constructor(client: RedisHashClient, options?: RedisHubBackendOptions);
20
20
  private key;
21
+ private layersKey;
21
22
  snapshot(room: string): Promise<CanvasElement[]>;
22
23
  get(room: string, id: string): Promise<CanvasElement | undefined>;
23
24
  apply(room: string, op: SyncOp): Promise<void>;
25
+ layerRecords(room: string): Promise<LayerRecord[]>;
26
+ getLayerRecord(room: string, id: string): Promise<LayerRecord | undefined>;
27
+ applyLayerRecord(room: string, record: LayerRecord): Promise<void>;
24
28
  }
25
29
 
26
30
  interface RedisPublisher {
package/dist/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  // src/redis-hub-backend.ts
2
- import { isValidElement } from "@fieldnotes/sync";
2
+ import {
3
+ isValidElement,
4
+ isValidLayerRecord
5
+ } from "@fieldnotes/sync";
3
6
  var RedisHubBackend = class {
4
7
  client;
5
8
  keyPrefix;
@@ -10,6 +13,9 @@ var RedisHubBackend = class {
10
13
  key(room) {
11
14
  return `${this.keyPrefix}${room}`;
12
15
  }
16
+ layersKey(room) {
17
+ return `${this.keyPrefix}${room}:layers`;
18
+ }
13
19
  async snapshot(room) {
14
20
  const map = await this.client.hGetAll(this.key(room));
15
21
  const out = [];
@@ -41,6 +47,33 @@ var RedisHubBackend = class {
41
47
  else if (op.kind === "remove") await this.client.hDel(key, op.id);
42
48
  else if (op.kind === "clear") await this.client.del(key);
43
49
  }
50
+ async layerRecords(room) {
51
+ const map = await this.client.hGetAll(this.layersKey(room));
52
+ const out = [];
53
+ for (const value of Object.values(map)) {
54
+ let parsed;
55
+ try {
56
+ parsed = JSON.parse(value);
57
+ } catch {
58
+ continue;
59
+ }
60
+ if (isValidLayerRecord(parsed)) out.push(parsed);
61
+ }
62
+ return out;
63
+ }
64
+ async getLayerRecord(room, id) {
65
+ const value = await this.client.hGet(this.layersKey(room), id);
66
+ if (value == null) return void 0;
67
+ try {
68
+ const parsed = JSON.parse(value);
69
+ return isValidLayerRecord(parsed) ? parsed : void 0;
70
+ } catch {
71
+ return void 0;
72
+ }
73
+ }
74
+ async applyLayerRecord(room, record) {
75
+ await this.client.hSet(this.layersKey(room), record.id, JSON.stringify(record));
76
+ }
44
77
  };
45
78
 
46
79
  // src/redis-hub-fanout.ts
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/redis-hub-backend.ts","../src/redis-hub-fanout.ts"],"sourcesContent":["import { isValidElement, type SyncOp } from '@fieldnotes/sync';\r\nimport type { CanvasElement } from '@fieldnotes/core';\r\nimport type { HubBackend } from '@fieldnotes/sync-server';\r\nimport type { RedisHashClient } from './redis-hash-client';\r\n\r\nexport interface RedisHubBackendOptions {\r\n keyPrefix?: string; // default 'fieldnotes:room:'\r\n}\r\n\r\nexport class RedisHubBackend implements HubBackend {\r\n private readonly client: RedisHashClient;\r\n private readonly keyPrefix: string;\r\n\r\n constructor(client: RedisHashClient, options: RedisHubBackendOptions = {}) {\r\n this.client = client;\r\n this.keyPrefix = options.keyPrefix ?? 'fieldnotes:room:';\r\n }\r\n\r\n private key(room: string): string {\r\n return `${this.keyPrefix}${room}`;\r\n }\r\n\r\n async snapshot(room: string): Promise<CanvasElement[]> {\r\n const map = await this.client.hGetAll(this.key(room));\r\n const out: CanvasElement[] = [];\r\n for (const value of Object.values(map)) {\r\n let parsed: unknown;\r\n try {\r\n parsed = JSON.parse(value);\r\n } catch {\r\n continue; // skip a corrupt stored value rather than throwing the whole snapshot\r\n }\r\n if (isValidElement(parsed)) out.push(parsed);\r\n }\r\n return out;\r\n }\r\n\r\n async get(room: string, id: string): Promise<CanvasElement | undefined> {\r\n const value = await this.client.hGet(this.key(room), id);\r\n if (value == null) return undefined;\r\n try {\r\n const parsed: unknown = JSON.parse(value);\r\n return isValidElement(parsed) ? parsed : undefined;\r\n } catch {\r\n return undefined;\r\n }\r\n }\r\n\r\n async apply(room: string, op: SyncOp): Promise<void> {\r\n const key = this.key(room);\r\n if (op.kind === 'upsert')\r\n await this.client.hSet(key, op.element.id, JSON.stringify(op.element));\r\n else if (op.kind === 'remove') await this.client.hDel(key, op.id);\r\n else if (op.kind === 'clear') await this.client.del(key);\r\n // request-snapshot/snapshot never reach apply (the hub only applies data ops)\r\n }\r\n}\r\n","import type { HubFanout } from '@fieldnotes/sync-server';\nimport type { RedisPublisher, RedisSubscriber } from './redis-fanout-client';\n\nexport interface RedisHubFanoutOptions {\n channel?: string;\n onError?: (err: unknown) => void;\n}\n\nexport class RedisHubFanout implements HubFanout {\n private readonly publisher: RedisPublisher;\n private readonly subscriber: RedisSubscriber;\n private readonly channel: string;\n private readonly onError: (err: unknown) => void;\n private readonly handlers = new Set<(payload: string) => void>();\n private subscribed = false;\n\n constructor(\n publisher: RedisPublisher,\n subscriber: RedisSubscriber,\n options: RedisHubFanoutOptions = {},\n ) {\n this.publisher = publisher;\n this.subscriber = subscriber;\n this.channel = options.channel ?? 'fieldnotes:fanout';\n this.onError = options.onError ?? (() => undefined);\n }\n\n async publish(payload: string): Promise<void> {\n try {\n await this.publisher.publish(this.channel, payload);\n } catch (error) {\n try {\n this.onError(error);\n } catch {\n /* preserve the publication failure even when the observer throws */\n }\n throw error;\n }\n }\n\n subscribe(handler: (payload: string) => void): () => void {\n this.handlers.add(handler);\n if (!this.subscribed) {\n this.subscribed = true;\n Promise.resolve(\n this.subscriber.subscribe(this.channel, (message) => {\n for (const h of this.handlers) {\n try {\n h(message);\n } catch {\n /* isolate handlers */\n }\n }\n }),\n ).catch(this.onError);\n }\n return () => this.handlers.delete(handler);\n }\n}\n"],"mappings":";AAAA,SAAS,sBAAmC;AASrC,IAAM,kBAAN,MAA4C;AAAA,EAChC;AAAA,EACA;AAAA,EAEjB,YAAY,QAAyB,UAAkC,CAAC,GAAG;AACzE,SAAK,SAAS;AACd,SAAK,YAAY,QAAQ,aAAa;AAAA,EACxC;AAAA,EAEQ,IAAI,MAAsB;AAChC,WAAO,GA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,SAAK,UAAU,QAAQ,YAAY,MAAM;AAAA,EAC3C;AAAA,EAEA,MAAM,QAAQ,SAAgC;AAC5C,QAAI;AACF,YAAM,KAAK,UAAU,QAAQ,KAAK,SAAS,OAAO;AAAA,IACpD,SAAS,OAAO;AACd,UAAI;AACF,aAAK,QAAQ,KAAK;AAAA,MACpB,QAAQ;AAAA,MAER;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,UAAU,SAAgD;AACxD,SAAK,SAAS,IAAI,OAAO;AACzB,QAAI,CAAC,KAAK,YAAY;AACpB,WAAK,aAAa;AAClB,cAAQ;AAAA,QACN,KAAK,WAAW,UAAU,KAAK,SAAS,CAAC,YAAY;AACnD,qBAAW,KAAK,KAAK,UAAU;AAC7B,gBAAI;AACF,gBAAE,OAAO;AAAA,YACX,QAAQ;AAAA,YAER;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,EAAE,MAAM,KAAK,OAAO;AAAA,IACtB;AACA,WAAO,MAAM,KAAK,SAAS,OAAO,OAAO;AAAA,EAC3C;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/redis-hub-backend.ts","../src/redis-hub-fanout.ts"],"sourcesContent":["import {\n isValidElement,\n isValidLayerRecord,\n type LayerRecord,\n type SyncOp,\n} from '@fieldnotes/sync';\nimport type { CanvasElement } from '@fieldnotes/core';\nimport type { HubBackend } from '@fieldnotes/sync-server';\nimport type { RedisHashClient } from './redis-hash-client';\n\nexport interface RedisHubBackendOptions {\n keyPrefix?: string; // default 'fieldnotes:room:'\n}\n\nexport class RedisHubBackend implements HubBackend {\n private readonly client: RedisHashClient;\n private readonly keyPrefix: string;\n\n constructor(client: RedisHashClient, options: RedisHubBackendOptions = {}) {\n this.client = client;\n this.keyPrefix = options.keyPrefix ?? 'fieldnotes:room:';\n }\n\n private key(room: string): string {\n return `${this.keyPrefix}${room}`;\n }\n\n private layersKey(room: string): string {\n return `${this.keyPrefix}${room}:layers`;\n }\n\n async snapshot(room: string): Promise<CanvasElement[]> {\n const map = await this.client.hGetAll(this.key(room));\n const out: CanvasElement[] = [];\n for (const value of Object.values(map)) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n continue; // skip a corrupt stored value rather than throwing the whole snapshot\n }\n if (isValidElement(parsed)) out.push(parsed);\n }\n return out;\n }\n\n async get(room: string, id: string): Promise<CanvasElement | undefined> {\n const value = await this.client.hGet(this.key(room), id);\n if (value == null) return undefined;\n try {\n const parsed: unknown = JSON.parse(value);\n return isValidElement(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n }\n\n async apply(room: string, op: SyncOp): Promise<void> {\n const key = this.key(room);\n if (op.kind === 'upsert')\n await this.client.hSet(key, op.element.id, JSON.stringify(op.element));\n else if (op.kind === 'remove') await this.client.hDel(key, op.id);\n // 'clear' deletes elements only; the layer ledger is a separate hash and survives.\n else if (op.kind === 'clear') await this.client.del(key);\n // request-snapshot/snapshot never reach apply (the hub only applies data ops)\n }\n\n async layerRecords(room: string): Promise<LayerRecord[]> {\n const map = await this.client.hGetAll(this.layersKey(room));\n const out: LayerRecord[] = [];\n for (const value of Object.values(map)) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n continue; // skip a corrupt stored value rather than throwing the whole ledger\n }\n if (isValidLayerRecord(parsed)) out.push(parsed);\n }\n return out;\n }\n\n async getLayerRecord(room: string, id: string): Promise<LayerRecord | undefined> {\n const value = await this.client.hGet(this.layersKey(room), id);\n if (value == null) return undefined;\n try {\n const parsed: unknown = JSON.parse(value);\n return isValidLayerRecord(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n }\n\n async applyLayerRecord(room: string, record: LayerRecord): Promise<void> {\n await this.client.hSet(this.layersKey(room), record.id, JSON.stringify(record));\n }\n}\n","import type { HubFanout } from '@fieldnotes/sync-server';\nimport type { RedisPublisher, RedisSubscriber } from './redis-fanout-client';\n\nexport interface RedisHubFanoutOptions {\n channel?: string;\n onError?: (err: unknown) => void;\n}\n\nexport class RedisHubFanout implements HubFanout {\n private readonly publisher: RedisPublisher;\n private readonly subscriber: RedisSubscriber;\n private readonly channel: string;\n private readonly onError: (err: unknown) => void;\n private readonly handlers = new Set<(payload: string) => void>();\n private subscribed = false;\n\n constructor(\n publisher: RedisPublisher,\n subscriber: RedisSubscriber,\n options: RedisHubFanoutOptions = {},\n ) {\n this.publisher = publisher;\n this.subscriber = subscriber;\n this.channel = options.channel ?? 'fieldnotes:fanout';\n this.onError = options.onError ?? (() => undefined);\n }\n\n async publish(payload: string): Promise<void> {\n try {\n await this.publisher.publish(this.channel, payload);\n } catch (error) {\n try {\n this.onError(error);\n } catch {\n /* preserve the publication failure even when the observer throws */\n }\n throw error;\n }\n }\n\n subscribe(handler: (payload: string) => void): () => void {\n this.handlers.add(handler);\n if (!this.subscribed) {\n this.subscribed = true;\n Promise.resolve(\n this.subscriber.subscribe(this.channel, (message) => {\n for (const h of this.handlers) {\n try {\n h(message);\n } catch {\n /* isolate handlers */\n }\n }\n }),\n ).catch(this.onError);\n }\n return () => this.handlers.delete(handler);\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AASA,IAAM,kBAAN,MAA4C;AAAA,EAChC;AAAA,EACA;AAAA,EAEjB,YAAY,QAAyB,UAAkC,CAAC,GAAG;AACzE,SAAK,SAAS;AACd,SAAK,YAAY,QAAQ,aAAa;AAAA,EACxC;AAAA,EAEQ,IAAI,MAAsB;AAChC,WAAO,GAAG,KAAK,SAAS,GAAG,IAAI;AAAA,EACjC;AAAA,EAEQ,UAAU,MAAsB;AACtC,WAAO,GAAG,KAAK,SAAS,GAAG,IAAI;AAAA,EACjC;AAAA,EAEA,MAAM,SAAS,MAAwC;AACrD,UAAM,MAAM,MAAM,KAAK,OAAO,QAAQ,KAAK,IAAI,IAAI,CAAC;AACpD,UAAM,MAAuB,CAAC;AAC9B,eAAW,SAAS,OAAO,OAAO,GAAG,GAAG;AACtC,UAAI;AACJ,UAAI;AACF,iBAAS,KAA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2
  "name": "@fieldnotes/sync-redis",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Redis-backed HubBackend for Field Notes real-time sync relay",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -36,14 +36,14 @@
36
36
  "fieldnotes"
37
37
  ],
38
38
  "dependencies": {
39
- "@fieldnotes/sync": "0.7.1"
39
+ "@fieldnotes/sync": "0.10.0"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@vitest/coverage-v8": "^4.1.0",
43
43
  "tsup": "^8.5.1",
44
44
  "vitest": "^4.1.0",
45
- "@fieldnotes/sync-server": "0.10.1",
46
- "@fieldnotes/core": "0.52.2"
45
+ "@fieldnotes/sync-server": "0.12.0",
46
+ "@fieldnotes/core": "0.53.0"
47
47
  },
48
48
  "scripts": {
49
49
  "build": "tsup",