* Finalize all shards by merging them into a single output file. * Recovers all records from all shards, validates no errors, and writes merged result. * Idempotent: returns early if already finalized or cleaned. * @throws Error if custom finalizer method throws
(opt?: Record<string, unknown>)
| 351 | * @throws Error if custom finalizer method throws |
| 352 | */ |
| 353 | finalize(opt?: Record<string, unknown>) { |
| 354 | if (this.#state !== 'active') { |
| 355 | return; |
| 356 | } |
| 357 | |
| 358 | // Ensure base directory exists before calling shardFiles() |
| 359 | ensureDirectoryExistsSync(this.#dir); |
| 360 | |
| 361 | const lastRecovery = this.shardFiles().map(f => ({ |
| 362 | file: f, |
| 363 | result: new WriteAheadLogFile({ |
| 364 | file: f, |
| 365 | codec: this.#format.codec, |
| 366 | }).recover(), |
| 367 | })); |
| 368 | |
| 369 | const records = lastRecovery.flatMap(({ result }) => result.records); |
| 370 | |
| 371 | if (this.#debug) { |
| 372 | this.#lastRecovery = lastRecovery; |
| 373 | } |
| 374 | |
| 375 | ensureDirectoryExistsSync(path.dirname(this.getFinalFilePath())); |
| 376 | |
| 377 | try { |
| 378 | fs.writeFileSync( |
| 379 | this.getFinalFilePath(), |
| 380 | this.#format.finalizer(filterValidRecords(records), opt), |
| 381 | ); |
| 382 | } catch (error) { |
| 383 | throw extendError( |
| 384 | error, |
| 385 | 'Could not finalize sharded wal. Finalizer method in format throws.', |
| 386 | { appendOriginalMessage: true }, |
| 387 | ); |
| 388 | } |
| 389 | |
| 390 | this.#state = 'finalized'; |
| 391 | } |
| 392 | |
| 393 | /** |
| 394 | * Cleanup shard files by removing them from disk. |
no test coverage detected