Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 31 additions & 6 deletions desktop/e2e/fixtures/mock-devsy.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
const fs = require("node:fs")
const path = require("node:path")
const os = require("node:os")
const { randomUUID } = require("node:crypto")
const { mergeTasks, withFileLock } = require("./mock-task-state.cjs")

const STATE_FILE = path.join(os.tmpdir(), "devsy-mock-state.json")

Expand Down Expand Up @@ -76,24 +78,47 @@ function defaultState() {
},
],
tasks: {},
deletedTasks: {},
}
}

function loadState() {
try {
const data = fs.readFileSync(STATE_FILE, "utf8")
return JSON.parse(data)
const state = JSON.parse(data)
state.tasks = state.tasks || {}
state.deletedTasks = state.deletedTasks || {}
return state
} catch {
return defaultState()
}
}

function saveState(state) {
fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2), "utf8")
function saveState(state, deletedTaskIds = []) {
withFileLock(`${STATE_FILE}.lock`, () => {
const latest = loadState()
const deletedTasks = {
...(latest.deletedTasks || {}),
...(state.deletedTasks || {}),
...Object.fromEntries(deletedTaskIds.map((id) => [id, true])),
}
const updated = {
...state,
deletedTasks,
tasks: mergeTasks(
latest.tasks || {},
state.tasks || {},
deletedTaskIds,
deletedTasks,
),
}
const temporaryFile = `${STATE_FILE}.${process.pid}.tmp`
fs.writeFileSync(temporaryFile, JSON.stringify(updated, null, 2), "utf8")
fs.renameSync(temporaryFile, STATE_FILE)
})
}

const state = loadState()
state.tasks = state.tasks || {}

const rawArgs = process.argv.slice(2)

