background-job.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. }
  25. type State = {
  26. jobs: SynchronizedRef.SynchronizedRef<Map<string, Active>>
  27. scope: Scope.Scope
  28. }
  29. type FinishResult = {
  30. info?: Info
  31. done?: Deferred.Deferred<Info>
  32. scope?: Scope.Closeable
  33. }
  34. type StartResult = { info: Info } | { info: Info; scope: Scope.Closeable; token: object }
  35. type ExtendResult = { extended: false } | { extended: true; scope: Scope.Closeable; token: object; sequence: number }
  36. export type StartInput = {
  37. id?: string
  38. type: string
  39. title?: string
  40. metadata?: Record<string, unknown>
  41. run: Effect.Effect<string, unknown>
  42. }
  43. export type ExtendInput = {
  44. id: string
  45. run: Effect.Effect<string, unknown>
  46. }
  47. export type WaitInput = {
  48. id: string
  49. timeout?: number
  50. }
  51. export type WaitResult = {
  52. info?: Info
  53. timedOut: boolean
  54. }
  55. export interface Interface {
  56. readonly list: () => Effect.Effect<Info[]>
  57. readonly get: (id: string) => Effect.Effect<Info | undefined>
  58. readonly start: (input: StartInput) => Effect.Effect<Info>
  59. readonly extend: (input: ExtendInput) => Effect.Effect<boolean>
  60. readonly wait: (input: WaitInput) => Effect.Effect<WaitResult>
  61. readonly cancel: (id: string) => Effect.Effect<Info | undefined>
  62. }
  63. export class Service extends Context.Service<Service, Interface>()("@opencode/BackgroundJob") {}
  64. function snapshot(job: Active): Info {
  65. return {
  66. ...job.info,
  67. ...(job.info.metadata ? { metadata: { ...job.info.metadata } } : {}),
  68. }
  69. }
  70. function errorText(error: unknown) {
  71. if (error instanceof Error) return error.message
  72. return String(error)
  73. }
  74. /**
  75. * Makes one scoped, process-local registry. Entries are intentionally not
  76. * durable: process restart or owner-scope closure loses status and interrupts
  77. * live work. Persisted observation, restart recovery, and remote workers need a
  78. * separate durable ownership slice rather than pretending this registry has
  79. * those semantics.
  80. */
  81. export const make = Effect.gen(function* () {
  82. const state: State = {
  83. jobs: yield* SynchronizedRef.make(new Map()),
  84. scope: yield* Scope.Scope,
  85. }
  86. const settle = Effect.fn("BackgroundJob.settle")(function* (
  87. id: string,
  88. token: object,
  89. sequence: number,
  90. exit: Exit.Exit<string, unknown>,
  91. ) {
  92. const completed_at = yield* Clock.currentTimeMillis
  93. const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [FinishResult, Map<string, Active>] => {
  94. const job = jobs.get(id)
  95. if (!job) return [{}, jobs]
  96. if (job.token !== token) return [{}, jobs]
  97. if (job.info.status !== "running") return [{ info: snapshot(job) }, jobs]
  98. const pending = job.pending - 1
  99. const output =
  100. Exit.isSuccess(exit) && (!job.output || sequence > job.output.sequence)
  101. ? { sequence, text: exit.value }
  102. : job.output
  103. if (Exit.isSuccess(exit) && pending > 0) {
  104. return [{}, new Map(jobs).set(id, { ...job, pending, output })]
  105. }
  106. const status: Exclude<Status, "running"> = Exit.isSuccess(exit)
  107. ? "completed"
  108. : Cause.hasInterruptsOnly(exit.cause)
  109. ? "cancelled"
  110. : "error"
  111. const next = {
  112. ...job,
  113. pending: 0,
  114. output,
  115. info: {
  116. ...job.info,
  117. status,
  118. completed_at,
  119. ...(output ? { output: output.text } : {}),
  120. ...(Exit.isFailure(exit) ? { error: errorText(Cause.squash(exit.cause)) } : {}),
  121. },
  122. }
  123. return [{ info: snapshot(next), done: job.done, scope: job.scope }, new Map(jobs).set(id, next)]
  124. })
  125. if (result.info && result.done) yield* Deferred.succeed(result.done, result.info).pipe(Effect.ignore)
  126. if (result.scope) {
  127. yield* Scope.close(result.scope, Exit.void).pipe(Effect.forkIn(state.scope, { startImmediately: true }))
  128. }
  129. return result.info
  130. })
  131. const fork = Effect.fn("BackgroundJob.fork")(function* (
  132. scope: Scope.Scope,
  133. id: string,
  134. token: object,
  135. sequence: number,
  136. run: Effect.Effect<string, unknown>,
  137. ) {
  138. return yield* run.pipe(
  139. Effect.matchCauseEffect({
  140. onSuccess: (output) => settle(id, token, sequence, Exit.succeed(output)),
  141. onFailure: (cause) => settle(id, token, sequence, Exit.failCause(cause)),
  142. }),
  143. Effect.asVoid,
  144. Effect.forkIn(scope, { startImmediately: true }),
  145. )
  146. })
  147. const list: Interface["list"] = Effect.fn("BackgroundJob.list")(function* () {
  148. return Array.from((yield* SynchronizedRef.get(state.jobs)).values())
  149. .map(snapshot)
  150. .toSorted((a, b) => a.started_at - b.started_at)
  151. })
  152. const get: Interface["get"] = Effect.fn("BackgroundJob.get")(function* (id) {
  153. const job = (yield* SynchronizedRef.get(state.jobs)).get(id)
  154. if (!job) return
  155. return snapshot(job)
  156. })
  157. const start: Interface["start"] = Effect.fn("BackgroundJob.start")(function* (input) {
  158. return yield* Effect.uninterruptibleMask((restore) =>
  159. Effect.gen(function* () {
  160. const id = input.id ?? Identifier.ascending("job")
  161. const started_at = yield* Clock.currentTimeMillis
  162. const done = yield* Deferred.make<Info>()
  163. const result = yield* SynchronizedRef.modifyEffect(
  164. state.jobs,
  165. Effect.fnUntraced(function* (jobs) {
  166. const existing = jobs.get(id)
  167. if (existing?.info.status === "running") {
  168. return [{ info: snapshot(existing) }, jobs] as readonly [StartResult, Map<string, Active>]
  169. }
  170. const scope = yield* Scope.fork(state.scope, "parallel")
  171. const token = {}
  172. const job = {
  173. info: {
  174. id,
  175. type: input.type,
  176. title: input.title,
  177. status: "running" as const,
  178. started_at,
  179. metadata: input.metadata,
  180. },
  181. done,
  182. scope,
  183. token,
  184. pending: 1,
  185. next: 1,
  186. }
  187. return [{ info: snapshot(job), scope, token }, new Map(jobs).set(id, job)] as readonly [
  188. StartResult,
  189. Map<string, Active>,
  190. ]
  191. }),
  192. )
  193. if ("scope" in result) yield* fork(result.scope, id, result.token, 0, restore(input.run))
  194. return result.info
  195. }),
  196. )
  197. })
  198. const extend: Interface["extend"] = Effect.fn("BackgroundJob.extend")(function* (input) {
  199. return yield* Effect.uninterruptibleMask((restore) =>
  200. Effect.gen(function* () {
  201. const result = yield* SynchronizedRef.modify(
  202. state.jobs,
  203. (jobs): readonly [ExtendResult, Map<string, Active>] => {
  204. const job = jobs.get(input.id)
  205. if (!job || job.info.status !== "running") return [{ extended: false }, jobs]
  206. return [
  207. { extended: true, scope: job.scope, token: job.token, sequence: job.next },
  208. new Map(jobs).set(input.id, {
  209. ...job,
  210. pending: job.pending + 1,
  211. next: job.next + 1,
  212. }),
  213. ]
  214. },
  215. )
  216. if (!result.extended) return false
  217. yield* fork(result.scope, input.id, result.token, result.sequence, restore(input.run))
  218. return true
  219. }),
  220. )
  221. })
  222. const wait: Interface["wait"] = Effect.fn("BackgroundJob.wait")(function* (input) {
  223. const job = (yield* SynchronizedRef.get(state.jobs)).get(input.id)
  224. if (!job) return { timedOut: false }
  225. if (job.info.status !== "running") return { info: snapshot(job), timedOut: false }
  226. if (input.timeout === undefined) return { info: yield* Deferred.await(job.done), timedOut: false }
  227. if (input.timeout <= 0) return { info: snapshot(job), timedOut: true }
  228. const info = yield* Deferred.await(job.done).pipe(Effect.timeoutOption(input.timeout))
  229. if (info._tag === "Some") return { info: info.value, timedOut: false }
  230. return { info: snapshot(job), timedOut: true }
  231. })
  232. const cancel: Interface["cancel"] = Effect.fn("BackgroundJob.cancel")(function* (id) {
  233. const completed_at = yield* Clock.currentTimeMillis
  234. const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [FinishResult, Map<string, Active>] => {
  235. const job = jobs.get(id)
  236. if (!job) return [{}, jobs]
  237. if (job.info.status !== "running") return [{ info: snapshot(job) }, jobs]
  238. const next = {
  239. ...job,
  240. pending: 0,
  241. info: {
  242. ...job.info,
  243. status: "cancelled" as const,
  244. completed_at,
  245. },
  246. }
  247. return [{ info: snapshot(next), done: job.done, scope: job.scope }, new Map(jobs).set(id, next)]
  248. })
  249. if (result.info && result.done) yield* Deferred.succeed(result.done, result.info).pipe(Effect.ignore)
  250. if (result.scope) yield* Scope.close(result.scope, Exit.void)
  251. return result.info
  252. })
  253. return Service.of({ list, get, start, extend, wait, cancel })
  254. })
  255. export const layer = Layer.effect(Service, make)
  256. export const defaultLayer = layer