instant_record 0.1.0 → 0.3.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +58 -0
- data/README.md +267 -61
- data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
- data/app/controllers/instant_record/events_controller.rb +58 -6
- data/app/controllers/instant_record/files_controller.rb +116 -0
- data/app/controllers/instant_record/mutations_controller.rb +84 -5
- data/app/controllers/instant_record/native_screens_controller.rb +60 -0
- data/app/controllers/instant_record/records_controller.rb +86 -8
- data/app/controllers/instant_record/shells_controller.rb +64 -0
- data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
- data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
- data/app/jobs/instant_record/shell_build_job.rb +16 -0
- data/app/models/instant_record/change.rb +36 -3
- data/app/models/instant_record/mutation_applier.rb +633 -50
- data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
- data/compiled/README.md +272 -0
- data/compiled/pipeline/browser_migrations.rb +18 -0
- data/compiled/pipeline/build.rb +13 -0
- data/compiled/pipeline/build_native.rb +14 -0
- data/compiled/pipeline/native/host.c +78 -0
- data/compiled/pipeline/native/instant_record_native.h +57 -0
- data/compiled/pipeline/native_shim.c +149 -0
- data/compiled/pipeline/reactor_shim.c +66 -0
- data/compiled/pipeline/sqlite/rh_shim.c +5 -0
- data/compiled/pipeline/sqlite_release.rb +43 -0
- data/compiled/toolchain.env.example +22 -0
- data/compiled/web/index.html +20 -0
- data/compiled/web/package-lock.json +884 -0
- data/compiled/web/package.json +17 -0
- data/compiled/web/src/app-host-core.js +556 -0
- data/compiled/web/src/app-host.js +16 -0
- data/compiled/web/src/branch-manager.js +140 -0
- data/compiled/web/src/branch-preview.js +397 -0
- data/compiled/web/src/changes.js +191 -0
- data/compiled/web/src/faults.js +172 -0
- data/compiled/web/src/flight-recorder.js +347 -0
- data/compiled/web/src/history-fill.js +68 -0
- data/compiled/web/src/http-headers.js +100 -0
- data/compiled/web/src/leader-election.js +705 -0
- data/compiled/web/src/main.js +608 -0
- data/compiled/web/src/manifest.js +112 -0
- data/compiled/web/src/opfs-wasi-core.js +109 -0
- data/compiled/web/src/opfs-wasi-file.js +8 -0
- data/compiled/web/src/reactor-runtime.js +1692 -0
- data/compiled/web/src/redactor.js +518 -0
- data/compiled/web/src/release-updates.js +48 -0
- data/compiled/web/src/replay.js +338 -0
- data/compiled/web/src/schema-recovery.js +204 -0
- data/compiled/web/src/server-request.js +68 -0
- data/compiled/web/src/sha256.js +98 -0
- data/compiled/web/src/shell.js +52 -0
- data/compiled/web/src/snapshot-store.js +38 -0
- data/compiled/web/src/sqlite-redactor.js +111 -0
- data/compiled/web/src/storage-backend.js +159 -0
- data/compiled/web/src/stream-leader.js +675 -0
- data/compiled/web/src/sync-context.js +91 -0
- data/compiled/web/src/sync-drain.js +104 -0
- data/compiled/web/src/sync-schedule.js +9 -0
- data/compiled/web/src/wasi-minimal.js +275 -0
- data/compiled/web/src/worker.js +39 -0
- data/compiled/web/vite.config.js +27 -0
- data/config/routes.rb +25 -0
- data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
- data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
- data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
- data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
- data/exe/instant_record_mcp +6 -0
- data/frontend/LiveList.js +67 -0
- data/frontend/chord.js +79 -0
- data/frontend/file.js +65 -0
- data/frontend/files.js +738 -0
- data/frontend/focus.js +10 -0
- data/frontend/held.js +192 -0
- data/frontend/http.js +76 -0
- data/frontend/index.js +53 -0
- data/frontend/keyboard.js +56 -0
- data/frontend/live.js +298 -0
- data/frontend/notices.js +118 -0
- data/frontend/package.json +15 -0
- data/frontend/range.js +10 -0
- data/frontend/selection.js +47 -0
- data/frontend/shortcuts.js +25 -0
- data/frontend/sync-notices.js +130 -0
- data/frontend/undo.js +48 -0
- data/frontend/window.js +181 -0
- data/lib/generators/instant_record/install/install_generator.rb +18 -30
- data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
- data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
- data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
- data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
- data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
- data/lib/instant_record/branch/sqlite_store.rb +142 -0
- data/lib/instant_record/branch.rb +388 -0
- data/lib/instant_record/client/notifier.rb +8 -12
- data/lib/instant_record/client/rebaser.rb +565 -0
- data/lib/instant_record/client/transport.rb +64 -42
- data/lib/instant_record/client.rb +1600 -169
- data/lib/instant_record/compiled_site.rb +85 -0
- data/lib/instant_record/compiler/app_stage.rb +212 -0
- data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
- data/lib/instant_record/compiler/browser_migrations.rb +161 -0
- data/lib/instant_record/compiler/entry_builder.rb +832 -0
- data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
- data/lib/instant_record/compiler/gem_vendor.rb +194 -0
- data/lib/instant_record/compiler/host_adapters.rb +506 -0
- data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
- data/lib/instant_record/compiler/manifest.rb +178 -0
- data/lib/instant_record/compiler/native_build.rb +586 -0
- data/lib/instant_record/compiler/native_contracts.rb +338 -0
- data/lib/instant_record/compiler/path_scrubber.rb +31 -0
- data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
- data/lib/instant_record/compiler/route_analyzer.rb +623 -0
- data/lib/instant_record/compiler/runner.rb +42 -0
- data/lib/instant_record/compiler/schema_lock.rb +606 -0
- data/lib/instant_record/compiler/source_pages.rb +77 -0
- data/lib/instant_record/compiler/static_linter.rb +770 -0
- data/lib/instant_record/compiler/swift_codegen.rb +341 -0
- data/lib/instant_record/compiler/toolchain.rb +219 -0
- data/lib/instant_record/compiler/wasm_build.rb +704 -0
- data/lib/instant_record/compiler/wasm_tree.rb +518 -0
- data/lib/instant_record/compiler.rb +277 -0
- data/lib/instant_record/configuration.rb +104 -0
- data/lib/instant_record/engine.rb +68 -18
- data/lib/instant_record/file_store.rb +162 -0
- data/lib/instant_record/files.rb +92 -0
- data/lib/instant_record/hlc.rb +387 -0
- data/lib/instant_record/host.rb +66 -0
- data/lib/instant_record/inertia/renderer.rb +52 -0
- data/lib/instant_record/inertia.rb +222 -0
- data/lib/instant_record/mcp/cli.rb +319 -0
- data/lib/instant_record/mcp/host_process.rb +229 -0
- data/lib/instant_record/mcp/http_exchange.rb +233 -0
- data/lib/instant_record/mcp/replica.rb +556 -0
- data/lib/instant_record/mcp/runtime.rb +406 -0
- data/lib/instant_record/mcp/server.rb +429 -0
- data/lib/instant_record/mcp.rb +47 -0
- data/lib/instant_record/native/contract.rb +367 -0
- data/lib/instant_record/native/node.rb +125 -0
- data/lib/instant_record/native/screen.rb +366 -0
- data/lib/instant_record/native/xcode_project.rb +344 -0
- data/lib/instant_record/native.rb +41 -0
- data/lib/instant_record/outbox_mutation.rb +81 -9
- data/lib/instant_record/outbox_upcaster.rb +161 -0
- data/lib/instant_record/read_tracker.rb +610 -0
- data/lib/instant_record/routing.rb +33 -0
- data/lib/instant_record/runtime_scoped.rb +4 -0
- data/lib/instant_record/shell.rb +486 -0
- data/lib/instant_record/sync_actions.rb +800 -0
- data/lib/instant_record/sync_metadata.rb +17 -2
- data/lib/instant_record/sync_notice.rb +234 -0
- data/lib/instant_record/sync_partition.rb +63 -0
- data/lib/instant_record/sync_scope.rb +300 -0
- data/lib/instant_record/sync_shape.rb +102 -0
- data/lib/instant_record/sync_window.rb +92 -15
- data/lib/instant_record/syncable.rb +313 -17
- data/lib/instant_record/testing/authoritative_server.rb +547 -0
- data/lib/instant_record/testing/chaos_simulator.rb +429 -0
- data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
- data/lib/instant_record/testing/fault_network.rb +140 -0
- data/lib/instant_record/testing/parity_suite.rb +435 -0
- data/lib/instant_record/testing/runtimes/base.rb +184 -0
- data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
- data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
- data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
- data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
- data/lib/instant_record/testing.rb +333 -0
- data/lib/instant_record/trace/redactor.rb +278 -0
- data/lib/instant_record/trace/replayer.rb +126 -0
- data/lib/instant_record/trace/schema_extractor.rb +37 -0
- data/lib/instant_record/trace.rb +22 -0
- data/lib/instant_record/version.rb +1 -1
- data/lib/instant_record.rb +107 -37
- data/lib/tasks/instant_record.rake +299 -47
- data/native/ios/InstantRecordNative/Package.swift +12 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
- data/native/ios/README.md +341 -0
- data/sig/instant_record/inertia.rbs +47 -0
- data/sig/instant_record/native.rbs +38 -0
- metadata +194 -18
- data/lib/generators/instant_record/install/templates/database.js +0 -32
- data/lib/generators/instant_record/install/templates/index.html +0 -69
- data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
- data/lib/instant_record/local_schema.rb +0 -75
- data/lib/instant_record/pglite_compat.rb +0 -40
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
// Leader-elected, visibility-aware SSE stream client for the compiled worker.
|
|
2
|
+
// One worker per (origin, scope) holds the streaming /events connection via
|
|
3
|
+
// navigator.locks and feeds complete SSE frames into the host; follower tabs
|
|
4
|
+
// receive persisted updates over BroadcastChannel and take over if the leader
|
|
5
|
+
// closes or enters simulated offline mode.
|
|
6
|
+
|
|
7
|
+
export const DEFAULTS = Object.freeze({
|
|
8
|
+
hiddenGraceMs: 5000,
|
|
9
|
+
peerTtlMs: 30000,
|
|
10
|
+
peerPingWaitMs: 250,
|
|
11
|
+
idleTimeoutMs: 60000,
|
|
12
|
+
minStreamDurationMs: 2000,
|
|
13
|
+
shortStreamDelayMs: 1000,
|
|
14
|
+
shortStreamBusyDelayMs: 100,
|
|
15
|
+
reconnectJitterMinMs: 50,
|
|
16
|
+
reconnectJitterMaxMs: 150,
|
|
17
|
+
backoffBaseMs: 1000,
|
|
18
|
+
backoffCapMs: 30000,
|
|
19
|
+
notReadyDelayMs: 250,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// Buffers incoming SSE text across arbitrary chunk boundaries (including CRLF
|
|
23
|
+
// split across chunks), emits complete \n\n-terminated frames that carry data,
|
|
24
|
+
// and drops comment-only heartbeat frames (": hb\n\n") without waking Wasm.
|
|
25
|
+
export class SseFrameBuffer {
|
|
26
|
+
constructor() {
|
|
27
|
+
this.pending = "";
|
|
28
|
+
this.trailingCr = false;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
feed(chunk) {
|
|
32
|
+
if (!chunk) return { framesText: "", count: 0 };
|
|
33
|
+
let text = this.trailingCr ? "\r" + chunk : chunk;
|
|
34
|
+
this.trailingCr = false;
|
|
35
|
+
if (text.endsWith("\r")) {
|
|
36
|
+
this.trailingCr = true;
|
|
37
|
+
text = text.slice(0, -1);
|
|
38
|
+
}
|
|
39
|
+
this.pending += text.replace(/\r\n?/g, "\n");
|
|
40
|
+
|
|
41
|
+
const frames = [];
|
|
42
|
+
let start = 0;
|
|
43
|
+
let cut;
|
|
44
|
+
while ((cut = this.pending.indexOf("\n\n", start)) !== -1) {
|
|
45
|
+
const block = this.pending.slice(start, cut);
|
|
46
|
+
start = cut + 2;
|
|
47
|
+
if (/^data:/m.test(block)) frames.push(block + "\n\n");
|
|
48
|
+
}
|
|
49
|
+
if (start > 0) this.pending = this.pending.slice(start);
|
|
50
|
+
return { framesText: frames.join(""), count: frames.length };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
reset() {
|
|
54
|
+
this.pending = "";
|
|
55
|
+
this.trailingCr = false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function streamScopeKey(mailboxScope = "", syncScope = "") {
|
|
60
|
+
return `${mailboxScope || "default"}:${syncScope || "anon"}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function eventsUrl(endpoint, { cursor = 0, identity = "", scope = "" } = {}) {
|
|
64
|
+
const params = [`after=${encodeURIComponent(String(cursor ?? 0))}`];
|
|
65
|
+
if (identity) params.push(`identity=${encodeURIComponent(identity)}`);
|
|
66
|
+
if (scope) params.push(`scope=${encodeURIComponent(scope)}`);
|
|
67
|
+
return `${endpoint}/events?${params.join("&")}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function createStreamLeader(options) {
|
|
71
|
+
const config = { ...DEFAULTS, ...options };
|
|
72
|
+
const tabId = config.tabId || globalThis.crypto.randomUUID();
|
|
73
|
+
const getEndpoint = typeof config.getEndpoint === "function" ? config.getEndpoint : () => config.endpoint;
|
|
74
|
+
const getSyncScope = typeof config.getSyncScope === "function" ? config.getSyncScope : () => config.syncScope || "";
|
|
75
|
+
const getHeaders = typeof config.getHeaders === "function" ? config.getHeaders : () => ({});
|
|
76
|
+
const scopeKey = streamScopeKey(config.mailboxScope, getSyncScope());
|
|
77
|
+
const lockName = `instant-record-stream/${scopeKey}`;
|
|
78
|
+
const channelName = `instant-record-spinel-stream/${scopeKey}`;
|
|
79
|
+
|
|
80
|
+
const locks = config.locks === undefined ? globalThis.navigator?.locks ?? null : config.locks;
|
|
81
|
+
const createChannel = config.createChannel || (name => (typeof BroadcastChannel !== "undefined" ? new BroadcastChannel(name) : null));
|
|
82
|
+
const fetchFn = config.fetch || ((...args) => globalThis.fetch(...args));
|
|
83
|
+
const setTimer = config.setTimeout || ((fn, ms) => globalThis.setTimeout(fn, ms));
|
|
84
|
+
const clearTimer = config.clearTimeout || (id => globalThis.clearTimeout(id));
|
|
85
|
+
const now = config.now || (() => Date.now());
|
|
86
|
+
const random = config.random || (() => Math.random());
|
|
87
|
+
const isOnlineFn = config.isOnline || (() => (typeof navigator === "undefined" ? true : navigator.onLine !== false));
|
|
88
|
+
const getLatencyMs = config.getLatencyMs || (() => 0);
|
|
89
|
+
const onReport = config.onReport || (() => {});
|
|
90
|
+
const onStreamStateChange = config.onStreamStateChange || (() => {});
|
|
91
|
+
|
|
92
|
+
let channel = null;
|
|
93
|
+
let started = false;
|
|
94
|
+
let stopped = false;
|
|
95
|
+
let suspended = false;
|
|
96
|
+
let canLead = config.canLead !== false;
|
|
97
|
+
let isLeader = false;
|
|
98
|
+
let lockAbortController = null;
|
|
99
|
+
let releaseLeadership = null;
|
|
100
|
+
let activeLoop = null;
|
|
101
|
+
|
|
102
|
+
let selfVisible = config.initialVisible !== false;
|
|
103
|
+
let online = isOnlineFn();
|
|
104
|
+
let offlineSimulated = !!(config.isOfflineSimulated && config.isOfflineSimulated());
|
|
105
|
+
let pausedForHidden = false;
|
|
106
|
+
let streamOpen = false;
|
|
107
|
+
let backoffMs = config.backoffBaseMs;
|
|
108
|
+
|
|
109
|
+
let fetchAbort = null;
|
|
110
|
+
let abortReason = null;
|
|
111
|
+
let hiddenGraceTimer = null;
|
|
112
|
+
let wakeResolve = null;
|
|
113
|
+
|
|
114
|
+
// peer tabId -> { visible: boolean, seenAt: number }
|
|
115
|
+
const peers = new Map();
|
|
116
|
+
|
|
117
|
+
const canElect = () => started && !stopped && !suspended && !offlineSimulated && canLead;
|
|
118
|
+
const activeLeader = () => isLeader && !stopped && !suspended && !offlineSimulated && canLead;
|
|
119
|
+
|
|
120
|
+
function eventsPathname() {
|
|
121
|
+
try {
|
|
122
|
+
const origin = globalThis.location?.origin || "http://localhost";
|
|
123
|
+
return new URL(getEndpoint() + "/events", origin).pathname;
|
|
124
|
+
} catch {
|
|
125
|
+
return getEndpoint() + "/events";
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function reportStream(status, ms, open) {
|
|
130
|
+
onReport({
|
|
131
|
+
kind: "stream",
|
|
132
|
+
method: "GET",
|
|
133
|
+
path: eventsPathname(),
|
|
134
|
+
status,
|
|
135
|
+
ms,
|
|
136
|
+
streamOpen: open,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function postCoord(message) {
|
|
141
|
+
if (!channel || stopped) return;
|
|
142
|
+
try {
|
|
143
|
+
channel.postMessage(message);
|
|
144
|
+
} catch {
|
|
145
|
+
// Channel closed during teardown.
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function updateStreamOpen(nextOpen, broadcast = false) {
|
|
150
|
+
const normalized = !!nextOpen;
|
|
151
|
+
if (streamOpen !== normalized) {
|
|
152
|
+
streamOpen = normalized;
|
|
153
|
+
onStreamStateChange(streamOpen);
|
|
154
|
+
}
|
|
155
|
+
if (broadcast && isLeader) {
|
|
156
|
+
postCoord({ type: "stream_state", tabId, open: streamOpen });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function anyVisible() {
|
|
161
|
+
if (selfVisible) return true;
|
|
162
|
+
for (const peer of peers.values()) {
|
|
163
|
+
if (peer.visible) return true;
|
|
164
|
+
}
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function hasStaleVisiblePeer() {
|
|
169
|
+
const cutoff = now() - config.peerTtlMs;
|
|
170
|
+
for (const peer of peers.values()) {
|
|
171
|
+
if (peer.visible && peer.seenAt <= cutoff) return true;
|
|
172
|
+
}
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function clearHiddenGrace() {
|
|
177
|
+
if (hiddenGraceTimer !== null) {
|
|
178
|
+
clearTimer(hiddenGraceTimer);
|
|
179
|
+
hiddenGraceTimer = null;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function wakeLoop() {
|
|
184
|
+
const resolve = wakeResolve;
|
|
185
|
+
wakeResolve = null;
|
|
186
|
+
if (resolve) resolve();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function abortCurrentFetch(reason) {
|
|
190
|
+
if (!fetchAbort) return;
|
|
191
|
+
abortReason = reason;
|
|
192
|
+
fetchAbort.abort();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function waitInterruptible(ms) {
|
|
196
|
+
if (!activeLeader()) return Promise.resolve();
|
|
197
|
+
return new Promise(resolve => {
|
|
198
|
+
let timer = null;
|
|
199
|
+
const done = () => {
|
|
200
|
+
if (timer !== null) {
|
|
201
|
+
clearTimer(timer);
|
|
202
|
+
timer = null;
|
|
203
|
+
}
|
|
204
|
+
if (wakeResolve === done) wakeResolve = null;
|
|
205
|
+
resolve();
|
|
206
|
+
};
|
|
207
|
+
wakeResolve = done;
|
|
208
|
+
if (ms != null) timer = setTimer(done, Math.max(0, ms));
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function evaluateVisibility() {
|
|
213
|
+
if (!activeLeader()) return;
|
|
214
|
+
if (anyVisible()) {
|
|
215
|
+
const wasHiddenOrGrace = pausedForHidden || hiddenGraceTimer !== null;
|
|
216
|
+
clearHiddenGrace();
|
|
217
|
+
if (pausedForHidden) {
|
|
218
|
+
pausedForHidden = false;
|
|
219
|
+
backoffMs = config.backoffBaseMs;
|
|
220
|
+
}
|
|
221
|
+
if (wasHiddenOrGrace) wakeLoop();
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (!pausedForHidden && hiddenGraceTimer === null) {
|
|
225
|
+
hiddenGraceTimer = setTimer(() => {
|
|
226
|
+
hiddenGraceTimer = null;
|
|
227
|
+
if (!activeLeader() || anyVisible()) return;
|
|
228
|
+
pausedForHidden = true;
|
|
229
|
+
abortCurrentFetch("hidden");
|
|
230
|
+
}, config.hiddenGraceMs);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function pruneStalePeers() {
|
|
235
|
+
const pingStartedAt = now();
|
|
236
|
+
postCoord({ type: "ping", tabId });
|
|
237
|
+
await new Promise(resolve => setTimer(resolve, config.peerPingWaitMs));
|
|
238
|
+
for (const [peerId, peer] of peers) {
|
|
239
|
+
if (peer.visible && peer.seenAt < pingStartedAt) peers.delete(peerId);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function jitteredDelay(baseMs) {
|
|
244
|
+
return Math.round(baseMs * (0.8 + random() * 0.4));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function reconnectJitter() {
|
|
248
|
+
const span = Math.max(0, config.reconnectJitterMaxMs - config.reconnectJitterMinMs);
|
|
249
|
+
return Math.round(config.reconnectJitterMinMs + random() * span);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function handleCoordMessage(event) {
|
|
253
|
+
const msg = event.data;
|
|
254
|
+
if (!msg || typeof msg !== "object" || msg.tabId === tabId || stopped || suspended) return;
|
|
255
|
+
|
|
256
|
+
if (msg.type === "hello" || msg.type === "visibility") {
|
|
257
|
+
peers.set(msg.tabId, { visible: !!msg.visible, seenAt: now() });
|
|
258
|
+
if (isLeader) {
|
|
259
|
+
if (msg.type === "hello") postCoord({ type: "stream_state", tabId, open: streamOpen });
|
|
260
|
+
evaluateVisibility();
|
|
261
|
+
}
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (msg.type === "bye") {
|
|
266
|
+
peers.delete(msg.tabId);
|
|
267
|
+
if (isLeader) evaluateVisibility();
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (msg.type === "discover" || msg.type === "ping") {
|
|
272
|
+
postCoord({ type: "visibility", tabId, visible: selfVisible });
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (msg.type === "stream_state") {
|
|
277
|
+
if (!isLeader && !offlineSimulated) updateStreamOpen(!!msg.open, false);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (msg.type === "wake") {
|
|
282
|
+
if (isLeader) {
|
|
283
|
+
backoffMs = config.backoffBaseMs;
|
|
284
|
+
if (msg.visible) {
|
|
285
|
+
peers.set(msg.tabId, { visible: true, seenAt: now() });
|
|
286
|
+
clearHiddenGrace();
|
|
287
|
+
pausedForHidden = false;
|
|
288
|
+
}
|
|
289
|
+
wakeLoop();
|
|
290
|
+
}
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (msg.type === "reconnect") {
|
|
295
|
+
if (isLeader) {
|
|
296
|
+
backoffMs = config.backoffBaseMs;
|
|
297
|
+
if (fetchAbort) abortCurrentFetch("reconnect");
|
|
298
|
+
else wakeLoop();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function openAndReadStream(params) {
|
|
304
|
+
const latency = getLatencyMs();
|
|
305
|
+
if (latency > 0) {
|
|
306
|
+
await waitInterruptible(latency);
|
|
307
|
+
if (!activeLeader() || !online || pausedForHidden) return;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const url = eventsUrl(getEndpoint(), {
|
|
311
|
+
cursor: params.cursor,
|
|
312
|
+
identity: params.identity,
|
|
313
|
+
scope: getSyncScope(),
|
|
314
|
+
});
|
|
315
|
+
const controller = new AbortController();
|
|
316
|
+
fetchAbort = controller;
|
|
317
|
+
abortReason = null;
|
|
318
|
+
|
|
319
|
+
let idleTimer = null;
|
|
320
|
+
const armIdleWatchdog = () => {
|
|
321
|
+
if (idleTimer !== null) clearTimer(idleTimer);
|
|
322
|
+
if (config.idleTimeoutMs > 0) {
|
|
323
|
+
idleTimer = setTimer(() => {
|
|
324
|
+
abortReason = "idle";
|
|
325
|
+
controller.abort();
|
|
326
|
+
}, config.idleTimeoutMs);
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
const clearIdleWatchdog = () => {
|
|
330
|
+
if (idleTimer !== null) {
|
|
331
|
+
clearTimer(idleTimer);
|
|
332
|
+
idleTimer = null;
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const openedAt = now();
|
|
337
|
+
let receivedEvents = 0;
|
|
338
|
+
let wasReset = false;
|
|
339
|
+
let failureStatus = null;
|
|
340
|
+
let reader = null;
|
|
341
|
+
|
|
342
|
+
try {
|
|
343
|
+
armIdleWatchdog();
|
|
344
|
+
const response = await fetchFn(url, {
|
|
345
|
+
method: "GET",
|
|
346
|
+
headers: { ...getHeaders(), Accept: "text/event-stream" },
|
|
347
|
+
signal: controller.signal,
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
if (!response || response.status !== 200) {
|
|
351
|
+
failureStatus = response ? response.status : "failed";
|
|
352
|
+
} else {
|
|
353
|
+
backoffMs = config.backoffBaseMs;
|
|
354
|
+
updateStreamOpen(true, true);
|
|
355
|
+
|
|
356
|
+
const frameBuffer = new SseFrameBuffer();
|
|
357
|
+
const consumeText = async text => {
|
|
358
|
+
const { framesText, count } = frameBuffer.feed(text);
|
|
359
|
+
if (count === 0) return false;
|
|
360
|
+
receivedEvents += count;
|
|
361
|
+
const applied = await config.applyFrames(framesText);
|
|
362
|
+
if (activeLeader() && online && !pausedForHidden) {
|
|
363
|
+
reportStream(200, Math.round(now() - openedAt), true);
|
|
364
|
+
}
|
|
365
|
+
if (applied?.reset) {
|
|
366
|
+
wasReset = true;
|
|
367
|
+
return true;
|
|
368
|
+
}
|
|
369
|
+
return false;
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
if (response.body && typeof response.body.getReader === "function") {
|
|
373
|
+
reader = response.body.getReader();
|
|
374
|
+
const decoder = new TextDecoder();
|
|
375
|
+
while (true) {
|
|
376
|
+
armIdleWatchdog();
|
|
377
|
+
const { value, done } = await reader.read();
|
|
378
|
+
if (done) {
|
|
379
|
+
const tail = decoder.decode();
|
|
380
|
+
if (tail) await consumeText(tail);
|
|
381
|
+
break;
|
|
382
|
+
}
|
|
383
|
+
const chunk = typeof value === "string" ? value : decoder.decode(value, { stream: true });
|
|
384
|
+
if (await consumeText(chunk)) {
|
|
385
|
+
abortReason = "reset";
|
|
386
|
+
controller.abort();
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
} else {
|
|
391
|
+
await consumeText(await response.text());
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
} catch {
|
|
395
|
+
failureStatus = "failed";
|
|
396
|
+
} finally {
|
|
397
|
+
clearIdleWatchdog();
|
|
398
|
+
if (reader) {
|
|
399
|
+
try { reader.cancel().catch(() => {}); } catch { /* ignore */ }
|
|
400
|
+
}
|
|
401
|
+
if (fetchAbort === controller) fetchAbort = null;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (!activeLeader()) return;
|
|
405
|
+
|
|
406
|
+
const reason = abortReason;
|
|
407
|
+
abortReason = null;
|
|
408
|
+
updateStreamOpen(false, true);
|
|
409
|
+
|
|
410
|
+
if (wasReset || reason === "reconnect" || reason === "reset") return;
|
|
411
|
+
if (reason === "hidden" || reason === "offline" || !online || pausedForHidden) return;
|
|
412
|
+
|
|
413
|
+
if (failureStatus !== null) {
|
|
414
|
+
reportStream(failureStatus, Math.round(now() - openedAt), false);
|
|
415
|
+
const delay = jitteredDelay(backoffMs);
|
|
416
|
+
backoffMs = Math.min(backoffMs * 2, config.backoffCapMs);
|
|
417
|
+
await waitInterruptible(delay);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const elapsed = now() - openedAt;
|
|
422
|
+
if (elapsed >= config.minStreamDurationMs) {
|
|
423
|
+
await waitInterruptible(reconnectJitter());
|
|
424
|
+
} else {
|
|
425
|
+
await waitInterruptible(receivedEvents > 0 ? config.shortStreamBusyDelayMs : config.shortStreamDelayMs);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function runLeaderLoop() {
|
|
430
|
+
while (activeLeader()) {
|
|
431
|
+
if (!online) {
|
|
432
|
+
updateStreamOpen(false, true);
|
|
433
|
+
await waitInterruptible(null);
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
if (!selfVisible && hasStaleVisiblePeer()) {
|
|
438
|
+
await pruneStalePeers();
|
|
439
|
+
if (!activeLeader()) break;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
if (!anyVisible()) {
|
|
443
|
+
if (!pausedForHidden) evaluateVisibility();
|
|
444
|
+
else updateStreamOpen(false, true);
|
|
445
|
+
await waitInterruptible(null);
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
pausedForHidden = false;
|
|
450
|
+
clearHiddenGrace();
|
|
451
|
+
|
|
452
|
+
let params;
|
|
453
|
+
try {
|
|
454
|
+
params = await config.getStreamParams();
|
|
455
|
+
} catch {
|
|
456
|
+
params = null;
|
|
457
|
+
}
|
|
458
|
+
if (!activeLeader()) break;
|
|
459
|
+
|
|
460
|
+
if (!params || !params.ready) {
|
|
461
|
+
updateStreamOpen(false, true);
|
|
462
|
+
await waitInterruptible(config.notReadyDelayMs);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
await openAndReadStream(params);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
async function assumeLeadership() {
|
|
471
|
+
if (!canElect()) return;
|
|
472
|
+
isLeader = true;
|
|
473
|
+
peers.clear();
|
|
474
|
+
pausedForHidden = !anyVisible();
|
|
475
|
+
postCoord({ type: "discover", tabId });
|
|
476
|
+
|
|
477
|
+
const released = new Promise(resolve => {
|
|
478
|
+
releaseLeadership = resolve;
|
|
479
|
+
});
|
|
480
|
+
const loop = runLeaderLoop();
|
|
481
|
+
activeLoop = loop;
|
|
482
|
+
await released;
|
|
483
|
+
|
|
484
|
+
isLeader = false;
|
|
485
|
+
releaseLeadership = null;
|
|
486
|
+
clearHiddenGrace();
|
|
487
|
+
abortCurrentFetch(offlineSimulated ? "offline" : "release");
|
|
488
|
+
wakeLoop();
|
|
489
|
+
try {
|
|
490
|
+
await loop;
|
|
491
|
+
} finally {
|
|
492
|
+
if (activeLoop === loop) activeLoop = null;
|
|
493
|
+
if (canElect() && !isLeader && !lockAbortController) requestLeadership();
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function requestLeadership() {
|
|
498
|
+
if (!canElect() || isLeader || lockAbortController || activeLoop) return;
|
|
499
|
+
if (!locks) {
|
|
500
|
+
assumeLeadership();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
const abortController = new AbortController();
|
|
504
|
+
lockAbortController = abortController;
|
|
505
|
+
locks
|
|
506
|
+
.request(lockName, { mode: "exclusive", signal: abortController.signal }, async () => {
|
|
507
|
+
if (lockAbortController === abortController) lockAbortController = null;
|
|
508
|
+
await assumeLeadership();
|
|
509
|
+
})
|
|
510
|
+
.catch(() => {
|
|
511
|
+
if (lockAbortController === abortController) lockAbortController = null;
|
|
512
|
+
})
|
|
513
|
+
.finally(() => {
|
|
514
|
+
if (canElect() && !isLeader && !lockAbortController && !activeLoop) {
|
|
515
|
+
requestLeadership();
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function releaseCurrentLeadership() {
|
|
521
|
+
clearHiddenGrace();
|
|
522
|
+
if (lockAbortController) {
|
|
523
|
+
const pending = lockAbortController;
|
|
524
|
+
lockAbortController = null;
|
|
525
|
+
pending.abort();
|
|
526
|
+
}
|
|
527
|
+
if (isLeader) {
|
|
528
|
+
abortCurrentFetch(offlineSimulated ? "offline" : "release");
|
|
529
|
+
const release = releaseLeadership;
|
|
530
|
+
releaseLeadership = null;
|
|
531
|
+
wakeLoop();
|
|
532
|
+
if (release) release();
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
return {
|
|
537
|
+
tabId,
|
|
538
|
+
lockName,
|
|
539
|
+
channelName,
|
|
540
|
+
|
|
541
|
+
isLeader: () => isLeader,
|
|
542
|
+
isStreamOpen: () => streamOpen,
|
|
543
|
+
|
|
544
|
+
start() {
|
|
545
|
+
if (started || stopped) return;
|
|
546
|
+
started = true;
|
|
547
|
+
channel = createChannel(channelName);
|
|
548
|
+
if (channel) channel.onmessage = handleCoordMessage;
|
|
549
|
+
postCoord({ type: "hello", tabId, visible: selfVisible });
|
|
550
|
+
if (offlineSimulated) {
|
|
551
|
+
reportStream("offline", 0, false);
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
requestLeadership();
|
|
555
|
+
},
|
|
556
|
+
|
|
557
|
+
setVisible(visible) {
|
|
558
|
+
const next = !!visible;
|
|
559
|
+
if (next === selfVisible) return;
|
|
560
|
+
selfVisible = next;
|
|
561
|
+
if (suspended || stopped) return;
|
|
562
|
+
postCoord({ type: "visibility", tabId, visible: selfVisible });
|
|
563
|
+
if (selfVisible) {
|
|
564
|
+
clearHiddenGrace();
|
|
565
|
+
if (isLeader) {
|
|
566
|
+
pausedForHidden = false;
|
|
567
|
+
backoffMs = config.backoffBaseMs;
|
|
568
|
+
wakeLoop();
|
|
569
|
+
} else {
|
|
570
|
+
postCoord({ type: "wake", tabId, visible: true, reason: "visible" });
|
|
571
|
+
}
|
|
572
|
+
} else if (isLeader) {
|
|
573
|
+
evaluateVisibility();
|
|
574
|
+
}
|
|
575
|
+
},
|
|
576
|
+
|
|
577
|
+
setOnline(nextOnline) {
|
|
578
|
+
const normalized = !!nextOnline;
|
|
579
|
+
if (normalized === online) return;
|
|
580
|
+
online = normalized;
|
|
581
|
+
if (!online) {
|
|
582
|
+
if (isLeader) {
|
|
583
|
+
abortCurrentFetch("offline");
|
|
584
|
+
updateStreamOpen(false, true);
|
|
585
|
+
}
|
|
586
|
+
} else {
|
|
587
|
+
backoffMs = config.backoffBaseMs;
|
|
588
|
+
if (isLeader) wakeLoop();
|
|
589
|
+
else postCoord({ type: "wake", tabId, reason: "online" });
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
|
|
593
|
+
setOfflineSimulated(nextOffline) {
|
|
594
|
+
const normalized = !!nextOffline;
|
|
595
|
+
if (normalized === offlineSimulated) return;
|
|
596
|
+
offlineSimulated = normalized;
|
|
597
|
+
if (offlineSimulated) {
|
|
598
|
+
updateStreamOpen(false, false);
|
|
599
|
+
reportStream("offline", 0, false);
|
|
600
|
+
releaseCurrentLeadership();
|
|
601
|
+
} else {
|
|
602
|
+
backoffMs = config.backoffBaseMs;
|
|
603
|
+
if (canElect()) {
|
|
604
|
+
postCoord({ type: "hello", tabId, visible: selfVisible });
|
|
605
|
+
postCoord({ type: "wake", tabId, visible: selfVisible, reason: "online" });
|
|
606
|
+
requestLeadership();
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
},
|
|
610
|
+
|
|
611
|
+
wake() {
|
|
612
|
+
if (!canElect()) return;
|
|
613
|
+
backoffMs = config.backoffBaseMs;
|
|
614
|
+
if (isLeader) wakeLoop();
|
|
615
|
+
else postCoord({ type: "wake", tabId, visible: selfVisible, reason: "sync" });
|
|
616
|
+
},
|
|
617
|
+
|
|
618
|
+
reconnect() {
|
|
619
|
+
if (!canElect()) return;
|
|
620
|
+
backoffMs = config.backoffBaseMs;
|
|
621
|
+
if (isLeader) {
|
|
622
|
+
if (fetchAbort) abortCurrentFetch("reconnect");
|
|
623
|
+
else wakeLoop();
|
|
624
|
+
} else {
|
|
625
|
+
postCoord({ type: "reconnect", tabId });
|
|
626
|
+
}
|
|
627
|
+
},
|
|
628
|
+
|
|
629
|
+
// BFCache suspension: release the Web Lock and pause without permanently closing
|
|
630
|
+
// the coordinator, so a subsequent pageshow (persisted) can resume cleanly.
|
|
631
|
+
suspend() {
|
|
632
|
+
if (stopped || suspended) return;
|
|
633
|
+
suspended = true;
|
|
634
|
+
selfVisible = false;
|
|
635
|
+
postCoord({ type: "bye", tabId });
|
|
636
|
+
updateStreamOpen(false, false);
|
|
637
|
+
releaseCurrentLeadership();
|
|
638
|
+
},
|
|
639
|
+
|
|
640
|
+
resume(visible = true) {
|
|
641
|
+
if (stopped || !suspended) return;
|
|
642
|
+
suspended = false;
|
|
643
|
+
selfVisible = !!visible;
|
|
644
|
+
backoffMs = config.backoffBaseMs;
|
|
645
|
+
if (started) {
|
|
646
|
+
postCoord({ type: "hello", tabId, visible: selfVisible });
|
|
647
|
+
if (canElect()) requestLeadership();
|
|
648
|
+
}
|
|
649
|
+
},
|
|
650
|
+
|
|
651
|
+
setCanLead(nextCanLead) {
|
|
652
|
+
const normalized = !!nextCanLead;
|
|
653
|
+
if (normalized === canLead) return;
|
|
654
|
+
canLead = normalized;
|
|
655
|
+
if (canLead) {
|
|
656
|
+
if (canElect()) requestLeadership();
|
|
657
|
+
} else {
|
|
658
|
+
releaseCurrentLeadership();
|
|
659
|
+
}
|
|
660
|
+
},
|
|
661
|
+
|
|
662
|
+
stop() {
|
|
663
|
+
if (stopped) return;
|
|
664
|
+
stopped = true;
|
|
665
|
+
suspended = false;
|
|
666
|
+
postCoord({ type: "bye", tabId });
|
|
667
|
+
updateStreamOpen(false, false);
|
|
668
|
+
releaseCurrentLeadership();
|
|
669
|
+
if (channel) {
|
|
670
|
+
try { channel.close(); } catch { /* ignore */ }
|
|
671
|
+
channel = null;
|
|
672
|
+
}
|
|
673
|
+
},
|
|
674
|
+
};
|
|
675
|
+
}
|