Expand Down Expand Up @@ -286,7 +311,7 @@ function handleUp(args) {
a === "-d=true",
)
if (isDetach) {
const taskId = `task-${Date.now()}`
const taskId = `task-${randomUUID()}`
state.tasks[taskId] = {
id: taskId,
status: "pending",
Expand Down Expand Up @@ -445,7 +470,7 @@ function handleTaskRm(args) {
return
}
delete state.tasks[id]
saveState(state)
saveState(state, [id])
out({})
}

Expand Down
80 changes: 80 additions & 0 deletions desktop/e2e/fixtures/mock-task-state.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"use strict"

const fs = require("node:fs")

function withFileLock(lockPath, update) {
const waitCell = new Int32Array(new SharedArrayBuffer(4))
let descriptor

while (descriptor === undefined) {
try {
descriptor = fs.openSync(lockPath, "wx")
} catch (error) {
if (error.code !== "EEXIST") throw error
if (removeStaleLock(lockPath)) continue
Atomics.wait(waitCell, 0, 0, 10)
}
}

try {
fs.writeSync(descriptor, String(process.pid))
return update()
} finally {
fs.closeSync(descriptor)
fs.unlinkSync(lockPath)
}
}

function removeStaleLock(lockPath) {
let contents
let stat
try {
contents = fs.readFileSync(lockPath, "utf8")
stat = fs.statSync(lockPath)
} catch (error) {
return error.code === "ENOENT"
}

const owner = Number(contents)
if (Number.isInteger(owner) && owner > 0) {
try {
process.kill(owner, 0)
return false
} catch (error) {
if (error.code !== "ESRCH") return false
}
} else if (Date.now() - stat.mtimeMs < 1000) {
return false
}

try {
const latest = fs.statSync(lockPath)
if (latest.dev !== stat.dev || latest.ino !== stat.ino) return false
fs.unlinkSync(lockPath)
return true
} catch (error) {
return error.code === "ENOENT"
}
}

function mergeTasks(current, update, deletedIds = [], tombstones = {}) {
const deleted = new Set([...Object.keys(tombstones), ...deletedIds])
const tasks = { ...current, ...update }
for (const id of deleted) delete tasks[id]

for (const [id, task] of Object.entries(current)) {
const next = update[id]
if (
!deleted.has(id) &&
next &&
task.status !== "pending" &&
task.status !== next.status
) {
tasks[id] = task
}
}

return tasks
}

module.exports = { mergeTasks, withFileLock }
167 changes: 167 additions & 0 deletions desktop/src/main/__tests__/mock-task-state.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import { createRequire } from "node:module"
import { once } from "node:events"
import { spawn, type ChildProcess } from "node:child_process"
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { describe, expect, it } from "vitest"

const require = createRequire(import.meta.url)
const { mergeTasks } = require("../../../e2e/fixtures/mock-task-state.cjs") as {
mergeTasks: (
current: Record<string, { status: string }>,
update: Record<string, { status: string }>,
deletedIds?: string[],
tombstones?: Record<string, boolean>,
) => Record<string, { status: string }>
}

describe("mock detached task persistence", () => {
it("preserves tasks created after a process loaded its state snapshot", () => {
const current = { "task-new": { status: "pending" } }
const staleUpdate = { "task-old": { status: "succeeded" } }

expect(mergeTasks(current, staleUpdate)).toEqual({
"task-new": { status: "pending" },
"task-old": { status: "succeeded" },
})
})

it("does not let a stale pending snapshot undo task cancellation", () => {
expect(
mergeTasks(
{ "task-1": { status: "failed" } },
{ "task-1": { status: "pending" } },
),
).toEqual({ "task-1": { status: "failed" } })
})

it("does not let stale completion overwrite task cancellation", () => {
expect(
mergeTasks(
{ "task-1": { status: "failed" } },
{ "task-1": { status: "succeeded" } },
),
).toEqual({ "task-1": { status: "failed" } })
})

it("applies explicit task removal", () => {
expect(
mergeTasks(
{ "task-1": { status: "succeeded" } },
{},
["task-1"],
),
).toEqual({})
})

it("does not recreate a task covered by a deletion tombstone", () => {
expect(
mergeTasks(
{},
{ "task-1": { status: "pending" } },
[],
{ "task-1": true },
),
).toEqual({})
})

it("does not restore a failed task when its ID is explicitly deleted", () => {
expect(
mergeTasks(
{ "task-1": { status: "failed" } },
{ "task-1": { status: "pending" } },
["task-1"],
),
).toEqual({})
})

it("serializes updates from separate processes", async () => {
const directory = mkdtempSync(join(tmpdir(), "mock-task-lock-"))
const lockPath = join(directory, "state.lock")
const releasePath = join(directory, "release")
const helperPath = require.resolve(
"../../../e2e/fixtures/mock-task-state.cjs",
)
const children: ChildProcess[] = []
const exits: Promise<unknown>[] = []
let output = ""
const observe = (child: ChildProcess) => {
child.stdout?.on("data", (chunk: Buffer) => {
output += chunk.toString()
})
return (line: string) =>
new Promise<void>((resolve, reject) => {
const check = () => {
if (output.includes(line)) resolve()
}
child.stdout?.on("data", check)
child.once("close", (code) => {
if (!output.includes(line))
reject(new Error(`child exited with ${code} before ${line}`))
})
check()
})
}
const launch = (source: string) => {
const child = spawn(process.execPath, ["-e", source], {
env: {
...process.env,
HELPER_PATH: helperPath,
LOCK_PATH: lockPath,
RELEASE_PATH: releasePath,
},
stdio: ["ignore", "pipe", "inherit"],
})
children.push(child)
exits.push(once(child, "exit"))
return { child, waitFor: observe(child) }
}

try {
const first = launch(`
const fs = require("node:fs")
const { withFileLock } = require(process.env.HELPER_PATH)
withFileLock(process.env.LOCK_PATH, () => {
process.stdout.write("locked\\n")
const cell = new Int32Array(new SharedArrayBuffer(4))
while (!fs.existsSync(process.env.RELEASE_PATH)) Atomics.wait(cell, 0, 0, 10)
})
`)
await first.waitFor("locked")

const second = launch(`
const { withFileLock } = require(process.env.HELPER_PATH)
process.stdout.write("waiting\\n")
withFileLock(process.env.LOCK_PATH, () => process.stdout.write("entered\\n"))
`)
await second.waitFor("waiting")
await new Promise<void>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout>
const check = () => {
if (!output.includes("entered")) return
clearTimeout(timer)
second.child.stdout?.off("data", check)
reject(new Error("entered before release"))
}
timer = setTimeout(() => {
second.child.stdout?.off("data", check)
resolve()
}, 100)
second.child.stdout?.on("data", check)
check()
})

writeFileSync(releasePath, "")
await second.waitFor("entered")
await Promise.all(exits)
} finally {
writeFileSync(releasePath, "")
for (const child of children) {
if (child.exitCode === null) child.kill()
}
await Promise.all(exits)
rmSync(directory, { recursive: true, force: true })
}
})
})
Loading