( root: string, input: CommitMemoryBundleInput, )
| 125 | } |
| 126 | |
| 127 | export async function commitMemoryBundle( |
| 128 | root: string, |
| 129 | input: CommitMemoryBundleInput, |
| 130 | ): Promise<MemoryBundleMutationResult> { |
| 131 | const memoryBytes = validateDocumentBytes('memory', input.memory); |
| 132 | const pendingBytes = |
| 133 | input.pending === null ? null : validateDocumentBytes('pending', input.pending); |
| 134 | const current = await readMemoryBundle(root); |
| 135 | if (current.revision !== input.expectedRevision) { |
| 136 | throw new MemoryBundleRevisionConflictError(input.expectedRevision, current); |
| 137 | } |
| 138 | |
| 139 | const target = bundleTarget(memoryBytes, pendingBytes); |
| 140 | if (target.snapshot.revision === current.revision) { |
| 141 | if (!input.backup) return { changed: false, snapshot: current }; |
| 142 | const directory = await prepareMemoryDirectory(root); |
| 143 | const currentBeforeBackup = await readMemoryBundle(root); |
| 144 | if (currentBeforeBackup.revision !== input.expectedRevision) { |
| 145 | throw new MemoryBundleRevisionConflictError(input.expectedRevision, currentBeforeBackup); |
| 146 | } |
| 147 | await writeMemoryBackup(directory, input.backup); |
| 148 | const currentAfterBackup = await readMemoryBundle(root); |
| 149 | if (currentAfterBackup.revision !== input.expectedRevision) { |
| 150 | throw new MemoryBundleRevisionConflictError(input.expectedRevision, currentAfterBackup); |
| 151 | } |
| 152 | return { changed: false, snapshot: currentAfterBackup }; |
| 153 | } |
| 154 | |
| 155 | const directory = await prepareMemoryDirectory(root); |
| 156 | await assertDirectoryBinding(directory); |
| 157 | const currentBeforePublication = await readMemoryBundle(root); |
| 158 | if (currentBeforePublication.revision !== input.expectedRevision) { |
| 159 | throw new MemoryBundleRevisionConflictError(input.expectedRevision, currentBeforePublication); |
| 160 | } |
| 161 | if (input.backup) { |
| 162 | await writeMemoryBackup(directory, input.backup); |
| 163 | const currentAfterBackup = await readMemoryBundle(root); |
| 164 | if (currentAfterBackup.revision !== input.expectedRevision) { |
| 165 | throw new MemoryBundleRevisionConflictError(input.expectedRevision, currentAfterBackup); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | await publishTransaction(directory, target, input.expectedRevision); |
| 170 | const committed = await readMemoryBundle(root); |
| 171 | if (committed.revision !== target.snapshot.revision) { |
| 172 | throw commitOutcomeUnknown( |
| 173 | 'Memory bundle publication could not be verified', |
| 174 | target.snapshot.revision, |
| 175 | new Error(`Expected ${target.snapshot.revision}, read ${committed.revision}`), |
| 176 | ); |
| 177 | } |
| 178 | return { changed: true, snapshot: committed }; |
| 179 | } |
| 180 | |
| 181 | export async function restoreMemoryBackup( |
| 182 | root: string, |
no test coverage detected