@alvarolorentedev/opencode-taskfeed 0.0.0-stage → 0.1.0-alpha.1
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.
- package/LICENSE +202 -0
- package/README.md +431 -2
- package/docs/architecture.md +123 -0
- package/docs/configuration.md +123 -0
- package/docs/development.md +312 -0
- package/docs/integrations.md +84 -0
- package/docs/operations.md +136 -0
- package/docs/releases/v0.1.0-alpha.1.md +164 -0
- package/docs/security.md +120 -0
- package/examples/README.md +7 -0
- package/examples/approvals/README.md +27 -0
- package/examples/flowgraph/config.yaml +28 -0
- package/examples/flowgraph/opencode.jsonc +14 -0
- package/examples/headless/README.md +25 -0
- package/examples/headless/config.yaml +21 -0
- package/examples/native-agent/config.yaml +31 -0
- package/examples/native-agent/opencode.jsonc +10 -0
- package/examples/playground/README.md +61 -0
- package/examples/playground/config.yaml +40 -0
- package/examples/playground/opencode.jsonc +5 -0
- package/package.json +89 -4
- package/src/config/load.ts +122 -0
- package/src/config/repository.ts +72 -0
- package/src/config/schema.ts +215 -0
- package/src/core/approval.ts +190 -0
- package/src/core/comments.ts +175 -0
- package/src/core/index.ts +5 -0
- package/src/core/ports.ts +185 -0
- package/src/core/state.ts +186 -0
- package/src/core/types.ts +430 -0
- package/src/executors/flowgraph/client.ts +27 -0
- package/src/executors/flowgraph/executor.ts +593 -0
- package/src/executors/flowgraph/lazy.ts +77 -0
- package/src/executors/flowgraph/rpc.ts +145 -0
- package/src/executors/flowgraph/worker.ts +538 -0
- package/src/executors/native/bridge.ts +421 -0
- package/src/executors/native/executor.ts +295 -0
- package/src/executors/native/prompt.ts +57 -0
- package/src/executors/native/trust.ts +105 -0
- package/src/index.ts +116 -0
- package/src/rpc.ts +75 -0
- package/src/runtime/backends.ts +27 -0
- package/src/runtime/engine.ts +2345 -0
- package/src/runtime/server-backends.ts +136 -0
- package/src/runtime/service.ts +276 -0
- package/src/sources/github/client.ts +98 -0
- package/src/sources/github/source.ts +490 -0
- package/src/storage/capacity.ts +223 -0
- package/src/storage/jobs.ts +249 -0
- package/src/storage/locks.ts +342 -0
- package/src/tui.tsx +399 -0
- package/src/util/ids.ts +18 -0
- package/src/util/logger.ts +52 -0
- package/src/util/process.ts +119 -0
- package/src/util/redact.ts +28 -0
- package/src/version.ts +2 -0
- package/src/workspaces/native.ts +162 -0
- package/src/workspaces/publication.ts +477 -0
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import type { Schema } from "effect"
|
|
2
|
+
import { FileMutex } from "./locks.js"
|
|
3
|
+
import { ControlRequestSchema, JobSchema, SettingsSchema, type ControlRequest, type Job, type Settings } from "../core/types.js"
|
|
4
|
+
import { stableHash } from "../util/ids.js"
|
|
5
|
+
|
|
6
|
+
export interface KVPort {
|
|
7
|
+
get(key: string): Promise<Schema.Json | undefined>
|
|
8
|
+
set(key: string, value: Schema.Json): Promise<void>
|
|
9
|
+
remove(key: string): Promise<void>
|
|
10
|
+
scan(options: { prefix: string; after?: string; limit?: number }): Promise<{
|
|
11
|
+
entries: readonly { key: string; value: Schema.Json }[]
|
|
12
|
+
next?: string
|
|
13
|
+
}>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class StateCorruptionError extends Error {
|
|
17
|
+
constructor(readonly key: string, message: string) {
|
|
18
|
+
super(message)
|
|
19
|
+
this.name = "StateCorruptionError"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ProjectStoreOptions {
|
|
24
|
+
readonly kv: KVPort
|
|
25
|
+
readonly projectKey: string
|
|
26
|
+
readonly lock?: FileMutex
|
|
27
|
+
readonly now?: () => number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function projectKeyFor(projectID: string, canonicalDirectory: string): string {
|
|
31
|
+
return stableHash(`${projectID}\0${canonicalDirectory}`, 40)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class ProjectStore {
|
|
35
|
+
readonly projectKey: string
|
|
36
|
+
private readonly kv: KVPort
|
|
37
|
+
private readonly mutex: FileMutex
|
|
38
|
+
private readonly now: () => number
|
|
39
|
+
|
|
40
|
+
constructor(options: ProjectStoreOptions) {
|
|
41
|
+
this.projectKey = options.projectKey
|
|
42
|
+
this.kv = options.kv
|
|
43
|
+
this.mutex = options.lock ?? new FileMutex(`/tmp/opencode-taskfeed-${process.pid}-${options.projectKey}.lock`)
|
|
44
|
+
this.now = options.now ?? Date.now
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private prefix(name: string): string {
|
|
48
|
+
return `${this.projectKey}/${name}/`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private jobKey(jobID: string): string {
|
|
52
|
+
return `${this.prefix("jobs")}${jobID}`
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private indexKey(taskKey: string): string {
|
|
56
|
+
return `${this.prefix("index")}${stableHash(taskKey, 40)}`
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private settingsKey(): string {
|
|
60
|
+
return `${this.projectKey}/settings`
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private controlKey(id: string): string {
|
|
64
|
+
return `${this.projectKey}/control/${id}`
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private schedulerGenerationKey(): string {
|
|
68
|
+
return `${this.projectKey}/scheduler-generation`
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async setSchedulerGeneration(generation: string): Promise<void> {
|
|
72
|
+
await this.kv.set(this.schedulerGenerationKey(), generation as never)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async schedulerGeneration(): Promise<string | undefined> {
|
|
76
|
+
const value = await this.kv.get(this.schedulerGenerationKey())
|
|
77
|
+
return typeof value === "string" ? value : undefined
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async clearSchedulerGeneration(generation: string): Promise<void> {
|
|
81
|
+
if ((await this.schedulerGeneration()) !== generation) return
|
|
82
|
+
await this.kv.remove(this.schedulerGenerationKey())
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async get(jobID: string): Promise<Job | undefined> {
|
|
86
|
+
const value = await this.kv.get(this.jobKey(jobID))
|
|
87
|
+
if (value === undefined) return undefined
|
|
88
|
+
const parsed = JobSchema.safeParse(value)
|
|
89
|
+
if (!parsed.success) throw new StateCorruptionError(this.jobKey(jobID), "Stored Taskfeed job is invalid")
|
|
90
|
+
return parsed.data
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async list(): Promise<Job[]> {
|
|
94
|
+
const jobs: Job[] = []
|
|
95
|
+
let after: string | undefined
|
|
96
|
+
for (;;) {
|
|
97
|
+
const page = await this.kv.scan({ prefix: this.prefix("jobs"), ...(after === undefined ? {} : { after }), limit: 100 })
|
|
98
|
+
for (const entry of page.entries) {
|
|
99
|
+
const parsed = JobSchema.safeParse(entry.value)
|
|
100
|
+
if (!parsed.success) throw new StateCorruptionError(entry.key, "Stored Taskfeed job is invalid")
|
|
101
|
+
jobs.push(parsed.data)
|
|
102
|
+
}
|
|
103
|
+
if (page.next === undefined) break
|
|
104
|
+
after = page.next
|
|
105
|
+
}
|
|
106
|
+
return jobs.sort((a, b) => a.createdAt - b.createdAt || a.taskKey.localeCompare(b.taskKey))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async findByTaskKey(taskKey: string): Promise<Job | undefined> {
|
|
110
|
+
const value = await this.kv.get(this.indexKey(taskKey))
|
|
111
|
+
if (typeof value !== "string") return undefined
|
|
112
|
+
return await this.get(value)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async create(job: Job): Promise<Job> {
|
|
116
|
+
const lock = await this.mutex.acquire()
|
|
117
|
+
if (!lock) throw new Error("Taskfeed state lock is unavailable")
|
|
118
|
+
try {
|
|
119
|
+
const existing = await this.findByTaskKey(job.taskKey)
|
|
120
|
+
if (existing) return existing
|
|
121
|
+
await this.saveUnlocked(job)
|
|
122
|
+
return job
|
|
123
|
+
} finally {
|
|
124
|
+
await lock.release()
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async mutate(jobID: string, mutation: (job: Job) => Job): Promise<Job> {
|
|
129
|
+
const lock = await this.mutex.acquire()
|
|
130
|
+
if (!lock) throw new Error("Taskfeed state lock is unavailable")
|
|
131
|
+
try {
|
|
132
|
+
const current = await this.get(jobID)
|
|
133
|
+
if (!current) throw new Error(`Taskfeed job ${jobID} not found`)
|
|
134
|
+
const next = JobSchema.parse(mutation(current))
|
|
135
|
+
await this.saveUnlocked(next)
|
|
136
|
+
return next
|
|
137
|
+
} finally {
|
|
138
|
+
await lock.release()
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async replace(job: Job): Promise<Job> {
|
|
143
|
+
const lock = await this.mutex.acquire()
|
|
144
|
+
if (!lock) throw new Error("Taskfeed state lock is unavailable")
|
|
145
|
+
try {
|
|
146
|
+
const parsed = JobSchema.parse(job)
|
|
147
|
+
await this.saveUnlocked(parsed)
|
|
148
|
+
return parsed
|
|
149
|
+
} finally {
|
|
150
|
+
await lock.release()
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private async saveUnlocked(job: Job): Promise<void> {
|
|
155
|
+
await this.kv.set(this.jobKey(job.jobID), job as never)
|
|
156
|
+
await this.kv.set(this.indexKey(job.taskKey), job.jobID as never)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async settings(): Promise<Settings> {
|
|
160
|
+
const value = await this.kv.get(this.settingsKey())
|
|
161
|
+
if (value === undefined) return { paused: false, updatedAt: 0, updatedBy: "default" }
|
|
162
|
+
const parsed = SettingsSchema.safeParse(value)
|
|
163
|
+
if (!parsed.success) throw new StateCorruptionError(this.settingsKey(), "Stored Taskfeed settings are invalid")
|
|
164
|
+
return parsed.data
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async enqueueControl(request: ControlRequest): Promise<ControlRequest> {
|
|
168
|
+
const lock = await this.mutex.acquire()
|
|
169
|
+
if (!lock) throw new Error("Taskfeed state lock is unavailable")
|
|
170
|
+
try {
|
|
171
|
+
const parsed = ControlRequestSchema.parse(request)
|
|
172
|
+
await this.kv.set(this.controlKey(parsed.id), parsed as never)
|
|
173
|
+
return parsed
|
|
174
|
+
} finally {
|
|
175
|
+
await lock.release()
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async controls(): Promise<ControlRequest[]> {
|
|
180
|
+
const values: ControlRequest[] = []
|
|
181
|
+
let after: string | undefined
|
|
182
|
+
for (;;) {
|
|
183
|
+
const page = await this.kv.scan({
|
|
184
|
+
prefix: `${this.projectKey}/control/`,
|
|
185
|
+
...(after === undefined ? {} : { after }),
|
|
186
|
+
limit: 100,
|
|
187
|
+
})
|
|
188
|
+
for (const entry of page.entries) {
|
|
189
|
+
const parsed = ControlRequestSchema.safeParse(entry.value)
|
|
190
|
+
if (!parsed.success) throw new StateCorruptionError(entry.key, "Stored Taskfeed control request is invalid")
|
|
191
|
+
values.push(parsed.data)
|
|
192
|
+
}
|
|
193
|
+
if (page.next === undefined) break
|
|
194
|
+
after = page.next
|
|
195
|
+
}
|
|
196
|
+
return values.sort((a, b) => a.at - b.at || a.id.localeCompare(b.id))
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async removeControl(id: string): Promise<void> {
|
|
200
|
+
await this.kv.remove(this.controlKey(id))
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async updateSettings(mutation: (settings: Settings) => Settings, updatedBy: string): Promise<Settings> {
|
|
204
|
+
const lock = await this.mutex.acquire()
|
|
205
|
+
if (!lock) throw new Error("Taskfeed state lock is unavailable")
|
|
206
|
+
try {
|
|
207
|
+
const current = await this.settings()
|
|
208
|
+
const next = SettingsSchema.parse({
|
|
209
|
+
...mutation(current),
|
|
210
|
+
updatedAt: this.now(),
|
|
211
|
+
updatedBy,
|
|
212
|
+
})
|
|
213
|
+
await this.kv.set(this.settingsKey(), next as never)
|
|
214
|
+
return next
|
|
215
|
+
} finally {
|
|
216
|
+
await lock.release()
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export class MemoryKV implements KVPort {
|
|
222
|
+
private readonly values = new Map<string, Schema.Json>()
|
|
223
|
+
|
|
224
|
+
async get(key: string): Promise<Schema.Json | undefined> {
|
|
225
|
+
const value = this.values.get(key)
|
|
226
|
+
return value === undefined ? undefined : structuredClone(value)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async set(key: string, value: Schema.Json): Promise<void> {
|
|
230
|
+
this.values.set(key, structuredClone(value))
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async remove(key: string): Promise<void> {
|
|
234
|
+
this.values.delete(key)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async scan(options: { prefix: string; after?: string; limit?: number }): Promise<{
|
|
238
|
+
entries: readonly { key: string; value: Schema.Json }[]
|
|
239
|
+
next?: string
|
|
240
|
+
}> {
|
|
241
|
+
const entries = [...this.values.entries()]
|
|
242
|
+
.filter(([key]) => key.startsWith(options.prefix) && (options.after === undefined || key > options.after))
|
|
243
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
244
|
+
.slice(0, options.limit ?? 100)
|
|
245
|
+
.map(([key, value]) => ({ key, value: structuredClone(value) }))
|
|
246
|
+
const last = entries.at(-1)?.key
|
|
247
|
+
return { entries, ...(entries.length === (options.limit ?? 100) && last !== undefined ? { next: last } : {}) }
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { open, lstat, mkdir, readFile, readdir, rm, writeFile, type FileHandle } from "node:fs/promises"
|
|
2
|
+
import os from "node:os"
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
import { randomUUID } from "node:crypto"
|
|
5
|
+
import lockfile from "proper-lockfile"
|
|
6
|
+
|
|
7
|
+
export function globalRoot(): string {
|
|
8
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : "user"
|
|
9
|
+
const runtime = process.env.XDG_RUNTIME_DIR
|
|
10
|
+
return runtime
|
|
11
|
+
? path.join(runtime, "opencode-taskfeed")
|
|
12
|
+
: path.join(os.tmpdir(), `opencode-taskfeed-${uid}`)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function ensureRoot(root: string): Promise<void> {
|
|
16
|
+
await mkdir(root, { recursive: true, mode: 0o700 })
|
|
17
|
+
const info = await lstatSafe(root)
|
|
18
|
+
if (!info || info.isSymbolicLink() || !info.isDirectory()) {
|
|
19
|
+
throw new Error(`Taskfeed lock root is not a directory: ${root}`)
|
|
20
|
+
}
|
|
21
|
+
if (typeof process.getuid === "function" && info.uid !== process.getuid()) {
|
|
22
|
+
throw new Error(`Taskfeed lock root is owned by another user: ${root}`)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface LockHandle {
|
|
27
|
+
readonly token: string
|
|
28
|
+
readonly generation: number
|
|
29
|
+
readonly path: string
|
|
30
|
+
heartbeat(): Promise<boolean>
|
|
31
|
+
isHeld(): Promise<boolean>
|
|
32
|
+
release(): Promise<boolean>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface LockOwner {
|
|
36
|
+
token: string
|
|
37
|
+
generation: number
|
|
38
|
+
pid: number
|
|
39
|
+
hostname: string
|
|
40
|
+
acquiredAt: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface LockOptions {
|
|
44
|
+
staleMs?: number
|
|
45
|
+
waitMs?: number
|
|
46
|
+
retryMs?: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function sleep(ms: number): Promise<void> {
|
|
50
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function code(error: unknown): string | undefined {
|
|
54
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
|
|
55
|
+
? error.code
|
|
56
|
+
: undefined
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function lstatSafe(file: string) {
|
|
60
|
+
try {
|
|
61
|
+
return await lstat(file)
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (code(error) === "ENOENT" || code(error) === "ENOTDIR") return undefined
|
|
64
|
+
throw error
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function readOwner(directory: string): Promise<LockOwner | undefined> {
|
|
69
|
+
try {
|
|
70
|
+
const source = await readFile(path.join(directory, "owner.json"), "utf8")
|
|
71
|
+
const value = JSON.parse(source) as Partial<LockOwner>
|
|
72
|
+
if (
|
|
73
|
+
typeof value.token !== "string" ||
|
|
74
|
+
typeof value.pid !== "number" ||
|
|
75
|
+
typeof value.acquiredAt !== "number"
|
|
76
|
+
) {
|
|
77
|
+
return undefined
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
token: value.token,
|
|
81
|
+
generation: typeof value.generation === "number" ? value.generation : 1,
|
|
82
|
+
pid: value.pid,
|
|
83
|
+
hostname: typeof value.hostname === "string" ? value.hostname : "unknown",
|
|
84
|
+
acquiredAt: value.acquiredAt,
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
return undefined
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function ageMs(file: string): Promise<number | undefined> {
|
|
92
|
+
const info = await lstatSafe(file)
|
|
93
|
+
return info ? Date.now() - info.mtimeMs : undefined
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function readLockOwner(path: string): Promise<LockOwner | undefined> {
|
|
97
|
+
return await readOwner(path)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function isLockOwnerCurrent(lockPath: string, token: string, staleMs = 30_000): Promise<boolean> {
|
|
101
|
+
const owner = await readOwner(lockPath)
|
|
102
|
+
if (!owner || owner.token !== token) return false
|
|
103
|
+
const age = await ageMs(path.join(lockPath, "owner.json"))
|
|
104
|
+
return age !== undefined && age <= staleMs
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Cross-process mutex implemented with an atomic directory create. Ownership
|
|
109
|
+
* metadata is written before the lock is considered live; a fresh directory is
|
|
110
|
+
* never reclaimed. Heartbeats use an open file descriptor so a former owner
|
|
111
|
+
* can never refresh a replacement owner's lease. Stale takeover and release
|
|
112
|
+
* are serialized with proper-lockfile, but the Taskfeed token and generation
|
|
113
|
+
* remain the authority: the guard only prevents two processes from mutating
|
|
114
|
+
* ownership metadata at the same time.
|
|
115
|
+
*
|
|
116
|
+
* shortcut: proper-lockfile judges staleness by mtime, so a process paused
|
|
117
|
+
* longer than staleMs can lose the guard. Scheduler/capacity tokens and
|
|
118
|
+
* generations still fence the former owner from mutating shared state.
|
|
119
|
+
*/
|
|
120
|
+
export class FileMutex {
|
|
121
|
+
constructor(
|
|
122
|
+
readonly path: string,
|
|
123
|
+
private readonly options: LockOptions = {},
|
|
124
|
+
) {}
|
|
125
|
+
|
|
126
|
+
private get staleMs(): number {
|
|
127
|
+
return this.options.staleMs ?? 30_000
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private async isStale(): Promise<boolean> {
|
|
131
|
+
const owner = await readOwner(this.path)
|
|
132
|
+
const age = owner ? await ageMs(path.join(this.path, "owner.json")) : await ageMs(this.path)
|
|
133
|
+
return age !== undefined && age > this.staleMs
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private async withGuard<T>(work: () => Promise<T>): Promise<T | undefined> {
|
|
137
|
+
const waitMs = Math.min(1_000, Math.max(100, this.options.waitMs ?? 1_000))
|
|
138
|
+
const guard = `${this.path}.guard`
|
|
139
|
+
await mkdir(path.dirname(guard), { recursive: true, mode: 0o700 })
|
|
140
|
+
let release: (() => Promise<void>) | undefined
|
|
141
|
+
try {
|
|
142
|
+
release = await lockfile.lock(guard, {
|
|
143
|
+
realpath: false,
|
|
144
|
+
stale: 10_000,
|
|
145
|
+
update: 4_000,
|
|
146
|
+
onCompromised: () => undefined,
|
|
147
|
+
retries: {
|
|
148
|
+
retries: Math.max(0, Math.ceil(waitMs / 25)),
|
|
149
|
+
minTimeout: 10,
|
|
150
|
+
maxTimeout: 25,
|
|
151
|
+
factor: 1,
|
|
152
|
+
},
|
|
153
|
+
})
|
|
154
|
+
return await work()
|
|
155
|
+
} catch (error) {
|
|
156
|
+
if (code(error) === "ELOCKED" || code(error) === "ECOMPROMISED") return undefined
|
|
157
|
+
throw error
|
|
158
|
+
} finally {
|
|
159
|
+
await release?.().catch(() => undefined)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private async install(generation: number): Promise<LockHandle | undefined> {
|
|
164
|
+
const token = randomUUID()
|
|
165
|
+
const owner: LockOwner = {
|
|
166
|
+
token,
|
|
167
|
+
generation,
|
|
168
|
+
pid: process.pid,
|
|
169
|
+
hostname: os.hostname(),
|
|
170
|
+
acquiredAt: Date.now(),
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
await mkdir(this.path, { mode: 0o700 })
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (code(error) === "EEXIST") return undefined
|
|
176
|
+
throw error
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
await writeFile(path.join(this.path, "owner.json"), JSON.stringify(owner), { mode: 0o600 })
|
|
180
|
+
} catch (error) {
|
|
181
|
+
await rm(this.path, { recursive: true, force: true }).catch(() => undefined)
|
|
182
|
+
throw error
|
|
183
|
+
}
|
|
184
|
+
return await this.handle(token, generation)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async tryAcquire(): Promise<LockHandle | undefined> {
|
|
188
|
+
await mkdir(path.dirname(this.path), { recursive: true, mode: 0o700 })
|
|
189
|
+
const generation = Math.max(Date.now(), 1)
|
|
190
|
+
return (
|
|
191
|
+
(await this.withGuard(async () => {
|
|
192
|
+
const fresh = await this.install(generation)
|
|
193
|
+
if (fresh) return fresh
|
|
194
|
+
if (!(await this.isStale())) return undefined
|
|
195
|
+
const previous = await readOwner(this.path)
|
|
196
|
+
const nextGeneration = Math.max(Date.now(), (previous?.generation ?? 0) + 1)
|
|
197
|
+
await rm(this.path, { recursive: true, force: true })
|
|
198
|
+
return await this.install(nextGeneration)
|
|
199
|
+
})) ?? undefined
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async acquire(): Promise<LockHandle | undefined> {
|
|
204
|
+
const timeout = this.options.waitMs ?? 5_000
|
|
205
|
+
const retry = this.options.retryMs ?? 25
|
|
206
|
+
const deadline = Date.now() + timeout
|
|
207
|
+
for (;;) {
|
|
208
|
+
const handle = await this.tryAcquire()
|
|
209
|
+
if (handle) return handle
|
|
210
|
+
if (Date.now() >= deadline) return undefined
|
|
211
|
+
await sleep(retry)
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private async handle(token: string, generation: number): Promise<LockHandle> {
|
|
216
|
+
const mutex = this
|
|
217
|
+
const directory = this.path
|
|
218
|
+
const ownerFile = path.join(directory, "owner.json")
|
|
219
|
+
let descriptor: FileHandle | undefined = await open(ownerFile, "r").catch(() => undefined)
|
|
220
|
+
const close = async () => {
|
|
221
|
+
const current = descriptor
|
|
222
|
+
descriptor = undefined
|
|
223
|
+
await current?.close().catch(() => undefined)
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
token,
|
|
227
|
+
generation,
|
|
228
|
+
path: directory,
|
|
229
|
+
async isHeld() {
|
|
230
|
+
const owner = await readOwner(directory)
|
|
231
|
+
return owner?.token === token && owner.generation === generation
|
|
232
|
+
},
|
|
233
|
+
async heartbeat() {
|
|
234
|
+
const owner = await readOwner(directory)
|
|
235
|
+
if (owner?.token !== token || owner.generation !== generation) {
|
|
236
|
+
await close()
|
|
237
|
+
return false
|
|
238
|
+
}
|
|
239
|
+
if (!descriptor) return false
|
|
240
|
+
try {
|
|
241
|
+
const now = new Date()
|
|
242
|
+
await descriptor.utimes(now, now)
|
|
243
|
+
return (await readOwner(directory))?.token === token
|
|
244
|
+
} catch {
|
|
245
|
+
await close()
|
|
246
|
+
return false
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
async release() {
|
|
250
|
+
try {
|
|
251
|
+
const released = await mutex.withGuard(async () => {
|
|
252
|
+
const owner = await readOwner(directory)
|
|
253
|
+
if (owner?.token !== token || owner.generation !== generation) return false
|
|
254
|
+
await rm(directory, { recursive: true, force: true })
|
|
255
|
+
return true
|
|
256
|
+
})
|
|
257
|
+
return released ?? false
|
|
258
|
+
} finally {
|
|
259
|
+
await close()
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export class FileLease {
|
|
267
|
+
private handle?: LockHandle
|
|
268
|
+
private readonly mutex: FileMutex
|
|
269
|
+
|
|
270
|
+
constructor(
|
|
271
|
+
readonly path: string,
|
|
272
|
+
private readonly staleMs = 30_000,
|
|
273
|
+
) {
|
|
274
|
+
this.mutex = new FileMutex(path, { staleMs, waitMs: 0 })
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
get token(): string | undefined {
|
|
278
|
+
return this.handle?.token
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
get generation(): number | undefined {
|
|
282
|
+
return this.handle?.generation
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async acquire(): Promise<boolean> {
|
|
286
|
+
if (this.handle) {
|
|
287
|
+
if (await this.handle.isHeld()) return true
|
|
288
|
+
await this.handle.release().catch(() => undefined)
|
|
289
|
+
this.handle = undefined
|
|
290
|
+
}
|
|
291
|
+
const handle = await this.mutex.tryAcquire()
|
|
292
|
+
this.handle = handle
|
|
293
|
+
return handle !== undefined
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async isLeader(): Promise<boolean> {
|
|
297
|
+
if (!this.handle) return false
|
|
298
|
+
return await this.handle.isHeld()
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async heartbeat(): Promise<boolean> {
|
|
302
|
+
if (!this.handle) return false
|
|
303
|
+
const held = await this.handle.heartbeat()
|
|
304
|
+
if (!held) this.handle = undefined
|
|
305
|
+
return held
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async release(): Promise<void> {
|
|
309
|
+
const handle = this.handle
|
|
310
|
+
this.handle = undefined
|
|
311
|
+
await handle?.release()
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export async function taskfeedRoot(): Promise<string> {
|
|
316
|
+
const root = globalRoot()
|
|
317
|
+
await ensureRoot(root)
|
|
318
|
+
return root
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export async function projectLockPath(projectKey: string, name: string): Promise<string> {
|
|
322
|
+
const root = await taskfeedRoot()
|
|
323
|
+
return path.join(root, name, `${projectKey.slice(0, 40)}.lock`)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export async function ensurePrivateDirectory(directory: string): Promise<string> {
|
|
327
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
328
|
+
const info = await lstatSafe(directory)
|
|
329
|
+
if (!info || info.isSymbolicLink() || !info.isDirectory()) {
|
|
330
|
+
throw new Error(`Unsafe Taskfeed directory: ${directory}`)
|
|
331
|
+
}
|
|
332
|
+
return directory
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export async function listJsonFiles(directory: string): Promise<string[]> {
|
|
336
|
+
try {
|
|
337
|
+
return (await readdir(directory)).filter((name) => name.endsWith(".json")).map((name) => path.join(directory, name))
|
|
338
|
+
} catch (error) {
|
|
339
|
+
if (code(error) === "ENOENT") return []
|
|
340
|
+
throw error
|
|
341
|
+
}
|
|
342
|
+
}
|