nowity 1.8.0 → 1.10.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.
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+ "use client";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.DEFAULT_ALLOWED_KEYS = exports.MASKED = exports.byteSize = exports.mutationPhases = exports.maskArgs = exports.NowityDevtools = void 0;
5
+ exports.formatMs = formatMs;
6
+ exports.formatBytes = formatBytes;
7
+ exports.formatServerTime = formatServerTime;
8
+ exports.axisTs = axisTs;
9
+ exports.visibleRecords = visibleRecords;
10
+ exports.NowityDevtoolsPanel = NowityDevtoolsPanel;
11
+ const jsx_runtime_1 = require("react/jsx-runtime");
12
+ /**
13
+ * `nowity/devtools` — a Network tab for the socket.
14
+ *
15
+ * A separate entry on purpose: the panel is for developers, so an application
16
+ * loads it with a dynamic `import("nowity/devtools")` behind its own access check
17
+ * and the code never reaches anyone else's bundle. Neither `nowity` nor
18
+ * `nowity/client` imports this module.
19
+ *
20
+ * The panel only reads a recorder ({@link NowityDevtools}) the client was asked
21
+ * to keep — `client.enableDevtools()` or the `devtools` option. Everything it
22
+ * shows is in the browser's memory already, masked; it sends nothing anywhere.
23
+ */
24
+ const react_1 = require("react");
25
+ const devtools_1 = require("./client/devtools");
26
+ var devtools_2 = require("./client/devtools");
27
+ Object.defineProperty(exports, "NowityDevtools", { enumerable: true, get: function () { return devtools_2.NowityDevtools; } });
28
+ Object.defineProperty(exports, "maskArgs", { enumerable: true, get: function () { return devtools_2.maskArgs; } });
29
+ Object.defineProperty(exports, "mutationPhases", { enumerable: true, get: function () { return devtools_2.mutationPhases; } });
30
+ Object.defineProperty(exports, "byteSize", { enumerable: true, get: function () { return devtools_2.byteSize; } });
31
+ Object.defineProperty(exports, "MASKED", { enumerable: true, get: function () { return devtools_2.MASKED; } });
32
+ Object.defineProperty(exports, "DEFAULT_ALLOWED_KEYS", { enumerable: true, get: function () { return devtools_2.DEFAULT_ALLOWED_KEYS; } });
33
+ const COLORS = {
34
+ subscribe: "#4f9cf9",
35
+ mutation: "#f5a524",
36
+ ws: "#9b8afb",
37
+ };
38
+ const STATUS_COLORS = {
39
+ pending: "#a1a1aa",
40
+ rejected: "#f87171",
41
+ error: "#f87171",
42
+ lost: "#f87171",
43
+ closed: "#71717a",
44
+ };
45
+ function formatMs(ms) {
46
+ if (ms === null || ms === undefined)
47
+ return "—";
48
+ if (ms >= 10000)
49
+ return `${(ms / 1000).toFixed(1)} s`;
50
+ if (ms >= 1000)
51
+ return `${(ms / 1000).toFixed(2)} s`;
52
+ return `${ms.toFixed(ms < 10 ? 1 : 0)} ms`;
53
+ }
54
+ function formatBytes(bytes) {
55
+ if (bytes === null || bytes === undefined)
56
+ return "—";
57
+ if (bytes >= 1024 * 1024)
58
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
59
+ if (bytes >= 1024)
60
+ return `${(bytes / 1024).toFixed(1)} kB`;
61
+ return `${bytes} B`;
62
+ }
63
+ /** Format of a server time: wall clock with milliseconds, UTC. */
64
+ function formatServerTime(serverTs) {
65
+ if (serverTs === null || serverTs === undefined || !Number.isFinite(serverTs))
66
+ return "—";
67
+ return new Date(serverTs).toISOString().slice(11, 23);
68
+ }
69
+ /**
70
+ * Where a record starts on the common axis: the server's clock, through ONE
71
+ * offset — the current estimate — for every record.
72
+ *
73
+ * Not `record.serverTs`: each record is stamped with the estimate of its own
74
+ * moment, and two estimates may differ by up to their uncertainty, which would
75
+ * swap records a few ms apart. All `ts` come from one monotonic clock, so one
76
+ * offset keeps their order exact and puts them on the server's axis at once.
77
+ * Without an estimate (`offsetMs` null) the page's own clock is the axis.
78
+ */
79
+ function axisTs(record, offsetMs) {
80
+ return record.ts + (offsetMs ?? 0);
81
+ }
82
+ /** Rows for the table: filtered, searched and sorted. Pure, for tests. */
83
+ function visibleRecords(records, filter, search, sort, desc) {
84
+ const needle = search.trim().toLowerCase();
85
+ const rows = records.filter((record) => (filter === "all" || record.type === filter) &&
86
+ (needle === "" || record.name.toLowerCase().includes(needle) || record.status.includes(needle)));
87
+ const key = (record) => {
88
+ switch (sort) {
89
+ case "name":
90
+ return record.name;
91
+ case "status":
92
+ return record.status;
93
+ case "latency":
94
+ return record.durationMs ?? Number.POSITIVE_INFINITY;
95
+ case "size":
96
+ return record.bytes ?? -1;
97
+ case "updates":
98
+ return record.meta.updateCount ?? 0;
99
+ default:
100
+ return record.ts;
101
+ }
102
+ };
103
+ rows.sort((a, b) => {
104
+ const ka = key(a);
105
+ const kb = key(b);
106
+ const order = ka < kb ? -1 : ka > kb ? 1 : a.id - b.id;
107
+ return desc ? -order : order;
108
+ });
109
+ return rows;
110
+ }
111
+ function useRecorder(recorder) {
112
+ const version = (0, react_1.useSyncExternalStore)((listener) => recorder.subscribe(listener), () => recorder.version, () => recorder.version);
113
+ return (0, react_1.useMemo)(() => ({ records: recorder.records, summary: recorder.summary() }), [recorder, version]);
114
+ }
115
+ const font = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
116
+ const styles = {
117
+ root: {
118
+ fontFamily: font,
119
+ fontSize: 12,
120
+ color: "#e4e4e7",
121
+ background: "#18181b",
122
+ border: "1px solid #3f3f46",
123
+ display: "flex",
124
+ flexDirection: "column",
125
+ minHeight: 0,
126
+ boxSizing: "border-box",
127
+ },
128
+ floating: {
129
+ position: "fixed",
130
+ left: 0,
131
+ right: 0,
132
+ bottom: 0,
133
+ zIndex: 2147483000,
134
+ boxShadow: "0 -4px 16px rgba(0,0,0,.4)",
135
+ },
136
+ bar: {
137
+ display: "flex",
138
+ flexWrap: "wrap",
139
+ alignItems: "center",
140
+ gap: 6,
141
+ padding: "4px 8px",
142
+ borderBottom: "1px solid #3f3f46",
143
+ background: "#27272a",
144
+ },
145
+ button: {
146
+ font: "inherit",
147
+ color: "inherit",
148
+ background: "#3f3f46",
149
+ border: "1px solid #52525b",
150
+ borderRadius: 4,
151
+ padding: "2px 8px",
152
+ cursor: "pointer",
153
+ },
154
+ input: {
155
+ font: "inherit",
156
+ color: "inherit",
157
+ background: "#09090b",
158
+ border: "1px solid #52525b",
159
+ borderRadius: 4,
160
+ padding: "2px 6px",
161
+ minWidth: 120,
162
+ },
163
+ th: {
164
+ position: "sticky",
165
+ top: 0,
166
+ background: "#27272a",
167
+ textAlign: "left",
168
+ fontWeight: 600,
169
+ padding: "3px 6px",
170
+ borderBottom: "1px solid #3f3f46",
171
+ cursor: "pointer",
172
+ whiteSpace: "nowrap",
173
+ userSelect: "none",
174
+ },
175
+ td: {
176
+ padding: "2px 6px",
177
+ borderBottom: "1px solid #27272a",
178
+ whiteSpace: "nowrap",
179
+ overflow: "hidden",
180
+ textOverflow: "ellipsis",
181
+ maxWidth: 320,
182
+ },
183
+ };
184
+ function SummaryItem({ label, value, testId }) {
185
+ return ((0, jsx_runtime_1.jsxs)("span", { "data-testid": testId, style: { whiteSpace: "nowrap" }, children: [(0, jsx_runtime_1.jsx)("span", { style: { color: "#a1a1aa" }, children: label }), " ", value] }));
186
+ }
187
+ /**
188
+ * The panel: page-startup summary, a table of every subscribe / mutation / socket
189
+ * event with a waterfall, filter, search, sort, details, copy as JSON and clear.
190
+ */
191
+ function NowityDevtoolsPanel({ recorder, onClose, floating, height = "40vh", title = "Nowity" }) {
192
+ const { records, summary } = useRecorder(recorder);
193
+ const [filter, setFilter] = (0, react_1.useState)("all");
194
+ const [search, setSearch] = (0, react_1.useState)("");
195
+ const [sort, setSort] = (0, react_1.useState)("start");
196
+ const [desc, setDesc] = (0, react_1.useState)(false);
197
+ const [selected, setSelected] = (0, react_1.useState)(null);
198
+ const [copied, setCopied] = (0, react_1.useState)(false);
199
+ const rows = (0, react_1.useMemo)(() => visibleRecords(records, filter, search, sort, desc), [records, filter, search, sort, desc]);
200
+ const offsetMs = summary.clock?.offsetMs ?? null;
201
+ const range = (0, react_1.useMemo)(() => {
202
+ let start = Number.POSITIVE_INFINITY;
203
+ let end = Number.NEGATIVE_INFINITY;
204
+ for (const record of rows) {
205
+ const at = axisTs(record, offsetMs);
206
+ start = Math.min(start, at);
207
+ end = Math.max(end, at + (record.durationMs ?? 0));
208
+ }
209
+ return rows.length === 0 ? { start: 0, span: 1 } : { start, span: Math.max(1, end - start) };
210
+ }, [rows, offsetMs]);
211
+ const detail = selected === null ? undefined : records.find((record) => record.id === selected);
212
+ const sortBy = (key) => {
213
+ if (sort === key)
214
+ setDesc(!desc);
215
+ else {
216
+ setSort(key);
217
+ setDesc(false);
218
+ }
219
+ };
220
+ const header = (key, label, style) => ((0, jsx_runtime_1.jsxs)("th", { style: { ...styles.th, ...style }, onClick: () => sortBy(key), "data-testid": `nowity-devtools-sort-${key}`, children: [label, sort === key ? (desc ? " ▼" : " ▲") : ""] }));
221
+ const copy = () => {
222
+ const json = recorder.export();
223
+ const clipboard = globalThis.navigator?.clipboard;
224
+ void clipboard?.writeText(json).then(() => setCopied(true), () => setCopied(false));
225
+ };
226
+ return ((0, jsx_runtime_1.jsxs)("section", { "data-testid": "nowity-devtools", "aria-label": title, style: { ...styles.root, ...(floating ? { ...styles.floating, height } : { height: "100%" }) }, children: [(0, jsx_runtime_1.jsxs)("div", { style: styles.bar, children: [(0, jsx_runtime_1.jsx)("strong", { children: title }), ["all", "subscribe", "mutation", "ws"].map((value) => ((0, jsx_runtime_1.jsx)("button", { type: "button", "data-testid": `nowity-devtools-filter-${value}`, "aria-pressed": filter === value, style: { ...styles.button, ...(filter === value ? { background: "#52525b" } : {}) }, onClick: () => setFilter(value), children: value }, value))), (0, jsx_runtime_1.jsx)("input", { type: "search", placeholder: "filter", "aria-label": "filter", "data-testid": "nowity-devtools-search", style: styles.input, value: search, onChange: (event) => setSearch(event.target.value) }), (0, jsx_runtime_1.jsx)("span", { style: { flex: 1 } }), (0, jsx_runtime_1.jsx)("button", { type: "button", style: styles.button, "data-testid": "nowity-devtools-copy", onClick: copy, children: copied ? "copied" : "copy JSON" }), (0, jsx_runtime_1.jsx)("button", { type: "button", style: styles.button, "data-testid": "nowity-devtools-clear", onClick: () => {
227
+ recorder.clear();
228
+ setSelected(null);
229
+ }, children: "clear" }), onClose && ((0, jsx_runtime_1.jsx)("button", { type: "button", style: styles.button, "data-testid": "nowity-devtools-close", "aria-label": "close", onClick: onClose, children: "\u00D7" }))] }), (0, jsx_runtime_1.jsxs)("div", { style: { ...styles.bar, background: "#1f1f23", gap: 14 }, "data-testid": "nowity-devtools-summary", children: [(0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-open", label: "ws open", value: formatMs(summary.openAt) }), (0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-welcome", label: "welcome", value: formatMs(summary.welcomeAt) }), (0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-subscribe", label: "1st subscribe", value: formatMs(summary.firstSubscribeAt) }), (0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-data", label: "1st data", value: formatMs(summary.firstDataAt) }), (0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-connections", label: "sockets", value: summary.connections }), (0, jsx_runtime_1.jsx)(SummaryItem, { label: "reconnects", testId: "nowity-devtools-summary-reconnects", value: summary.reconnects }), (0, jsx_runtime_1.jsx)(SummaryItem, { label: "live", testId: "nowity-devtools-summary-live", value: `${summary.openSubscriptions} (${summary.pendingSubscriptions} pending)` }), (0, jsx_runtime_1.jsx)(SummaryItem, { label: "mutations pending", testId: "nowity-devtools-summary-mutations", value: summary.pendingMutations }), (0, jsx_runtime_1.jsx)(SummaryItem, { label: "server clock", testId: "nowity-devtools-summary-clock", value: summary.clock && summary.clock.offsetMs !== null
230
+ ? `±${formatMs(summary.clock.uncertaintyMs)} (rtt ${formatMs(summary.clock.rttMs)}, ${summary.clock.sampleCount} samples)`
231
+ : "not synced" })] }), (0, jsx_runtime_1.jsxs)("div", { style: { display: "flex", flex: 1, minHeight: 0 }, children: [(0, jsx_runtime_1.jsxs)("div", { style: { flex: 1, overflow: "auto", minWidth: 0 }, children: [(0, jsx_runtime_1.jsxs)("table", { style: { borderCollapse: "collapse", width: "100%", tableLayout: "auto" }, children: [(0, jsx_runtime_1.jsx)("thead", { children: (0, jsx_runtime_1.jsxs)("tr", { children: [header("name", "name"), header("status", "status"), header("start", "start"), header("latency", "latency"), header("size", "size"), header("updates", "updates"), (0, jsx_runtime_1.jsx)("th", { style: { ...styles.th, width: "30%", cursor: "default" }, children: "waterfall" })] }) }), (0, jsx_runtime_1.jsx)("tbody", { children: rows.map((record) => {
232
+ const left = ((axisTs(record, offsetMs) - range.start) / range.span) * 100;
233
+ const width = Math.max(0.5, ((record.durationMs ?? 0) / range.span) * 100);
234
+ return ((0, jsx_runtime_1.jsxs)("tr", { "data-testid": "nowity-devtools-row", "data-type": record.type, "data-name": record.name, "data-status": record.status, "data-server-ts": record.serverTs ?? undefined, onClick: () => setSelected(record.id === selected ? null : record.id), style: { cursor: "pointer", background: record.id === selected ? "#27272a" : undefined }, children: [(0, jsx_runtime_1.jsxs)("td", { style: styles.td, title: record.name, children: [(0, jsx_runtime_1.jsx)("span", { style: { color: COLORS[record.type], marginRight: 4 }, children: "\u25CF" }), record.name] }), (0, jsx_runtime_1.jsxs)("td", { style: { ...styles.td, color: STATUS_COLORS[record.status] }, "data-testid": "nowity-devtools-row-status", children: [record.status, record.meta.code ? ` (${record.meta.code})` : ""] }), (0, jsx_runtime_1.jsx)("td", { style: styles.td, "data-testid": "nowity-devtools-row-start", title: offsetMs === null
235
+ ? "server clock not synced"
236
+ : `server ${formatServerTime(axisTs(record, offsetMs))} UTC ±${formatMs(summary.clock?.uncertaintyMs)}`, children: formatMs(record.ts) }), (0, jsx_runtime_1.jsx)("td", { style: styles.td, "data-testid": "nowity-devtools-row-latency", children: formatMs(record.durationMs) }), (0, jsx_runtime_1.jsx)("td", { style: styles.td, children: formatBytes(record.bytes) }), (0, jsx_runtime_1.jsx)("td", { style: styles.td, children: record.meta.updateCount ?? "" }), (0, jsx_runtime_1.jsx)("td", { style: { ...styles.td, position: "relative", maxWidth: "none" }, children: (0, jsx_runtime_1.jsx)("div", { style: {
237
+ position: "absolute",
238
+ top: 4,
239
+ bottom: 4,
240
+ left: `${left}%`,
241
+ width: `${Math.min(width, 100 - left)}%`,
242
+ minWidth: 2,
243
+ background: COLORS[record.type],
244
+ opacity: record.status === "pending" ? 0.4 : 0.85,
245
+ borderRadius: 2,
246
+ } }) })] }, record.id));
247
+ }) })] }), rows.length === 0 && ((0, jsx_runtime_1.jsx)("div", { style: { padding: 12, color: "#a1a1aa" }, "data-testid": "nowity-devtools-empty", children: "nothing recorded" }))] }), detail && ((0, jsx_runtime_1.jsxs)("div", { "data-testid": "nowity-devtools-detail", style: {
248
+ margin: 0,
249
+ width: "34%",
250
+ overflow: "auto",
251
+ padding: 8,
252
+ borderLeft: "1px solid #3f3f46",
253
+ background: "#09090b",
254
+ }, children: [(0, jsx_runtime_1.jsx)(Phases, { phases: (0, devtools_1.mutationPhases)(detail) }), (0, jsx_runtime_1.jsx)("pre", { style: { margin: 0, whiteSpace: "pre-wrap", wordBreak: "break-word" }, children: JSON.stringify(detail, null, 2) })] }))] })] }));
255
+ }
256
+ const PHASE_COLORS = {
257
+ client: "#f5a524",
258
+ server: "#4f9cf9",
259
+ database: "#9b8afb",
260
+ };
261
+ /** A mutation's steps on the server's clock, from sending it. */
262
+ function Phases({ phases }) {
263
+ if (phases.length === 0)
264
+ return null;
265
+ const end = Math.max(1, ...phases.map((phase) => phase.offsetMs));
266
+ return ((0, jsx_runtime_1.jsx)("table", { "data-testid": "nowity-devtools-phases", style: { borderCollapse: "collapse", width: "100%", marginBottom: 8 }, children: (0, jsx_runtime_1.jsx)("tbody", { children: phases.map((phase) => ((0, jsx_runtime_1.jsxs)("tr", { "data-testid": "nowity-devtools-phase", "data-phase": phase.name, "data-clock": phase.clock, children: [(0, jsx_runtime_1.jsx)("td", { style: { ...styles.td, color: PHASE_COLORS[phase.clock] }, children: phase.name }), (0, jsx_runtime_1.jsxs)("td", { style: styles.td, title: `${formatServerTime(phase.serverTs)} UTC (${phase.clock} clock)`, children: ["+", formatMs(phase.offsetMs), phase.uncertaintyMs !== null ? ` ±${formatMs(phase.uncertaintyMs)}` : ""] }), (0, jsx_runtime_1.jsx)("td", { style: { ...styles.td, position: "relative", width: "50%", maxWidth: "none" }, children: (0, jsx_runtime_1.jsx)("div", { style: {
267
+ position: "absolute",
268
+ top: 5,
269
+ bottom: 5,
270
+ left: `${Math.max(0, Math.min(100, (phase.offsetMs / end) * 100))}%`,
271
+ width: 3,
272
+ background: PHASE_COLORS[phase.clock],
273
+ } }) })] }, phase.name))) }) }));
274
+ }
@@ -51,6 +51,7 @@ interface OutboxRow {
51
51
  after: Row | null;
52
52
  client_id: string | null;
53
53
  mutation_id: string | null;
54
+ written_ms?: number | string | null;
54
55
  }
