Skip to content

Commit

Permalink
chore(cu): write wasm memory to tmp file then rename to prevent corru…
Browse files Browse the repository at this point in the history
…ption of previous file on error
  • Loading branch information
TillaTheHun0 committed Sep 3, 2024
1 parent 2a632fa commit ec897d2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
4 changes: 3 additions & 1 deletion servers/cu/src/bootstrap.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { randomBytes } from 'node:crypto'
import { writeFile, mkdir } from 'node:fs/promises'
import { writeFile, mkdir, rename as renameFile } from 'node:fs/promises'
import { createReadStream } from 'node:fs'
import { BroadcastChannel } from 'node:worker_threads'

Expand Down Expand Up @@ -172,6 +172,7 @@ export const createApis = async (ctx) => {
const writeProcessMemoryFile = AoProcessClient.writeProcessMemoryFileWith({
DIR: ctx.PROCESS_MEMORY_CACHE_FILE_DIR,
writeFile,
renameFile,
mkdir
})

Expand All @@ -188,6 +189,7 @@ export const createApis = async (ctx) => {
*/
DIR: ctx.PROCESS_MEMORY_FILE_CHECKPOINTS_DIR,
writeFile,
renameFile,
mkdir
})

Expand Down
23 changes: 16 additions & 7 deletions servers/cu/src/effects/ao-process.js
Original file line number Diff line number Diff line change
Expand Up @@ -472,17 +472,26 @@ export function readProcessMemoryFileWith ({ DIR, readFile }) {
}
}

export function writeProcessMemoryFileWith ({ DIR, writeFile, mkdir }) {
export function writeProcessMemoryFileWith ({ DIR, writeFile, renameFile, mkdir }) {
return ({ Memory, evaluation }) => {
const file = `state-${evaluation.processId}.dat`
const dest = `state-${evaluation.processId}.dat`
const tmp = `${dest}.tmp`

return lock.acquire(file, () => {
const { stop: stopTimer } = timer('writeProcessMemoryFile', { file })
const path = join(DIR, file)
return lock.acquire(dest, () => {
const { stop: stopTimer } = timer('writeProcessMemoryFile', { file: tmp })

const tmpPath = join(DIR, tmp)
const destPath = join(DIR, dest)
/**
* By first writing to a temp file, we prevent corrupting a previous file checkpoint
* if for whatever reason the writing is not successful ie. node process is terminated
*
* Then we rename the tmp to the dest file, effectively overwriting it, atomically.
*/
return mkdir(DIR, { recursive: true })
.then(() => writeFile(path, Memory))
.then(() => file)
.then(() => writeFile(tmpPath, Memory))
.then(() => renameFile(tmpPath, destPath))
.then(() => dest)
.finally(stopTimer)
})
}
Expand Down

0 comments on commit ec897d2

Please sign in to comment.