( table: TableDefinition, requestId: string )
| 150 | * across the upload. Concurrent misses write the same version-pinned key (idempotent). |
| 151 | */ |
| 152 | export async function getOrCreateTableSnapshot( |
| 153 | table: TableDefinition, |
| 154 | requestId: string |
| 155 | ): Promise<TableSnapshotRef> { |
| 156 | const shapeHash = schemaFingerprint(table) |
| 157 | const version = await readRowsVersion(table.id) |
| 158 | const key = snapshotKey(table.workspaceId, table.id, version, shapeHash) |
| 159 | |
| 160 | const head = await headObject(key, SNAPSHOT_STORAGE_CONTEXT) |
| 161 | if (head) { |
| 162 | logger.info(`[${requestId}] Snapshot hit`, { tableId: table.id, version, size: head.size }) |
| 163 | return { key, size: head.size, version } |
| 164 | } |
| 165 | |
| 166 | logger.info(`[${requestId}] Snapshot miss; materializing`, { tableId: table.id, version }) |
| 167 | const size = await materialize(table, key) |
| 168 | |
| 169 | const after = await readRowsVersion(table.id) |
| 170 | if (after !== version) { |
| 171 | // The table mutated mid-scan: the bytes under `key` may be torn. Re-key to the new version and |
| 172 | // rebuild once (or reuse if a concurrent writer already stored it); drop the stale object. |
| 173 | logger.info(`[${requestId}] rows_version advanced during materialize; re-keying`, { |
| 174 | tableId: table.id, |
| 175 | from: version, |
| 176 | to: after, |
| 177 | }) |
| 178 | const newKey = snapshotKey(table.workspaceId, table.id, after, shapeHash) |
| 179 | const newHead = await headObject(newKey, SNAPSHOT_STORAGE_CONTEXT) |
| 180 | const newSize = newHead ? newHead.size : await materialize(table, newKey) |
| 181 | await deleteFile({ key, context: SNAPSHOT_STORAGE_CONTEXT }).catch(() => {}) |
| 182 | void deletePreviousVersion(table, after, shapeHash) |
| 183 | return { key: newKey, size: newSize, version: after } |
| 184 | } |
| 185 | |
| 186 | void deletePreviousVersion(table, version, shapeHash) |
| 187 | return { key, size, version } |
| 188 | } |
no test coverage detected