@cirtium/acent-connect 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ import { readdir, rm, stat } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { bridgeCheckState } from "./bridge-checks.mjs"
4
+
5
+ const maxIdle = 7 * 24 * 60 * 60_000
6
+ const sweepInterval = 60 * 60_000
7
+
8
+ async function optional(operation) {
9
+ try {
10
+ return await operation()
11
+ } catch (error) {
12
+ if (error.code === "ENOENT") return null
13
+ throw error
14
+ }
15
+ }
16
+
17
+ export function createBridgeRetention({
18
+ readJson,
19
+ writeJson,
20
+ lock,
21
+ isId,
22
+ hasJobWorker,
23
+ workerAlive,
24
+ }) {
25
+ const sweeps = new Map()
26
+
27
+ async function directories(root, matches = isId) {
28
+ const entries = await optional(() => readdir(root, { withFileTypes: true }))
29
+ return (entries ?? [])
30
+ .filter((entry) => entry.isDirectory() && matches(entry.name))
31
+ .map((entry) => entry.name)
32
+ }
33
+
34
+ async function sweep(projectDir) {
35
+ const cutoff = Date.now() - maxIdle
36
+ const jobPath = (id) => join(projectDir, id, "job.json")
37
+ const jobIsOld = (job) =>
38
+ job && Math.max(job.startedAt ?? 0, job.finishedAt ?? 0) < cutoff
39
+
40
+ async function removeOldJobWork(id) {
41
+ const path = jobPath(id)
42
+ const work = join(projectDir, id, "work")
43
+ if (
44
+ !jobIsOld(await readJson(path, null)) ||
45
+ !(await optional(() => stat(work)))
46
+ )
47
+ return
48
+ await lock(join(projectDir, "jobs"), async () => {
49
+ const job = await readJson(path, null)
50
+ if (!jobIsOld(job) || (await hasJobWorker(projectDir, job))) return
51
+ if (!job.workExpiredAt) {
52
+ job.workExpiredAt = Date.now()
53
+ await writeJson(path, job)
54
+ }
55
+ await rm(work, { recursive: true, force: true })
56
+ })
57
+ }
58
+
59
+ async function removeOldVerification(id) {
60
+ const parent = join(projectDir, id)
61
+ const directory = join(parent, "verification")
62
+ const record = join(parent, "verification.json")
63
+ const isOld = async () => {
64
+ const info = await optional(() => stat(record))
65
+ return info && info.mtimeMs < cutoff
66
+ }
67
+ if (!(await optional(() => stat(directory))) || !(await isOld())) return
68
+ await lock(directory, async () => {
69
+ if (!(await isOld())) return
70
+ const verification = await readJson(record, null)
71
+ for (const attempt of await directories(directory)) {
72
+ const work = join(directory, attempt)
73
+ if ((await bridgeCheckState(work)).status === "running") continue
74
+ if (
75
+ verification?.attempt === attempt &&
76
+ verification.status === "checks_running"
77
+ )
78
+ await writeJson(record, {
79
+ ...verification,
80
+ status: "checks_failed",
81
+ details: { reason: "workspace_expired" },
82
+ })
83
+ await rm(work, { recursive: true, force: true })
84
+ }
85
+ })
86
+ }
87
+
88
+ const refinements = join(projectDir, "refinements")
89
+ async function removeOldRefinement(id) {
90
+ const directory = join(refinements, id)
91
+ const path = join(directory, "cycle.json")
92
+ const stage = join(directory, "staging")
93
+ const isOld = async () => {
94
+ const record = await optional(() => stat(path))
95
+ return record && record.mtimeMs < cutoff
96
+ }
97
+ if (!(await isOld()) || !(await optional(() => stat(stage)))) return
98
+ await lock(directory, async () => {
99
+ if (!(await isOld())) return
100
+ const cycle = await readJson(path, null)
101
+ if (!cycle) return
102
+ if (
103
+ isId(cycle.checkAttempt) &&
104
+ (await bridgeCheckState(join(stage, "checks", cycle.checkAttempt)))
105
+ .status === "running"
106
+ )
107
+ return
108
+ const delegates = [
109
+ ...(cycle.reviews ?? []).map((review) => review.id),
110
+ cycle.repairId,
111
+ ].filter(isId)
112
+ for (const delegate of delegates) {
113
+ const job = await readJson(jobPath(delegate), null)
114
+ if (job && (await hasJobWorker(projectDir, job))) return
115
+ }
116
+ if (!["verified", "cancelled", "expired"].includes(cycle.status)) {
117
+ cycle.status = "expired"
118
+ cycle.waiting = []
119
+ cycle.patchPath = undefined
120
+ cycle.details = { reason: "workspace_expired" }
121
+ await writeJson(path, cycle)
122
+ }
123
+ await rm(stage, { recursive: true, force: true })
124
+ })
125
+ }
126
+
127
+ // A bad record or a busy lock can only defer that copy's cleanup.
128
+ for (const id of await directories(projectDir)) {
129
+ await removeOldJobWork(id).catch(() => {})
130
+ await removeOldVerification(id).catch(() => {})
131
+ }
132
+ for (const id of await directories(refinements))
133
+ await removeOldRefinement(id).catch(() => {})
134
+ const previews = join(projectDir, "previews")
135
+ for (const entry of await directories(previews, (name) =>
136
+ /^acent-patch-[a-zA-Z0-9]{6}$/.test(name)
137
+ )) {
138
+ const path = join(previews, entry)
139
+ await (async () => {
140
+ const info = await optional(() => stat(path))
141
+ if (!info || info.mtimeMs >= cutoff) return
142
+ const owner = await readJson(
143
+ join(path, ".git", "acent-preview.json"),
144
+ null
145
+ )
146
+ if (!workerAlive(owner?.pid))
147
+ await rm(path, { recursive: true, force: true })
148
+ })().catch(() => {})
149
+ }
150
+ }
151
+
152
+ return async function collect(root, currentProject) {
153
+ const existing = sweeps.get(root)
154
+ if (existing) return existing
155
+ const pending = (async () => {
156
+ await sweep(currentProject).catch(() => {})
157
+ for (const project of await directories(root, (name) =>
158
+ /^[a-f0-9]{64}$/.test(name)
159
+ )) {
160
+ const directory = join(root, project)
161
+ if (directory !== currentProject) await sweep(directory).catch(() => {})
162
+ }
163
+ })().catch(() => {})
164
+ sweeps.set(root, pending)
165
+ setTimeout(() => sweeps.delete(root), sweepInterval).unref()
166
+ await pending
167
+ }
168
+ }