@beesolve/realtime-client 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/DOCS.md +22 -0
- package/README.md +82 -2
- package/dist/index.d.ts +72 -0
- package/dist/index.js +345 -0
- package/dist/paho.d.ts +33 -0
- package/dist/paho.js +6 -0
- package/dist/shared/@beesolve/realtime-client-cb8r06f6.js +73 -0
- package/dist/transport.d.ts +31 -0
- package/dist/transport.js +0 -0
- package/docs/how-to/delivery-semantics.md +34 -0
- package/docs/how-to/getting-started.md +67 -0
- package/docs/how-to/limits.md +12 -0
- package/package.json +47 -4
package/DOCS.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @beesolve/realtime-client - Documentation
|
|
2
|
+
|
|
3
|
+
**Keywords:** realtime, browser, MQTT, WebSocket, IoT Core, createRealtimeClient, RealtimeClient, RealtimeClientProps, RealtimeStatus, RealtimeSubscribeOptions, RealtimeTransport, RealtimeTransportFactory, pahoTransport, paho-mqtt, subscribe, onStatus, reconnect, disconnect, canConnect, keepAliveSeconds, qos, retry, backoff, onInvalid, blocked, connected, reconnecting, best effort, refetch
|
|
4
|
+
|
|
5
|
+
> This documentation is published inside the installed package and matches the installed version. Prefer it over prior knowledge or older examples found online.
|
|
6
|
+
|
|
7
|
+
> Full source and examples: https://github.com/BeeSolve/packages/tree/main/packages/realtime-client
|
|
8
|
+
|
|
9
|
+
## How-To Guides
|
|
10
|
+
|
|
11
|
+
| Guide | Description |
|
|
12
|
+
| --------------------------------------------------------- | --------------------------------------------------------- |
|
|
13
|
+
| [Getting Started](./docs/how-to/getting-started.md) | Create a client, subscribe, handle status |
|
|
14
|
+
| [Delivery Semantics](./docs/how-to/delivery-semantics.md) | Best effort delivery, refetch on connect, reconnects |
|
|
15
|
+
| [Limits](./docs/how-to/limits.md) | Channel, payload and policy limits that affect the client |
|
|
16
|
+
|
|
17
|
+
## Further Reading
|
|
18
|
+
|
|
19
|
+
- [README](./README.md) - API reference
|
|
20
|
+
- [CHANGELOG](./CHANGELOG.md) - Version history
|
|
21
|
+
- [@beesolve/realtime-server](https://github.com/BeeSolve/packages/tree/main/packages/realtime-server) - CDK, authorizer and publisher
|
|
22
|
+
- [Architecture Decision Records](https://github.com/BeeSolve/packages/tree/main/packages/realtime-client/docs) (GitHub only)
|
package/README.md
CHANGED
|
@@ -1,3 +1,83 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Realtime Client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small browser client for server-to-browser realtime updates over MQTT/WebSocket (AWS IoT Core), with a transport abstraction so the MQTT library can be replaced.
|
|
4
|
+
|
|
5
|
+
> [!WARNING]
|
|
6
|
+
> **Pre-1.0 - unstable API.** This package is `0.x` and under active
|
|
7
|
+
> development. Breaking changes can land in any `0.x` release without a major
|
|
8
|
+
> version bump. Pin an exact version and review the changelog before upgrading.
|
|
9
|
+
> Once the API stabilizes and the package reaches `1.0.0`, it follows semantic
|
|
10
|
+
> versioning and this notice is removed.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
bun add @beesolve/realtime-client @beesolve/realtime-core
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
(or `npm install @beesolve/realtime-client @beesolve/realtime-core`)
|
|
19
|
+
|
|
20
|
+
The server side is `@beesolve/realtime-server`. The client connects to `wss://<your host>/mqtt`, a CloudFront behavior that forwards the session cookie to the IoT authorizer.
|
|
21
|
+
|
|
22
|
+
## Quick Start
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { createRealtimeClient } from "@beesolve/realtime-client";
|
|
26
|
+
|
|
27
|
+
import { orderPaid } from "./channels"; // defined with defineChannel from @beesolve/realtime-core
|
|
28
|
+
|
|
29
|
+
const realtime = createRealtimeClient({ scope: "myapp-dev" });
|
|
30
|
+
|
|
31
|
+
realtime.onStatus((status) => {
|
|
32
|
+
if (status === "connected") void refetchOrders();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const unsubscribe = realtime.subscribe(orderPaid, (payload) => {
|
|
36
|
+
console.log(payload.orderId);
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The client connects lazily on the first `subscribe`, shares one MQTT subscription per channel, validates each payload against the channel schema and reconnects with backoff.
|
|
41
|
+
|
|
42
|
+
## API
|
|
43
|
+
|
|
44
|
+
### `createRealtimeClient(props)`
|
|
45
|
+
|
|
46
|
+
| Prop | Default | Description |
|
|
47
|
+
| --------------------- | --------------------------------------------- | ----------------------------------------------------------------------------- |
|
|
48
|
+
| `scope` | required | Topic scope shared with the server. Messages of other scopes are ignored. |
|
|
49
|
+
| `url` | `wss://${location.host}/mqtt` | WebSocket URL. |
|
|
50
|
+
| `transport` | `pahoTransport()` | A `RealtimeTransportFactory`. See the transport export below. |
|
|
51
|
+
| `canConnect` | none | Checked before every attempt. Returning `false` sets the status to `blocked`. |
|
|
52
|
+
| `retry` | `{ initialDelayMs: 1000, maxDelayMs: 30000 }` | Exponential backoff bounds with full jitter. |
|
|
53
|
+
| `inactivityTimeoutMs` | `30000` | Delay between the last unsubscribe and the disconnect. |
|
|
54
|
+
| `keepAliveSeconds` | `60` | MQTT keepalive. Values under 30 throw, because shorter pings are billed. |
|
|
55
|
+
| `qos` | `0` | Subscription QoS. `1` asks for broker acknowledgements and may cost more. |
|
|
56
|
+
|
|
57
|
+
### `RealtimeClient`
|
|
58
|
+
|
|
59
|
+
| Method | Description |
|
|
60
|
+
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
61
|
+
| `subscribe(channel, handler, options?)` | Registers a handler and returns a function that removes it. `options.onInvalid` receives `RealtimePayloadError` for bad JSON or schema failures. |
|
|
62
|
+
| `onStatus(listener)` | Listens to status changes and returns an unsubscribe function. |
|
|
63
|
+
| `reconnect()` | Drops the connection and connects again right away. |
|
|
64
|
+
| `disconnect()` | Closes the connection. A later `subscribe` or `reconnect` connects again. |
|
|
65
|
+
|
|
66
|
+
`RealtimeStatus` is `"idle" | "connecting" | "connected" | "reconnecting" | "blocked"`. The status becomes `connected` after every reconnect, so use it to refetch state.
|
|
67
|
+
|
|
68
|
+
### Subpath exports
|
|
69
|
+
|
|
70
|
+
| Import | Exports |
|
|
71
|
+
| ------------------------------------- | ---------------------------------------------------------- |
|
|
72
|
+
| `@beesolve/realtime-client` | `createRealtimeClient` and the types above |
|
|
73
|
+
| `@beesolve/realtime-client/transport` | `RealtimeTransport`, `RealtimeTransportFactory` types |
|
|
74
|
+
| `@beesolve/realtime-client/paho` | `pahoTransport()`, loads `paho-mqtt` with a dynamic import |
|
|
75
|
+
|
|
76
|
+
## Cost
|
|
77
|
+
|
|
78
|
+
See the [Cost section of `@beesolve/realtime-server`](https://github.com/BeeSolve/packages/tree/main/packages/realtime-server#cost). The client defaults (keepalive 60s, QoS 0) are chosen to keep it low.
|
|
79
|
+
|
|
80
|
+
## Further Reading
|
|
81
|
+
|
|
82
|
+
- [DOCS.md](./DOCS.md) - Agent-oriented index
|
|
83
|
+
- [Architecture Decision Records](https://github.com/BeeSolve/packages/tree/main/packages/realtime-client/docs) (GitHub only)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { RealtimePayloadError } from "@beesolve/realtime-core";
|
|
2
|
+
import { Channel } from "@beesolve/realtime-core";
|
|
3
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
|
+
/** The MQTT operations the realtime client needs. Implement it to replace paho-mqtt. */
|
|
5
|
+
interface RealtimeTransport {
|
|
6
|
+
/**
|
|
7
|
+
* Opens the connection and resolves after the broker acknowledged it.
|
|
8
|
+
* `keepAliveSeconds` is at least 30, because pings under 30 seconds are billed.
|
|
9
|
+
*/
|
|
10
|
+
connect(props: {
|
|
11
|
+
url: string;
|
|
12
|
+
clientId: string;
|
|
13
|
+
keepAliveSeconds: number;
|
|
14
|
+
}): Promise<void>;
|
|
15
|
+
subscribe(props: {
|
|
16
|
+
filter: string;
|
|
17
|
+
qos: 0 | 1;
|
|
18
|
+
}): Promise<void>;
|
|
19
|
+
unsubscribe(filter: string): Promise<void>;
|
|
20
|
+
/** Closes the connection. Must not report it through `onConnectionLost`. */
|
|
21
|
+
disconnect(): void;
|
|
22
|
+
onMessage(listener: (message: {
|
|
23
|
+
topic: string;
|
|
24
|
+
payload: string;
|
|
25
|
+
}) => void): void;
|
|
26
|
+
/** Called when an established connection drops. */
|
|
27
|
+
onConnectionLost(listener: (error: {
|
|
28
|
+
code: number;
|
|
29
|
+
message: string;
|
|
30
|
+
}) => void): void;
|
|
31
|
+
}
|
|
32
|
+
/** Creates a transport. May load the underlying MQTT library lazily. */
|
|
33
|
+
type RealtimeTransportFactory = () => Promise<RealtimeTransport>;
|
|
34
|
+
type RealtimeStatus = "idle" | "connecting" | "connected" | "reconnecting" | "blocked";
|
|
35
|
+
interface RealtimeClientProps {
|
|
36
|
+
/** Topic scope shared with the server. Messages of other scopes are ignored. */
|
|
37
|
+
readonly scope: string;
|
|
38
|
+
/** Defaults to `wss://${location.host}/mqtt`. */
|
|
39
|
+
readonly url?: string;
|
|
40
|
+
/** Defaults to a lazily loaded paho-mqtt transport. */
|
|
41
|
+
readonly transport?: RealtimeTransportFactory;
|
|
42
|
+
/** Checked before every connection attempt. Returning false sets the status to `blocked`. */
|
|
43
|
+
readonly canConnect?: () => boolean | Promise<boolean>;
|
|
44
|
+
/** Backoff bounds with full jitter. Defaults to 1000 and 30000. */
|
|
45
|
+
readonly retry?: {
|
|
46
|
+
readonly initialDelayMs?: number;
|
|
47
|
+
readonly maxDelayMs?: number;
|
|
48
|
+
};
|
|
49
|
+
/** Delay between the last unsubscribe and the disconnect. Defaults to 30000. */
|
|
50
|
+
readonly inactivityTimeoutMs?: number;
|
|
51
|
+
/** MQTT keepalive, at least 30 because shorter pings are billed. Defaults to 60. */
|
|
52
|
+
readonly keepAliveSeconds?: number;
|
|
53
|
+
/** Subscription QoS. Defaults to 0, which is cheaper. Use 1 to get broker acknowledgements. */
|
|
54
|
+
readonly qos?: 0 | 1;
|
|
55
|
+
}
|
|
56
|
+
interface RealtimeSubscribeOptions {
|
|
57
|
+
/** Called when a payload is not valid JSON or does not satisfy the channel schema. */
|
|
58
|
+
readonly onInvalid?: (error: RealtimePayloadError) => void;
|
|
59
|
+
}
|
|
60
|
+
interface RealtimeClient {
|
|
61
|
+
/** Registers a handler. Connects lazily. Returns a function that removes the handler. */
|
|
62
|
+
subscribe<TSchema extends StandardSchemaV1>(channel: Channel<string, TSchema>, handler: (payload: StandardSchemaV1.InferOutput<TSchema>) => void, options?: RealtimeSubscribeOptions): () => void;
|
|
63
|
+
/** Listens to status changes. Returns a function that removes the listener. */
|
|
64
|
+
onStatus(listener: (status: RealtimeStatus) => void): () => void;
|
|
65
|
+
/** Drops the current connection and connects again right away. */
|
|
66
|
+
reconnect(): void;
|
|
67
|
+
/** Closes the connection. A later `subscribe` or `reconnect` connects again. */
|
|
68
|
+
disconnect(): void;
|
|
69
|
+
}
|
|
70
|
+
/** Creates a client that shares one MQTT subscription per channel and reconnects with backoff. */
|
|
71
|
+
declare function createRealtimeClient(props: RealtimeClientProps): RealtimeClient;
|
|
72
|
+
export { RealtimeClient, RealtimeClientProps, RealtimeStatus, RealtimeSubscribeOptions, createRealtimeClient };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import {
|
|
2
|
+
pahoTransport2
|
|
3
|
+
} from "./shared/@beesolve/realtime-client-cb8r06f6.js";
|
|
4
|
+
|
|
5
|
+
// packages/realtime-client/src/client.ts
|
|
6
|
+
import {
|
|
7
|
+
RealtimePayloadError,
|
|
8
|
+
isTopicSafeId,
|
|
9
|
+
parsePayload,
|
|
10
|
+
parseTopic,
|
|
11
|
+
toSubscriptionFilter
|
|
12
|
+
} from "@beesolve/realtime-core";
|
|
13
|
+
function createRealtimeClient(props) {
|
|
14
|
+
const {
|
|
15
|
+
scope,
|
|
16
|
+
canConnect,
|
|
17
|
+
keepAliveSeconds = defaultKeepAliveSeconds,
|
|
18
|
+
qos = 0,
|
|
19
|
+
inactivityTimeoutMs = defaultInactivityTimeoutMs
|
|
20
|
+
} = props;
|
|
21
|
+
const initialDelayMs = props.retry?.initialDelayMs ?? defaultInitialDelayMs;
|
|
22
|
+
const maxDelayMs = props.retry?.maxDelayMs ?? defaultMaxDelayMs;
|
|
23
|
+
const createTransport = props.transport ?? pahoTransport2();
|
|
24
|
+
if (!isTopicSafeId(scope)) {
|
|
25
|
+
throw new Error(`Invalid scope "${scope}": expected [A-Za-z0-9_-]{1,128}`);
|
|
26
|
+
}
|
|
27
|
+
if (keepAliveSeconds < minKeepAliveSeconds) {
|
|
28
|
+
throw new Error(`keepAliveSeconds must be at least ${minKeepAliveSeconds} (shorter pings are billed), got ${keepAliveSeconds}`);
|
|
29
|
+
}
|
|
30
|
+
const channels = {};
|
|
31
|
+
const statusListeners = new Set;
|
|
32
|
+
const subscribedFilters = new Set;
|
|
33
|
+
let status = "idle";
|
|
34
|
+
let transport;
|
|
35
|
+
let activeTransport;
|
|
36
|
+
let attempt = 0;
|
|
37
|
+
let attemptId = 0;
|
|
38
|
+
let closed = false;
|
|
39
|
+
let syncTimer;
|
|
40
|
+
let syncRunning = false;
|
|
41
|
+
let syncAgain = false;
|
|
42
|
+
let inactivityTimer;
|
|
43
|
+
let retryTimer;
|
|
44
|
+
let stableTimer;
|
|
45
|
+
return { subscribe, onStatus, reconnect, disconnect };
|
|
46
|
+
function subscribe(channel, handler, options) {
|
|
47
|
+
toSubscriptionFilter({ scope, channel: channel.name });
|
|
48
|
+
const entry = async (incoming) => {
|
|
49
|
+
if ("error" in incoming) {
|
|
50
|
+
reportInvalid({ error: incoming.error, onInvalid: options?.onInvalid });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const payload = await parsePayload({ schema: channel.schema, value: incoming.value });
|
|
55
|
+
handler(payload);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (error instanceof RealtimePayloadError) {
|
|
58
|
+
reportInvalid({ error, onInvalid: options?.onInvalid });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
console.error("[realtime] handler failed", error);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
const handlers = channels[channel.name] ??= new Set;
|
|
65
|
+
handlers.add(entry);
|
|
66
|
+
closed = false;
|
|
67
|
+
clearTimeout(inactivityTimer);
|
|
68
|
+
inactivityTimer = undefined;
|
|
69
|
+
scheduleSync();
|
|
70
|
+
let removed = false;
|
|
71
|
+
return () => {
|
|
72
|
+
if (removed)
|
|
73
|
+
return;
|
|
74
|
+
removed = true;
|
|
75
|
+
handlers.delete(entry);
|
|
76
|
+
if (handlers.size === 0 && channels[channel.name] === handlers)
|
|
77
|
+
delete channels[channel.name];
|
|
78
|
+
if (Object.keys(channels).length === 0)
|
|
79
|
+
startInactivityTimer();
|
|
80
|
+
scheduleSync();
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function onStatus(listener) {
|
|
84
|
+
statusListeners.add(listener);
|
|
85
|
+
return () => {
|
|
86
|
+
statusListeners.delete(listener);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function reconnect() {
|
|
90
|
+
closed = false;
|
|
91
|
+
teardown();
|
|
92
|
+
attempt = 0;
|
|
93
|
+
if (hasSubscriptions())
|
|
94
|
+
connectAttempt();
|
|
95
|
+
}
|
|
96
|
+
function disconnect() {
|
|
97
|
+
closed = true;
|
|
98
|
+
teardown();
|
|
99
|
+
setStatus("idle");
|
|
100
|
+
}
|
|
101
|
+
function setStatus(next) {
|
|
102
|
+
if (status === next)
|
|
103
|
+
return;
|
|
104
|
+
status = next;
|
|
105
|
+
debug("status", next);
|
|
106
|
+
for (const listener of statusListeners) {
|
|
107
|
+
try {
|
|
108
|
+
listener(next);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
console.error("[realtime] status listener failed", error);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function hasSubscriptions() {
|
|
115
|
+
return Object.keys(channels).length > 0;
|
|
116
|
+
}
|
|
117
|
+
function teardown() {
|
|
118
|
+
attemptId++;
|
|
119
|
+
clearTimeout(retryTimer);
|
|
120
|
+
clearTimeout(stableTimer);
|
|
121
|
+
clearTimeout(syncTimer);
|
|
122
|
+
clearTimeout(inactivityTimer);
|
|
123
|
+
retryTimer = stableTimer = syncTimer = inactivityTimer = undefined;
|
|
124
|
+
const previous = transport;
|
|
125
|
+
transport = activeTransport = undefined;
|
|
126
|
+
subscribedFilters.clear();
|
|
127
|
+
if (previous != null) {
|
|
128
|
+
try {
|
|
129
|
+
previous.disconnect();
|
|
130
|
+
} catch (error) {
|
|
131
|
+
debug("disconnect failed", error);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function startInactivityTimer() {
|
|
136
|
+
clearTimeout(inactivityTimer);
|
|
137
|
+
inactivityTimer = setTimeout(() => {
|
|
138
|
+
inactivityTimer = undefined;
|
|
139
|
+
debug("disconnecting after inactivity");
|
|
140
|
+
teardown();
|
|
141
|
+
setStatus("idle");
|
|
142
|
+
}, inactivityTimeoutMs);
|
|
143
|
+
}
|
|
144
|
+
function scheduleSync() {
|
|
145
|
+
clearTimeout(syncTimer);
|
|
146
|
+
syncTimer = setTimeout(() => {
|
|
147
|
+
syncTimer = undefined;
|
|
148
|
+
sync();
|
|
149
|
+
}, syncDebounceMs);
|
|
150
|
+
}
|
|
151
|
+
async function sync() {
|
|
152
|
+
if (syncRunning) {
|
|
153
|
+
syncAgain = true;
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (closed)
|
|
157
|
+
return;
|
|
158
|
+
if (!hasSubscriptions() && transport == null)
|
|
159
|
+
return;
|
|
160
|
+
if (transport == null) {
|
|
161
|
+
if (status === "idle") {
|
|
162
|
+
attempt = 0;
|
|
163
|
+
connectAttempt();
|
|
164
|
+
}
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (activeTransport == null)
|
|
168
|
+
return;
|
|
169
|
+
syncRunning = true;
|
|
170
|
+
try {
|
|
171
|
+
do {
|
|
172
|
+
syncAgain = false;
|
|
173
|
+
await applySubscriptions(activeTransport);
|
|
174
|
+
} while (syncAgain && activeTransport != null);
|
|
175
|
+
} finally {
|
|
176
|
+
syncRunning = false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async function applySubscriptions(target) {
|
|
180
|
+
const wanted = new Set(Object.keys(channels).map((name) => toSubscriptionFilter({ scope, channel: name })));
|
|
181
|
+
for (const filter of subscribedFilters) {
|
|
182
|
+
if (wanted.has(filter))
|
|
183
|
+
continue;
|
|
184
|
+
subscribedFilters.delete(filter);
|
|
185
|
+
try {
|
|
186
|
+
await target.unsubscribe(filter);
|
|
187
|
+
debug("unsubscribed", filter);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
console.error("[realtime] unsubscribe failed", filter, error);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
for (const filter of wanted) {
|
|
193
|
+
if (subscribedFilters.has(filter))
|
|
194
|
+
continue;
|
|
195
|
+
await target.subscribe({ filter, qos });
|
|
196
|
+
subscribedFilters.add(filter);
|
|
197
|
+
debug("subscribed", filter);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async function connectAttempt() {
|
|
201
|
+
const id = ++attemptId;
|
|
202
|
+
clearTimeout(retryTimer);
|
|
203
|
+
retryTimer = undefined;
|
|
204
|
+
setStatus(attempt === 0 ? "connecting" : "reconnecting");
|
|
205
|
+
if (canConnect != null) {
|
|
206
|
+
let allowed;
|
|
207
|
+
try {
|
|
208
|
+
allowed = await canConnect();
|
|
209
|
+
} catch (error) {
|
|
210
|
+
console.error("[realtime] canConnect failed", error);
|
|
211
|
+
allowed = false;
|
|
212
|
+
}
|
|
213
|
+
if (id !== attemptId)
|
|
214
|
+
return;
|
|
215
|
+
if (!allowed) {
|
|
216
|
+
debug("connect blocked");
|
|
217
|
+
setStatus("blocked");
|
|
218
|
+
retryTimer = setTimeout(() => void connectAttempt(), maxDelayMs);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const clientId = `rt-${crypto.randomUUID()}`;
|
|
223
|
+
let created;
|
|
224
|
+
try {
|
|
225
|
+
created = await createTransport();
|
|
226
|
+
if (id !== attemptId)
|
|
227
|
+
return;
|
|
228
|
+
transport = created;
|
|
229
|
+
created.onMessage((message) => {
|
|
230
|
+
if (id === attemptId)
|
|
231
|
+
route(message);
|
|
232
|
+
});
|
|
233
|
+
created.onConnectionLost((error) => {
|
|
234
|
+
if (id === attemptId)
|
|
235
|
+
handleConnectionLost(error);
|
|
236
|
+
});
|
|
237
|
+
await created.connect({ url: props.url ?? defaultUrl(), clientId, keepAliveSeconds });
|
|
238
|
+
if (id !== attemptId)
|
|
239
|
+
return;
|
|
240
|
+
subscribedFilters.clear();
|
|
241
|
+
await applySubscriptions(created);
|
|
242
|
+
if (id !== attemptId)
|
|
243
|
+
return;
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (id !== attemptId)
|
|
246
|
+
return;
|
|
247
|
+
debug("connect failed", error);
|
|
248
|
+
dropTransport(created);
|
|
249
|
+
scheduleRetry();
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
activeTransport = created;
|
|
253
|
+
clearTimeout(stableTimer);
|
|
254
|
+
stableTimer = setTimeout(() => {
|
|
255
|
+
attempt = 0;
|
|
256
|
+
}, stableConnectionMs);
|
|
257
|
+
setStatus("connected");
|
|
258
|
+
scheduleSync();
|
|
259
|
+
}
|
|
260
|
+
function handleConnectionLost(error) {
|
|
261
|
+
debug("connection lost", error);
|
|
262
|
+
attemptId++;
|
|
263
|
+
clearTimeout(stableTimer);
|
|
264
|
+
stableTimer = undefined;
|
|
265
|
+
const lost = transport;
|
|
266
|
+
transport = activeTransport = undefined;
|
|
267
|
+
subscribedFilters.clear();
|
|
268
|
+
dropTransport(lost);
|
|
269
|
+
if (!hasSubscriptions()) {
|
|
270
|
+
setStatus("idle");
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
scheduleRetry();
|
|
274
|
+
}
|
|
275
|
+
function dropTransport(target) {
|
|
276
|
+
if (target == null)
|
|
277
|
+
return;
|
|
278
|
+
if (transport === target)
|
|
279
|
+
transport = activeTransport = undefined;
|
|
280
|
+
try {
|
|
281
|
+
target.disconnect();
|
|
282
|
+
} catch (error) {
|
|
283
|
+
debug("disconnect failed", error);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function scheduleRetry() {
|
|
287
|
+
setStatus("reconnecting");
|
|
288
|
+
const ceiling = Math.min(maxDelayMs, initialDelayMs * 2 ** attempt);
|
|
289
|
+
const delay = Math.random() * ceiling;
|
|
290
|
+
attempt++;
|
|
291
|
+
debug("retrying in", Math.round(delay), "ms");
|
|
292
|
+
clearTimeout(retryTimer);
|
|
293
|
+
retryTimer = setTimeout(() => void connectAttempt(), delay);
|
|
294
|
+
}
|
|
295
|
+
async function route(message) {
|
|
296
|
+
try {
|
|
297
|
+
const parsed = parseTopic({ scope, topic: message.topic });
|
|
298
|
+
if (parsed == null)
|
|
299
|
+
return;
|
|
300
|
+
const handlers = channels[parsed.channel];
|
|
301
|
+
if (handlers == null)
|
|
302
|
+
return;
|
|
303
|
+
const incoming = parseJson(message.payload);
|
|
304
|
+
for (const handler of handlers) {
|
|
305
|
+
await handler(incoming);
|
|
306
|
+
}
|
|
307
|
+
} catch (error) {
|
|
308
|
+
console.error("[realtime] failed to route message", error);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
var defaultKeepAliveSeconds = 60;
|
|
313
|
+
var minKeepAliveSeconds = 30;
|
|
314
|
+
var defaultInactivityTimeoutMs = 30000;
|
|
315
|
+
var defaultInitialDelayMs = 1000;
|
|
316
|
+
var defaultMaxDelayMs = 30000;
|
|
317
|
+
var stableConnectionMs = 60000;
|
|
318
|
+
var syncDebounceMs = 50;
|
|
319
|
+
function parseJson(payload) {
|
|
320
|
+
try {
|
|
321
|
+
return { value: JSON.parse(payload) };
|
|
322
|
+
} catch {
|
|
323
|
+
return { error: new RealtimePayloadError([{ message: "Payload is not valid JSON" }]) };
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function defaultUrl() {
|
|
327
|
+
return `wss://${globalThis.location.host}/mqtt`;
|
|
328
|
+
}
|
|
329
|
+
function reportInvalid(props) {
|
|
330
|
+
if (props.onInvalid == null) {
|
|
331
|
+
console.error("[realtime] invalid payload", props.error);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
props.onInvalid(props.error);
|
|
336
|
+
} catch (error) {
|
|
337
|
+
console.error("[realtime] onInvalid failed", error);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
function debug(...args) {
|
|
341
|
+
console.debug("[realtime]", ...args);
|
|
342
|
+
}
|
|
343
|
+
export {
|
|
344
|
+
createRealtimeClient
|
|
345
|
+
};
|
package/dist/paho.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** The MQTT operations the realtime client needs. Implement it to replace paho-mqtt. */
|
|
2
|
+
interface RealtimeTransport {
|
|
3
|
+
/**
|
|
4
|
+
* Opens the connection and resolves after the broker acknowledged it.
|
|
5
|
+
* `keepAliveSeconds` is at least 30, because pings under 30 seconds are billed.
|
|
6
|
+
*/
|
|
7
|
+
connect(props: {
|
|
8
|
+
url: string;
|
|
9
|
+
clientId: string;
|
|
10
|
+
keepAliveSeconds: number;
|
|
11
|
+
}): Promise<void>;
|
|
12
|
+
subscribe(props: {
|
|
13
|
+
filter: string;
|
|
14
|
+
qos: 0 | 1;
|
|
15
|
+
}): Promise<void>;
|
|
16
|
+
unsubscribe(filter: string): Promise<void>;
|
|
17
|
+
/** Closes the connection. Must not report it through `onConnectionLost`. */
|
|
18
|
+
disconnect(): void;
|
|
19
|
+
onMessage(listener: (message: {
|
|
20
|
+
topic: string;
|
|
21
|
+
payload: string;
|
|
22
|
+
}) => void): void;
|
|
23
|
+
/** Called when an established connection drops. */
|
|
24
|
+
onConnectionLost(listener: (error: {
|
|
25
|
+
code: number;
|
|
26
|
+
message: string;
|
|
27
|
+
}) => void): void;
|
|
28
|
+
}
|
|
29
|
+
/** Creates a transport. May load the underlying MQTT library lazily. */
|
|
30
|
+
type RealtimeTransportFactory = () => Promise<RealtimeTransport>;
|
|
31
|
+
/** Transport backed by paho-mqtt. The library is loaded with a dynamic `import()` on first use. */
|
|
32
|
+
declare function pahoTransport(): RealtimeTransportFactory;
|
|
33
|
+
export { pahoTransport };
|
package/dist/paho.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// packages/realtime-client/paho.ts
|
|
2
|
+
var connectTimeoutSeconds = 15;
|
|
3
|
+
function pahoTransport2() {
|
|
4
|
+
return async () => {
|
|
5
|
+
const { default: Paho } = await import("paho-mqtt");
|
|
6
|
+
return createPahoTransport(Paho);
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
function createPahoTransport(Paho) {
|
|
10
|
+
let client;
|
|
11
|
+
let messageListener = () => {};
|
|
12
|
+
let connectionLostListener = () => {};
|
|
13
|
+
return {
|
|
14
|
+
connect: (props) => new Promise((resolve, reject) => {
|
|
15
|
+
const created = new Paho.Client(props.url, props.clientId);
|
|
16
|
+
client = created;
|
|
17
|
+
created.onMessageArrived = (message) => {
|
|
18
|
+
messageListener({ topic: message.destinationName, payload: message.payloadString });
|
|
19
|
+
};
|
|
20
|
+
created.onConnectionLost = (error) => {
|
|
21
|
+
if (error.errorCode === 0)
|
|
22
|
+
return;
|
|
23
|
+
connectionLostListener({ code: error.errorCode, message: error.errorMessage });
|
|
24
|
+
};
|
|
25
|
+
created.connect({
|
|
26
|
+
mqttVersion: 4,
|
|
27
|
+
useSSL: true,
|
|
28
|
+
cleanSession: true,
|
|
29
|
+
timeout: connectTimeoutSeconds,
|
|
30
|
+
keepAliveInterval: props.keepAliveSeconds,
|
|
31
|
+
onSuccess: () => resolve(),
|
|
32
|
+
onFailure: (error) => {
|
|
33
|
+
reject(new Error(`MQTT connect failed (${error.errorCode}): ${error.errorMessage}`));
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}),
|
|
37
|
+
subscribe: (props) => new Promise((resolve, reject) => {
|
|
38
|
+
requireClient(client).subscribe(props.filter, {
|
|
39
|
+
qos: props.qos,
|
|
40
|
+
onSuccess: () => resolve(),
|
|
41
|
+
onFailure: (error) => {
|
|
42
|
+
reject(new Error(`MQTT subscribe to ${props.filter} failed (${error.errorCode}): ${error.errorMessage}`));
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}),
|
|
46
|
+
unsubscribe: (filter) => new Promise((resolve, reject) => {
|
|
47
|
+
requireClient(client).unsubscribe(filter, {
|
|
48
|
+
onSuccess: () => resolve(),
|
|
49
|
+
onFailure: (error) => {
|
|
50
|
+
reject(new Error(`MQTT unsubscribe from ${filter} failed (${error.errorCode}): ${error.errorMessage}`));
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
}),
|
|
54
|
+
disconnect: () => {
|
|
55
|
+
if (client?.isConnected() === true)
|
|
56
|
+
client.disconnect();
|
|
57
|
+
client = undefined;
|
|
58
|
+
},
|
|
59
|
+
onMessage: (listener) => {
|
|
60
|
+
messageListener = listener;
|
|
61
|
+
},
|
|
62
|
+
onConnectionLost: (listener) => {
|
|
63
|
+
connectionLostListener = listener;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function requireClient(client) {
|
|
68
|
+
if (client == null)
|
|
69
|
+
throw new Error("MQTT transport is not connected");
|
|
70
|
+
return client;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export { pahoTransport2 };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** The MQTT operations the realtime client needs. Implement it to replace paho-mqtt. */
|
|
2
|
+
interface RealtimeTransport {
|
|
3
|
+
/**
|
|
4
|
+
* Opens the connection and resolves after the broker acknowledged it.
|
|
5
|
+
* `keepAliveSeconds` is at least 30, because pings under 30 seconds are billed.
|
|
6
|
+
*/
|
|
7
|
+
connect(props: {
|
|
8
|
+
url: string;
|
|
9
|
+
clientId: string;
|
|
10
|
+
keepAliveSeconds: number;
|
|
11
|
+
}): Promise<void>;
|
|
12
|
+
subscribe(props: {
|
|
13
|
+
filter: string;
|
|
14
|
+
qos: 0 | 1;
|
|
15
|
+
}): Promise<void>;
|
|
16
|
+
unsubscribe(filter: string): Promise<void>;
|
|
17
|
+
/** Closes the connection. Must not report it through `onConnectionLost`. */
|
|
18
|
+
disconnect(): void;
|
|
19
|
+
onMessage(listener: (message: {
|
|
20
|
+
topic: string;
|
|
21
|
+
payload: string;
|
|
22
|
+
}) => void): void;
|
|
23
|
+
/** Called when an established connection drops. */
|
|
24
|
+
onConnectionLost(listener: (error: {
|
|
25
|
+
code: number;
|
|
26
|
+
message: string;
|
|
27
|
+
}) => void): void;
|
|
28
|
+
}
|
|
29
|
+
/** Creates a transport. May load the underlying MQTT library lazily. */
|
|
30
|
+
type RealtimeTransportFactory = () => Promise<RealtimeTransport>;
|
|
31
|
+
export { RealtimeTransport, RealtimeTransportFactory };
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# How to: Handle Best-Effort Delivery
|
|
2
|
+
|
|
3
|
+
Delivery is best effort. The client uses `cleanSession: true` and there is no offline queue. Treat a message as a notification and fetch authoritative state from your API.
|
|
4
|
+
|
|
5
|
+
## Rules
|
|
6
|
+
|
|
7
|
+
- A message sent while a client is disconnected is lost.
|
|
8
|
+
- The client reports `connected` after the first connection and after every reconnect. Refetch on it.
|
|
9
|
+
- Subscriptions use QoS 0 by default. Set `qos: 1` in `createRealtimeClient` for broker acknowledgements. It can raise outbound messaging cost.
|
|
10
|
+
- The backend publishes with QoS 1, so `publish()` resolves after the broker accepted the message. It does not mean a browser received it.
|
|
11
|
+
|
|
12
|
+
## Pattern: notify, then refetch or apply
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
realtime.onStatus((status) => {
|
|
16
|
+
if (status === "connected") void refetchOrders();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
realtime.subscribe(orderPaid, ({ orderId }) => {
|
|
20
|
+
void refetchOrder(orderId);
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Reconnects you should expect
|
|
25
|
+
|
|
26
|
+
- **Revocation latency.** IoT re-runs the authorizer lazily, on the first message after `refreshAfter` (default 1h) using the original handshake headers. A user who signed out can keep receiving messages until then. Lower `refreshAfter` on `Realtime` (minimum 5m) when that matters. Each refresh costs one authorizer run per active connection.
|
|
27
|
+
- **Session rotation.** With `@beesolve/auth-service` the session id rotates about every hour and the old id expires after about 30s. The next IoT refresh then presents a dead session id, IoT closes the socket and the client reconnects with the new cookie and resubscribes. Expect one reconnect per hour and refetch on `connected`.
|
|
28
|
+
- **Maximum connection duration.** IoT closes the connection at the earlier of the session expiry and `maxConnectionDuration` (default 24h).
|
|
29
|
+
- **Backoff.** `retry` bounds the delay (default 1s to 30s, full jitter). The attempt counter resets after a connection stayed up for 60s.
|
|
30
|
+
|
|
31
|
+
## See Also
|
|
32
|
+
|
|
33
|
+
- [Getting Started](./getting-started.md)
|
|
34
|
+
- [Limits](./limits.md)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# How to: Subscribe to Realtime Updates in the Browser
|
|
2
|
+
|
|
3
|
+
## Prerequisites
|
|
4
|
+
|
|
5
|
+
- A deployed `Realtime` construct from `@beesolve/realtime-server` with its WebSocket behavior on your CloudFront distribution (see its getting-started guide)
|
|
6
|
+
- The channel definitions shared with the server
|
|
7
|
+
|
|
8
|
+
## Steps
|
|
9
|
+
|
|
10
|
+
### 1. Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
bun add @beesolve/realtime-client @beesolve/realtime-core
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
### 2. Create one client per page
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createRealtimeClient } from "@beesolve/realtime-client";
|
|
20
|
+
|
|
21
|
+
export const realtime = createRealtimeClient({
|
|
22
|
+
scope: "myapp-dev",
|
|
23
|
+
canConnect: () => document.cookie.includes("aSID=1"),
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`scope` must equal the scope passed to `Realtime` on the server. `canConnect` is optional. With auth-service the readable `aSID=1` cookie signals a signed-in user, so signed-out visitors do not open sockets that the authorizer would reject. While it returns `false` the status is `blocked` and the client retries after the maximum backoff delay.
|
|
28
|
+
|
|
29
|
+
### 3. Subscribe
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { orderPaid } from "./channels";
|
|
33
|
+
|
|
34
|
+
const unsubscribe = realtime.subscribe(
|
|
35
|
+
orderPaid,
|
|
36
|
+
(payload) => {
|
|
37
|
+
console.log("paid", payload.orderId);
|
|
38
|
+
},
|
|
39
|
+
{ onInvalid: (error) => console.warn(error.issues) },
|
|
40
|
+
);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Call `unsubscribe()` when the component goes away. When the last handler is removed the client disconnects after `inactivityTimeoutMs` (30s).
|
|
44
|
+
|
|
45
|
+
### 4. React to status
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
const stop = realtime.onStatus((status) => {
|
|
49
|
+
if (status === "connected") void refetchOrders();
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### 5. Replace the transport (optional)
|
|
54
|
+
|
|
55
|
+
Pass `transport` a `RealtimeTransportFactory` from `@beesolve/realtime-client/transport` to use another MQTT library. The default `pahoTransport()` loads `paho-mqtt` on first use.
|
|
56
|
+
|
|
57
|
+
## Common Pitfalls
|
|
58
|
+
|
|
59
|
+
- A failed handshake looks like a network drop (paho error code 8), so the client cannot tell a revoked session from a lost connection. It retries with exponential backoff and jitter.
|
|
60
|
+
- `keepAliveSeconds` below 30 throws.
|
|
61
|
+
- Handlers that throw are logged with `console.error` and do not affect other handlers.
|
|
62
|
+
- The default URL needs `location.host`. Pass `url` outside the browser.
|
|
63
|
+
|
|
64
|
+
## See Also
|
|
65
|
+
|
|
66
|
+
- [Delivery Semantics](./delivery-semantics.md)
|
|
67
|
+
- [Limits](./limits.md)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# How to: Stay Within the Limits
|
|
2
|
+
|
|
3
|
+
| Limit | Value | Where it applies |
|
|
4
|
+
| ---------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
|
|
5
|
+
| Subscriptions per connection | 50 (AWS IoT quota) | One MQTT subscription per distinct channel, so at most 50 channels per tab. The client does not enforce this. |
|
|
6
|
+
| Payload size | 128 KB | Enforced by `publish()`. Messages are metered in 5 KB increments. |
|
|
7
|
+
| Topic length | under 256 bytes | Enforced by `toTopic` and `toSubscriptionFilter`. |
|
|
8
|
+
| Topic levels | 8 (scope, group and up to 6 channel levels) | IoT allows 8 levels. `defineChannel` allows 1-6 channel levels. |
|
|
9
|
+
| Keepalive | at least 30s | Enforced by the client. Pings of 30s or more are not billed. |
|
|
10
|
+
| Connection lifetime | 5m to 24h | Set by `Realtime` (`maxConnectionDuration`). |
|
|
11
|
+
|
|
12
|
+
See the server [limits guide](https://github.com/BeeSolve/packages/blob/main/packages/realtime-server/docs/how-to/limits.md) for policy and account limits.
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@beesolve/realtime-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/BeeSolve/packages.git"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"docs/how-to",
|
|
12
|
+
"DOCS.md"
|
|
13
|
+
],
|
|
14
|
+
"type": "module",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"import": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"./transport": {
|
|
24
|
+
"import": {
|
|
25
|
+
"types": "./dist/transport.d.ts",
|
|
26
|
+
"default": "./dist/transport.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"./paho": {
|
|
30
|
+
"import": {
|
|
31
|
+
"types": "./dist/paho.d.ts",
|
|
32
|
+
"default": "./dist/paho.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"type-check": "tsc --noEmit"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@beesolve/realtime-core": "^0.1.0",
|
|
42
|
+
"@standard-schema/spec": "^1.1.0",
|
|
43
|
+
"paho-mqtt": "1.1.0"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/paho-mqtt": "^1.0.10",
|
|
47
|
+
"valibot": "^1.5.0"
|
|
48
|
+
}
|
|
49
|
+
}
|