55
56
  /**
56
57
  * Change source built on an outbox table filled by triggers, woken by
@@ -1 +1 @@
1
- {"version":3,"file":"outbox-change-source.d.ts","sourceRoot":"","sources":["../../../src/server/change-source/outbox-change-source.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAc,MAAM,IAAI,CAAC;AAE3C,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAElE,MAAM,WAAW,yBAAyB;IACtC,IAAI,EAAE,IAAI,CAAC;IACX,yCAAyC;IACzC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;;;;;;OAQG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;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O,CAAC,KAAK,CAA+B;IAC5C,OAAO,CAAC,UAAU,CAA+B;IACjD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAA8B;IAC9C,sEAAsE;IACtE,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,SAAS,CAAK;gBAEV,IAAI,EAAE,yBAAyB;IAYrC,aAAa,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC;IAWrD,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IA6BzD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAsB3B;;;;;;;;;OASG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAc5B,OAAO,CAAC,IAAI;YAKE,SAAS;IA2BvB,8DAA8D;YAChD,aAAa;IAS3B;;;;;;OAMG;IACG,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;YAOhB,KAAK;CA6BtB;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,EAAE,GAAG,gBAAgB,CAS/E;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,gBAAgB,EAAE,CAyBxE"}
1
+ {"version":3,"file":"outbox-change-source.d.ts","sourceRoot":"","sources":["../../../src/server/change-source/outbox-change-source.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAc,MAAM,IAAI,CAAC;AAE3C,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAElE,MAAM,WAAW,yBAAyB;IACtC,IAAI,EAAE,IAAI,CAAC;IACX,yCAAyC;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normalize_1 = require("../../core/normalize");
8
- const SELECT_COLUMNS = `seq::text AS seq, xid::text AS xid, tbl, op, pk, before, after, client_id, mutation_id::text AS mutation_id`;
8
+ const SELECT_COLUMNS = `seq::text AS seq, xid::text AS xid, tbl, op, pk, before, after, client_id, mutation_id::text AS mutation_id, (extract(epoch FROM created_at) * 1000)::float8 AS written_ms`;
9
9
  /**
10
10
  * Change source built on an outbox table filled by triggers, woken by
11
11
  * LISTEN/NOTIFY.
@@ -253,6 +253,7 @@ function groupByTransaction(rows) {
253
253
  // always whole here — a row leaving a live query's filter is visible
254
254
  // without any per-table configuration.
255
255
  beforeComplete: true,
256
+ ...(row.written_ms !== null && row.written_ms !== undefined ? { writtenAt: Number(row.written_ms) } : {}),
256
257
  });
257
258
  }
258
259
  return batches;
@@ -118,6 +118,11 @@ export declare class EngineSession {
118
118
  readonly connectionId: `${string}-${string}-${string}-${string}-${string}`;
119
119
  /** What the client last said it is looking at (`setContext`). */
