flock.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import { describe, expect, test } from "bun:test"
  2. import fs from "fs/promises"
  3. import { spawn } from "child_process"
  4. import path from "path"
  5. import os from "os"
  6. import { Flock } from "@opencode-ai/core/util/flock"
  7. import { Hash } from "@opencode-ai/core/util/hash"
  8. type Msg = {
  9. key: string
  10. dir: string
  11. staleMs?: number
  12. timeoutMs?: number
  13. baseDelayMs?: number
  14. maxDelayMs?: number
  15. holdMs?: number
  16. ready?: string
  17. active?: string
  18. done?: string
  19. }
  20. const root = path.join(import.meta.dir, "../..")
  21. const worker = path.join(import.meta.dir, "../fixture/flock-worker.ts")
  22. async function tmpdir() {
  23. const dir = await fs.mkdtemp(path.join(os.tmpdir(), "flock-test-"))
  24. return {
  25. path: dir,
  26. async [Symbol.asyncDispose]() {
  27. await fs.rm(dir, { recursive: true, force: true })
  28. },
  29. }
  30. }
  31. function lock(dir: string, key: string) {
  32. return path.join(dir, Hash.fast(key) + ".lock")
  33. }
  34. function sleep(ms: number) {
  35. return new Promise<void>((resolve) => {
  36. setTimeout(resolve, ms)
  37. })
  38. }
  39. async function exists(file: string) {
  40. return fs
  41. .stat(file)
  42. .then(() => true)
  43. .catch(() => false)
  44. }
  45. async function wait(file: string, timeout = 3_000) {
  46. const stop = Date.now() + timeout
  47. while (Date.now() < stop) {
  48. if (await exists(file)) return
  49. await sleep(20)
  50. }
  51. throw new Error(`Timed out waiting for file: ${file}`)
  52. }
  53. function run(msg: Msg) {
  54. return new Promise<{ code: number; stdout: Buffer; stderr: Buffer }>((resolve) => {
  55. const proc = spawn(process.execPath, [worker, JSON.stringify(msg)], {
  56. cwd: root,
  57. })
  58. const stdout: Buffer[] = []
  59. const stderr: Buffer[] = []
  60. proc.stdout?.on("data", (data) => stdout.push(Buffer.from(data)))
  61. proc.stderr?.on("data", (data) => stderr.push(Buffer.from(data)))
  62. proc.on("close", (code) => {
  63. resolve({
  64. code: code ?? 1,
  65. stdout: Buffer.concat(stdout),
  66. stderr: Buffer.concat(stderr),
  67. })
  68. })
  69. })
  70. }
  71. function spawnWorker(msg: Msg) {
  72. return spawn(process.execPath, [worker, JSON.stringify(msg)], {
  73. cwd: root,
  74. stdio: ["ignore", "pipe", "pipe"],
  75. })
  76. }
  77. async function stopWorker(proc: ReturnType<typeof spawnWorker>) {
  78. if (proc.exitCode !== null || proc.signalCode !== null) return
  79. const closed = new Promise<void>((resolve) => proc.once("close", () => resolve()))
  80. if (process.platform !== "win32" || !proc.pid) {
  81. proc.kill()
  82. await closed
  83. return
  84. }
  85. await new Promise<void>((resolve) => {
  86. const killProc = spawn("taskkill", ["/pid", String(proc.pid), "/T", "/F"])
  87. killProc.on("close", () => {
  88. proc.kill()
  89. resolve()
  90. })
  91. })
  92. await closed
  93. }
  94. async function readJson<T>(p: string): Promise<T> {
  95. return JSON.parse(await fs.readFile(p, "utf8"))
  96. }
  97. describe("util.flock", () => {
  98. test("enforces mutual exclusion under process contention", async () => {
  99. await using tmp = await tmpdir()
  100. const dir = path.join(tmp.path, "locks")
  101. const done = path.join(tmp.path, "done.log")
  102. const active = path.join(tmp.path, "active")
  103. const key = "flock:stress"
  104. const n = 16
  105. const out = await Promise.all(
  106. Array.from({ length: n }, () =>
  107. run({
  108. key,
  109. dir,
  110. done,
  111. active,
  112. holdMs: 30,
  113. staleMs: 1_000,
  114. timeoutMs: 15_000,
  115. }),
  116. ),
  117. )
  118. expect(out.map((x) => x.code)).toEqual(Array.from({ length: n }, () => 0))
  119. expect(out.map((x) => x.stderr.toString()).filter(Boolean)).toEqual([])
  120. const lines = (await fs.readFile(done, "utf8"))
  121. .split("\n")
  122. .map((x) => x.trim())
  123. .filter(Boolean)
  124. expect(lines.length).toBe(n)
  125. }, 20_000)
  126. test("times out while waiting when lock is still healthy", async () => {
  127. await using tmp = await tmpdir()
  128. const dir = path.join(tmp.path, "locks")
  129. const key = "flock:timeout"
  130. const ready = path.join(tmp.path, "ready")
  131. const proc = spawnWorker({
  132. key,
  133. dir,
  134. ready,
  135. holdMs: 20_000,
  136. staleMs: 10_000,
  137. timeoutMs: 30_000,
  138. })
  139. try {
  140. await wait(ready, 5_000)
  141. const seen: string[] = []
  142. const err = await Flock.withLock(key, async () => {}, {
  143. dir,
  144. staleMs: 10_000,
  145. timeoutMs: 1_000,
  146. onWait: (tick) => {
  147. seen.push(tick.key)
  148. },
  149. }).catch((err) => err)
  150. expect(err).toBeInstanceOf(Error)
  151. if (!(err instanceof Error)) throw err
  152. expect(err.message).toContain("Timed out waiting for lock")
  153. expect(seen.length).toBeGreaterThan(0)
  154. expect(seen.every((x) => x === key)).toBe(true)
  155. } finally {
  156. await stopWorker(proc).catch(() => undefined)
  157. }
  158. }, 15_000)
  159. test("recovers after a crashed lock owner", async () => {
  160. await using tmp = await tmpdir()
  161. const dir = path.join(tmp.path, "locks")
  162. const key = "flock:crash"
  163. const ready = path.join(tmp.path, "ready")
  164. const proc = spawnWorker({
  165. key,
  166. dir,
  167. ready,
  168. holdMs: 20_000,
  169. staleMs: 500,
  170. timeoutMs: 30_000,
  171. })
  172. await wait(ready, 5_000)
  173. await stopWorker(proc)
  174. let hit = false
  175. await Flock.withLock(
  176. key,
  177. async () => {
  178. hit = true
  179. },
  180. {
  181. dir,
  182. staleMs: 500,
  183. timeoutMs: 8_000,
  184. },
  185. )
  186. expect(hit).toBe(true)
  187. }, 20_000)
  188. test("breaks stale lock dirs when heartbeat is missing", async () => {
  189. await using tmp = await tmpdir()
  190. const dir = path.join(tmp.path, "locks")
  191. const key = "flock:missing-heartbeat"
  192. const lockDir = lock(dir, key)
  193. await fs.mkdir(lockDir, { recursive: true })
  194. const old = new Date(Date.now() - 2_000)
  195. await fs.utimes(lockDir, old, old)
  196. let hit = false
  197. await Flock.withLock(
  198. key,
  199. async () => {
  200. hit = true
  201. },
  202. {
  203. dir,
  204. staleMs: 200,
  205. timeoutMs: 3_000,
  206. },
  207. )
  208. expect(hit).toBe(true)
  209. })
  210. test("recovers when a stale breaker claim was left behind", async () => {
  211. await using tmp = await tmpdir()
  212. const dir = path.join(tmp.path, "locks")
  213. const key = "flock:stale-breaker"
  214. const lockDir = lock(dir, key)
  215. const breaker = lockDir + ".breaker"
  216. await fs.mkdir(lockDir, { recursive: true })
  217. await fs.mkdir(breaker)
  218. const old = new Date(Date.now() - 2_000)
  219. await fs.utimes(lockDir, old, old)
  220. await fs.utimes(breaker, old, old)
  221. let hit = false
  222. await Flock.withLock(
  223. key,
  224. async () => {
  225. hit = true
  226. },
  227. {
  228. dir,
  229. staleMs: 200,
  230. timeoutMs: 3_000,
  231. },
  232. )
  233. expect(hit).toBe(true)
  234. expect(await exists(breaker)).toBe(false)
  235. })
  236. test("fails clearly if lock dir is removed while held", async () => {
  237. await using tmp = await tmpdir()
  238. const dir = path.join(tmp.path, "locks")
  239. const key = "flock:compromised"
  240. const lockDir = lock(dir, key)
  241. const err = await Flock.withLock(
  242. key,
  243. async () => {
  244. await fs.rm(lockDir, {
  245. recursive: true,
  246. force: true,
  247. })
  248. },
  249. {
  250. dir,
  251. staleMs: 1_000,
  252. timeoutMs: 3_000,
  253. },
  254. ).catch((err) => err)
  255. expect(err).toBeInstanceOf(Error)
  256. if (!(err instanceof Error)) throw err
  257. expect(err.message).toContain("compromised")
  258. let hit = false
  259. await Flock.withLock(
  260. key,
  261. async () => {
  262. hit = true
  263. },
  264. {
  265. dir,
  266. staleMs: 200,
  267. timeoutMs: 3_000,
  268. },
  269. )
  270. expect(hit).toBe(true)
  271. })
  272. test("writes owner metadata while lock is held", async () => {
  273. await using tmp = await tmpdir()
  274. const dir = path.join(tmp.path, "locks")
  275. const key = "flock:meta"
  276. const file = path.join(lock(dir, key), "meta.json")
  277. await Flock.withLock(
  278. key,
  279. async () => {
  280. const json = await readJson<{
  281. token?: unknown
  282. pid?: unknown
  283. hostname?: unknown
  284. createdAt?: unknown
  285. }>(file)
  286. expect(typeof json.token).toBe("string")
  287. expect(typeof json.pid).toBe("number")
  288. expect(typeof json.hostname).toBe("string")
  289. expect(typeof json.createdAt).toBe("string")
  290. },
  291. {
  292. dir,
  293. staleMs: 1_000,
  294. timeoutMs: 3_000,
  295. },
  296. )
  297. })
  298. test("supports acquire with await using", async () => {
  299. await using tmp = await tmpdir()
  300. const dir = path.join(tmp.path, "locks")
  301. const key = "flock:acquire"
  302. const lockDir = lock(dir, key)
  303. {
  304. await using _ = await Flock.acquire(key, {
  305. dir,
  306. staleMs: 1_000,
  307. timeoutMs: 3_000,
  308. })
  309. expect(await exists(lockDir)).toBe(true)
  310. }
  311. expect(await exists(lockDir)).toBe(false)
  312. })
  313. test("refuses token mismatch release and recovers from stale", async () => {
  314. await using tmp = await tmpdir()
  315. const dir = path.join(tmp.path, "locks")
  316. const key = "flock:token"
  317. const lockDir = lock(dir, key)
  318. const meta = path.join(lockDir, "meta.json")
  319. const err = await Flock.withLock(
  320. key,
  321. async () => {
  322. const json = await readJson<{ token?: string }>(meta)
  323. json.token = "tampered"
  324. await fs.writeFile(meta, JSON.stringify(json, null, 2))
  325. },
  326. {
  327. dir,
  328. staleMs: 500,
  329. timeoutMs: 3_000,
  330. },
  331. ).catch((err) => err)
  332. expect(err).toBeInstanceOf(Error)
  333. if (!(err instanceof Error)) throw err
  334. expect(err.message).toContain("token mismatch")
  335. expect(await exists(lockDir)).toBe(true)
  336. let hit = false
  337. await Flock.withLock(
  338. key,
  339. async () => {
  340. hit = true
  341. },
  342. {
  343. dir,
  344. staleMs: 500,
  345. timeoutMs: 6_000,
  346. },
  347. )
  348. expect(hit).toBe(true)
  349. })
  350. test("fails clearly on unwritable lock roots", async () => {
  351. if (process.platform === "win32") return
  352. await using tmp = await tmpdir()
  353. const dir = path.join(tmp.path, "locks")
  354. const key = "flock:perm"
  355. await fs.mkdir(dir, { recursive: true })
  356. await fs.chmod(dir, 0o500)
  357. try {
  358. const err = await Flock.withLock(key, async () => {}, {
  359. dir,
  360. staleMs: 100,
  361. timeoutMs: 500,
  362. }).catch((err) => err)
  363. expect(err).toBeInstanceOf(Error)
  364. if (!(err instanceof Error)) throw err
  365. const text = err.message
  366. expect(text.includes("EACCES") || text.includes("EPERM")).toBe(true)
  367. } finally {
  368. await fs.chmod(dir, 0o700)
  369. }
  370. })
  371. })