background-job.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. export * as BackgroundJob from "./background-job"
  2. import { Cause, Clock, Context, Deferred, Effect, Exit, Layer, Scope, SynchronizedRef } from "effect"
  3. import { Identifier } from "./id/id"
  4. export type Status = "running" | "completed" | "error" | "cancelled"
  5. export type Info = {
  6. id: string
  7. type: string
  8. title?: string
  9. status: Status
  10. started_at: number
  11. completed_at?: number
  12. output?: string
  13. error?: string
  14. metadata?: Record<string, unknown>
  15. }
  16. type Active = {
  17. info: Info
  18. done: Deferred.Deferred<Info>
  19. scope: Scope.Closeable
  20. token: object
  21. pending: number
  22. next: number
  23. output?: { sequence: number; text: string }
  24. tail: Deferred.Deferred<void>
  25. promoted: Deferred.Deferred<Info>
  26. onPromote?: Effect.Effect<void>
  27. }
  28. type State = {
  29. jobs: SynchronizedRef.SynchronizedRef<Map<string, Active>>
  30. scope: Scope.Scope
  31. }
  32. type FinishResult = {
  33. info?: Info
  34. done?: Deferred.Deferred<Info>
  35. scope?: Scope.Closeable
  36. }
  37. type PromoteResult = {
  38. info?: Info
  39. promoted?: Deferred.Deferred<Info>
  40. onPromote?: Effect.Effect<void>
  41. }
  42. type StartResult = { info: Info } | { info: Info; scope: Scope.Closeable; token: object }
  43. type ExtendResult =
  44. | { extended: false }
  45. | {
  46. extended: true
  47. previous: Deferred.Deferred<void>
  48. scope: Scope.Closeable
  49. tail: Deferred.Deferred<void>
  50. token: object
  51. sequence: number
  52. }
  53. export type StartInput = {
  54. id?: string
  55. type: string
  56. title?: string
  57. metadata?: Record<string, unknown>
  58. onPromote?: Effect.Effect<void>
  59. run: Effect.Effect<string, unknown>
  60. }
  61. export type ExtendInput = {
  62. id: string
  63. run: Effect.Effect<string, unknown>
  64. }
  65. export type WaitInput = {
  66. id: string
  67. timeout?: number
  68. }
  69. export type WaitResult = {
  70. info?: Info
  71. timedOut: boolean
  72. }
  73. export interface Interface {
  74. readonly list: () => Effect.Effect<Info[]>
  75. readonly get: (id: string) => Effect.Effect<Info | undefined>
  76. readonly start: (input: StartInput) => Effect.Effect<Info>
  77. readonly extend: (input: ExtendInput) => Effect.Effect<boolean>
  78. readonly wait: (input: WaitInput) => Effect.Effect<WaitResult>
  79. readonly waitForPromotion: (id: string) => Effect.Effect<Info>
  80. readonly promote: (id: string) => Effect.Effect<Info | undefined>
  81. readonly cancel: (id: string) => Effect.Effect<Info | undefined>
  82. }
  83. export class Service extends Context.Service<Service, Interface>()("@opencode/BackgroundJob") {}
  84. function snapshot(job: Active): Info {
  85. return {
  86. ...job.info,
  87. ...(job.info.metadata ? { metadata: { ...job.info.metadata } } : {}),
  88. }
  89. }
  90. function errorText(error: unknown) {
  91. if (error instanceof Error) return error.message
  92. return String(error)
  93. }
  94. /**
  95. * Makes one scoped, process-local registry. Entries are intentionally not
  96. * durable: process restart or owner-scope closure loses status and interrupts
  97. * live work. Persisted observation, restart recovery, and remote workers need a
  98. * separate durable ownership slice rather than pretending this registry has
  99. * those semantics.
  100. */
  101. export const make = Effect.gen(function* () {
  102. const state: State = {
  103. jobs: yield* SynchronizedRef.make(new Map()),
  104. scope: yield* Scope.Scope,
  105. }
  106. const settle = Effect.fn("BackgroundJob.settle")(function* (
  107. id: string,
  108. token: object,
  109. sequence: number,
  110. exit: Exit.Exit<string, unknown>,
  111. ) {
  112. const completed_at = yield* Clock.currentTimeMillis
  113. const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [FinishResult, Map<string, Active>] => {
  114. const job = jobs.get(id)
  115. if (!job) return [{}, jobs]
  116. if (job.token !== token) return [{}, jobs]
  117. if (job.info.status !== "running") return [{ info: snapshot(job) }, jobs]
  118. const pending = job.pending - 1
  119. const output =
  120. Exit.isSuccess(exit) && (!job.output || sequence > job.output.sequence)
  121. ? { sequence, text: exit.value }
  122. : job.output
  123. if (Exit.isSuccess(exit) && pending > 0) {
  124. return [{}, new Map(jobs).set(id, { ...job, pending, output })]
  125. }
  126. const status: Exclude<Status, "running"> = Exit.isSuccess(exit)
  127. ? "completed"
  128. : Cause.hasInterruptsOnly(exit.cause)
  129. ? "cancelled"
  130. : "error"
  131. const next = {
  132. ...job,
  133. onPromote: undefined,
  134. pending: 0,
  135. output,
  136. info: {
  137. ...job.info,
  138. status,
  139. completed_at,
  140. ...(output ? { output: output.text } : {}),
  141. ...(Exit.isFailure(exit) ? { error: errorText(Cause.squash(exit.cause)) } : {}),
  142. },
  143. }
  144. return [{ info: snapshot(next), done: job.done, scope: job.scope }, new Map(jobs).set(id, next)]
  145. })
  146. if (result.info && result.done) yield* Deferred.succeed(result.done, result.info).pipe(Effect.ignore)
  147. if (result.scope) {
  148. yield* Scope.close(result.scope, Exit.void).pipe(Effect.forkIn(state.scope, { startImmediately: true }))
  149. }
  150. return result.info
  151. })
  152. const fork = Effect.fn("BackgroundJob.fork")(function* (
  153. scope: Scope.Scope,
  154. id: string,
  155. token: object,
  156. sequence: number,
  157. run: Effect.Effect<string, unknown>,
  158. ) {
  159. return yield* run.pipe(
  160. Effect.matchCauseEffect({
  161. onSuccess: (output) => settle(id, token, sequence, Exit.succeed(output)),
  162. onFailure: (cause) => settle(id, token, sequence, Exit.failCause(cause)),
  163. }),
  164. Effect.asVoid,
  165. Effect.forkIn(scope, { startImmediately: true }),
  166. )
  167. })
  168. const list: Interface["list"] = Effect.fn("BackgroundJob.list")(function* () {
  169. return Array.from((yield* SynchronizedRef.get(state.jobs)).values())
  170. .map(snapshot)
  171. .toSorted((a, b) => a.started_at - b.started_at)
  172. })
  173. const get: Interface["get"] = Effect.fn("BackgroundJob.get")(function* (id) {
  174. const job = (yield* SynchronizedRef.get(state.jobs)).get(id)
  175. if (!job) return
  176. return snapshot(job)
  177. })
  178. const start: Interface["start"] = Effect.fn("BackgroundJob.start")(function* (input) {
  179. return yield* Effect.uninterruptibleMask((restore) =>
  180. Effect.gen(function* () {
  181. const id = input.id ?? Identifier.ascending("job")
  182. const started_at = yield* Clock.currentTimeMillis
  183. const done = yield* Deferred.make<Info>()
  184. const promoted = yield* Deferred.make<Info>()
  185. const tail = yield* Deferred.make<void>()
  186. const result = yield* SynchronizedRef.modifyEffect(
  187. state.jobs,
  188. Effect.fnUntraced(function* (jobs) {
  189. const existing = jobs.get(id)
  190. if (existing?.info.status === "running") {
  191. return [{ info: snapshot(existing) }, jobs] as readonly [StartResult, Map<string, Active>]
  192. }
  193. const scope = yield* Scope.fork(state.scope, "parallel")
  194. const token = {}
  195. const job = {
  196. info: {
  197. id,
  198. type: input.type,
  199. title: input.title,
  200. status: "running" as const,
  201. started_at,
  202. metadata: input.metadata,
  203. },
  204. done,
  205. scope,
  206. token,
  207. pending: 1,
  208. next: 1,
  209. tail,
  210. promoted,
  211. onPromote: input.onPromote,
  212. }
  213. return [{ info: snapshot(job), scope, token }, new Map(jobs).set(id, job)] as readonly [
  214. StartResult,
  215. Map<string, Active>,
  216. ]
  217. }),
  218. )
  219. if ("scope" in result)
  220. yield* fork(
  221. result.scope,
  222. id,
  223. result.token,
  224. 0,
  225. restore(input.run).pipe(Effect.ensuring(Deferred.succeed(tail, undefined))),
  226. )
  227. return result.info
  228. }),
  229. )
  230. })
  231. const extend: Interface["extend"] = Effect.fn("BackgroundJob.extend")(function* (input) {
  232. return yield* Effect.uninterruptibleMask((restore) =>
  233. Effect.gen(function* () {
  234. const tail = yield* Deferred.make<void>()
  235. const result = yield* SynchronizedRef.modify(
  236. state.jobs,
  237. (jobs): readonly [ExtendResult, Map<string, Active>] => {
  238. const job = jobs.get(input.id)
  239. if (!job || job.info.status !== "running") return [{ extended: false }, jobs]
  240. return [
  241. { extended: true, previous: job.tail, scope: job.scope, tail, token: job.token, sequence: job.next },
  242. new Map(jobs).set(input.id, {
  243. ...job,
  244. pending: job.pending + 1,
  245. next: job.next + 1,
  246. tail,
  247. }),
  248. ]
  249. },
  250. )
  251. if (!result.extended) return false
  252. yield* fork(
  253. result.scope,
  254. input.id,
  255. result.token,
  256. result.sequence,
  257. Deferred.await(result.previous).pipe(
  258. Effect.andThen(restore(input.run)),
  259. Effect.ensuring(Deferred.succeed(result.tail, undefined)),
  260. ),
  261. )
  262. return true
  263. }),
  264. )
  265. })
  266. const wait: Interface["wait"] = Effect.fn("BackgroundJob.wait")(function* (input) {
  267. const job = (yield* SynchronizedRef.get(state.jobs)).get(input.id)
  268. if (!job) return { timedOut: false }
  269. if (job.info.status !== "running") return { info: snapshot(job), timedOut: false }
  270. if (input.timeout === undefined) return { info: yield* Deferred.await(job.done), timedOut: false }
  271. if (input.timeout <= 0) return { info: snapshot(job), timedOut: true }
  272. const info = yield* Deferred.await(job.done).pipe(Effect.timeoutOption(input.timeout))
  273. if (info._tag === "Some") return { info: info.value, timedOut: false }
  274. return { info: snapshot(job), timedOut: true }
  275. })
  276. const waitForPromotion: Interface["waitForPromotion"] = Effect.fn("BackgroundJob.waitForPromotion")(function* (id) {
  277. const job = (yield* SynchronizedRef.get(state.jobs)).get(id)
  278. if (!job || job.info.status !== "running") return yield* Effect.never
  279. if (job.info.metadata?.background === true) return snapshot(job)
  280. return yield* Deferred.await(job.promoted)
  281. })
  282. const promote: Interface["promote"] = Effect.fn("BackgroundJob.promote")(function* (id) {
  283. const result = yield* SynchronizedRef.modifyEffect(
  284. state.jobs,
  285. Effect.fnUntraced(function* (jobs) {
  286. const job = jobs.get(id)
  287. if (!job || job.info.status !== "running") return [{}, jobs] as readonly [PromoteResult, Map<string, Active>]
  288. if (job.info.metadata?.background === true)
  289. return [{ info: snapshot(job) }, jobs] as readonly [PromoteResult, Map<string, Active>]
  290. const next = {
  291. ...job,
  292. onPromote: undefined,
  293. info: {
  294. ...job.info,
  295. metadata: { ...job.info.metadata, background: true },
  296. },
  297. }
  298. return [
  299. { info: snapshot(next), onPromote: job.onPromote, promoted: job.promoted },
  300. new Map(jobs).set(id, next),
  301. ] as readonly [PromoteResult, Map<string, Active>]
  302. }),
  303. )
  304. if (result.info && result.promoted) yield* Deferred.succeed(result.promoted, result.info).pipe(Effect.ignore)
  305. if (result.onPromote) yield* result.onPromote.pipe(Effect.ignore)
  306. return result.info
  307. })
  308. const cancel: Interface["cancel"] = Effect.fn("BackgroundJob.cancel")(function* (id) {
  309. const completed_at = yield* Clock.currentTimeMillis
  310. const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [FinishResult, Map<string, Active>] => {
  311. const job = jobs.get(id)
  312. if (!job) return [{}, jobs]
  313. if (job.info.status !== "running") return [{ info: snapshot(job) }, jobs]
  314. const next = {
  315. ...job,
  316. onPromote: undefined,
  317. pending: 0,
  318. info: {
  319. ...job.info,
  320. status: "cancelled" as const,
  321. completed_at,
  322. },
  323. }
  324. return [{ info: snapshot(next), done: job.done, scope: job.scope }, new Map(jobs).set(id, next)]
  325. })
  326. if (result.info && result.done) yield* Deferred.succeed(result.done, result.info).pipe(Effect.ignore)
  327. if (result.scope) yield* Scope.close(result.scope, Exit.void)
  328. return result.info
  329. })
  330. return Service.of({ list, get, start, extend, wait, waitForPromotion, promote, cancel })
  331. })
  332. export const layer = Layer.effect(Service, make)
  333. export const defaultLayer = layer