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
data/frontend/files.js ADDED
@@ -0,0 +1,738 @@
1
+ // A record's file, kept in the browser.
2
+ //
3
+ // A model that declares `sync_file` has records that carry a file: bytes too
4
+ // large for a column (a recording, a render). The record syncs as any other
5
+ // does. Its bytes are kept here, in the origin's private file system, where
6
+ // they are at hand with no connection:
7
+ //
8
+ // import { fileStore } from "instant_record"
9
+ // const files = fileStore()
10
+ //
11
+ // const id = crypto.randomUUID()
12
+ // const about = await files.attach("Recording", id, blob) // written here first
13
+ // // ...create the record with that id; `about` is { filename, content_type, byte_size }
14
+ //
15
+ // const file = await files.open("Recording", id) // here, or fetched and kept
16
+ //
17
+ // A file written here is sent to the server in the background, in pieces, and
18
+ // goes on from where it stopped after a reload or a lost connection. A file
19
+ // made on another device is fetched when it is asked for, a piece at a time,
20
+ // and kept. A file never changes: new bytes are a new record.
21
+ //
22
+ // Room is the browser's to give. A file the server holds can be fetched
23
+ // again, so it may be dropped here to make room, least recently used first. A
24
+ // file the server does not hold yet is never dropped, and neither is a pinned
25
+ // one. Nothing here needs a local database: beside the compiled runtime and on
26
+ // a page Rails serves it does the same thing.
27
+
28
+ const ROOT = "instant-record-files"
29
+ const META = "meta"
30
+ // 512 KiB stays safely below common 1-2 MB reverse-proxy request body ceilings.
31
+ export const DEFAULT_CHUNK_SIZE = 512 * 1024
32
+ const CHANGED = "instant-record:records-changed"
33
+ const RETRY_BASE_MS = 2000
34
+ const RETRY_CAP_MS = 60000
35
+ // What `usedAt` is good for is an order, so it is not rewritten on every read.
36
+ const TOUCH_MS = 60000
37
+
38
+ // The server does not hold the file: its record has not reached it, the
39
+ // upload has not finished, or the asker may not see it.
40
+ export class FileMissing extends Error {
41
+ constructor(type, id) {
42
+ super(`${type} ${id} has no file on the server`)
43
+ this.name = "FileMissing"
44
+ }
45
+ }
46
+
47
+ // No room for the bytes, after everything that may be dropped was.
48
+ export class NoRoom extends Error {
49
+ constructor(bytes) {
50
+ super(`No room to keep ${bytes} bytes`)
51
+ this.name = "QuotaExceededError"
52
+ this.bytes = bytes
53
+ }
54
+ }
55
+
56
+ const safe = (name) => encodeURIComponent(String(name)).replace(/^\./, "%2E")
57
+ const token = () => (globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`).replace(/[^\w-]/g, "")
58
+ const full = (error) => error?.name === "QuotaExceededError"
59
+ const missing = (error) => error?.name === "NotFoundError"
60
+
61
+ async function entries(folder) {
62
+ const found = []
63
+ for await (const [name, handle] of folder.entries()) found.push([name, handle])
64
+ return found
65
+ }
66
+
67
+ export class FileStore {
68
+ #root = null
69
+ #listeners = new Set()
70
+ #downloads = new Map()
71
+ #chains = new Map()
72
+ #syncing = null
73
+ #again = false
74
+ #timer = null
75
+ #retryMs = RETRY_BASE_MS
76
+ #stops = []
77
+ #asked = false
78
+
79
+ constructor(options = {}) {
80
+ const page = typeof window === "undefined" ? {} : window.__spinel || {}
81
+ this.endpoint = String(options.endpoint ?? page.endpoint ?? "/instant_record").replace(/\/$/, "")
82
+ // Who is asking, for a server that reads it from a `scope` parameter. A
83
+ // server that reads its session gets the cookie instead.
84
+ this.scope = options.scope ?? page.scope ?? ""
85
+ // Files of different accounts in one browser stay apart under a name.
86
+ this.name = options.name ? safe(options.name) : ""
87
+ const configuredChunkSize = options.chunkSize ?? options.pieceSize ?? page.chunkSize ?? page.pieceSize ?? DEFAULT_CHUNK_SIZE
88
+ if (!Number.isInteger(configuredChunkSize) || configuredChunkSize <= 0) {
89
+ throw new RangeError("chunkSize must be a positive integer")
90
+ }
91
+ this.pieceSize = configuredChunkSize
92
+ // The most bytes to hold here. Past it, or near the browser's own limit,
93
+ // files the server holds are dropped to make room.
94
+ this.budget = options.budget ?? Infinity
95
+ this.headroom = options.headroom ?? 0.9
96
+ this.persistent = options.persist ?? true
97
+ this.storage = options.storage ?? globalThis.navigator?.storage
98
+ this.locks = options.locks === undefined ? globalThis.navigator?.locks : options.locks
99
+ this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args))
100
+ this.channel = options.channel === undefined && typeof BroadcastChannel !== "undefined"
101
+ ? new BroadcastChannel(`${ROOT}/${this.name}`)
102
+ : options.channel || null
103
+ if (this.channel) this.channel.onmessage = (event) => this.#tell({ ...event.data, remote: true })
104
+ }
105
+
106
+ // True where the browser has a private file system that can be written from
107
+ // a page. Without one, `open` still reads from the server and keeps nothing.
108
+ get supported() {
109
+ return typeof this.storage?.getDirectory === "function"
110
+ }
111
+
112
+ get chunkSize() {
113
+ return this.pieceSize
114
+ }
115
+
116
+ set chunkSize(value) {
117
+ if (!Number.isInteger(value) || value <= 0) throw new RangeError("chunkSize must be a positive integer")
118
+ this.pieceSize = value
119
+ }
120
+
121
+ // ── writing ────────────────────────────────────────────────────────────────
122
+
123
+ // Keep `blob` as the file of the record `type`/`id`, and queue it for the
124
+ // server. Answers what a record says about its file, under the names an
125
+ // Active Storage blob uses, for the form that creates the record.
126
+ async attach(type, id, blob, { name, contentType, pinned = false } = {}) {
127
+ if (!blob?.size) throw new TypeError("A file needs bytes")
128
+ if (!this.supported) throw new Error("This browser has no private file system to keep a file in")
129
+ if (this.persistent && !this.#asked) {
130
+ this.#asked = true
131
+ this.persist()
132
+ }
133
+ const meta = {
134
+ type: String(type), id: String(id), name: name ?? blob.name ?? "", contentType: contentType ?? blob.type ?? "",
135
+ size: blob.size, piece: this.pieceSize, upload: token(), complete: false, uploaded: false, pinned,
136
+ addedAt: Date.now(), usedAt: Date.now(),
137
+ }
138
+ await this.#locked(meta, async () => {
139
+ if (await this.#meta(type, id)) throw new Error(`${type} ${id} already has a file. A new file is a new record.`)
140
+ await this.#room(meta, meta.size)
141
+ try {
142
+ // Whatever an interrupted attach left here is not part of this file.
143
+ await this.#drop(meta)
144
+ const folder = await this.#folder(type, id, true)
145
+ await this.#write(folder, META, JSON.stringify(meta))
146
+ for (let index = 0; index * meta.piece < meta.size; index++) {
147
+ await this.#piece(folder, index, blob.slice(index * meta.piece, (index + 1) * meta.piece), meta)
148
+ }
149
+ meta.complete = true
150
+ await this.#write(folder, META, JSON.stringify(meta))
151
+ } catch (error) {
152
+ await this.#drop(meta)
153
+ throw full(error) ? new NoRoom(blob.size) : error
154
+ }
155
+ })
156
+ this.#announce("added", meta)
157
+ this.sync()
158
+ return { filename: meta.name, content_type: meta.contentType, byte_size: meta.size }
159
+ }
160
+
161
+ // ── reading ────────────────────────────────────────────────────────────────
162
+
163
+ // The file if it is here, else null. Asks nothing of the server.
164
+ async get(type, id, { touch = true } = {}) {
165
+ const meta = await this.#meta(type, id)
166
+ if (!meta?.complete) return null
167
+ try {
168
+ const folder = await this.#folder(type, id)
169
+ const parts = []
170
+ for (let index = 0; index * meta.piece < meta.size; index++) {
171
+ parts.push(await (await folder.getFileHandle(String(index))).getFile())
172
+ }
173
+ if (touch && Date.now() - meta.usedAt > TOUCH_MS) {
174
+ this.#write(folder, META, JSON.stringify({ ...meta, usedAt: Date.now() })).catch(() => {})
175
+ }
176
+ return new File(parts, meta.name || meta.id, { type: meta.contentType })
177
+ } catch (error) {
178
+ if (!missing(error)) throw error
179
+ // A piece is gone: the browser cleared it, or another tab is dropping
180
+ // the file. What is left is no file.
181
+ return null
182
+ }
183
+ }
184
+
185
+ // The file: from here, or fetched from the server and kept. Throws
186
+ // FileMissing when the server does not hold it, and whatever `fetch` throws
187
+ // when there is no connection.
188
+ async open(type, id, options = {}) {
189
+ return (await this.get(type, id)) || this.download(type, id, options)
190
+ }
191
+
192
+ // An address for an <audio> or an <img>. The caller revokes it.
193
+ async url(type, id, options) {
194
+ return URL.createObjectURL(await this.open(type, id, options))
195
+ }
196
+
197
+ // Fetch a file from the server and keep it, as `open` does for one that is
198
+ // not here: a piece at a time, going on from the pieces already held.
199
+ // `onProgress` is told { received, size }.
200
+ download(type, id, { onProgress, signal } = {}) {
201
+ const key = `${type}/${id}`
202
+ if (!this.#downloads.has(key)) {
203
+ const fetching = this.#download(String(type), String(id), onProgress, signal)
204
+ .finally(() => this.#downloads.delete(key))
205
+ this.#downloads.set(key, fetching)
206
+ }
207
+ return this.#downloads.get(key)
208
+ }
209
+
210
+ // ── what is here ───────────────────────────────────────────────────────────
211
+
212
+ // What is known here about a record's file, or null: { type, id, name,
213
+ // contentType, size, local, uploaded, pinned, failed, addedAt, usedAt }.
214
+ // `local` says the whole file is here. `uploaded` says the server holds it.
215
+ async stat(type, id) {
216
+ const meta = await this.#meta(type, id)
217
+ return meta && this.#shown(meta)
218
+ }
219
+
220
+ async list() {
221
+ return (await this.#metas()).map((meta) => this.#shown(meta))
222
+ }
223
+
224
+ // How much is held and how much room there is: { files, bytes, waiting,
225
+ // waitingBytes, quota, usage, persisted }. `waiting` counts the files the
226
+ // server does not hold yet. `quota` and `usage` are the browser's estimate
227
+ // for the whole origin, null where it gives none.
228
+ async usage() {
229
+ const metas = await this.#metas()
230
+ const held = metas.filter((meta) => meta.complete)
231
+ const waiting = held.filter((meta) => !meta.uploaded)
232
+ const estimate = await this.#estimate()
233
+ return {
234
+ files: held.length,
235
+ // A file that is half fetched counts whole: its room is spoken for.
236
+ bytes: metas.reduce((sum, meta) => sum + meta.size, 0),
237
+ waiting: waiting.length,
238
+ waitingBytes: waiting.reduce((sum, meta) => sum + meta.size, 0),
239
+ quota: estimate.quota ?? null,
240
+ usage: estimate.usage ?? null,
241
+ persisted: (await this.storage?.persisted?.().catch(() => false)) ?? false,
242
+ }
243
+ }
244
+
245
+ // Ask the browser not to clear this origin's storage when the disk fills.
246
+ // Without it a browser short of room may drop everything, files the server
247
+ // never received among them. Answers whether it agreed.
248
+ async persist() {
249
+ try {
250
+ return (await this.storage?.persist?.()) ?? false
251
+ } catch {
252
+ return false
253
+ }
254
+ }
255
+
256
+ // ── keeping and dropping ───────────────────────────────────────────────────
257
+
258
+ // A pinned file is never dropped to make room.
259
+ pin(type, id) { return this.#mark(type, id, { pinned: true }) }
260
+ unpin(type, id) { return this.#mark(type, id, { pinned: false }) }
261
+
262
+ // Drop a file from here, whether or not the server holds it.
263
+ async remove(type, id) {
264
+ const meta = (await this.#meta(type, id)) || { type: String(type), id: String(id) }
265
+ await this.#locked(meta, () => this.#drop(meta))
266
+ this.#announce("removed", meta)
267
+ }
268
+
269
+ // Drop the files of `type` whose records are gone: every one whose id is
270
+ // not in `ids`. A page that has the list of records calls this with it.
271
+ async prune(type, ids) {
272
+ const kept = new Set([...ids].map(String))
273
+ const gone = (await this.#metas()).filter((meta) => meta.type === String(type) && !kept.has(meta.id))
274
+ for (const meta of gone) await this.remove(meta.type, meta.id)
275
+ return gone.length
276
+ }
277
+
278
+ // Drop everything, or every file of one type: for a sign-out.
279
+ async clear(type) {
280
+ const gone = (await this.#metas()).filter((meta) => type === undefined || meta.type === String(type))
281
+ for (const meta of gone) await this.remove(meta.type, meta.id)
282
+ return gone.length
283
+ }
284
+
285
+ // Make room for `bytes` by dropping files the server holds, least recently
286
+ // used first. Answers how many bytes went.
287
+ free(bytes) {
288
+ return this.#evict(bytes, null)
289
+ }
290
+
291
+ // ── sending ────────────────────────────────────────────────────────────────
292
+
293
+ // Send the files the server does not hold yet. One pass runs at a time, in
294
+ // one tab at a time, and a call made during a pass makes it go round again.
295
+ // Answers { sent, waiting }: `waiting` files were not taken, because their
296
+ // record has not reached the server or the connection dropped.
297
+ sync() {
298
+ if (this.#syncing) {
299
+ this.#again = true
300
+ return this.#syncing
301
+ }
302
+ this.#syncing = (async () => {
303
+ let result = { sent: 0, waiting: 0 }
304
+ do {
305
+ this.#again = false
306
+ const pass = await this.#exclusive("upload", () => this.#drain(), { ifAvailable: true })
307
+ // Another tab is sending. It is asked to look again when it is done,
308
+ // and this one looks again later in case that tab is closed first.
309
+ if (!pass) {
310
+ this.channel?.postMessage({ event: "sync" })
311
+ this.#later(1)
312
+ } else result = { sent: result.sent + pass.sent, waiting: pass.waiting }
313
+ } while (this.#again)
314
+ return result
315
+ })().finally(() => { this.#syncing = null })
316
+ return this.#syncing
317
+ }
318
+
319
+ // Send what is waiting whenever it may get through: now, when the
320
+ // connection returns, when the local database changes (a record may have
321
+ // reached the server), and after a wait that lengthens while nothing does.
322
+ start() {
323
+ if (this.#stops.length || typeof window === "undefined") return this
324
+ const kick = () => { this.#retryMs = RETRY_BASE_MS; this.sync() }
325
+ for (const name of ["online", CHANGED]) {
326
+ window.addEventListener(name, kick)
327
+ this.#stops.push(() => window.removeEventListener(name, kick))
328
+ }
329
+ this.#stops.push(this.subscribe((detail) => {
330
+ if (detail.event === "sync" && detail.remote) this.sync()
331
+ // After a pass, come back for whatever it left.
332
+ if (detail.event === "synced" && !detail.remote) this.#later(detail.waiting)
333
+ }))
334
+ this.tidy().then(kick, kick)
335
+ return this
336
+ }
337
+
338
+ stop() {
339
+ clearTimeout(this.#timer)
340
+ this.#timer = null
341
+ for (const stop of this.#stops.splice(0)) stop()
342
+ }
343
+
344
+ // Told of everything that happens to a file, here or in another tab:
345
+ // { event, type, id, ... } where event is added, progress, uploaded, failed,
346
+ // fetched, evicted or removed. Answers a function that stops the telling.
347
+ subscribe(listener) {
348
+ this.#listeners.add(listener)
349
+ return () => this.#listeners.delete(listener)
350
+ }
351
+
352
+ // Remove what an interrupted `attach` left: pieces of a file that was never
353
+ // whole and that the server never had.
354
+ async tidy() {
355
+ const dead = (await this.#metas({ torn: true })).filter((meta) => !meta.complete && !meta.uploaded)
356
+ for (const meta of dead) {
357
+ await this.#locked(meta, async () => {
358
+ const now = await this.#meta(meta.type, meta.id, { torn: true })
359
+ if (!now || (!now.complete && !now.uploaded)) await this.#drop(meta)
360
+ }, { ifAvailable: true })
361
+ }
362
+ return dead.length
363
+ }
364
+
365
+ // The file's address on the server.
366
+ serverUrl(type, id, params = {}, path = "") {
367
+ const url = new URL(`${this.endpoint}/files/${encodeURIComponent(type)}/${encodeURIComponent(id)}${path}`,
368
+ globalThis.location?.href || "http://localhost")
369
+ if (this.scope) url.searchParams.set("scope", this.scope)
370
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, String(value))
371
+ return url.href
372
+ }
373
+
374
+ // ── inside ─────────────────────────────────────────────────────────────────
375
+
376
+ async #download(type, id, onProgress, signal) {
377
+ if (!this.supported) return this.#whole(type, id, signal)
378
+ const lock = { type, id }
379
+ let unkept = false
380
+ const fetched = await this.#locked(lock, async () => {
381
+ // Another tab may have fetched it while this one waited.
382
+ const here = await this.get(type, id)
383
+ if (here) return here
384
+
385
+ // Pieces of a fetch that was cut off are kept and built on. Anything
386
+ // else that is here is not this file: the server is asked afresh.
387
+ let meta = await this.#meta(type, id)
388
+ if (!meta?.uploaded || meta.complete) {
389
+ const head = await this.#ask(this.serverUrl(type, id), { method: "HEAD", signal })
390
+ if (head.status === 404) throw new FileMissing(type, id)
391
+ if (!head.ok) throw new Error(`The server answered ${head.status} for ${type} ${id}`)
392
+ await this.#drop({ type, id })
393
+ const advertised = Number(head.headers.get("x-instant-record-chunk-size"))
394
+ const piece = Number.isInteger(advertised) && advertised > 0 ? Math.min(this.pieceSize, advertised) : this.pieceSize
395
+ meta = {
396
+ type, id, name: "", contentType: head.headers.get("content-type") || "",
397
+ size: Number(head.headers.get("content-length")), piece, upload: null,
398
+ complete: false, uploaded: true, pinned: false, addedAt: Date.now(), usedAt: Date.now(),
399
+ }
400
+ if (!(meta.size > 0)) throw new Error(`The server gave no size for ${type} ${id}`)
401
+ }
402
+ try {
403
+ const folder = await this.#folder(type, id, true)
404
+ const held = await this.#held(folder, meta)
405
+ await this.#room(meta, meta.size - held.length * meta.piece)
406
+ await this.#write(folder, META, JSON.stringify(meta))
407
+ for (let index = 0; index * meta.piece < meta.size; index++) {
408
+ const from = index * meta.piece
409
+ const to = Math.min(from + meta.piece, meta.size) - 1
410
+ if (!held.includes(index)) {
411
+ const reply = await this.#ask(this.serverUrl(type, id), { headers: { Range: `bytes=${from}-${to}` }, signal })
412
+ if (reply.status === 404) throw new FileMissing(type, id)
413
+ if (!reply.ok) throw new Error(`The server answered ${reply.status} for ${type} ${id}`)
414
+ let piece = await reply.blob()
415
+ // A server that takes no ranges sends the whole file every time.
416
+ if (reply.status === 200 && piece.size === meta.size) piece = piece.slice(from, to + 1)
417
+ if (piece.size !== to - from + 1) throw new Error(`A piece of ${type} ${id} arrived the wrong size`)
418
+ await this.#piece(folder, index, piece, meta)
419
+ }
420
+ onProgress?.({ received: to + 1, size: meta.size })
421
+ this.#tell({ event: "progress", type, id, received: to + 1, size: meta.size })
422
+ }
423
+ meta.complete = true
424
+ await this.#write(folder, META, JSON.stringify(meta))
425
+ return this.get(type, id, { touch: false })
426
+ } catch (error) {
427
+ if (!full(error)) throw error
428
+ // No room for it even after dropping what could go: the pieces are
429
+ // given back, and the file is read without being kept.
430
+ await this.#drop(meta)
431
+ unkept = true
432
+ }
433
+ })
434
+ if (unkept) return this.#whole(type, id, signal)
435
+ this.#announce("fetched", lock)
436
+ return fetched
437
+ }
438
+
439
+ // The file read straight from the server, into memory, and not kept.
440
+ async #whole(type, id, signal) {
441
+ const reply = await this.#ask(this.serverUrl(type, id), { signal })
442
+ if (reply.status === 404) throw new FileMissing(type, id)
443
+ if (!reply.ok) throw new Error(`The server answered ${reply.status} for ${type} ${id}`)
444
+ const blob = await reply.blob()
445
+ return new File([blob], String(id), { type: reply.headers.get("content-type") || blob.type })
446
+ }
447
+
448
+ async #drain() {
449
+ const waiting = (await this.#metas())
450
+ .filter((meta) => meta.complete && !meta.uploaded && !meta.failed)
451
+ .sort((a, b) => a.addedAt - b.addedAt)
452
+ let sent = 0
453
+ let left = 0
454
+ for (const meta of waiting) {
455
+ try {
456
+ (await this.#send(meta)) ? sent++ : left++
457
+ } catch {
458
+ // No connection, or a server in trouble: the rest wait with this one.
459
+ left = waiting.length - sent
460
+ break
461
+ }
462
+ }
463
+ this.#tell({ event: "synced", sent, waiting: left })
464
+ return { sent, waiting: left }
465
+ }
466
+
467
+ // One file to the server, from wherever its upload stands. Answers whether
468
+ // the server now holds it.
469
+ async #send(meta) {
470
+ const blob = await this.get(meta.type, meta.id, { touch: false })
471
+ if (!blob) return false
472
+ const standing = await this.#ask(this.serverUrl(meta.type, meta.id, { upload: meta.upload }, "/upload"))
473
+ // The record has not reached the server yet. It goes up with the next
474
+ // sync pass, and this is asked again after it.
475
+ if (standing.status === 404) return false
476
+ if (!standing.ok) throw new Error(`The server answered ${standing.status}`)
477
+ let { complete, offset, chunk_size: serverChunkSize } = await standing.json()
478
+ let step = Number.isInteger(serverChunkSize) && serverChunkSize > 0 ? Math.min(this.pieceSize, serverChunkSize) : this.pieceSize
479
+
480
+ for (let turns = 0; !complete; turns++) {
481
+ // Every turn moves the offset forward. One that does not is a server
482
+ // and a browser that disagree, which no number of tries will settle.
483
+ if (turns > Math.ceil(meta.size / step) + 8) throw new Error("The upload is not moving")
484
+ const reply = await this.#ask(this.serverUrl(meta.type, meta.id, { upload: meta.upload, offset, size: meta.size }), {
485
+ method: "PUT", headers: { "content-type": "application/octet-stream" },
486
+ body: blob.slice(offset, offset + step),
487
+ })
488
+ if (reply.status === 404) return false
489
+ if (reply.status === 409) {
490
+ const conflict = await reply.json()
491
+ offset = conflict.offset
492
+ if (Number.isInteger(conflict.chunk_size) && conflict.chunk_size > 0) step = Math.min(step, conflict.chunk_size)
493
+ continue
494
+ }
495
+ if (reply.status === 413) {
496
+ const body = await reply.json().catch(() => ({}))
497
+ if (Number.isInteger(body.chunk_size) && body.chunk_size > 0 && body.chunk_size < step) {
498
+ step = body.chunk_size
499
+ continue
500
+ }
501
+ const failed = body.error || "refused (413)"
502
+ await this.#mark(meta.type, meta.id, { failed })
503
+ this.#announce("failed", meta, { reason: failed })
504
+ return false
505
+ }
506
+ if ([400, 415, 422].includes(reply.status)) {
507
+ // The server will not take this file however often it is sent.
508
+ const failed = (await reply.json().catch(() => ({}))).error || `refused (${reply.status})`
509
+ await this.#mark(meta.type, meta.id, { failed })
510
+ this.#announce("failed", meta, { reason: failed })
511
+ return false
512
+ }
513
+ if (!reply.ok) throw new Error(`The server answered ${reply.status}`)
514
+ const accepted = await reply.json()
515
+ ;({ complete, offset } = accepted)
516
+ if (Number.isInteger(accepted.chunk_size) && accepted.chunk_size > 0) step = Math.min(step, accepted.chunk_size)
517
+ this.#tell({ event: "progress", type: meta.type, id: meta.id, sent: offset, size: meta.size })
518
+ }
519
+ await this.#mark(meta.type, meta.id, { uploaded: true })
520
+ this.#announce("uploaded", meta)
521
+ return true
522
+ }
523
+
524
+ #later(waiting) {
525
+ clearTimeout(this.#timer)
526
+ this.#timer = null
527
+ if (!waiting || !this.#stops.length) {
528
+ this.#retryMs = RETRY_BASE_MS
529
+ return
530
+ }
531
+ this.#timer = setTimeout(() => this.sync(), this.#retryMs)
532
+ this.#retryMs = Math.min(this.#retryMs * 2, RETRY_CAP_MS)
533
+ }
534
+
535
+ async #ask(url, { signal, ...options } = {}) {
536
+ const limit = typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(120000) : undefined
537
+ const both = signal && limit && AbortSignal.any ? AbortSignal.any([signal, limit]) : signal || limit
538
+ return this.fetch(url, { credentials: "same-origin", ...options, signal: both })
539
+ }
540
+
541
+ // Room for the file `keep`, which has `bytes` still to write: inside this
542
+ // store's budget, and inside what the browser says the origin may hold.
543
+ async #room(keep, bytes) {
544
+ if (bytes <= 0) return
545
+ const estimate = await this.#estimate()
546
+ const others = (await this.#metas({ torn: true }))
547
+ .filter((meta) => !(meta.type === keep.type && meta.id === keep.id))
548
+ .reduce((sum, meta) => sum + meta.size, 0)
549
+ const over = Math.max(
550
+ others + keep.size - this.budget,
551
+ estimate.quota ? (estimate.usage || 0) + bytes - estimate.quota * this.headroom : 0,
552
+ )
553
+ if (over > 0 && (await this.#evict(over, keep)) < over) throw new NoRoom(bytes)
554
+ }
555
+
556
+ async #evict(bytes, keep) {
557
+ const droppable = (await this.#metas())
558
+ .filter((meta) => meta.uploaded && !meta.pinned && !(keep && meta.type === keep.type && meta.id === keep.id))
559
+ // A file that is half fetched goes before a whole one.
560
+ .sort((a, b) => Number(a.complete) - Number(b.complete) || a.usedAt - b.usedAt)
561
+ let freed = 0
562
+ for (const meta of droppable) {
563
+ if (freed >= bytes) break
564
+ if (this.#downloads.has(`${meta.type}/${meta.id}`)) continue
565
+ const dropped = await this.#locked(meta, async () => {
566
+ await this.#drop(meta)
567
+ return true
568
+ }, { ifAvailable: true })
569
+ if (!dropped) continue
570
+ freed += meta.size
571
+ this.#announce("evicted", meta)
572
+ }
573
+ return freed
574
+ }
575
+
576
+ async #estimate() {
577
+ try {
578
+ return (await this.storage?.estimate?.()) || {}
579
+ } catch {
580
+ return {}
581
+ }
582
+ }
583
+
584
+ // A piece is written whole or not at all: the browser swaps it in when the
585
+ // stream closes. A disk that fills on the way gets one more try, after
586
+ // dropping what may go.
587
+ async #piece(folder, index, blob, keep) {
588
+ try {
589
+ await this.#write(folder, String(index), blob)
590
+ } catch (error) {
591
+ if (!full(error) || (await this.#evict(blob.size, keep)) < blob.size) throw error
592
+ await this.#write(folder, String(index), blob)
593
+ }
594
+ }
595
+
596
+ async #write(folder, name, data) {
597
+ const handle = await folder.getFileHandle(name, { create: true })
598
+ const stream = await handle.createWritable()
599
+ try {
600
+ await stream.write(data)
601
+ await stream.close()
602
+ } catch (error) {
603
+ await stream.abort?.().catch(() => {})
604
+ throw error
605
+ }
606
+ }
607
+
608
+ // The indexes of the pieces already here.
609
+ async #held(folder, meta) {
610
+ const held = []
611
+ for (const [name] of await entries(folder)) {
612
+ const index = Number(name)
613
+ if (name !== META && Number.isInteger(index) && index * meta.piece < meta.size) held.push(index)
614
+ }
615
+ return held
616
+ }
617
+
618
+ async #mark(type, id, change) {
619
+ const lock = { type: String(type), id: String(id) }
620
+ return this.#locked(lock, async () => {
621
+ const meta = await this.#meta(type, id)
622
+ if (!meta) return false
623
+ await this.#write(await this.#folder(type, id), META, JSON.stringify({ ...meta, ...change }))
624
+ return true
625
+ })
626
+ }
627
+
628
+ async #drop({ type, id }) {
629
+ try {
630
+ const parent = await this.#folder(type)
631
+ await parent?.removeEntry(safe(id), { recursive: true })
632
+ } catch (error) {
633
+ if (!missing(error)) throw error
634
+ }
635
+ }
636
+
637
+ async #top() {
638
+ if (!this.supported) return null
639
+ if (!this.#root) {
640
+ this.#root = (async () => {
641
+ const origin = await this.storage.getDirectory()
642
+ const root = await origin.getDirectoryHandle(ROOT, { create: true })
643
+ return this.name ? root.getDirectoryHandle(`name-${this.name}`, { create: true }) : root
644
+ })()
645
+ this.#root.catch(() => { this.#root = null })
646
+ }
647
+ return this.#root
648
+ }
649
+
650
+ // The folder of a type, or of one record's file in it. Null when it is not
651
+ // there and is not to be made.
652
+ async #folder(type, id, create = false) {
653
+ try {
654
+ const top = await this.#top()
655
+ const types = await top?.getDirectoryHandle(`type-${safe(type)}`, { create })
656
+ return id === undefined ? types : await types?.getDirectoryHandle(safe(id), { create })
657
+ } catch (error) {
658
+ if (missing(error)) return null
659
+ throw error
660
+ }
661
+ }
662
+
663
+ // What is written beside a file's pieces. `torn` also answers for one that
664
+ // an interrupted attach left; nothing else looks at those.
665
+ async #meta(type, id, { torn = false } = {}) {
666
+ const folder = await this.#folder(type, id)
667
+ return folder ? this.#read(folder, torn) : null
668
+ }
669
+
670
+ async #read(folder, torn) {
671
+ try {
672
+ const meta = JSON.parse(await (await (await folder.getFileHandle(META)).getFile()).text())
673
+ return torn || meta.complete || meta.uploaded ? meta : null
674
+ } catch (error) {
675
+ if (missing(error) || error instanceof SyntaxError) return null
676
+ throw error
677
+ }
678
+ }
679
+
680
+ async #metas({ torn = false } = {}) {
681
+ const top = await this.#top()
682
+ if (!top) return []
683
+ const metas = []
684
+ for (const [name, types] of await entries(top)) {
685
+ if (types.kind !== "directory" || !name.startsWith("type-")) continue
686
+ for (const [, folder] of await entries(types)) {
687
+ const meta = folder.kind === "directory" && (await this.#read(folder, torn))
688
+ if (meta) metas.push(meta)
689
+ }
690
+ }
691
+ return metas
692
+ }
693
+
694
+ #shown(meta) {
695
+ return {
696
+ type: meta.type, id: meta.id, name: meta.name, contentType: meta.contentType, size: meta.size,
697
+ local: meta.complete, uploaded: meta.uploaded, pinned: meta.pinned, failed: meta.failed || null,
698
+ addedAt: meta.addedAt, usedAt: meta.usedAt,
699
+ }
700
+ }
701
+
702
+ #announce(event, { type, id }, more = {}) {
703
+ const detail = { event, type, id, ...more }
704
+ this.channel?.postMessage(detail)
705
+ this.#tell(detail)
706
+ }
707
+
708
+ #tell(detail) {
709
+ for (const listener of this.#listeners) listener(detail)
710
+ }
711
+
712
+ // One writer at a time for a file, across the tabs of this origin where the
713
+ // browser has locks and within this page where it has none.
714
+ #locked({ type, id }, work, options) {
715
+ return this.#exclusive(`file/${safe(type)}/${safe(id)}`, work, options)
716
+ }
717
+
718
+ #exclusive(name, work, { ifAvailable = false } = {}) {
719
+ const key = `${ROOT}/${this.name}/${name}`
720
+ if (this.locks) {
721
+ return this.locks.request(key, { ifAvailable }, (lock) => (lock ? work() : undefined))
722
+ }
723
+ const before = this.#chains.get(key)
724
+ if (before && ifAvailable) return Promise.resolve(undefined)
725
+ const run = (before || Promise.resolve()).catch(() => {}).then(work)
726
+ const settled = run.catch(() => {}).finally(() => {
727
+ if (this.#chains.get(key) === settled) this.#chains.delete(key)
728
+ })
729
+ this.#chains.set(key, settled)
730
+ return run
731
+ }
732
+ }
733
+
734
+ // One store for the page. Its uploads start with it.
735
+ export function fileStore(options = {}) {
736
+ const store = new FileStore(options)
737
+ return options.auto === false ? store : store.start()
738
+ }