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.
Files changed (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,191 @@
1
+ // Typed row-delta bus helpers shared by the compiled worker, AppHost, and main.js.
2
+ //
3
+ // Wire format from /host/notify and ir_notice():
4
+ // "" -> not notified
5
+ // "records_changed" -> wildcard: anything may have changed (changes: null)
6
+ // "records_changed\n<line>" -> one compact JSON delta per line:
7
+ // {"type","id","op","changed_columns","attrs"}
8
+ // (or legacy "Type:id" lines, normalized cleanly),
9
+ // plus any "sync_notice:<json>" lines for quarantined
10
+ // rejections or LWW conflicts.
11
+ const NOTICE_PREFIX = "sync_notice:";
12
+
13
+ export function normalizeDelta(raw) {
14
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
15
+ if (typeof raw.type !== "string" || !raw.type) return null;
16
+ if (raw.id === undefined || raw.id === null || raw.id === "") return null;
17
+ return {
18
+ type: raw.type,
19
+ id: String(raw.id),
20
+ op: typeof raw.op === "string" && raw.op ? raw.op : "update",
21
+ changed_columns: Array.isArray(raw.changed_columns) ? raw.changed_columns.map(String) : [],
22
+ attrs: raw.attrs && typeof raw.attrs === "object" && !Array.isArray(raw.attrs) ? raw.attrs : {},
23
+ };
24
+ }
25
+
26
+ export function readNotice(text) {
27
+ if (typeof text !== "string" || !text.startsWith("records_changed")) {
28
+ return { notified: false, changes: null, notices: [] };
29
+ }
30
+ const lines = text.split("\n").slice(1).filter(Boolean);
31
+ if (lines.length === 0) return { notified: true, changes: null, notices: [] };
32
+
33
+ const changes = [];
34
+ const notices = [];
35
+ let unlisted = false;
36
+ for (const line of lines) {
37
+ if (line.startsWith(NOTICE_PREFIX)) {
38
+ try {
39
+ notices.push(JSON.parse(line.slice(NOTICE_PREFIX.length)));
40
+ } catch {
41
+ // Ignore malformed notice lines so record refresh still succeeds.
42
+ }
43
+ continue;
44
+ }
45
+ if (unlisted) continue;
46
+ if (line.startsWith("{")) {
47
+ try {
48
+ const delta = normalizeDelta(JSON.parse(line));
49
+ if (!delta) unlisted = true;
50
+ else changes.push(delta);
51
+ } catch {
52
+ unlisted = true;
53
+ }
54
+ } else {
55
+ const at = line.indexOf(":");
56
+ if (at <= 0) {
57
+ unlisted = true;
58
+ } else {
59
+ changes.push({
60
+ type: line.slice(0, at),
61
+ id: line.slice(at + 1),
62
+ op: null,
63
+ changed_columns: [],
64
+ attrs: {},
65
+ });
66
+ }
67
+ }
68
+ }
69
+ return {
70
+ notified: true,
71
+ changes: !unlisted && changes.length ? changes : null,
72
+ notices,
73
+ };
74
+ }
75
+
76
+ export function encodeBroadcast(revision, changes = null) {
77
+ return {
78
+ revision: revision ?? null,
79
+ changes: Array.isArray(changes) ? changes : null,
80
+ };
81
+ }
82
+
83
+ export function decodeBroadcast(message) {
84
+ if (typeof message === "number") {
85
+ return { revision: message, changes: null };
86
+ }
87
+ if (!message || typeof message !== "object") {
88
+ return { revision: null, changes: null };
89
+ }
90
+ const rawChanges = Array.isArray(message.changes) ? message.changes : null;
91
+ if (!rawChanges) {
92
+ return { revision: message.revision ?? null, changes: null };
93
+ }
94
+ const changes = [];
95
+ for (const item of rawChanges) {
96
+ const delta = normalizeDelta(item);
97
+ if (!delta) return { revision: message.revision ?? null, changes: null };
98
+ changes.push(delta);
99
+ }
100
+ return { revision: message.revision ?? null, changes };
101
+ }
102
+
103
+ export function parseReads(text) {
104
+ if (typeof text !== "string" || !text.trim()) return null;
105
+ try {
106
+ const parsed = JSON.parse(text);
107
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
108
+ const tables = Array.isArray(parsed.tables) ? parsed.tables.map(String) : [];
109
+ const models = Array.isArray(parsed.models) ? parsed.models.map(String) : [];
110
+ const partitions = parsed.partitions && typeof parsed.partitions === "object" && !Array.isArray(parsed.partitions)
111
+ ? parsed.partitions
112
+ : {};
113
+ return { tables, models, partitions };
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ export function mergeReads(base, extra) {
120
+ if (!extra) return base || null;
121
+ if (!base) return extra;
122
+
123
+ const tables = [...new Set([...(base.tables || []), ...(extra.tables || [])])].sort();
124
+ const models = [...new Set([...(base.models || []), ...(extra.models || [])])].sort();
125
+ const baseKeys = new Set([...(base.models || []), ...(base.tables || [])]);
126
+ const extraKeys = new Set([...(extra.models || []), ...(extra.tables || [])]);
127
+ const allKeys = new Set([...baseKeys, ...extraKeys]);
128
+ const partitions = {};
129
+
130
+ for (const key of allKeys) {
131
+ const inBase = baseKeys.has(key);
132
+ const inExtra = extraKeys.has(key);
133
+ const a = base.partitions?.[key];
134
+ const b = extra.partitions?.[key];
135
+
136
+ if (inBase && inExtra) {
137
+ if (!a || !b) continue; // unconstrained in at least one read -> whole-table dependency
138
+ const merged = {};
139
+ for (const [col, vals] of Object.entries(a)) {
140
+ if (!Object.prototype.hasOwnProperty.call(b, col)) continue;
141
+ merged[col] = [...new Set([...vals.map(String), ...b[col].map(String)])].sort();
142
+ }
143
+ if (Object.keys(merged).length) partitions[key] = merged;
144
+ } else if (inBase && a && Object.keys(a).length) {
145
+ partitions[key] = a;
146
+ } else if (inExtra && b && Object.keys(b).length) {
147
+ partitions[key] = b;
148
+ }
149
+ }
150
+
151
+ return { tables, models, partitions };
152
+ }
153
+
154
+ export function affectsReads(changes, reads) {
155
+ if (!changes || !reads) return true;
156
+ if (changes.length === 0) return false;
157
+
158
+ const models = Array.isArray(reads.models) ? reads.models : [];
159
+ const tables = Array.isArray(reads.tables) ? reads.tables : [];
160
+ if (models.length === 0 && tables.length === 0) return false;
161
+
162
+ const partitions = reads.partitions && typeof reads.partitions === "object" ? reads.partitions : {};
163
+
164
+ return changes.some((delta) => {
165
+ if (!delta || typeof delta !== "object") return true;
166
+ const type = delta.type || "";
167
+ const table = delta.table || "";
168
+ let matchedKey = null;
169
+ if (type && models.includes(type)) matchedKey = type;
170
+ else if (table && tables.includes(table)) matchedKey = table;
171
+ if (!matchedKey) return false;
172
+
173
+ const constraints = partitions[matchedKey] || (table ? partitions[table] : null);
174
+ if (!constraints || typeof constraints !== "object") return true;
175
+
176
+ const attrs = delta.attrs;
177
+ if (!attrs || typeof attrs !== "object") return true;
178
+ const changedCols = Array.isArray(delta.changed_columns) ? delta.changed_columns : [];
179
+
180
+ for (const [col, allowed] of Object.entries(constraints)) {
181
+ if (delta.op === "update" && changedCols.includes(col)) continue;
182
+ if (!Object.prototype.hasOwnProperty.call(attrs, col)) continue;
183
+ const val = attrs[col];
184
+ if (val === null || val === undefined) continue;
185
+ if (!Array.isArray(allowed) || !allowed.map(String).includes(String(val))) {
186
+ return false;
187
+ }
188
+ }
189
+ return true;
190
+ });
191
+ }
@@ -0,0 +1,172 @@
1
+ // Structured WASM fault telemetry, bridged Ruby notification parsing, and a
2
+ // fail-loud circuit breaker shared by AppHost, the browser worker, and Node replay.
3
+
4
+ export class WasmFaultError extends Error {
5
+ constructor(fault, { cause } = {}) {
6
+ super(fault?.message || "WASM runtime fault", cause ? { cause } : undefined);
7
+ this.name = "WasmFaultError";
8
+ this.fault = fault;
9
+ this.exit = fault?.exit;
10
+ this.errors = Array.isArray(fault?.errors) ? fault.errors.slice() : [];
11
+ this.trapped = !!fault?.trapped;
12
+ this.fatal = !!fault?.fatal;
13
+ this.exportName = fault?.exportName || "";
14
+ }
15
+ }
16
+
17
+ export function isTrapExit(exit) {
18
+ return typeof exit === "string" && exit.startsWith("trap:");
19
+ }
20
+
21
+ export function buildFault({
22
+ exportName,
23
+ exit,
24
+ errors = [],
25
+ trapped = isTrapExit(exit),
26
+ fatal = trapped || exportName === "wasm_boot",
27
+ stack = null,
28
+ at = Date.now(),
29
+ }) {
30
+ const stderr = Array.isArray(errors) ? errors.map(String).filter(Boolean) : [];
31
+ const message =
32
+ stderr[0] ||
33
+ (typeof exit === "string" ? exit : `WASM export ${exportName || "unknown"} exited with status ${exit}`);
34
+ const fault = {
35
+ kind: trapped ? "wasm_trap" : "ruby_error",
36
+ exportName: exportName || "unknown",
37
+ exit,
38
+ trapped: !!trapped,
39
+ fatal: !!fatal,
40
+ message,
41
+ errors: stderr,
42
+ at,
43
+ };
44
+ if (stack) fault.stack = String(stack);
45
+ return fault;
46
+ }
47
+
48
+ // Parse bridged ActiveSupport::Notifications written to /host/events by Ruby's
49
+ // InstantRecord::Client. Accepts a JSON array (preferred) or NDJSON lines so a
50
+ // partial write before a hard trap still degrades safely.
51
+ export function readEvents(text) {
52
+ if (!text || !text.trim()) return [];
53
+ const trimmed = text.trim();
54
+ try {
55
+ const parsed = JSON.parse(trimmed);
56
+ if (Array.isArray(parsed)) return parsed.filter((item) => item && typeof item === "object");
57
+ if (parsed && typeof parsed === "object") return [parsed];
58
+ } catch {
59
+ const events = [];
60
+ for (const line of trimmed.split("\n")) {
61
+ if (!line.trim()) continue;
62
+ try {
63
+ const parsed = JSON.parse(line);
64
+ if (parsed && typeof parsed === "object") events.push(parsed);
65
+ } catch {
66
+ // Ignore truncated trailing line if a hard trap interrupted mid-write.
67
+ }
68
+ }
69
+ return events;
70
+ }
71
+ return [];
72
+ }
73
+
74
+ export class CircuitBreaker {
75
+ constructor({ maxConsecutiveFailures = 3, onTrip = null, clock = () => Date.now() } = {}) {
76
+ this.maxConsecutiveFailures = Math.max(1, maxConsecutiveFailures);
77
+ this.onTrip = onTrip;
78
+ this.clock = clock;
79
+ this.state = "closed";
80
+ this.consecutiveByExport = new Map();
81
+ this.consecutiveFailures = 0;
82
+ this.totalFaults = 0;
83
+ this.trippedAt = null;
84
+ this.tripReason = null;
85
+ this.lastFault = null;
86
+ }
87
+
88
+ isOpen() {
89
+ return this.state === "open";
90
+ }
91
+
92
+ recordSuccess(exportName = null) {
93
+ if (this.state !== "closed") return;
94
+ if (exportName) {
95
+ this.consecutiveByExport.delete(exportName);
96
+ this.consecutiveFailures = Math.max(0, ...this.consecutiveByExport.values());
97
+ } else {
98
+ this.consecutiveByExport.clear();
99
+ this.consecutiveFailures = 0;
100
+ }
101
+ }
102
+
103
+ recordFault(fault) {
104
+ const normalized = fault || buildFault({ exportName: "unknown", exit: 1 });
105
+ this.totalFaults += 1;
106
+ const key = normalized.exportName || "unknown";
107
+ const nextCount = (this.consecutiveByExport.get(key) || 0) + 1;
108
+ this.consecutiveByExport.set(key, nextCount);
109
+ this.consecutiveFailures = Math.max(nextCount, ...this.consecutiveByExport.values());
110
+ this.lastFault = normalized;
111
+
112
+ let trippedNow = false;
113
+ const shouldTrip =
114
+ normalized.fatal ||
115
+ normalized.trapped ||
116
+ normalized.exportName === "wasm_boot" ||
117
+ nextCount >= this.maxConsecutiveFailures;
118
+
119
+ if (shouldTrip && this.state !== "open") {
120
+ this.state = "open";
121
+ this.trippedAt = this.clock();
122
+ this.tripReason = normalized.fatal || normalized.trapped
123
+ ? `fatal ${normalized.kind} in ${normalized.exportName}`
124
+ : `${nextCount} consecutive WASM faults in ${normalized.exportName}`;
125
+ trippedNow = true;
126
+ this.onTrip?.(this.snapshot());
127
+ }
128
+
129
+ return {
130
+ trippedNow,
131
+ open: this.isOpen(),
132
+ snapshot: this.snapshot(),
133
+ };
134
+ }
135
+
136
+ assertClosed(operation = "operation") {
137
+ if (!this.isOpen()) return;
138
+ const detail = this.lastFault?.message ? `: ${this.lastFault.message}` : "";
139
+ throw new WasmFaultError(
140
+ buildFault({
141
+ exportName: this.lastFault?.exportName || operation,
142
+ exit: this.lastFault?.exit ?? "trap: circuit_open",
143
+ errors: this.lastFault?.errors || [],
144
+ trapped: !!this.lastFault?.trapped,
145
+ fatal: true,
146
+ at: this.clock(),
147
+ }),
148
+ { cause: new Error(`InstantRecord circuit breaker is open during ${operation}${detail}`) },
149
+ );
150
+ }
151
+
152
+ reset() {
153
+ this.state = "closed";
154
+ this.consecutiveByExport.clear();
155
+ this.consecutiveFailures = 0;
156
+ this.trippedAt = null;
157
+ this.tripReason = null;
158
+ }
159
+
160
+ snapshot() {
161
+ return {
162
+ state: this.state,
163
+ consecutiveFailures: this.consecutiveFailures,
164
+ consecutiveByExport: Object.fromEntries(this.consecutiveByExport.entries()),
165
+ maxConsecutiveFailures: this.maxConsecutiveFailures,
166
+ totalFaults: this.totalFaults,
167
+ trippedAt: this.trippedAt,
168
+ tripReason: this.tripReason,
169
+ lastFault: this.lastFault,
170
+ };
171
+ }
172
+ }
@@ -0,0 +1,347 @@
1
+ // Opt-in rolling flight recorder for InstantRecord's WASI reactor boundary.
2
+ // Uses a two-epoch ring buffer so exported `.irtrace` files always start from
3
+ // a consistent base DB checkpoint (with SHA-256 digest and schema-aware PII
4
+ // redaction) immediately preceding `steps[0]`.
5
+ import { Redactor } from "./redactor.js";
6
+ import { bytesToBase64, sha256Hex } from "./sha256.js";
7
+
8
+ export const TRACE_FORMAT = "instant_record.trace";
9
+ export const TRACE_VERSION = 1;
10
+ const DEFAULT_MAX_ENTRIES = 100;
11
+ const DEFAULT_MAX_CHECKPOINT_BYTES = 8 * 1024 * 1024;
12
+ const decoder = new TextDecoder();
13
+
14
+ function isValidUtf8(bytes) {
15
+ try {
16
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
17
+ return true;
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ function copyBytes(bytes) {
24
+ if (!bytes) return null;
25
+ const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
26
+ return arr.slice();
27
+ }
28
+
29
+ export class FlightRecorder {
30
+ constructor({
31
+ enabled = false,
32
+ maxEntries = DEFAULT_MAX_ENTRIES,
33
+ checkpointEvery = null,
34
+ maxCheckpointBytes = DEFAULT_MAX_CHECKPOINT_BYTES,
35
+ schema = {},
36
+ piiColumns = {},
37
+ safeColumns = {},
38
+ salt = null,
39
+ clock = () => Date.now(),
40
+ } = {}) {
41
+ this.enabled = !!enabled;
42
+ this.maxEntries = Math.max(1, Number(maxEntries) || DEFAULT_MAX_ENTRIES);
43
+ this.checkpointEvery = Math.max(1, Number(checkpointEvery) || Math.max(1, Math.floor(this.maxEntries / 2)));
44
+ this.maxCheckpointBytes = Math.max(0, Number(maxCheckpointBytes) || DEFAULT_MAX_CHECKPOINT_BYTES);
45
+ this.schema = schema || {};
46
+ this.piiColumns = piiColumns || {};
47
+ this.safeColumns = safeColumns || {};
48
+ this.salt = salt || null;
49
+ this.clock = clock;
50
+
51
+ this.seq = 0;
52
+ this.droppedEntries = 0;
53
+ this.epochs = [];
54
+ this.faults = [];
55
+ this.meta = {};
56
+ }
57
+
58
+ configure(options = {}) {
59
+ if (typeof options.enabled === "boolean") this.enabled = options.enabled;
60
+ if (options.maxEntries != null) {
61
+ this.maxEntries = Math.max(1, Number(options.maxEntries) || DEFAULT_MAX_ENTRIES);
62
+ this.checkpointEvery = Math.max(1, Number(options.checkpointEvery) || Math.max(1, Math.floor(this.maxEntries / 2)));
63
+ }
64
+ if (options.checkpointEvery != null) {
65
+ this.checkpointEvery = Math.max(1, Number(options.checkpointEvery));
66
+ }
67
+ if (options.maxCheckpointBytes != null) {
68
+ this.maxCheckpointBytes = Math.max(0, Number(options.maxCheckpointBytes));
69
+ }
70
+ if (options.schema) this.schema = options.schema;
71
+ if (options.piiColumns) this.piiColumns = options.piiColumns;
72
+ if (options.safeColumns) this.safeColumns = options.safeColumns;
73
+ if (options.salt) this.salt = options.salt;
74
+ if (options.meta) this.meta = { ...this.meta, ...options.meta };
75
+ if (!this.enabled) return this.status();
76
+ return this.status();
77
+ }
78
+
79
+ clear() {
80
+ this.epochs = [];
81
+ this.faults = [];
82
+ this.droppedEntries = 0;
83
+ this.seq = 0;
84
+ }
85
+
86
+ captureCheckpoint({ dbBytes = null, schemaVersion = 0, env = {}, cookies = {} } = {}) {
87
+ if (!this.enabled) return null;
88
+ const copied = copyBytes(dbBytes);
89
+ const checkpoint = {
90
+ capturedAt: this.clock(),
91
+ dbBytes: copied,
92
+ digest: copied ? sha256Hex(copied) : null,
93
+ byteLength: copied ? copied.length : 0,
94
+ schemaVersion: Number(schemaVersion) || 0,
95
+ env: { ...env },
96
+ cookies: cookies instanceof Map ? Object.fromEntries(cookies.entries()) : { ...(cookies || {}) },
97
+ };
98
+ this.epochs = [{ checkpoint, steps: [] }];
99
+ return checkpoint;
100
+ }
101
+
102
+ ensureEpoch(hostSnapshot) {
103
+ if (this.epochs.length === 0) {
104
+ this.captureCheckpoint(hostSnapshot || {});
105
+ return;
106
+ }
107
+ const newest = this.epochs[this.epochs.length - 1];
108
+ if (newest.steps.length >= this.checkpointEvery && hostSnapshot) {
109
+ const copied = copyBytes(hostSnapshot.dbBytes);
110
+ this.epochs.push({
111
+ checkpoint: {
112
+ capturedAt: this.clock(),
113
+ dbBytes: copied,
114
+ digest: copied ? sha256Hex(copied) : null,
115
+ byteLength: copied ? copied.length : 0,
116
+ schemaVersion: Number(hostSnapshot.schemaVersion) || 0,
117
+ env: { ...(hostSnapshot.env || {}) },
118
+ cookies: hostSnapshot.cookies instanceof Map
119
+ ? Object.fromEntries(hostSnapshot.cookies.entries())
120
+ : { ...(hostSnapshot.cookies || {}) },
121
+ },
122
+ steps: [],
123
+ });
124
+ }
125
+ }
126
+
127
+ recordStep({ exportName, inputBytes, exchanges = [], outcome = {}, preCallSnapshot = null }) {
128
+ if (!this.enabled) return null;
129
+ this.ensureEpoch(preCallSnapshot);
130
+
131
+ const bytes = copyBytes(inputBytes) || new Uint8Array();
132
+ const step = {
133
+ seq: ++this.seq,
134
+ at: this.clock(),
135
+ exportName,
136
+ inputBytes: bytes,
137
+ exchanges: exchanges.map((ex) => ({
138
+ method: ex.method,
139
+ url: ex.url,
140
+ requestBody: ex.requestBody ?? "",
141
+ status: ex.status ?? 0,
142
+ responseBody: ex.responseBody ?? "",
143
+ })),
144
+ outcome: {
145
+ exit: outcome.exit,
146
+ trapped: !!outcome.trapped,
147
+ errors: Array.isArray(outcome.errors) ? outcome.errors.slice() : [],
148
+ outDigest: outcome.out ? sha256Hex(outcome.out) : null,
149
+ outByteLength: outcome.out ? outcome.out.length : 0,
150
+ events: Array.isArray(outcome.events) ? outcome.events.map((e) => ({ ...e })) : [],
151
+ fault: outcome.fault ? { ...outcome.fault } : null,
152
+ },
153
+ };
154
+
155
+ const current = this.epochs[this.epochs.length - 1];
156
+ current.steps.push(step);
157
+
158
+ if (step.outcome.fault) {
159
+ this.faults.push({ seq: step.seq, ...step.outcome.fault });
160
+ if (this.faults.length > this.maxEntries) this.faults.shift();
161
+ }
162
+
163
+ this.pruneEpochs();
164
+ return step;
165
+ }
166
+
167
+ pruneEpochs() {
168
+ while (this.epochs.length > 1 && this.totalSteps() > this.maxEntries) {
169
+ const dropped = this.epochs.shift();
170
+ this.droppedEntries += dropped.steps.length;
171
+ }
172
+ }
173
+
174
+ totalSteps() {
175
+ return this.epochs.reduce((sum, epoch) => sum + epoch.steps.length, 0);
176
+ }
177
+
178
+ status() {
179
+ const base = this.epochs[0]?.checkpoint || null;
180
+ return {
181
+ enabled: this.enabled,
182
+ maxEntries: this.maxEntries,
183
+ stepCount: this.totalSteps(),
184
+ epochCount: this.epochs.length,
185
+ droppedEntries: this.droppedEntries,
186
+ faultCount: this.faults.length,
187
+ baseDigest: base?.digest || null,
188
+ baseByteLength: base?.byteLength || 0,
189
+ };
190
+ }
191
+
192
+ exportTrace({
193
+ redact = true,
194
+ includeUnredactedDatabase = false,
195
+ redactDatabase = null,
196
+ meta = {},
197
+ circuit = null,
198
+ } = {}) {
199
+ const redactor = redact
200
+ ? new Redactor({
201
+ schema: this.schema,
202
+ piiColumns: this.piiColumns,
203
+ safeColumns: this.safeColumns,
204
+ salt: this.salt,
205
+ })
206
+ : null;
207
+
208
+ const baseEpoch = this.epochs[0] || null;
209
+ const base = baseEpoch?.checkpoint || null;
210
+ const allSteps = this.epochs.flatMap((epoch) => epoch.steps);
211
+
212
+ let checkpoint;
213
+ if (!base || !base.dbBytes || base.dbBytes.length === 0) {
214
+ checkpoint = {
215
+ mode: "empty",
216
+ digest: null,
217
+ originalDigest: null,
218
+ byteLength: 0,
219
+ schemaVersion: base?.schemaVersion || 0,
220
+ encoding: null,
221
+ data: null,
222
+ redacted: true,
223
+ cookies: redactor ? redactor.redactCookies(base?.cookies || {}) : { ...(base?.cookies || {}) },
224
+ env: redactor ? redactor.redactEnv(base?.env || {}) : { ...(base?.env || {}) },
225
+ };
226
+ } else if (base.dbBytes.length > this.maxCheckpointBytes) {
227
+ checkpoint = {
228
+ mode: "digest",
229
+ digest: base.digest,
230
+ originalDigest: base.digest,
231
+ byteLength: base.byteLength,
232
+ schemaVersion: base.schemaVersion,
233
+ encoding: null,
234
+ data: null,
235
+ redacted: true,
236
+ omittedReason: "exceeds_budget",
237
+ cookies: redactor ? redactor.redactCookies(base.cookies) : { ...base.cookies },
238
+ env: redactor ? redactor.redactEnv(base.env) : { ...base.env },
239
+ };
240
+ } else if (!redact || includeUnredactedDatabase) {
241
+ checkpoint = {
242
+ mode: "sqlite3",
243
+ digest: base.digest,
244
+ originalDigest: base.digest,
245
+ byteLength: base.byteLength,
246
+ schemaVersion: base.schemaVersion,
247
+ encoding: "base64",
248
+ data: bytesToBase64(base.dbBytes),
249
+ redacted: false,
250
+ cookies: redactor ? redactor.redactCookies(base.cookies) : { ...base.cookies },
251
+ env: redactor ? redactor.redactEnv(base.env) : { ...base.env },
252
+ };
253
+ } else if (typeof redactDatabase === "function") {
254
+ const dbResult = redactDatabase(base.dbBytes, redactor);
255
+ const redactedBytes = copyBytes(dbResult.bytes);
256
+ checkpoint = {
257
+ mode: "sqlite3",
258
+ digest: dbResult.digest || sha256Hex(redactedBytes),
259
+ originalDigest: base.digest,
260
+ byteLength: redactedBytes.length,
261
+ schemaVersion: base.schemaVersion,
262
+ encoding: "base64",
263
+ data: bytesToBase64(redactedBytes),
264
+ redacted: true,
265
+ redactedColumns: dbResult.redactedColumns || {},
266
+ cookies: redactor.redactCookies(base.cookies),
267
+ env: redactor.redactEnv(base.env),
268
+ };
269
+ } else if (!redactor.hasSchemaPii()) {
270
+ checkpoint = {
271
+ mode: "sqlite3",
272
+ digest: base.digest,
273
+ originalDigest: base.digest,
274
+ byteLength: base.byteLength,
275
+ schemaVersion: base.schemaVersion,
276
+ encoding: "base64",
277
+ data: bytesToBase64(base.dbBytes),
278
+ redacted: true,
279
+ redactedColumns: {},
280
+ cookies: redactor.redactCookies(base.cookies),
281
+ env: redactor.redactEnv(base.env),
282
+ };
283
+ } else {
284
+ checkpoint = {
285
+ mode: "digest",
286
+ digest: base.digest,
287
+ originalDigest: base.digest,
288
+ byteLength: base.byteLength,
289
+ schemaVersion: base.schemaVersion,
290
+ encoding: null,
291
+ data: null,
292
+ redacted: true,
293
+ omittedReason: "pii_redaction_required",
294
+ piiColumns: redactor.schemaPiiMap(),
295
+ cookies: redactor.redactCookies(base.cookies),
296
+ env: redactor.redactEnv(base.env),
297
+ };
298
+ }
299
+
300
+ const steps = allSteps.map((step) => {
301
+ const utf8 = isValidUtf8(step.inputBytes);
302
+ let input;
303
+ if (utf8) {
304
+ const rawText = decoder.decode(step.inputBytes);
305
+ input = {
306
+ encoding: "utf8",
307
+ data: redactor ? redactor.redactWasiInput(step.exportName, rawText) : rawText,
308
+ };
309
+ } else {
310
+ input = {
311
+ encoding: "base64",
312
+ data: bytesToBase64(step.inputBytes),
313
+ };
314
+ }
315
+ return {
316
+ seq: step.seq,
317
+ at: step.at,
318
+ exportName: step.exportName,
319
+ input,
320
+ exchanges: step.exchanges.map((ex) => (redactor ? redactor.redactExchange(ex) : { ...ex })),
321
+ outcome: {
322
+ ...step.outcome,
323
+ events: step.outcome.events.map((ev) => (redactor ? redactor.redactNotification(ev) : { ...ev })),
324
+ },
325
+ };
326
+ });
327
+
328
+ return {
329
+ format: TRACE_FORMAT,
330
+ version: TRACE_VERSION,
331
+ recordedAt: new Date(this.clock()).toISOString(),
332
+ meta: {
333
+ ...this.meta,
334
+ ...meta,
335
+ maxEntries: this.maxEntries,
336
+ droppedEntries: this.droppedEntries,
337
+ },
338
+ redaction: redactor
339
+ ? redactor.manifest()
340
+ : { enabled: false, strategy: "none", schema: {}, redactedColumns: {}, redactedFields: [] },
341
+ checkpoint,
342
+ steps,
343
+ faults: this.faults.map((f) => ({ ...f })),
344
+ circuit: circuit || null,
345
+ };
346
+ }
347
+ }