(
store: StoreResources,
now: number,
stageId: string,
segment: number,
batches: Arr.NonEmptyReadonlyArray<EventLogEncryption.EncryptedBatch>
)
| 777 | }) |
| 778 | |
| 779 | const stagePart = ( |
| 780 | store: StoreResources, |
| 781 | now: number, |
| 782 | stageId: string, |
| 783 | segment: number, |
| 784 | batches: Arr.NonEmptyReadonlyArray<EventLogEncryption.EncryptedBatch> |
| 785 | ): Effect.Effect< |
| 786 | "Stored" | "AlreadyStored", |
| 787 | EventLogServerEncrypted.CompactionInvalidRequest | EventLogServerEncrypted.CompactionNotFound | SqlError.SqlError |
| 788 | > => { |
| 789 | const invalid = !Number.isSafeInteger(segment) || segment < 0 || segment >= maxSegments |
| 790 | ? "Invalid segment index" |
| 791 | : batches.length > positionsPerSegment |
| 792 | ? "Too many batches in a segment" |
| 793 | : undefined |
| 794 | // A Part that fails validation closes the stage. |
| 795 | if (invalid !== undefined) { |
| 796 | return Effect.andThen( |
| 797 | abort(store, stageId), |
| 798 | Effect.fail(new EventLogServerEncrypted.CompactionInvalidRequest({ stageId, message: invalid })) |
| 799 | ) |
| 800 | } |
| 801 | const { scope, snapshotTableSql } = store |
| 802 | return sql.withTransaction(Effect.gen(function*() { |
| 803 | yield* lockStore(scope) |
| 804 | const stage = yield* selectStage(scope, stageId, true) |
| 805 | if (stage === undefined || stage.state !== "open" || stage.expiresAt <= now) { |
| 806 | return yield* notFound(stageId) |
| 807 | } |
| 808 | // The snapshot table's key makes a retried segment insert nothing. |
| 809 | // `sequence` and `last_sequence` stay null until commit. |
| 810 | const rows = batches.map((batch, i) => ({ |
| 811 | batch_set: stageId, |
| 812 | batch_position: segment * positionsPerSegment + i, |
| 813 | entry_count: batch.entryIds.length, |
| 814 | iv: batch.iv, |
| 815 | entry_ids: concatEntryIds(batch.entryIds), |
| 816 | encrypted_batch: batch.encryptedBatch |
| 817 | })) |
| 818 | let inserted = 0 |
| 819 | for (const chunk of Arr.chunksOf(rows, 200)) { |
| 820 | inserted += yield* insertNew(snapshotTableSql, chunk, ["batch_set", "batch_position"]) |
| 821 | } |
| 822 | if (inserted === 0) return "AlreadyStored" as const |
| 823 | yield* sql`UPDATE ${stagesSql} SET expires_at = ${now + stageTtlMillis} WHERE id = ${stageId}` |
| 824 | return "Stored" as const |
| 825 | })) |
| 826 | } |
| 827 | |
| 828 | const stagedHeaders = Effect.fnUntraced(function*( |
| 829 | { scope, snapshotTableSql }: StoreResources, |
no test coverage detected