@rebasepro/server-postgres 0.34.1 → 0.34.2
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/dist/{cli-console-E5TM3GaL.js → cli-console-oVdz6rG3.js} +2 -2
- package/dist/{cli-console-E5TM3GaL.js.map → cli-console-oVdz6rG3.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.es.js +3 -3
- package/dist/{open-rebase-DykxNl1j.js → open-rebase-BQrU-FAV.js} +282 -13
- package/dist/open-rebase-BQrU-FAV.js.map +1 -0
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +60 -3
- package/dist/services/channel-bus/index.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +11 -0
- package/dist/services/socket-stats.d.ts +77 -0
- package/dist/socket-opt-ins.d.ts +8 -1
- package/dist/{websocket-CvmbzBeS.js → websocket-C9Ev5FQs.js} +73 -9
- package/dist/websocket-C9Ev5FQs.js.map +1 -0
- package/dist/websocket.d.ts +9 -0
- package/package.json +7 -7
- package/dist/open-rebase-DykxNl1j.js.map +0 -1
- package/dist/websocket-CvmbzBeS.js.map +0 -1
|
@@ -13,8 +13,13 @@
|
|
|
13
13
|
* is the same trick the entity path uses (notify an address, refetch the
|
|
14
14
|
* row), applied to a different table, and for the same reason: any database
|
|
15
15
|
* login can `LISTEN`. On an ephemeral channel there is nothing to point at,
|
|
16
|
-
* so
|
|
17
|
-
*
|
|
16
|
+
* so a frame over the ceiling is cut into parts that leave together, in one
|
|
17
|
+
* statement, and each instance puts them back together (see
|
|
18
|
+
* {@link FrameAssembler}). It used to be refused instead: delivered on the
|
|
19
|
+
* sender's instance and nowhere else, with an error frame to a sender that
|
|
20
|
+
* had no reason to read one — a game screen's ~10 KB state reached the
|
|
21
|
+
* phones on its own pod and silently never the others. Only a frame over
|
|
22
|
+
* {@link PG_BUS_MAX_FRAME_BYTES} is refused now.
|
|
18
23
|
*
|
|
19
24
|
* - **A notify is a query on the primary database.** Not a slow one, but it
|
|
20
25
|
* competes with the application's real queries, and that — not throughput —
|
|
@@ -38,6 +43,14 @@ export declare const CHANNEL_BUS_NOTIFY_CHANNEL = "rebase_channel_bus";
|
|
|
38
43
|
* check cannot fail at the server for being a few bytes over.
|
|
39
44
|
*/
|
|
40
45
|
export declare const PG_NOTIFY_MAX_PAYLOAD_BYTES = 7500;
|
|
46
|
+
/**
|
|
47
|
+
* The largest frame the Postgres bus carries, cut into parts, in bytes of
|
|
48
|
+
* encoded JSON. A frame larger than this is refused to its sender, as every
|
|
49
|
+
* oversized frame used to be. One MiB is ~190 notifications in one statement:
|
|
50
|
+
* far past any state a realtime app should broadcast, short of making the bus
|
|
51
|
+
* a file transfer.
|
|
52
|
+
*/
|
|
53
|
+
export declare const PG_BUS_MAX_FRAME_BYTES: number;
|
|
41
54
|
/**
|
|
42
55
|
* How long a batching window stays open.
|
|
43
56
|
*
|
|
@@ -50,9 +63,16 @@ export declare class PostgresChannelBus implements ChannelBus {
|
|
|
50
63
|
private readonly db;
|
|
51
64
|
private readonly connectionString;
|
|
52
65
|
readonly kind: "postgres";
|
|
53
|
-
|
|
66
|
+
/**
|
|
67
|
+
* What the bus carries, not what one notification does: a frame over
|
|
68
|
+
* {@link PG_NOTIFY_MAX_PAYLOAD_BYTES} travels in parts.
|
|
69
|
+
*/
|
|
70
|
+
readonly maxFrameBytes: number;
|
|
54
71
|
readonly publishesOnDemand = true;
|
|
55
72
|
private listener?;
|
|
73
|
+
private readonly assembler;
|
|
74
|
+
/** Frames this instance cut into parts, so its own listener skips putting them back together. */
|
|
75
|
+
private readonly ownPartIds;
|
|
56
76
|
private readonly batchWindowMs;
|
|
57
77
|
/**
|
|
58
78
|
* Frames waiting for the current window to close.
|
|
@@ -101,6 +121,43 @@ export declare class PostgresChannelBus implements ChannelBus {
|
|
|
101
121
|
*/
|
|
102
122
|
private send;
|
|
103
123
|
}
|
|
124
|
+
/** One part of a frame too large for a single notification. */
|
|
125
|
+
export interface ChannelBusPart {
|
|
126
|
+
/** The same for every part of one frame. */
|
|
127
|
+
id: string;
|
|
128
|
+
/** This part's place, from 0. */
|
|
129
|
+
i: number;
|
|
130
|
+
/** How many parts the frame has. */
|
|
131
|
+
n: number;
|
|
132
|
+
/** A slice of the payload's UTF-8 bytes, base64: no character is ever cut in two. */
|
|
133
|
+
data: string;
|
|
134
|
+
}
|
|
135
|
+
/** Cut a bus payload into parts, each of which fits one notification. */
|
|
136
|
+
export declare function splitIntoParts(payload: string, id: string): ChannelBusPart[];
|
|
137
|
+
/** The part a notification carries, or undefined when it carries a whole frame. */
|
|
138
|
+
export declare function parsePart(payload: string): ChannelBusPart | undefined;
|
|
139
|
+
/**
|
|
140
|
+
* Puts frames that travelled in parts back together.
|
|
141
|
+
*
|
|
142
|
+
* The parts of one frame are sent in one statement, so they arrive in a row;
|
|
143
|
+
* a frame still waiting after {@link PART_ASSEMBLY_TIMEOUT_MS} lost one (the
|
|
144
|
+
* listener reconnected between them) and is dropped, as a lost notification
|
|
145
|
+
* always was.
|
|
146
|
+
*/
|
|
147
|
+
export declare class FrameAssembler {
|
|
148
|
+
private readonly now;
|
|
149
|
+
private readonly pending;
|
|
150
|
+
private pendingBytes;
|
|
151
|
+
constructor(now?: () => number);
|
|
152
|
+
/** Add a part; the whole payload once its last part is in, otherwise undefined. */
|
|
153
|
+
add(part: ChannelBusPart): string | undefined;
|
|
154
|
+
/** How many frames are waiting for parts. */
|
|
155
|
+
get size(): number;
|
|
156
|
+
clear(): void;
|
|
157
|
+
private expire;
|
|
158
|
+
private dropOldest;
|
|
159
|
+
private forget;
|
|
160
|
+
}
|
|
104
161
|
/**
|
|
105
162
|
* Parse a bus payload into the frames it carries.
|
|
106
163
|
*
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
import { type ChannelBus, type ChannelBusSetting } from "@rebasepro/types";
|
|
18
18
|
import type { PgSqlDatabase } from "../../interfaces.js";
|
|
19
19
|
export * from "./ChannelBus.js";
|
|
20
|
-
export { PostgresChannelBus, CHANNEL_BUS_NOTIFY_CHANNEL, PG_NOTIFY_MAX_PAYLOAD_BYTES, DEFAULT_BATCH_WINDOW_MS, parseChannelBusFrame, parseChannelBusPayload } from "./PostgresChannelBus.js";
|
|
20
|
+
export { PostgresChannelBus, CHANNEL_BUS_NOTIFY_CHANNEL, PG_NOTIFY_MAX_PAYLOAD_BYTES, PG_BUS_MAX_FRAME_BYTES, DEFAULT_BATCH_WINDOW_MS, FrameAssembler, splitIntoParts, parsePart, parseChannelBusFrame, parseChannelBusPayload } from "./PostgresChannelBus.js";
|
|
21
21
|
export interface ChannelBusDeps {
|
|
22
22
|
db: PgSqlDatabase<Record<string, unknown>>;
|
|
23
23
|
/**
|
|
@@ -311,6 +311,8 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
|
|
|
311
311
|
private busFramesPublished;
|
|
312
312
|
/** Frames not sent because no other instance had members. See {@link counts}. */
|
|
313
313
|
private busFramesSkipped;
|
|
314
|
+
/** Frames and bytes pushed to each socket, for the line its close logs. */
|
|
315
|
+
private readonly trafficByClient;
|
|
314
316
|
private busStartedAt;
|
|
315
317
|
private busGossipInterval?;
|
|
316
318
|
/**
|
|
@@ -959,6 +961,15 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
|
|
|
959
961
|
* socket, and {@link removeClient} drops what it held.
|
|
960
962
|
*/
|
|
961
963
|
private sendRaw;
|
|
964
|
+
/**
|
|
965
|
+
* What a socket is in and what it was pushed, for the line its close
|
|
966
|
+
* logs. Read before the socket's own close handler forgets it.
|
|
967
|
+
*/
|
|
968
|
+
describeClient(clientId: string): {
|
|
969
|
+
channels: string[];
|
|
970
|
+
framesOut: number;
|
|
971
|
+
bytesOut: number;
|
|
972
|
+
};
|
|
962
973
|
/**
|
|
963
974
|
* Extract parent paths from a nested path like "posts/70/tags"
|
|
964
975
|
* Returns ["posts", "posts/70"] for the example above
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What happens to this process's sockets: who opened and closed them and why,
|
|
3
|
+
* what they carried, and what was refused on them.
|
|
4
|
+
*
|
|
5
|
+
* A socket that closed used to leave one debug line, and that only outside
|
|
6
|
+
* production, so "the phones keep losing the room" had nothing to be read
|
|
7
|
+
* against: not whether the server let a socket go (no pong, a backlog, a
|
|
8
|
+
* session that ended, a shutdown), the client did (a close frame, its own
|
|
9
|
+
* watchdog) or the network did (a connection that just went). Every close now
|
|
10
|
+
* names its cause, here for `/metrics` and in one info line per socket.
|
|
11
|
+
*
|
|
12
|
+
* Process-wide, like the send budget in `socket-liveness.ts`: `/metrics` is
|
|
13
|
+
* per process, and every socket server in it counts in the same totals.
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
import type { RealtimeSocketTotals } from "@rebasepro/types";
|
|
18
|
+
/**
|
|
19
|
+
* Who ended a socket.
|
|
20
|
+
*
|
|
21
|
+
* - `client`: the client sent a close frame (a tab closed, a sign-out, an app
|
|
22
|
+
* that closed its client).
|
|
23
|
+
* - `client_watchdog`: the client gave up on the socket itself — its
|
|
24
|
+
* heartbeat or wake check found it silent — and said so with 4003.
|
|
25
|
+
* - `network`: the connection went without a close frame (1006): a phone that
|
|
26
|
+
* lost signal, a proxy that dropped it, a NAT that forgot it.
|
|
27
|
+
* - `no_pong`: this server let it go after it missed a ping.
|
|
28
|
+
* - `backlog`: this server let it go for not reading what it was sent.
|
|
29
|
+
* - `session`: its identity ended (signed out, revoked, expired).
|
|
30
|
+
* - `ceiling`: refused for its user's socket ceiling.
|
|
31
|
+
* - `shutdown`: this server is shutting down.
|
|
32
|
+
* - `oversized_frame`: it sent a frame larger than the server reads.
|
|
33
|
+
* - `server`: this server closed it for another reason.
|
|
34
|
+
*/
|
|
35
|
+
export type SocketCloser = "client" | "client_watchdog" | "network" | "no_pong" | "backlog" | "session" | "ceiling" | "shutdown" | "oversized_frame" | "server";
|
|
36
|
+
/** The close code the SDK closes a socket with when its own watchdog gave up on it. */
|
|
37
|
+
export declare const CLIENT_WATCHDOG_CLOSE_CODE = 4003;
|
|
38
|
+
/**
|
|
39
|
+
* Record that this server is ending `ws`, and why, before it closes or
|
|
40
|
+
* terminates it. The first cause given is the one kept.
|
|
41
|
+
*/
|
|
42
|
+
export declare function noteServerClose(ws: object, cause: SocketCloser): void;
|
|
43
|
+
/** Who ended `ws`, given the code its `close` event carried. */
|
|
44
|
+
export declare function closerOf(ws: object, code: number): SocketCloser;
|
|
45
|
+
/**
|
|
46
|
+
* A close code as a metric label: the codes the protocol defines and the ones
|
|
47
|
+
* Rebase uses as themselves, anything else as `other` — a client may close
|
|
48
|
+
* with any of two thousand application codes, and a label per one is
|
|
49
|
+
* unbounded.
|
|
50
|
+
*/
|
|
51
|
+
export declare function closeCodeLabel(code: number): string;
|
|
52
|
+
/**
|
|
53
|
+
* Refusals worth counting: each drops what a client sent, and only the client
|
|
54
|
+
* was told. `AUTH_UNAVAILABLE` is a frame refused because the auth store could
|
|
55
|
+
* not re-check the identity (past the channel grace); `UNAUTHORIZED` one from
|
|
56
|
+
* a socket that is not signed in. Both are what an app that rebuilds its link
|
|
57
|
+
* on a channel error reads as a lost connection.
|
|
58
|
+
*/
|
|
59
|
+
export type SocketRefusal = "RATE_LIMITED" | "CHANNEL_FORBIDDEN" | "CHANNEL_BUS_PAYLOAD_TOO_LARGE" | "FRAME_TOO_LARGE" | "AUTH_UNAVAILABLE" | "UNAUTHORIZED";
|
|
60
|
+
export declare class SocketStats {
|
|
61
|
+
private opened;
|
|
62
|
+
private readonly closedBy;
|
|
63
|
+
private readonly closeCodes;
|
|
64
|
+
private framesIn;
|
|
65
|
+
private bytesIn;
|
|
66
|
+
private framesOut;
|
|
67
|
+
private bytesOut;
|
|
68
|
+
private readonly refused;
|
|
69
|
+
noteOpened(): void;
|
|
70
|
+
noteClosed(closer: SocketCloser, code: number): void;
|
|
71
|
+
noteFrameIn(bytes: number): void;
|
|
72
|
+
noteFrameOut(bytes: number): void;
|
|
73
|
+
noteRefused(code: SocketRefusal): void;
|
|
74
|
+
totals(): RealtimeSocketTotals;
|
|
75
|
+
}
|
|
76
|
+
/** This process's totals. */
|
|
77
|
+
export declare const socketStats: SocketStats;
|
package/dist/socket-opt-ins.d.ts
CHANGED
|
@@ -31,13 +31,18 @@ import { WebSocket } from "ws";
|
|
|
31
31
|
* - `cancel_sql`: the server takes `CANCEL_SQL { requestId }`, which stops a
|
|
32
32
|
* console run (`EXECUTE_SQL`, `mode: "script"`) of the same socket. A client
|
|
33
33
|
* sends it only to a server whose `hello` listed it.
|
|
34
|
+
* - `ping`: the server answers `{ "type": "ping" }` with a heartbeat at once.
|
|
35
|
+
* A page that slept (a locked phone, a frozen tab) cannot tell a socket
|
|
36
|
+
* that died meanwhile from one the sleep merely kept quiet; it asks, and
|
|
37
|
+
* keeps the socket if it answers. Before this it judged the silence, and
|
|
38
|
+
* dropped healthy sockets on every wake.
|
|
34
39
|
*
|
|
35
40
|
* @module
|
|
36
41
|
*/
|
|
37
42
|
/** The query parameter a client names its opt-ins in. */
|
|
38
43
|
export declare const SOCKET_OPT_IN_PARAM = "rebase_caps";
|
|
39
44
|
/** Every behaviour this server can be asked for. */
|
|
40
|
-
export declare const SOCKET_OPT_INS: readonly ["heartbeat", "channel_seq", "cancel_sql"];
|
|
45
|
+
export declare const SOCKET_OPT_INS: readonly ["heartbeat", "channel_seq", "cancel_sql", "ping"];
|
|
41
46
|
export type SocketOptIn = typeof SOCKET_OPT_INS[number];
|
|
42
47
|
/** How often a socket that asked for heartbeats is sent one, by default. */
|
|
43
48
|
export declare const DEFAULT_HEARTBEAT_INTERVAL_MS = 30000;
|
|
@@ -55,6 +60,8 @@ export declare function requestedOptIns(url: string | undefined): Set<SocketOptI
|
|
|
55
60
|
* messages (which it is never sent live) from the ones it missed.
|
|
56
61
|
*/
|
|
57
62
|
export declare function helloFrame(optIns: ReadonlySet<SocketOptIn>, heartbeatMs: number, clientId: string): string;
|
|
63
|
+
/** A heartbeat, also the answer to a `ping`. */
|
|
64
|
+
export declare const HEARTBEAT_FRAME: string;
|
|
58
65
|
/**
|
|
59
66
|
* Send a heartbeat every `intervalMs` to each socket `sockets()` lists. One
|
|
60
67
|
* timer for the whole server, unref'd so it never holds the process open.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
|
|
4
|
-
import {
|
|
4
|
+
import { F as terminateIfBacklogged, I as closerOf, L as noteServerClose, N as budgetSendBuffers, P as reapSilentSockets, R as socketStats, dt as sqlRoleRanAs, ft as SQL_RESULT_BYTE_BUDGET, gt as assertReadRequestReadable, ht as resolveNestedPath, lt as effectiveSqlRole, mt as isNestedPath, pt as SqlResultTooLargeError } from "./open-rebase-BQrU-FAV.js";
|
|
5
5
|
import { r as BranchingUnsupportedError } from "./BranchService-BLcVK_Rd.js";
|
|
6
6
|
import { ApiError, DATABASE_UNAVAILABLE_MESSAGE, RUNTIME_DEFAULT_MAX_BODY_SIZE, assertFieldOpsValid, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertUserCreationBodyValid, assertWriteRequestValid, createUserThroughAuthTable, decideImpersonation, declaredErrorAnswer, extractUserFromToken, getAccessModel, isAuthTable, isDatabaseUnreachable, logger, resolveConflictTarget, resolveRequireAuth, safeCompare } from "@rebasepro/server";
|
|
7
7
|
import { ANONYMOUS_USER_ID, ListLimitError, hasAdminRole, isSQLAdmin, isSchemaAdmin, resolveClientListLimit, scopeGrants, scopesForRoles } from "@rebasepro/types";
|
|
@@ -42,6 +42,11 @@ import { inspect } from "util";
|
|
|
42
42
|
* - `cancel_sql`: the server takes `CANCEL_SQL { requestId }`, which stops a
|
|
43
43
|
* console run (`EXECUTE_SQL`, `mode: "script"`) of the same socket. A client
|
|
44
44
|
* sends it only to a server whose `hello` listed it.
|
|
45
|
+
* - `ping`: the server answers `{ "type": "ping" }` with a heartbeat at once.
|
|
46
|
+
* A page that slept (a locked phone, a frozen tab) cannot tell a socket
|
|
47
|
+
* that died meanwhile from one the sleep merely kept quiet; it asks, and
|
|
48
|
+
* keeps the socket if it answers. Before this it judged the silence, and
|
|
49
|
+
* dropped healthy sockets on every wake.
|
|
45
50
|
*
|
|
46
51
|
* @module
|
|
47
52
|
*/
|
|
@@ -51,7 +56,8 @@ var SOCKET_OPT_IN_PARAM = "rebase_caps";
|
|
|
51
56
|
var SOCKET_OPT_INS = [
|
|
52
57
|
"heartbeat",
|
|
53
58
|
"channel_seq",
|
|
54
|
-
"cancel_sql"
|
|
59
|
+
"cancel_sql",
|
|
60
|
+
"ping"
|
|
55
61
|
];
|
|
56
62
|
function isSocketOptIn(name) {
|
|
57
63
|
return SOCKET_OPT_INS.includes(name);
|
|
@@ -84,6 +90,7 @@ function helloFrame(optIns, heartbeatMs, clientId) {
|
|
|
84
90
|
...optIns.has("channel_seq") ? { clientId } : {}
|
|
85
91
|
});
|
|
86
92
|
}
|
|
93
|
+
/** A heartbeat, also the answer to a `ping`. */
|
|
87
94
|
var HEARTBEAT_FRAME = JSON.stringify({ type: "heartbeat" });
|
|
88
95
|
/**
|
|
89
96
|
* Send a heartbeat every `intervalMs` to each socket `sockets()` lists. One
|
|
@@ -114,6 +121,8 @@ var websocket_exports = /* @__PURE__ */ __exportAll({
|
|
|
114
121
|
isSocketRealtimeService: () => isSocketRealtimeService,
|
|
115
122
|
socketRealtimeMissing: () => socketRealtimeMissing
|
|
116
123
|
});
|
|
124
|
+
/** How many channel names a socket's close line lists; the count is always there. */
|
|
125
|
+
var LOGGED_CHANNELS = 5;
|
|
117
126
|
/**
|
|
118
127
|
* Narrow a bootstrapper's realtime provider to what the socket calls.
|
|
119
128
|
*
|
|
@@ -489,6 +498,13 @@ function refuseUpgrade(socket) {
|
|
|
489
498
|
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
490
499
|
}
|
|
491
500
|
/** A frame's size in bytes, however `ws` delivered it. */
|
|
501
|
+
/** One query parameter of a socket's upgrade URL, cut to a length a log line can carry. */
|
|
502
|
+
function socketQueryParam(url, name) {
|
|
503
|
+
if (!url) return void 0;
|
|
504
|
+
const query = url.indexOf("?");
|
|
505
|
+
if (query === -1) return void 0;
|
|
506
|
+
return new URLSearchParams(url.slice(query + 1)).get(name)?.slice(0, 80) ?? void 0;
|
|
507
|
+
}
|
|
492
508
|
function frameBytes(data) {
|
|
493
509
|
if (Array.isArray(data)) return data.reduce((total, chunk) => total + chunk.length, 0);
|
|
494
510
|
return data.byteLength;
|
|
@@ -740,6 +756,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
740
756
|
} }
|
|
741
757
|
}));
|
|
742
758
|
} catch {}
|
|
759
|
+
noteServerClose(session.ws, "session");
|
|
743
760
|
session.ws.close(SESSION_ENDED_CLOSE_CODE, message.slice(0, 120));
|
|
744
761
|
}
|
|
745
762
|
/**
|
|
@@ -906,6 +923,43 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
906
923
|
const clientId = `client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
907
924
|
const origin = connectionOrigin(request);
|
|
908
925
|
wsDebug(`WebSocket client connected: ${clientId}`);
|
|
926
|
+
const openedAt = Date.now();
|
|
927
|
+
let framesIn = 0;
|
|
928
|
+
let bytesIn = 0;
|
|
929
|
+
/** Who it signed in as last, kept after a session that ended forgets it. */
|
|
930
|
+
let lastUid;
|
|
931
|
+
socketStats.noteOpened();
|
|
932
|
+
logger.info("[WebSocket Server] Socket opened", {
|
|
933
|
+
clientId,
|
|
934
|
+
affinity: socketQueryParam(request?.url, "affinity"),
|
|
935
|
+
caps: socketQueryParam(request?.url, "rebase_caps")
|
|
936
|
+
});
|
|
937
|
+
ws.on("close", (code, reasonBuffer) => {
|
|
938
|
+
const closedBy = closerOf(ws, code);
|
|
939
|
+
socketStats.noteClosed(closedBy, code);
|
|
940
|
+
if (code === 1009) socketStats.noteRefused("FRAME_TOO_LARGE");
|
|
941
|
+
const described = realtimeService.describeClient?.(clientId);
|
|
942
|
+
const channels = described?.channels ?? [];
|
|
943
|
+
const tcp = request?.socket;
|
|
944
|
+
logger.info("[WebSocket Server] Socket closed", {
|
|
945
|
+
clientId,
|
|
946
|
+
uid: clientSessions.get(clientId)?.user?.uid ?? lastUid,
|
|
947
|
+
closedBy,
|
|
948
|
+
code,
|
|
949
|
+
reason: reasonBuffer && reasonBuffer.length > 0 ? reasonBuffer.toString("utf8").slice(0, 120) : void 0,
|
|
950
|
+
ageMs: Date.now() - openedAt,
|
|
951
|
+
channelCount: channels.length,
|
|
952
|
+
channels: channels.slice(0, LOGGED_CHANNELS),
|
|
953
|
+
framesIn,
|
|
954
|
+
framesOut: described?.framesOut,
|
|
955
|
+
bytesIn: tcp?.bytesRead ?? bytesIn,
|
|
956
|
+
bytesOut: tcp?.bytesWritten ?? described?.bytesOut
|
|
957
|
+
});
|
|
958
|
+
wsDebug(`WebSocket client disconnected: ${clientId}`);
|
|
959
|
+
const session = clientSessions.get(clientId);
|
|
960
|
+
if (session?.expiryTimer) clearTimeout(session.expiryTimer);
|
|
961
|
+
clientSessions.delete(clientId);
|
|
962
|
+
});
|
|
909
963
|
const optIns = requestedOptIns(request?.url);
|
|
910
964
|
if (optIns) {
|
|
911
965
|
ws.send(helloFrame(optIns, heartbeatIntervalMs, clientId));
|
|
@@ -928,20 +982,19 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
928
982
|
});
|
|
929
983
|
realtimeService.addClient(clientId, ws);
|
|
930
984
|
const sqlRuns = /* @__PURE__ */ new Map();
|
|
931
|
-
ws.on("close", () => {
|
|
932
|
-
wsDebug(`WebSocket client disconnected: ${clientId}`);
|
|
933
|
-
const session = clientSessions.get(clientId);
|
|
934
|
-
if (session?.expiryTimer) clearTimeout(session.expiryTimer);
|
|
935
|
-
clientSessions.delete(clientId);
|
|
936
|
-
});
|
|
937
985
|
ws.on("error", (error) => {
|
|
938
986
|
wsDebug(`WebSocket client ${clientId} error: ${error.message}`);
|
|
939
987
|
});
|
|
940
988
|
ws.on("message", inBackendScope(async (message) => {
|
|
941
989
|
if (terminateIfBacklogged(ws, clientId)) return;
|
|
990
|
+
const inBytes = frameBytes(message);
|
|
991
|
+
framesIn++;
|
|
992
|
+
bytesIn += inBytes;
|
|
993
|
+
socketStats.noteFrameIn(inBytes);
|
|
942
994
|
let requestId;
|
|
943
995
|
try {
|
|
944
996
|
if (!clientSessions.get(clientId)?.authenticated && frameBytes(message) > MAX_UNAUTHENTICATED_FRAME_BYTES) {
|
|
997
|
+
noteServerClose(ws, "oversized_frame");
|
|
945
998
|
ws.close(1009, "Authenticate before sending anything larger than a token.");
|
|
946
999
|
return;
|
|
947
1000
|
}
|
|
@@ -974,6 +1027,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
974
1027
|
}
|
|
975
1028
|
session.channelMessageCount++;
|
|
976
1029
|
if (session.channelMessageCount > WS_CHANNEL_RATE_LIMIT) {
|
|
1030
|
+
socketStats.noteRefused("RATE_LIMITED");
|
|
977
1031
|
sendError("ERROR", "RATE_LIMITED", "Too many channel messages. Please slow down.");
|
|
978
1032
|
return;
|
|
979
1033
|
}
|
|
@@ -984,12 +1038,17 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
984
1038
|
}
|
|
985
1039
|
session.messageCount++;
|
|
986
1040
|
if (session.messageCount > WS_RATE_LIMIT) {
|
|
1041
|
+
socketStats.noteRefused("RATE_LIMITED");
|
|
987
1042
|
sendError("ERROR", "RATE_LIMITED", "Too many requests. Please slow down.");
|
|
988
1043
|
return;
|
|
989
1044
|
}
|
|
990
1045
|
}
|
|
991
1046
|
}
|
|
992
1047
|
}
|
|
1048
|
+
if (type === "ping" && optIns?.has("ping")) {
|
|
1049
|
+
ws.send(HEARTBEAT_FRAME);
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
993
1052
|
if (type === "AUTHENTICATE") {
|
|
994
1053
|
const { token, impersonate } = payload || {};
|
|
995
1054
|
if (!token) {
|
|
@@ -1035,10 +1094,12 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
1035
1094
|
if (held >= maxSocketsPerUser) {
|
|
1036
1095
|
logger.warn(`[WebSocket Server] Refused a socket for ${verifiedUser.uid} (counted as ${bucket}): ${held} already open, ceiling ${maxSocketsPerUser}`);
|
|
1037
1096
|
sendError("ERROR", "TOO_MANY_SOCKETS", `This user already has ${held} realtime connections open on this server, the most it allows (REALTIME_MAX_SOCKETS_PER_USER). Close another tab or client and try again.`);
|
|
1097
|
+
noteServerClose(ws, "ceiling");
|
|
1038
1098
|
ws.close(TOO_MANY_SOCKETS_CLOSE_CODE, "Too many realtime connections for this user");
|
|
1039
1099
|
return;
|
|
1040
1100
|
}
|
|
1041
1101
|
}
|
|
1102
|
+
lastUid = verifiedUser.uid;
|
|
1042
1103
|
if (session) {
|
|
1043
1104
|
session.user = verifiedUser;
|
|
1044
1105
|
session.authenticated = true;
|
|
@@ -1076,6 +1137,8 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
1076
1137
|
session.recheckAfter = Date.now() + CHANNEL_RECHECK_MIN_MS;
|
|
1077
1138
|
wsDebug(`[WebSocket Server] Auth store unavailable (${outcome.unavailable.code}); honouring ${clientId}'s last check for a channel frame`);
|
|
1078
1139
|
} else {
|
|
1140
|
+
socketStats.noteRefused("AUTH_UNAVAILABLE");
|
|
1141
|
+
if (channelFrame) logger.warn(`[WebSocket Server] Refused a channel frame from ${clientId}: the auth store has not answered for ${Math.round((Date.now() - session.checkedAt) / 1e3)} s (${outcome.unavailable.code})`);
|
|
1079
1142
|
sendError("ERROR", outcome.unavailable.code, outcome.unavailable.message);
|
|
1080
1143
|
return;
|
|
1081
1144
|
}
|
|
@@ -1083,6 +1146,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
1083
1146
|
}
|
|
1084
1147
|
if (requireAuth) {
|
|
1085
1148
|
if (!clientSessions.get(clientId)?.authenticated) {
|
|
1149
|
+
socketStats.noteRefused("UNAUTHORIZED");
|
|
1086
1150
|
sendError("ERROR", "UNAUTHORIZED", "Authentication required");
|
|
1087
1151
|
return;
|
|
1088
1152
|
}
|
|
@@ -1709,4 +1773,4 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
1709
1773
|
//#endregion
|
|
1710
1774
|
export { createPostgresWebSocket as a, websocket_exports as c, TOO_MANY_SOCKETS_CLOSE_CODE as i, PUBLIC_TYPES as n, isSocketRealtimeService as o, SESSION_ENDED_CLOSE_CODE as r, socketRealtimeMissing as s, ADMIN_PLANE_TYPES as t };
|
|
1711
1775
|
|
|
1712
|
-
//# sourceMappingURL=websocket-
|
|
1776
|
+
//# sourceMappingURL=websocket-C9Ev5FQs.js.map
|