120
120
  context: PresenceContext | null;
121
+ /**
122
+ * Send this connection where its changes spent their time (`TxTiming`).
123
+ * Set by the socket front end from its `timing` option; off by default.
124
+ */
125
+ timing: boolean;
121
126
  constructor(info: SessionInfo, send: (msg: ServerMessage) => void);
122
127
  }
123
128
  /**
@@ -136,6 +141,10 @@ export interface MutationOutcome {
136
141
  lastMutationId: number;
137
142
  /** What the mutator returned. Absent for a replayed mutation. */
138
143
  value?: unknown;
144
+ /** Server clock (epoch ms) when its turn came — the mutations before it were done. */
145
+ startedAt?: number;
146
+ /** Server clock when its transaction committed. Absent when it was rolled back. */
147
+ committedAt?: number;
139
148
  }
140
149
  /**
141
150
  * The sync engine: turns change events into per-subscription patches.
@@ -1 +1 @@
1
- {"version":3,"file":"sync-engine.d.ts","sourceRoot":"","sources":["../../src/server/sync-engine.ts"],"names":[],"mappings":"AAIA,OAAO,EAEH,KAAK,aAAa,EAElB,KAAK,aAAa,EAIrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAGH,KAAK,WAAW,E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qI7B;;;;;;;OAOG;YACW,SAAS;YAMT,SAAS;YAgBT,kBAAkB;YAQlB,mBAAmB;CAiBpC"}
@@ -35,6 +35,11 @@ class EngineSession {
35
35
  this.connectionId = (0, node_crypto_1.randomUUID)();
36
36
  /** What the client last said it is looking at (`setContext`). */
