@krizaka/realtime 0.0.0-stage → 0.1.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 +202 -0
- package/README.md +115 -2
- package/dist/chunk-GBVW7BAQ.js +90 -0
- package/dist/chunk-GBVW7BAQ.js.map +1 -0
- package/dist/chunk-HJCRR3FF.js +194 -0
- package/dist/chunk-HJCRR3FF.js.map +1 -0
- package/dist/chunk-WHRDA5M4.js +73 -0
- package/dist/chunk-WHRDA5M4.js.map +1 -0
- package/dist/index.d.ts +106 -0
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -0
- package/dist/pg.d.ts +57 -0
- package/dist/pg.js +90 -0
- package/dist/pg.js.map +1 -0
- package/dist/postgres.d.ts +40 -0
- package/dist/postgres.js +12 -0
- package/dist/postgres.js.map +1 -0
- package/dist/redis.d.ts +52 -0
- package/dist/redis.js +163 -0
- package/dist/redis.js.map +1 -0
- package/dist/sse.d.ts +41 -0
- package/dist/sse.js +9 -0
- package/dist/sse.js.map +1 -0
- package/dist/types-BP1h40fn.d.ts +64 -0
- package/package.json +151 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,116 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @krizaka/realtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Realtime for a Node app, behind **one interface**: a bus (publish / subscribe by channel), presence (who is
|
|
4
|
+
connected, by heartbeat and time-to-live) and Server-Sent Events. The adapter is a deployment choice — memory,
|
|
5
|
+
**PostgreSQL LISTEN/NOTIFY** or **Redis / Valkey** — and the code that publishes and subscribes never knows which.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @krizaka/realtime
|
|
9
|
+
npm install pg # for the PostgreSQL adapter's pgChannel (optional peer)
|
|
10
|
+
npm install ioredis # for the Redis / Valkey adapter (optional peer)
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
ESM only, Node ≥ 20. The root entry loads no driver.
|
|
14
|
+
|
|
15
|
+
## What is in it
|
|
16
|
+
|
|
17
|
+
| Entry | What | Needs |
|
|
18
|
+
| :-- | :-- | :-- |
|
|
19
|
+
| `@krizaka/realtime` | `RealtimeBus`, `PresenceStore` and their types · `createBus` · `busKind` · `memoryBus` · `postgresBus` · `ReplicatedPresence` · `eventStream`, `sseFrame` | nothing |
|
|
20
|
+
| `@krizaka/realtime/sse` | `eventStream`, `sseFrame` alone (an edge route that only streams) | nothing |
|
|
21
|
+
| `@krizaka/realtime/postgres` | `postgresBus`, `PostgresChannel`, `NOTIFY_LIMIT`, `DEFAULT_CHANNEL` | a `PostgresChannel` |
|
|
22
|
+
| `@krizaka/realtime/pg` | `pgChannel` — a `PostgresChannel` on node-postgres | `pg` |
|
|
23
|
+
| `@krizaka/realtime/redis` | `redisBus`, `RedisPresence`, `DEFAULT_PREFIX` | `ioredis` |
|
|
24
|
+
|
|
25
|
+
## The contract
|
|
26
|
+
|
|
27
|
+
- **Best-effort.** `publish` never throws; when the network fails, the event still reaches this instance's
|
|
28
|
+
subscribers. Durable facts (messages, bids) live in the database and are replayed from it — never from the bus.
|
|
29
|
+
- **Small payloads.** Ids and small facts; PostgreSQL caps a NOTIFY at 8 000 bytes (`NOTIFY_LIMIT` = 7 900 with the
|
|
30
|
+
envelope).
|
|
31
|
+
- **Presence is never a database write per beat.** A connection beats (`beat`) every third of `ttlMs` (default
|
|
32
|
+
45 s); a closed one lingers `graceMs` (default 10 s) so a reconnection changes nothing; `settle` after the grace
|
|
33
|
+
tells whether the person went offline. Every call answers the change it caused, once, so the caller publishes it
|
|
34
|
+
once — whichever instance noticed it.
|
|
35
|
+
- **Fail loudly on configuration.** `createBus` refuses a bus that cannot work (redis without a URL, postgres without a
|
|
36
|
+
channel) instead of falling back to memory.
|
|
37
|
+
|
|
38
|
+
## Wiring it once
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
// lib/realtime.ts — the app's one realtime door
|
|
42
|
+
import { busKind, createBus, eventStream, type RealtimeBus } from "@krizaka/realtime";
|
|
43
|
+
import { pgChannel } from "@krizaka/realtime/pg";
|
|
44
|
+
import { redisBus } from "@krizaka/realtime/redis";
|
|
45
|
+
|
|
46
|
+
import { pool } from "./db"; // the app's own pool (a transaction pooler is fine for NOTIFY)
|
|
47
|
+
|
|
48
|
+
let bus: RealtimeBus | undefined;
|
|
49
|
+
export function realtimeBus() {
|
|
50
|
+
return (bus ??= createBus({
|
|
51
|
+
kind: busKind(process.env.REALTIME_BUS), // postgres (default) · redis · memory
|
|
52
|
+
// LISTEN needs a session: a direct connection, never PgBouncer in transaction mode.
|
|
53
|
+
postgres: pgChannel({ listen: process.env.DATABASE_DIRECT_URL!, notify: pool }),
|
|
54
|
+
channel: "myapp_events", // one NOTIFY channel per app
|
|
55
|
+
redisBus,
|
|
56
|
+
redisUrl: process.env.REDIS_URL,
|
|
57
|
+
prefix: "myapp:rt:", // one key prefix per app on a shared server
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// app/api/events/route.ts — a Server-Sent Events stream
|
|
62
|
+
export function GET() {
|
|
63
|
+
return eventStream({
|
|
64
|
+
retryMs: 2000,
|
|
65
|
+
heartbeatMs: 15_000,
|
|
66
|
+
maxLifetimeMs: 300_000, // under the platform's request timeout; the client comes back
|
|
67
|
+
start: ({ send }) => realtimeBus().subscribe(`user:${userId}`, (event) => send({ data: event })),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The package reads **no environment variable**: the app decides which URL is the direct one, which channel and which
|
|
73
|
+
prefix are its own. Bring your own `PostgresChannel` (`{ notify, listen }`) if your app already has a LISTEN
|
|
74
|
+
connection; `pgChannel` is only the ready-made one.
|
|
75
|
+
|
|
76
|
+
## Which adapter
|
|
77
|
+
|
|
78
|
+
| Adapter | Fan-out | Presence | Choose it when |
|
|
79
|
+
| :-- | :-- | :-- | :-- |
|
|
80
|
+
| `memory` | inside one process | in memory | tests, one instance without a database |
|
|
81
|
+
| `postgres` (default) | `NOTIFY` to every instance's `LISTEN` — every instance receives every event | each instance's memory, replicated over the same channel (changes + a snapshot every 30 s) | one to ~3 instances: no extra service to run or pay for |
|
|
82
|
+
| `redis` | Redis / Valkey pub/sub, one subscription per channel that has a listener on the instance | in Redis, one atomic script per beat, keys that expire by themselves | more instances or many open streams: an event crosses the network only to instances that listen |
|
|
83
|
+
|
|
84
|
+
Switch to **Redis / Valkey** when the instances multiply (every PostgreSQL instance receives every event and the
|
|
85
|
+
NOTIFY queue is shared with the database), when presence must survive an instance's restart without a 75 s fade, or
|
|
86
|
+
when a managed cache is already there. Switching is a variable and a restart.
|
|
87
|
+
|
|
88
|
+
### PostgreSQL behind a pooler
|
|
89
|
+
|
|
90
|
+
`LISTEN` lives as long as its **session**. Behind PgBouncer (or any pooler) in **transaction** mode, the subscription
|
|
91
|
+
is lost between transactions: give `pgChannel` a **direct** connection string for `listen` (DigitalOcean, Supabase,
|
|
92
|
+
Neon and others all offer one next to the pooled one), and pass the app's pooled `pool` as `notify` — a NOTIFY is one
|
|
93
|
+
statement and goes through a transaction pooler. Without `notify`, `pgChannel` opens a pool of two connections on the
|
|
94
|
+
`listen` URL. The LISTEN connection reconnects by itself (1 s, doubling, capped at 30 s); while it is down, the
|
|
95
|
+
instance still publishes to the others and delivers its own events locally (`bus.connected` is `false`).
|
|
96
|
+
|
|
97
|
+
## How the Krizaka products use it
|
|
98
|
+
|
|
99
|
+
- **A video platform**: one `user:<id>` topic per account (messages, receipts, typing, notifications), `presence:<id>`
|
|
100
|
+
delivered only to those allowed to see it, one topic per live auction and per challenge; the chat stream replays
|
|
101
|
+
missed messages from the database with `Last-Event-ID`, then follows the bus.
|
|
102
|
+
- **A dating app**: the agent's reply streamed as SSE, the events of an account (a batch is ready, a new intro, a
|
|
103
|
+
message) on `user:<id>`, the messages of an intro on `intro:<id>`.
|
|
104
|
+
|
|
105
|
+
Both run `postgres` by default and keep `redis` one variable away.
|
|
106
|
+
|
|
107
|
+
## Tests
|
|
108
|
+
|
|
109
|
+
`pnpm --filter @krizaka/realtime test` covers every adapter without a server (100 % enforced): the PostgreSQL bus over
|
|
110
|
+
an in-memory channel, `pgChannel` over a fake driver. The contract against real servers — two instances per adapter,
|
|
111
|
+
delivery under a second, order of a burst, presence announced once — runs with `REALTIME_IT=1`
|
|
112
|
+
(`pnpm --filter @krizaka/realtime test:integration`, `DATABASE_URL` and `REDIS_URL`), in CI's "Realtime adapters" job.
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
Apache-2.0 © Krizaka
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// src/sse.ts
|
|
2
|
+
var clean = (value) => value.replace(/[\r\n]/g, " ");
|
|
3
|
+
function sseFrame(frame) {
|
|
4
|
+
let out = "";
|
|
5
|
+
if (frame.comment !== void 0) out += `: ${clean(frame.comment)}
|
|
6
|
+
`;
|
|
7
|
+
if (frame.retry !== void 0) out += `retry: ${Math.max(0, Math.round(frame.retry))}
|
|
8
|
+
`;
|
|
9
|
+
if (frame.id !== void 0) out += `id: ${clean(frame.id)}
|
|
10
|
+
`;
|
|
11
|
+
if (frame.event !== void 0) out += `event: ${clean(frame.event)}
|
|
12
|
+
`;
|
|
13
|
+
if (frame.data !== void 0) out += `data: ${JSON.stringify(frame.data)}
|
|
14
|
+
`;
|
|
15
|
+
return `${out}
|
|
16
|
+
`;
|
|
17
|
+
}
|
|
18
|
+
function eventStream(options) {
|
|
19
|
+
const encoder = new TextEncoder();
|
|
20
|
+
const abort = new AbortController();
|
|
21
|
+
const cleanups = [];
|
|
22
|
+
let ended = false;
|
|
23
|
+
let controllerRef = null;
|
|
24
|
+
const end = () => {
|
|
25
|
+
if (ended) return;
|
|
26
|
+
ended = true;
|
|
27
|
+
abort.abort();
|
|
28
|
+
for (const cleanup of cleanups.splice(0).reverse()) {
|
|
29
|
+
try {
|
|
30
|
+
cleanup();
|
|
31
|
+
} catch {
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
controllerRef?.close();
|
|
36
|
+
} catch {
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const send = (frame) => {
|
|
40
|
+
if (ended || !controllerRef) return;
|
|
41
|
+
try {
|
|
42
|
+
controllerRef.enqueue(encoder.encode(sseFrame(frame)));
|
|
43
|
+
} catch {
|
|
44
|
+
end();
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const stream = new ReadableStream({
|
|
48
|
+
async start(controller) {
|
|
49
|
+
controllerRef = controller;
|
|
50
|
+
if (options.retryMs) send({ retry: options.retryMs });
|
|
51
|
+
const heartbeat = setInterval(() => {
|
|
52
|
+
send({ comment: "heartbeat" });
|
|
53
|
+
options.onHeartbeat?.();
|
|
54
|
+
}, options.heartbeatMs ?? 15e3);
|
|
55
|
+
cleanups.push(() => clearInterval(heartbeat));
|
|
56
|
+
if (options.maxLifetimeMs) {
|
|
57
|
+
const lifetime = setTimeout(end, options.maxLifetimeMs);
|
|
58
|
+
cleanups.push(() => clearTimeout(lifetime));
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
const cleanup = await options.start({ send, close: end, signal: abort.signal });
|
|
62
|
+
if (cleanup) {
|
|
63
|
+
if (ended) cleanup();
|
|
64
|
+
else cleanups.push(cleanup);
|
|
65
|
+
}
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.warn("[realtime] stream start failed", error.message);
|
|
68
|
+
end();
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
cancel() {
|
|
72
|
+
end();
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return new Response(stream, {
|
|
76
|
+
headers: {
|
|
77
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
78
|
+
"Cache-Control": "no-cache, no-transform",
|
|
79
|
+
Connection: "keep-alive",
|
|
80
|
+
"X-Accel-Buffering": "no",
|
|
81
|
+
...options.headers
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export {
|
|
87
|
+
sseFrame,
|
|
88
|
+
eventStream
|
|
89
|
+
};
|
|
90
|
+
//# sourceMappingURL=chunk-GBVW7BAQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sse.ts"],"sourcesContent":["/**\n * Server-Sent Events, framed by hand (the format is four fields). `eventStream` turns a few callbacks into a web\n * `Response` any runtime serves: heartbeats keep proxies from closing an idle stream, `retry` tells the browser how\n * fast to come back, and a maximum lifetime ends the stream cleanly before a platform's own request timeout does\n * (the client reconnects at once, with `Last-Event-ID`).\n */\n\nexport interface SseFrame {\n /** The event's id: the browser sends the last one back as `Last-Event-ID` when it reconnects. */\n id?: string;\n /** A named event (`addEventListener(name)`); absent: `message`. */\n event?: string;\n data?: unknown;\n /** Reconnection delay the client should use (ms). */\n retry?: number;\n /** A comment line (heartbeats). */\n comment?: string;\n}\n\nconst clean = (value: string) => value.replace(/[\\r\\n]/g, \" \");\n\nexport function sseFrame(frame: SseFrame): string {\n let out = \"\";\n if (frame.comment !== undefined) out += `: ${clean(frame.comment)}\\n`;\n if (frame.retry !== undefined) out += `retry: ${Math.max(0, Math.round(frame.retry))}\\n`;\n if (frame.id !== undefined) out += `id: ${clean(frame.id)}\\n`;\n if (frame.event !== undefined) out += `event: ${clean(frame.event)}\\n`;\n if (frame.data !== undefined) out += `data: ${JSON.stringify(frame.data)}\\n`;\n return `${out}\\n`;\n}\n\nexport interface EventStreamControls {\n send(frame: SseFrame): void;\n /** Ends the stream from the server side (the client reconnects). */\n close(): void;\n /** Aborted when the client goes away or the stream ends. */\n signal: AbortSignal;\n}\n\nexport interface EventStreamOptions {\n /** Runs once the stream is open; returns the cleanup to run when it ends. */\n start(controls: EventStreamControls): void | (() => void) | Promise<void | (() => void)>;\n /** Heartbeat period (ms) — below every proxy's idle timeout. */\n heartbeatMs?: number;\n /** Called at each heartbeat (presence refreshes its TTL there). */\n onHeartbeat?: () => void;\n /** Ends the stream after this long (ms, 0: never) — under a platform's hard request timeout. */\n maxLifetimeMs?: number;\n /** Reconnection delay sent to the client (ms). */\n retryMs?: number;\n headers?: Record<string, string>;\n}\n\nexport function eventStream(options: EventStreamOptions): Response {\n const encoder = new TextEncoder();\n const abort = new AbortController();\n const cleanups: (() => void)[] = [];\n let ended = false;\n let controllerRef: ReadableStreamDefaultController<Uint8Array> | null = null;\n\n const end = () => {\n if (ended) return;\n ended = true;\n abort.abort();\n for (const cleanup of cleanups.splice(0).reverse()) {\n try {\n cleanup();\n } catch {\n /* keep cleaning */\n }\n }\n try {\n controllerRef?.close();\n } catch {\n /* already closed */\n }\n };\n\n const send = (frame: SseFrame) => {\n if (ended || !controllerRef) return;\n try {\n controllerRef.enqueue(encoder.encode(sseFrame(frame)));\n } catch {\n /* v8 ignore next -- defensive: the runtime closed the stream under us (ended guards the known paths) */\n end();\n }\n };\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n controllerRef = controller;\n if (options.retryMs) send({ retry: options.retryMs });\n const heartbeat = setInterval(() => {\n send({ comment: \"heartbeat\" });\n options.onHeartbeat?.();\n }, options.heartbeatMs ?? 15_000);\n cleanups.push(() => clearInterval(heartbeat));\n if (options.maxLifetimeMs) {\n const lifetime = setTimeout(end, options.maxLifetimeMs);\n cleanups.push(() => clearTimeout(lifetime));\n }\n try {\n const cleanup = await options.start({ send, close: end, signal: abort.signal });\n if (cleanup) {\n if (ended) cleanup();\n else cleanups.push(cleanup);\n }\n } catch (error) {\n console.warn(\"[realtime] stream start failed\", (error as Error).message);\n end();\n }\n },\n cancel() {\n end();\n },\n });\n\n return new Response(stream, {\n headers: {\n \"Content-Type\": \"text/event-stream; charset=utf-8\",\n \"Cache-Control\": \"no-cache, no-transform\",\n Connection: \"keep-alive\",\n \"X-Accel-Buffering\": \"no\",\n ...options.headers,\n },\n });\n}\n"],"mappings":";AAmBA,IAAM,QAAQ,CAAC,UAAkB,MAAM,QAAQ,WAAW,GAAG;AAEtD,SAAS,SAAS,OAAyB;AAChD,MAAI,MAAM;AACV,MAAI,MAAM,YAAY,OAAW,QAAO,KAAK,MAAM,MAAM,OAAO,CAAC;AAAA;AACjE,MAAI,MAAM,UAAU,OAAW,QAAO,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,KAAK,CAAC,CAAC;AAAA;AACpF,MAAI,MAAM,OAAO,OAAW,QAAO,OAAO,MAAM,MAAM,EAAE,CAAC;AAAA;AACzD,MAAI,MAAM,UAAU,OAAW,QAAO,UAAU,MAAM,MAAM,KAAK,CAAC;AAAA;AAClE,MAAI,MAAM,SAAS,OAAW,QAAO,SAAS,KAAK,UAAU,MAAM,IAAI,CAAC;AAAA;AACxE,SAAO,GAAG,GAAG;AAAA;AACf;AAwBO,SAAS,YAAY,SAAuC;AACjE,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,QAAQ,IAAI,gBAAgB;AAClC,QAAM,WAA2B,CAAC;AAClC,MAAI,QAAQ;AACZ,MAAI,gBAAoE;AAExE,QAAM,MAAM,MAAM;AAChB,QAAI,MAAO;AACX,YAAQ;AACR,UAAM,MAAM;AACZ,eAAW,WAAW,SAAS,OAAO,CAAC,EAAE,QAAQ,GAAG;AAClD,UAAI;AACF,gBAAQ;AAAA,MACV,QAAQ;AAAA,MAER;AAAA,IACF;AACA,QAAI;AACF,qBAAe,MAAM;AAAA,IACvB,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,QAAM,OAAO,CAAC,UAA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3
|
+
var rank = (state) => state === "online" ? 2 : state === "away" ? 1 : 0;
|
|
4
|
+
|
|
5
|
+
// src/presence.ts
|
|
6
|
+
var MAX_LAST_SEEN = 1e5;
|
|
7
|
+
var ReplicatedPresence = class {
|
|
8
|
+
constructor(config) {
|
|
9
|
+
this.config = config;
|
|
10
|
+
this.options = { ...DEFAULT_PRESENCE, ...config };
|
|
11
|
+
this.snapshotTtlMs = config.snapshotTtlMs ?? 75e3;
|
|
12
|
+
this.snapshotPage = config.snapshotPage ?? 150;
|
|
13
|
+
}
|
|
14
|
+
config;
|
|
15
|
+
options;
|
|
16
|
+
local = /* @__PURE__ */ new Map();
|
|
17
|
+
remote = /* @__PURE__ */ new Map();
|
|
18
|
+
announced = /* @__PURE__ */ new Map();
|
|
19
|
+
/** The local view last told to the other instances. */
|
|
20
|
+
told = /* @__PURE__ */ new Map();
|
|
21
|
+
lastSeen = /* @__PURE__ */ new Map();
|
|
22
|
+
listeners = /* @__PURE__ */ new Set();
|
|
23
|
+
snapshotTtlMs;
|
|
24
|
+
snapshotPage;
|
|
25
|
+
/** This instance's view of one person: the best of its live connections (expired ones are dropped). */
|
|
26
|
+
localState(userId, now) {
|
|
27
|
+
const conns = this.local.get(userId);
|
|
28
|
+
if (!conns) return "offline";
|
|
29
|
+
let best = "offline";
|
|
30
|
+
for (const [id, conn] of conns) {
|
|
31
|
+
if (conn.expiresAt <= now) conns.delete(id);
|
|
32
|
+
else if (rank(conn.state) > rank(best)) best = conn.state;
|
|
33
|
+
}
|
|
34
|
+
if (conns.size === 0) this.local.delete(userId);
|
|
35
|
+
return best;
|
|
36
|
+
}
|
|
37
|
+
remoteState(userId, now) {
|
|
38
|
+
const views = this.remote.get(userId);
|
|
39
|
+
if (!views) return "offline";
|
|
40
|
+
let best = "offline";
|
|
41
|
+
for (const [instance, view] of views) {
|
|
42
|
+
if (view.expiresAt <= now) views.delete(instance);
|
|
43
|
+
else if (rank(view.state) > rank(best)) best = view.state;
|
|
44
|
+
}
|
|
45
|
+
if (views.size === 0) this.remote.delete(userId);
|
|
46
|
+
return best;
|
|
47
|
+
}
|
|
48
|
+
state(userId, now) {
|
|
49
|
+
const a = this.localState(userId, now);
|
|
50
|
+
const b = this.remoteState(userId, now);
|
|
51
|
+
return rank(a) >= rank(b) ? a : b;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Compares with what was announced; records and returns the change. A change caused by another instance's report is
|
|
55
|
+
* returned only when it is an offline the reporter may not have seen (both instances lost the person at once): the
|
|
56
|
+
* instance with the greater id announces it — at most a duplicate, never a person left online forever.
|
|
57
|
+
*/
|
|
58
|
+
evaluate(userId, now, own, reporter) {
|
|
59
|
+
const local = this.localState(userId, now);
|
|
60
|
+
if ((this.told.get(userId) ?? "offline") !== local) {
|
|
61
|
+
if (local === "offline") this.told.delete(userId);
|
|
62
|
+
else this.told.set(userId, local);
|
|
63
|
+
this.config.broadcast?.({ t: "d", i: this.config.instanceId, u: userId, s: local, at: now });
|
|
64
|
+
}
|
|
65
|
+
const next = this.state(userId, now);
|
|
66
|
+
const previous = this.announced.get(userId) ?? "offline";
|
|
67
|
+
if (next === "offline") {
|
|
68
|
+
this.announced.delete(userId);
|
|
69
|
+
if (previous !== "offline") this.see(userId, now);
|
|
70
|
+
} else {
|
|
71
|
+
this.announced.set(userId, next);
|
|
72
|
+
this.see(userId, now);
|
|
73
|
+
}
|
|
74
|
+
if (next === previous) return null;
|
|
75
|
+
if (own) return { userId, state: next, at: now };
|
|
76
|
+
if (next === "offline" && reporter !== void 0 && this.config.instanceId > reporter) return { userId, state: next, at: now };
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
see(userId, at) {
|
|
80
|
+
if (this.lastSeen.size >= MAX_LAST_SEEN && !this.lastSeen.has(userId)) this.lastSeen.clear();
|
|
81
|
+
this.lastSeen.set(userId, at);
|
|
82
|
+
}
|
|
83
|
+
async beat(userId, connectionId, state, now = Date.now()) {
|
|
84
|
+
let conns = this.local.get(userId);
|
|
85
|
+
if (!conns) this.local.set(userId, conns = /* @__PURE__ */ new Map());
|
|
86
|
+
conns.set(connectionId, { state, expiresAt: now + this.options.ttlMs });
|
|
87
|
+
return this.evaluate(userId, now, true);
|
|
88
|
+
}
|
|
89
|
+
async leave(userId, connectionId, now = Date.now()) {
|
|
90
|
+
const conn = this.local.get(userId)?.get(connectionId);
|
|
91
|
+
if (conn) conn.expiresAt = Math.min(conn.expiresAt, now + this.options.graceMs);
|
|
92
|
+
return this.evaluate(userId, now, true);
|
|
93
|
+
}
|
|
94
|
+
async settle(userId, now = Date.now()) {
|
|
95
|
+
return this.evaluate(userId, now, true);
|
|
96
|
+
}
|
|
97
|
+
async get(userIds, now = Date.now()) {
|
|
98
|
+
const out = /* @__PURE__ */ new Map();
|
|
99
|
+
for (const id of userIds) {
|
|
100
|
+
const state = this.state(id, now);
|
|
101
|
+
out.set(id, { state, lastSeenAt: state === "offline" ? this.lastSeen.get(id) ?? null : now });
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
onChange(listener) {
|
|
106
|
+
this.listeners.add(listener);
|
|
107
|
+
return () => void this.listeners.delete(listener);
|
|
108
|
+
}
|
|
109
|
+
/** Another instance spoke (ignored when it is this one). */
|
|
110
|
+
receive(replica, now = Date.now()) {
|
|
111
|
+
if (replica.i === this.config.instanceId) return;
|
|
112
|
+
const expiresAt = now + this.snapshotTtlMs;
|
|
113
|
+
const apply = (userId, state) => {
|
|
114
|
+
let views = this.remote.get(userId);
|
|
115
|
+
if (state === "offline") {
|
|
116
|
+
views?.delete(replica.i);
|
|
117
|
+
if (views && views.size === 0) this.remote.delete(userId);
|
|
118
|
+
} else {
|
|
119
|
+
if (!views) this.remote.set(userId, views = /* @__PURE__ */ new Map());
|
|
120
|
+
views.set(replica.i, { state, expiresAt });
|
|
121
|
+
}
|
|
122
|
+
const change = this.evaluate(userId, now, false, replica.i);
|
|
123
|
+
if (change) for (const listener of this.listeners) listener(change);
|
|
124
|
+
};
|
|
125
|
+
if (replica.t === "d") apply(replica.u, replica.s);
|
|
126
|
+
else for (const [userId, state] of replica.users) apply(userId, state);
|
|
127
|
+
}
|
|
128
|
+
/** This instance's connected people, in pages small enough for the bus (sent at a regular pace). */
|
|
129
|
+
snapshot(now = Date.now()) {
|
|
130
|
+
const users = [];
|
|
131
|
+
for (const userId of [...this.local.keys()]) {
|
|
132
|
+
const state = this.localState(userId, now);
|
|
133
|
+
if (state !== "offline") users.push([userId, state]);
|
|
134
|
+
}
|
|
135
|
+
const pages = [];
|
|
136
|
+
for (let i = 0; i < users.length; i += this.snapshotPage) {
|
|
137
|
+
pages.push({ t: "s", i: this.config.instanceId, at: now, users: users.slice(i, i + this.snapshotPage) });
|
|
138
|
+
}
|
|
139
|
+
return pages;
|
|
140
|
+
}
|
|
141
|
+
/** How many connections this instance holds (metrics, tests). */
|
|
142
|
+
get connections() {
|
|
143
|
+
let n = 0;
|
|
144
|
+
for (const conns of this.local.values()) n += conns.size;
|
|
145
|
+
return n;
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
// src/memory.ts
|
|
150
|
+
import { randomUUID } from "crypto";
|
|
151
|
+
import { EventEmitter } from "events";
|
|
152
|
+
function localEmitter() {
|
|
153
|
+
const emitter = new EventEmitter();
|
|
154
|
+
emitter.setMaxListeners(0);
|
|
155
|
+
return emitter;
|
|
156
|
+
}
|
|
157
|
+
function emitSafely(emitter, channel, event) {
|
|
158
|
+
for (const listener of emitter.listeners(channel)) {
|
|
159
|
+
try {
|
|
160
|
+
listener(event);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
console.warn(`[realtime] a subscriber of ${channel} failed`, error.message);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function memoryBus(options = {}) {
|
|
167
|
+
const emitter = localEmitter();
|
|
168
|
+
const presence = new ReplicatedPresence({ instanceId: randomUUID(), ...options });
|
|
169
|
+
return {
|
|
170
|
+
kind: "memory",
|
|
171
|
+
connected: true,
|
|
172
|
+
presence,
|
|
173
|
+
async publish(channel, event) {
|
|
174
|
+
emitSafely(emitter, channel, event);
|
|
175
|
+
},
|
|
176
|
+
subscribe(channel, handler) {
|
|
177
|
+
emitter.on(channel, handler);
|
|
178
|
+
return () => void emitter.off(channel, handler);
|
|
179
|
+
},
|
|
180
|
+
async close() {
|
|
181
|
+
emitter.removeAllListeners();
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export {
|
|
187
|
+
DEFAULT_PRESENCE,
|
|
188
|
+
rank,
|
|
189
|
+
ReplicatedPresence,
|
|
190
|
+
localEmitter,
|
|
191
|
+
emitSafely,
|
|
192
|
+
memoryBus
|
|
193
|
+
};
|
|
194
|
+
//# sourceMappingURL=chunk-HJCRR3FF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/presence.ts","../src/memory.ts"],"sourcesContent":["/**\n * The realtime contract. Application code knows these interfaces only; which adapter carries them (memory, PostgreSQL\n * LISTEN/NOTIFY, Redis / Valkey) is a deployment choice (`createBus`).\n */\n\nexport type Unsubscribe = () => void;\n\n/** What a connection says about its person: in front of the screen, or connected but idle / hidden. */\nexport type ConnectionState = \"online\" | \"away\";\n/** A person's presence: the best state among their connections, `offline` when none is left. */\nexport type PresenceState = ConnectionState | \"offline\";\n\nexport interface PresenceInfo {\n state: PresenceState;\n /** Epoch ms the person was last connected (null: never seen by this store — the caller may know better). */\n lastSeenAt: number | null;\n}\n\n/** A person's presence changed (the store announces each change once, whichever instance noticed it). */\nexport interface PresenceChange {\n userId: string;\n state: PresenceState;\n at: number;\n}\n\nexport interface PresenceOptions {\n /** How long a connection counts without a new beat (ms). Beats come at a third of it. */\n ttlMs: number;\n /** How long a closed connection still counts (ms): a reconnection inside it changes nothing (no offline flicker). */\n graceMs: number;\n}\n\n/**\n * Who is connected, kept by heartbeat and time-to-live — never a database write per beat. Every method answers the\n * change it caused, if any, so the caller publishes it once.\n */\nexport interface PresenceStore {\n /** A connection is (still) there, in this state: opens it or refreshes its TTL. */\n beat(userId: string, connectionId: string, state: ConnectionState, now?: number): Promise<PresenceChange | null>;\n /** A connection closed: it lingers `graceMs`, then the person may be offline — `settle` tells. */\n leave(userId: string, connectionId: string, now?: number): Promise<PresenceChange | null>;\n /** Re-evaluates a person after expiries (the caller runs it once the grace has passed). */\n settle(userId: string, now?: number): Promise<PresenceChange | null>;\n /** The presence of these people (absent from the store: offline, last seen unknown). */\n get(userIds: string[], now?: number): Promise<Map<string, PresenceInfo>>;\n /**\n * Changes this instance discovers on its own rather than as the answer to a call (another instance's report that\n * makes a person offline). Announce them like the others. Returns the unsubscribe function.\n */\n onChange(listener: (change: PresenceChange) => void): Unsubscribe;\n}\n\nexport type BusKind = \"memory\" | \"postgres\" | \"redis\";\n\n/**\n * The bus: events by channel to every subscriber of every instance, and presence. Best-effort by design — a publish\n * never throws; durable facts (messages) live in the database and are replayed from it, never from the bus.\n */\nexport interface RealtimeBus {\n readonly kind: BusKind;\n /** True while events published by other instances reach this one (always true for `memory`). */\n readonly connected: boolean;\n readonly presence: PresenceStore;\n publish(channel: string, event: unknown): Promise<void>;\n subscribe(channel: string, handler: (event: unknown) => void): Unsubscribe;\n close(): Promise<void>;\n}\n\nexport const DEFAULT_PRESENCE: PresenceOptions = { ttlMs: 45_000, graceMs: 10_000 };\n\n/** The rank of a state: a person is as present as their most present connection. */\nexport const rank = (state: PresenceState) => (state === \"online\" ? 2 : state === \"away\" ? 1 : 0);\n","import { type ConnectionState, DEFAULT_PRESENCE, type PresenceChange, type PresenceInfo, type PresenceOptions, type PresenceState, type PresenceStore,rank } from \"./types\";\n\n/**\n * Presence in this process's memory, optionally replicated between instances through the bus that carries it\n * (PostgreSQL LISTEN/NOTIFY). Each instance keeps its own connections (heartbeat + TTL) and tells the others its\n * *local* view of a person when it changes, plus a snapshot of everyone connected to it at a regular pace; a person's\n * presence is the best of the local view and the views of the other instances still heard from.\n *\n * Changes are announced once: by the instance where the event happened (a remote report only updates what this\n * instance believes was announced). An instance that dies stops refreshing its snapshot: its people fade out after\n * `snapshotTtlMs` (no event — clients refresh presence on a slow poll as a fallback).\n */\n\n/** What an instance tells the others: one person's local state (`d` = delta), or a page of its connected people. */\nexport type PresenceReplica =\n | { t: \"d\"; i: string; u: string; s: PresenceState; at: number }\n | { t: \"s\"; i: string; at: number; users: [string, ConnectionState][] };\n\ninterface Conn {\n state: ConnectionState;\n expiresAt: number;\n}\n\nexport interface ReplicatedPresenceOptions extends Partial<PresenceOptions> {\n /** This instance's id (random per process). */\n instanceId: string;\n /** Sends a replica to the other instances (absent: a single instance). */\n broadcast?: (replica: PresenceReplica) => void;\n /** How long another instance's snapshot counts (ms) — about 2.5 snapshot intervals. */\n snapshotTtlMs?: number;\n /** The most people a snapshot page carries (a PostgreSQL NOTIFY payload stays under 8 KB). */\n snapshotPage?: number;\n}\n\nconst MAX_LAST_SEEN = 100_000;\n\nexport class ReplicatedPresence implements PresenceStore {\n readonly options: PresenceOptions;\n private readonly local = new Map<string, Map<string, Conn>>();\n private readonly remote = new Map<string, Map<string, { state: ConnectionState; expiresAt: number }>>();\n private readonly announced = new Map<string, PresenceState>();\n /** The local view last told to the other instances. */\n private readonly told = new Map<string, PresenceState>();\n private readonly lastSeen = new Map<string, number>();\n private readonly listeners = new Set<(change: PresenceChange) => void>();\n private readonly snapshotTtlMs: number;\n private readonly snapshotPage: number;\n\n constructor(private readonly config: ReplicatedPresenceOptions) {\n this.options = { ...DEFAULT_PRESENCE, ...config };\n this.snapshotTtlMs = config.snapshotTtlMs ?? 75_000;\n this.snapshotPage = config.snapshotPage ?? 150;\n }\n\n /** This instance's view of one person: the best of its live connections (expired ones are dropped). */\n private localState(userId: string, now: number): PresenceState {\n const conns = this.local.get(userId);\n if (!conns) return \"offline\";\n let best: PresenceState = \"offline\";\n for (const [id, conn] of conns) {\n if (conn.expiresAt <= now) conns.delete(id);\n else if (rank(conn.state) > rank(best)) best = conn.state;\n }\n if (conns.size === 0) this.local.delete(userId);\n return best;\n }\n\n private remoteState(userId: string, now: number): PresenceState {\n const views = this.remote.get(userId);\n if (!views) return \"offline\";\n let best: PresenceState = \"offline\";\n for (const [instance, view] of views) {\n if (view.expiresAt <= now) views.delete(instance);\n else if (rank(view.state) > rank(best)) best = view.state;\n }\n if (views.size === 0) this.remote.delete(userId);\n return best;\n }\n\n private state(userId: string, now: number): PresenceState {\n const a = this.localState(userId, now);\n const b = this.remoteState(userId, now);\n return rank(a) >= rank(b) ? a : b;\n }\n\n /**\n * Compares with what was announced; records and returns the change. A change caused by another instance's report is\n * returned only when it is an offline the reporter may not have seen (both instances lost the person at once): the\n * instance with the greater id announces it — at most a duplicate, never a person left online forever.\n */\n private evaluate(userId: string, now: number, own: boolean, reporter?: string): PresenceChange | null {\n const local = this.localState(userId, now);\n if ((this.told.get(userId) ?? \"offline\") !== local) {\n if (local === \"offline\") this.told.delete(userId);\n else this.told.set(userId, local);\n this.config.broadcast?.({ t: \"d\", i: this.config.instanceId, u: userId, s: local, at: now });\n }\n const next = this.state(userId, now);\n const previous = this.announced.get(userId) ?? \"offline\";\n if (next === \"offline\") {\n this.announced.delete(userId);\n if (previous !== \"offline\") this.see(userId, now);\n } else {\n this.announced.set(userId, next);\n this.see(userId, now);\n }\n if (next === previous) return null;\n if (own) return { userId, state: next, at: now };\n if (next === \"offline\" && reporter !== undefined && this.config.instanceId > reporter) return { userId, state: next, at: now };\n return null;\n }\n\n private see(userId: string, at: number) {\n if (this.lastSeen.size >= MAX_LAST_SEEN && !this.lastSeen.has(userId)) this.lastSeen.clear();\n this.lastSeen.set(userId, at);\n }\n\n async beat(userId: string, connectionId: string, state: ConnectionState, now = Date.now()) {\n let conns = this.local.get(userId);\n if (!conns) this.local.set(userId, (conns = new Map()));\n conns.set(connectionId, { state, expiresAt: now + this.options.ttlMs });\n return this.evaluate(userId, now, true);\n }\n\n async leave(userId: string, connectionId: string, now = Date.now()) {\n const conn = this.local.get(userId)?.get(connectionId);\n // The connection lingers for the grace period: a reconnection inside it changes nothing.\n if (conn) conn.expiresAt = Math.min(conn.expiresAt, now + this.options.graceMs);\n return this.evaluate(userId, now, true);\n }\n\n async settle(userId: string, now = Date.now()) {\n return this.evaluate(userId, now, true);\n }\n\n async get(userIds: string[], now = Date.now()) {\n const out = new Map<string, PresenceInfo>();\n for (const id of userIds) {\n const state = this.state(id, now);\n out.set(id, { state, lastSeenAt: state === \"offline\" ? (this.lastSeen.get(id) ?? null) : now });\n }\n return out;\n }\n\n onChange(listener: (change: PresenceChange) => void) {\n this.listeners.add(listener);\n return () => void this.listeners.delete(listener);\n }\n\n /** Another instance spoke (ignored when it is this one). */\n receive(replica: PresenceReplica, now = Date.now()) {\n if (replica.i === this.config.instanceId) return;\n const expiresAt = now + this.snapshotTtlMs;\n const apply = (userId: string, state: PresenceState) => {\n let views = this.remote.get(userId);\n if (state === \"offline\") {\n views?.delete(replica.i);\n if (views && views.size === 0) this.remote.delete(userId);\n } else {\n if (!views) this.remote.set(userId, (views = new Map()));\n views.set(replica.i, { state, expiresAt });\n }\n const change = this.evaluate(userId, now, false, replica.i);\n if (change) for (const listener of this.listeners) listener(change);\n };\n if (replica.t === \"d\") apply(replica.u, replica.s);\n else for (const [userId, state] of replica.users) apply(userId, state);\n }\n\n /** This instance's connected people, in pages small enough for the bus (sent at a regular pace). */\n snapshot(now = Date.now()): PresenceReplica[] {\n const users: [string, ConnectionState][] = [];\n for (const userId of [...this.local.keys()]) {\n const state = this.localState(userId, now);\n if (state !== \"offline\") users.push([userId, state]);\n }\n const pages: PresenceReplica[] = [];\n for (let i = 0; i < users.length; i += this.snapshotPage) {\n pages.push({ t: \"s\", i: this.config.instanceId, at: now, users: users.slice(i, i + this.snapshotPage) });\n }\n return pages;\n }\n\n /** How many connections this instance holds (metrics, tests). */\n get connections(): number {\n let n = 0;\n for (const conns of this.local.values()) n += conns.size;\n return n;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { EventEmitter } from \"node:events\";\n\nimport { ReplicatedPresence } from \"./presence\";\nimport type { PresenceOptions, RealtimeBus } from \"./types\";\n\n/**\n * One process, no network: events go from publisher to subscribers through an EventEmitter. For tests and a single\n * instance without a database; it is also the local fan-out every other adapter uses inside an instance.\n */\nexport function localEmitter(): EventEmitter {\n const emitter = new EventEmitter();\n emitter.setMaxListeners(0);\n return emitter;\n}\n\n/** Hands an event to a channel's local subscribers; a failing subscriber never stops the others. */\nexport function emitSafely(emitter: EventEmitter, channel: string, event: unknown) {\n for (const listener of emitter.listeners(channel)) {\n try {\n (listener as (e: unknown) => void)(event);\n } catch (error) {\n console.warn(`[realtime] a subscriber of ${channel} failed`, (error as Error).message);\n }\n }\n}\n\nexport function memoryBus(options: Partial<PresenceOptions> = {}): RealtimeBus {\n const emitter = localEmitter();\n const presence = new ReplicatedPresence({ instanceId: randomUUID(), ...options });\n return {\n kind: \"memory\",\n connected: true,\n presence,\n async publish(channel, event) {\n emitSafely(emitter, channel, event);\n },\n subscribe(channel, handler) {\n emitter.on(channel, handler);\n return () => void emitter.off(channel, handler);\n },\n async close() {\n emitter.removeAllListeners();\n },\n };\n}\n"],"mappings":";AAoEO,IAAM,mBAAoC,EAAE,OAAO,MAAQ,SAAS,IAAO;AAG3E,IAAM,OAAO,CAAC,UAA0B,UAAU,WAAW,IAAI,UAAU,SAAS,IAAI;;;ACrC/F,IAAM,gBAAgB;AAEf,IAAM,qBAAN,MAAkD;AAAA,EAYvD,YAA6B,QAAmC;AAAnC;AAC3B,SAAK,UAAU,EAAE,GAAG,kBAAkB,GAAG,OAAO;AAChD,SAAK,gBAAgB,OAAO,iBAAiB;AAC7C,SAAK,eAAe,OAAO,gBAAgB;AAAA,EAC7C;AAAA,EAJ6B;AAAA,EAXpB;AAAA,EACQ,QAAQ,oBAAI,IAA+B;AAAA,EAC3C,SAAS,oBAAI,IAAwE;AAAA,EACrF,YAAY,oBAAI,IAA2B;AAAA;AAAA,EAE3C,OAAO,oBAAI,IA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