37
37
  this.context = null;
38
+ /**
39
+ * Send this connection where its changes spent their time (`TxTiming`).
40
+ * Set by the socket front end from its `timing` option; off by default.
41
+ */
42
+ this.timing = false;
38
43
  }
39
44
  }
40
45
  exports.EngineSession = EngineSession;
@@ -106,7 +111,11 @@ class SyncEngine {
106
111
  return;
107
112
  this.started = true;
108
113
  const from = await this.opts.snapshots.withSnapshot((snap) => this.opts.source.startPosition(snap));
109
- await this.opts.source.start(from, (batch) => this.run(() => this.timedBatch(batch)));
114
+ await this.opts.source.start(from, (batch) => {
115
+ // Taken before the queue: waiting behind other work is part of the push.
116
+ const readAt = Date.now();
117
+ return this.run(() => this.timedBatch(batch, readAt));
118
+ });
110
119
  }
111
120
  async stop() {
112
121
  if (!this.started)
@@ -331,16 +340,17 @@ class SyncEngine {
331
340
  }
332
341
  // ------------------------------------------------------------------ change fan-out
333
342
  /** `handleBatch`, with the one number worth watching taken around it. */
334
- async timedBatch(batch) {
343
+ async timedBatch(batch, readAt = Date.now()) {
335
344
  const started = process.hrtime.bigint();
336
345
  try {
337
- await this.handleBatch(batch);
346
+ await this.handleBatch(batch, readAt);
338
347
  }
339
348
  finally {
340
349
  this.stats.fanOutMs += Number(process.hrtime.bigint() - started) / 1e6;
341
350
  }
342
351
  }
343
- async handleBatch(batch) {
352
+ async handleBatch(batch, readAt) {
353
+ const fanOutAt = Date.now();
344
354
  const invalidatedScopes = new Set();
345
355
  let revalidateEverything = false;
346
356
  for (const event of batch.events) {
@@ -480,6 +490,7 @@ class SyncEngine {
480
490
  t: "tx",
481
491
  position: batch.position,
482
492
  lastMutationId,
493
+ ...(session.timing ? { timing: txTiming(batch, session, readAt, fanOutAt) } : {}),
483
494
  patches,
484
495
  ...(snapshots.length ? { snapshots } : {}),
485
496
  ...(revoked.length ? { revoked } : {}),
@@ -740,6 +751,7 @@ class SyncEngine {
740
751
  async executeMutation(session, mutationId, name, args) {
741
752
  const clientId = session.info.clientId;
742
753
  const committed = [];
754
+ const startedAt = Date.now();
743
755
  try {
744
756
  const def = this.opts.mutators.get(name);
745
757
  const outcome = await this.opts.writes.withWrite(async (w) => {
@@ -761,7 +773,7 @@ class SyncEngine {
761
773
  // Idempotency: a mutation resent after a reconnect must not be
762
774
  // applied twice.
763
775
  if (mutationId <= last)
764
- return { ok: true, lastMutationId: last };
776
+ return { ok: true, lastMutationId: last, replayed: true };
765
777
  if (mutationId !== last + 1) {
766
778
  // The one place a client id shared by two connections is
767
779
  // caught for certain. `openSession` reports the collision
@@ -789,6 +801,8 @@ class SyncEngine {
789
801
  WHERE client_id = $1`, [clientId, mutationId]);
790
802
  return { ok: true, lastMutationId: mutationId, value };
791
803
  });
804
+ // A replay committed nothing; a commit time would be fiction.
805
+ const committedAt = outcome.replayed ? undefined : Date.now();
792
806
  for (const fn of committed) {
793
807
  try {
794
808
  fn();
@@ -797,7 +811,8 @@ class SyncEngine {
797
811
  this.onError(err);
798
812
  }
799
813
  }
800
- return outcome;
814
+ const { replayed: _replayed, ...rest } = outcome;
815
+ return { ...rest, startedAt, ...(committedAt !== undefined ? { committedAt } : {}) };
801
816
  }
802
817
  catch (err) {
803
818
  // A refused mutation is a normal outcome of the write path, not an
@@ -811,7 +826,7 @@ class SyncEngine {
811
826
  // resend into an acknowledged no-op, which is the very write loss
812
827
  // this check exists to prevent.
813
828
  if (err instanceof ClientIdTaken) {
814
- return { ok: false, error: err.message, lastMutationId: mutationId - 1 };
829
+ return { ok: false, error: err.message, lastMutationId: mutationId - 1, startedAt };
815
830
  }
816
831
  // The write is rolled back, but the mutation id is burned in its own
817
832
  // transaction. Otherwise the client would keep a rejected mutation in
@@ -829,6 +844,7 @@ class SyncEngine {
829
844
  ok: false,
830
845
  error: err.message,
831
846
  lastMutationId: mutationId,
847
+ startedAt,
832
848
  };
833
849
  }
834
850
  }
@@ -910,3 +926,17 @@ function sameIds(a, b) {
910
926
  }
911
927
  return true;
912
928
  }
929
+ /**
930
+ * The server's side of one push, for a connection that gets timing. `sentAt`
931
+ * is stamped by the socket as the message leaves.
932
+ */
933
+ function txTiming(batch, session, readAt, fanOutAt) {
934
+ let writtenAt;
935
+ for (const event of batch.events) {
936
+ if (event.writtenAt === undefined || event.clientId !== session.info.clientId)
937
+ continue;
938
+ if (writtenAt === undefined || event.writtenAt < writtenAt)
939
+ writtenAt = event.writtenAt;
940
+ }
941
+ return { ...(writtenAt !== undefined ? { writtenAt } : {}), readAt, fanOutAt, sentAt: fanOutAt };
942
+ }
@@ -1,4 +1,5 @@
1
1
  import * as http from "http";
2
+ import type { SessionInfo } from "./query";
2
3
  import type { SyncEngine } from "./sync-engine";
3
4
  export interface AuthRequest {
4
5
  url: string | undefined;
@@ -42,6 +43,17 @@ export interface NowitySyncServerOptions {
42
43
  intervalMs?: number;
43
44
  maxMissed?: number;
44
45
  } | false;
46
+ /**
47
+ * Send a connection where its writes spent their time on the server —
48
+ * received, started, committed, read from the outbox, pushed (`timing` on
49
+ * `mutation-result` and `tx`), for a developer panel to lay next to the
50
+ * client's own times.
51
+ *
52
+ * Off unless set. A function decides per connection, once, at its hello —
53
+ * the place to say "admins only" from the database rather than from
54
+ * anything the client claims. Its failure means off.
55
+ */
56
+ timing?: boolean | ((session: SessionInfo) => boolean | Promise<boolean>);
45
57
  onError?: (err: Error) => void;
46
58
  }
47
59
  /** WebSocket front end for {@link SyncEngine}. */
@@ -63,6 +75,12 @@ export declare class NowitySyncServer {
63
75
  /** Pings sent since the socket last proved it is alive. */
64
76
  private readonly missed;
65
77
  private heartbeatTimer;
78
+ /** When this socket's last hello arrived, for the clock in the welcome. */
79
+ private readonly helloAt;
80
+ /** Sockets that get timing (see {@link NowitySyncServerOptions.timing}). */
81
+ private readonly timed;
82
+ /** Pongs sent in the current window, per socket. */
83
+ private readonly pings;
66
84
  constructor(opts: NowitySyncServerOptions);
67
85
  /** Start listening; resolves with the actual port. */
68
86
  listen(): Promise<number>;
@@ -73,6 +91,8 @@ export declare class NowitySyncServer {
73
91
  private startHeartbeat;
74
92
  private handleConnection;
75
93
  private handleMessage;
94
+ private allowPing;
95
+ private timingFor;
76
96
  private sendTo;
77
97
  }
78
98
  //# sourceMappingURL=ws-server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ws-server.d.ts","sourceRoot":"","sources":["../../src/server/ws-server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAK7B,OAAO,KAAK,EAAiB,UAAU,EAAE,MAAM,eAAe,CAAC;AAE/D,MAAM,WAAW,WAAW;IACxB,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB,OAAO,EAAE,IAAI,CAAC,mBAAmB,CAAC;CACrC;AAED,yEAAyE;AACzE,MAAM,WAAW,UAAU;IACvB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED,MAAM,WAAW,uBAAuB;IACpC,MAAM,EAAE,UAAU,CAAC;IACnB;;;OAGG;IACH,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG,UAAU,GAAG,IAAI,CAAC;IACpF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;;OAKG;IACH,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC;IACrB;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,KAAK,CAAC;IAChE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