@leitwerk-dev/worker-runners 0.2.0 → 0.2.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.
Files changed (121) hide show
  1. package/dist/{chunk-6BSZBMHH.js → chunk-2P3CWUP3.js} +1 -7
  2. package/dist/chunk-2P3CWUP3.js.map +1 -0
  3. package/dist/{chunk-D56NJQ5X.js → chunk-6UZ2REWV.js} +1 -1
  4. package/dist/chunk-6UZ2REWV.js.map +1 -0
  5. package/dist/{chunk-7NF2P2VP.js → chunk-A3XSYWA5.js} +2 -2
  6. package/dist/chunk-A3XSYWA5.js.map +1 -0
  7. package/dist/{chunk-YBSX4N2K.js → chunk-BRIIMAZX.js} +13 -13
  8. package/dist/chunk-BRIIMAZX.js.map +1 -0
  9. package/dist/{chunk-OSS62AOL.js → chunk-DFPYUJIK.js} +4 -1
  10. package/dist/chunk-DFPYUJIK.js.map +1 -0
  11. package/dist/{chunk-63BBCX7B.js → chunk-H4JEE3ZT.js} +2 -1
  12. package/dist/chunk-H4JEE3ZT.js.map +1 -0
  13. package/dist/chunk-ISH4647R.js +506 -0
  14. package/dist/chunk-ISH4647R.js.map +1 -0
  15. package/dist/{chunk-ISEDLYKQ.js → chunk-V7TTFLGE.js} +30 -12
  16. package/dist/chunk-V7TTFLGE.js.map +1 -0
  17. package/dist/{chunk-YJMHXKNO.js → chunk-YDYI3BD2.js} +13 -6
  18. package/dist/chunk-YDYI3BD2.js.map +1 -0
  19. package/dist/{chunk-7X5FBNT7.js → chunk-ZGFD76I6.js} +3 -1
  20. package/dist/chunk-ZGFD76I6.js.map +1 -0
  21. package/dist/docker-client-public.d.ts +2 -0
  22. package/dist/docker-client-public.d.ts.map +1 -0
  23. package/dist/docker-client-public.js +7 -0
  24. package/dist/docker-client-public.js.map +1 -0
  25. package/dist/{docker-engine-client-CnXspTGq.d.ts → docker-engine-client-Btw6ZTXk.d.ts} +45 -18
  26. package/dist/docker-engine-client.d.ts +44 -17
  27. package/dist/docker-engine-client.d.ts.map +1 -1
  28. package/dist/docker-engine-http-client.d.ts +18 -1
  29. package/dist/docker-engine-http-client.d.ts.map +1 -1
  30. package/dist/docker-engine-http-client.js +1 -1
  31. package/dist/docker-public.d.ts +2 -0
  32. package/dist/docker-public.d.ts.map +1 -0
  33. package/dist/docker-public.js +13 -0
  34. package/dist/docker-public.js.map +1 -0
  35. package/dist/docker-worker-runner.d.ts +19 -9
  36. package/dist/docker-worker-runner.d.ts.map +1 -1
  37. package/dist/docker-worker-runner.js +6 -6
  38. package/dist/index.d.ts +2 -12
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +1 -260
  41. package/dist/index.js.map +1 -1
  42. package/dist/{kubernetes-api-client-DD2YevYP.d.ts → kubernetes-api-client-CEe7pHC4.d.ts} +212 -88
  43. package/dist/kubernetes-api-client.d.ts +80 -0
  44. package/dist/kubernetes-api-client.d.ts.map +1 -1
  45. package/dist/kubernetes-client-public.d.ts +2 -0
  46. package/dist/kubernetes-client-public.d.ts.map +1 -0
  47. package/dist/kubernetes-client-public.js +9 -0
  48. package/dist/kubernetes-client-public.js.map +1 -0
  49. package/dist/kubernetes-http-client.d.ts +11 -0
  50. package/dist/kubernetes-http-client.d.ts.map +1 -1
  51. package/dist/kubernetes-http-client.js +5 -500
  52. package/dist/kubernetes-http-client.js.map +1 -1
  53. package/dist/kubernetes-manifests.d.ts +151 -8
  54. package/dist/kubernetes-manifests.d.ts.map +1 -1
  55. package/dist/kubernetes-public.d.ts +2 -0
  56. package/dist/kubernetes-public.d.ts.map +1 -0
  57. package/dist/kubernetes-public.js +13 -0
  58. package/dist/kubernetes-public.js.map +1 -0
  59. package/dist/kubernetes-volume-pool-api.d.ts +46 -1
  60. package/dist/kubernetes-volume-pool-api.d.ts.map +1 -1
  61. package/dist/kubernetes-volume-pool.d.ts +18 -1
  62. package/dist/kubernetes-volume-pool.d.ts.map +1 -1
  63. package/dist/kubernetes-worker-runner.d.ts +27 -11
  64. package/dist/kubernetes-worker-runner.d.ts.map +1 -1
  65. package/dist/kubernetes-worker-runner.js +6 -6
  66. package/dist/local-public.d.ts +2 -0
  67. package/dist/local-public.d.ts.map +1 -0
  68. package/dist/local-public.js +11 -0
  69. package/dist/local-public.js.map +1 -0
  70. package/dist/local-worker-runner.d.ts +15 -8
  71. package/dist/local-worker-runner.d.ts.map +1 -1
  72. package/dist/local-worker-runner.js +2 -2
  73. package/dist/process-volume-retention.d.ts +15 -0
  74. package/dist/process-volume-retention.d.ts.map +1 -1
  75. package/dist/runner-utils.d.ts +5 -0
  76. package/dist/runner-utils.d.ts.map +1 -1
  77. package/dist/session-transfer-helper-cli.js +1 -1
  78. package/dist/session-transfer-helper.d.ts +3 -0
  79. package/dist/session-transfer-helper.d.ts.map +1 -1
  80. package/dist/session-transfer-helper.js +1 -1
  81. package/dist/types-public.d.ts +3 -0
  82. package/dist/types-public.d.ts.map +1 -0
  83. package/dist/types-public.js +7 -0
  84. package/dist/types-public.js.map +1 -0
  85. package/dist/types.d.ts +87 -29
  86. package/dist/types.d.ts.map +1 -1
  87. package/dist/types.js +1 -1
  88. package/dist/worker-labels.d.ts +29 -2
  89. package/dist/worker-labels.d.ts.map +1 -1
  90. package/package.json +23 -28
  91. package/src/docker-client-public.ts +1 -0
  92. package/src/docker-engine-client.ts +59 -20
  93. package/src/docker-engine-http-client.ts +13 -0
  94. package/src/docker-public.ts +1 -0
  95. package/src/docker-worker-runner.ts +19 -9
  96. package/src/index.ts +0 -98
  97. package/src/kubernetes-api-client.ts +112 -6
  98. package/src/kubernetes-client-public.ts +1 -0
  99. package/src/kubernetes-http-client.ts +11 -0
  100. package/src/kubernetes-manifests.ts +211 -16
  101. package/src/kubernetes-public.ts +1 -0
  102. package/src/kubernetes-volume-pool-api.ts +58 -4
  103. package/src/kubernetes-volume-pool.ts +19 -1
  104. package/src/kubernetes-worker-runner.ts +54 -14
  105. package/src/local-public.ts +1 -0
  106. package/src/local-worker-runner.ts +15 -8
  107. package/src/process-volume-retention.ts +15 -0
  108. package/src/runner-utils.ts +8 -1
  109. package/src/session-transfer-helper.ts +3 -0
  110. package/src/types-public.ts +12 -0
  111. package/src/types.ts +90 -30
  112. package/src/worker-labels.ts +29 -2
  113. package/dist/chunk-63BBCX7B.js.map +0 -1
  114. package/dist/chunk-6BSZBMHH.js.map +0 -1
  115. package/dist/chunk-7NF2P2VP.js.map +0 -1
  116. package/dist/chunk-7X5FBNT7.js.map +0 -1
  117. package/dist/chunk-D56NJQ5X.js.map +0 -1
  118. package/dist/chunk-ISEDLYKQ.js.map +0 -1
  119. package/dist/chunk-OSS62AOL.js.map +0 -1
  120. package/dist/chunk-YBSX4N2K.js.map +0 -1
  121. package/dist/chunk-YJMHXKNO.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/docker-engine-http-client.ts"],"sourcesContent":["import http from \"node:http\";\nimport { text as readText } from \"node:stream/consumers\";\nimport type {\n\tDockerContainerExit,\n\tDockerContainerInspect,\n\tDockerContainerSpec,\n\tDockerEngineClient,\n} from \"./docker-engine-client.js\";\n\nexport class DockerEngineHttpError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly statusCode: number,\n\t\treadonly body: string,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\nexport function isDockerEngineNotFoundError(error: unknown): boolean {\n\treturn error instanceof DockerEngineHttpError && error.statusCode === 404;\n}\n\nexport interface ParsedDockerEngineSocket {\n\tsocketPath?: string;\n\tbaseUrl?: URL;\n}\n\nexport function parseDockerEngineSocket(value: string): ParsedDockerEngineSocket {\n\tif (value.startsWith(\"unix://\")) {\n\t\tconst socketPath = value.slice(\"unix://\".length);\n\t\tif (!socketPath.startsWith(\"/\"))\n\t\t\tthrow new Error(\"docker.socket unix:// URL must contain an absolute path\");\n\t\treturn { socketPath };\n\t}\n\tif (value.startsWith(\"http://\")) return { baseUrl: new URL(value) };\n\tif (value.startsWith(\"https://\")) {\n\t\tthrow new Error(\n\t\t\t\"docker.socket https:// is not supported by the built-in Docker adapter; use unix:// or http://\",\n\t\t);\n\t}\n\tif (value.startsWith(\"/\")) return { socketPath: value };\n\tthrow new Error(\n\t\t`Unsupported docker.socket value '${value}'; expected unix:///path/to/docker.sock`,\n\t);\n}\n\nexport interface DockerEngineHttpClientOptions {\n\tsocket: string;\n\tapiVersion?: string;\n}\n\ninterface DockerApiRequest {\n\tmethod: \"GET\" | \"POST\" | \"DELETE\";\n\tpath: string;\n\tquery?: Record<string, string>;\n\tbody?: unknown;\n}\n\nfunction encodeQuery(query?: Record<string, string>): string {\n\tif (!query) return \"\";\n\tconst params = new URLSearchParams(query);\n\tconst text = params.toString();\n\treturn text ? `?${text}` : \"\";\n}\n\nfunction toMounts(spec: DockerContainerSpec): Array<Record<string, unknown>> {\n\treturn spec.mounts.map((mount) => ({\n\t\tType: mount.source.startsWith(\"/\") ? \"bind\" : \"volume\",\n\t\tSource: mount.source,\n\t\tTarget: mount.target,\n\t\tReadOnly: mount.readOnly ?? false,\n\t\t...(mount.volumeSubpath !== undefined\n\t\t\t? { VolumeOptions: { Subpath: mount.volumeSubpath, NoCopy: true } }\n\t\t\t: {}),\n\t}));\n}\n\nfunction requireVolumeSubpathApiVersion(value: unknown): string {\n\tif (typeof value === \"string\" && /^\\d+\\.\\d+$/.test(value)) {\n\t\tconst [major = 0, minor = 0] = value.split(\".\").map(Number);\n\t\tif (major > 1 || (major === 1 && minor >= 45)) return value;\n\t}\n\tthrow new Error(\"Scoped Docker volume mounts require Docker Engine 26.0 or newer (API 1.45+)\");\n}\n\nfunction toContainerCreateBody(spec: DockerContainerSpec): Record<string, unknown> {\n\treturn {\n\t\tImage: spec.image,\n\t\tEnv: spec.env,\n\t\tLabels: spec.labels,\n\t\t...(spec.command ? { Cmd: spec.command } : {}),\n\t\tHostConfig: {\n\t\t\tMounts: toMounts(spec),\n\t\t\tNetworkMode: spec.networkMode,\n\t\t\tPrivileged: spec.privileged,\n\t\t\t...(spec.runtime ? { Runtime: spec.runtime } : {}),\n\t\t\t...(spec.nanoCpus ? { NanoCpus: spec.nanoCpus } : {}),\n\t\t\t...(spec.memoryBytes ? { Memory: spec.memoryBytes } : {}),\n\t\t},\n\t};\n}\n\ninterface DockerInspectResponse {\n\tId: string;\n\tState?: { Running?: boolean };\n\tConfig?: { Labels?: Record<string, string> };\n}\n\ninterface DockerWaitResponse {\n\tStatusCode?: number;\n\tError?: { Message?: string };\n}\n\ninterface DockerCreateResponse {\n\tId: string;\n}\n\ninterface DockerListContainerResponse {\n\tId: string;\n\tLabels?: Record<string, string>;\n}\n\nfunction mapInspect(raw: DockerInspectResponse): DockerContainerInspect {\n\treturn {\n\t\tid: raw.Id,\n\t\trunning: raw.State?.Running === true,\n\t\tlabels: raw.Config?.Labels ?? {},\n\t};\n}\n\nfunction mapWait(raw: DockerWaitResponse): DockerContainerExit {\n\treturn {\n\t\tstatusCode: Number(raw.StatusCode ?? 0),\n\t\t...(raw.Error?.Message ? { error: raw.Error.Message } : {}),\n\t};\n}\n\nexport function createDockerEngineHttpClient(\n\toptions: DockerEngineHttpClientOptions,\n): DockerEngineClient {\n\tconst endpoint = parseDockerEngineSocket(options.socket);\n\tconst configuredApiVersion = options.apiVersion?.replace(/^v/, \"\");\n\tasync function request<T>(\n\t\tapiReq: DockerApiRequest,\n\t\tapiVersion = configuredApiVersion,\n\t): Promise<T> {\n\t\tconst prefix = apiVersion ? `/v${apiVersion}` : \"\";\n\t\tconst path = `${prefix}${apiReq.path}${encodeQuery(apiReq.query)}`;\n\t\tconst body = apiReq.body === undefined ? undefined : JSON.stringify(apiReq.body);\n\t\tconst response = await new Promise<http.IncomingMessage>((resolve, reject) => {\n\t\t\tconst req = http.request(\n\t\t\t\t{\n\t\t\t\t\tmethod: apiReq.method,\n\t\t\t\t\tpath: endpoint.baseUrl ? `${endpoint.baseUrl.pathname.replace(/\\/$/, \"\")}${path}` : path,\n\t\t\t\t\tsocketPath: endpoint.socketPath,\n\t\t\t\t\thostname: endpoint.baseUrl?.hostname,\n\t\t\t\t\tport: endpoint.baseUrl?.port,\n\t\t\t\t\theaders: body\n\t\t\t\t\t\t? { \"content-type\": \"application/json\", \"content-length\": Buffer.byteLength(body) }\n\t\t\t\t\t\t: undefined,\n\t\t\t\t},\n\t\t\t\tresolve,\n\t\t\t);\n\t\t\treq.on(\"error\", reject);\n\t\t\treq.end(body);\n\t\t});\n\t\tconst text = await readText(response);\n\t\tif ((response.statusCode ?? 500) >= 400) {\n\t\t\tthrow new DockerEngineHttpError(\n\t\t\t\t`Docker Engine ${apiReq.method} ${apiReq.path} failed with ${response.statusCode}: ${text}`,\n\t\t\t\tresponse.statusCode ?? 500,\n\t\t\t\ttext,\n\t\t\t);\n\t\t}\n\t\treturn (text ? JSON.parse(text) : undefined) as T;\n\t}\n\treturn {\n\t\tasync createContainer(spec) {\n\t\t\tlet apiVersion = configuredApiVersion;\n\t\t\tif (spec.mounts.some((mount) => mount.volumeSubpath !== undefined)) {\n\t\t\t\tconst version =\n\t\t\t\t\tconfiguredApiVersion ??\n\t\t\t\t\t(await request<{ ApiVersion?: string }>({ method: \"GET\", path: \"/version\" })).ApiVersion;\n\t\t\t\t// Pin this request to an API that understands Subpath. An older daemon\n\t\t\t\t// must reject the request, never ignore the option and mount the volume root.\n\t\t\t\tapiVersion = requireVolumeSubpathApiVersion(version);\n\t\t\t}\n\t\t\tconst raw = await request<DockerCreateResponse>(\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\tpath: \"/containers/create\",\n\t\t\t\t\tquery: { name: spec.name },\n\t\t\t\t\tbody: toContainerCreateBody(spec),\n\t\t\t\t},\n\t\t\t\tapiVersion,\n\t\t\t);\n\t\t\treturn { id: raw.Id };\n\t\t},\n\t\tasync startContainer(id) {\n\t\t\tawait request({ method: \"POST\", path: `/containers/${encodeURIComponent(id)}/start` });\n\t\t},\n\t\tasync stopContainer(id, opts) {\n\t\t\tawait request({\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tpath: `/containers/${encodeURIComponent(id)}/stop`,\n\t\t\t\tquery: { t: String(opts.timeoutSeconds) },\n\t\t\t});\n\t\t},\n\t\tasync removeContainer(id, opts) {\n\t\t\tawait request({\n\t\t\t\tmethod: \"DELETE\",\n\t\t\t\tpath: `/containers/${encodeURIComponent(id)}`,\n\t\t\t\tquery: { force: opts.force ? \"1\" : \"0\", v: \"1\" },\n\t\t\t});\n\t\t},\n\t\tasync inspectContainer(id) {\n\t\t\treturn mapInspect(\n\t\t\t\tawait request<DockerInspectResponse>({\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\tpath: `/containers/${encodeURIComponent(id)}/json`,\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tasync listContainers(filter) {\n\t\t\tconst raw = await request<DockerListContainerResponse[]>({\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tpath: \"/containers/json\",\n\t\t\t\tquery: {\n\t\t\t\t\tfilters: JSON.stringify({\n\t\t\t\t\t\tlabel: Object.entries(filter.labels).map(([key, value]) => `${key}=${value}`),\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn raw.map((c) => ({ id: c.Id, labels: c.Labels ?? {} }));\n\t\t},\n\t\tasync waitContainer(id) {\n\t\t\treturn mapWait(\n\t\t\t\tawait request<DockerWaitResponse>({\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\tpath: `/containers/${encodeURIComponent(id)}/wait`,\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tasync ensureVolume(name) {\n\t\t\tawait request({ method: \"POST\", path: \"/volumes/create\", body: { Name: name } });\n\t\t},\n\t\tasync removeVolume(name) {\n\t\t\ttry {\n\t\t\t\tawait request({ method: \"DELETE\", path: `/volumes/${encodeURIComponent(name)}` });\n\t\t\t} catch (error) {\n\t\t\t\tif (!isDockerEngineNotFoundError(error)) throw error;\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";AAAA,OAAO,UAAU;AACjB,SAAS,QAAQ,gBAAgB;AAQ1B,IAAM,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IAAI,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,QAAQ,EAAE,UAAU,CAAC,EAAE,EAAE;AAAA,IAC7D;AAAA,IACA,MAAM,cAAc,IAAI;AACvB,aAAO;AAAA,QACN,MAAM,QAA4B;AAAA,UACjC,QAAQ;AAAA,UACR,MAAM,eAAe,mBAAmB,EAAE,CAAC;AAAA,QAC5C,CAAC;AAAA,MACF;AAAA,IACD;AAAA,IACA,MAAM,aAAa,MAAM;AACxB,YAAM,QAAQ,EAAE,QAAQ,QAAQ,MAAM,mBAAmB,MAAM,EAAE,MAAM,KAAK,EAAE,CAAC;AAAA,IAChF;AAAA,IACA,MAAM,aAAa,MAAM;AACxB,UAAI;AACH,cAAM,QAAQ,EAAE,QAAQ,UAAU,MAAM,YAAY,mBAAmB,IAAI,CAAC,GAAG,CAAC;AAAA,MACjF,SAAS,OAAO;AACf,YAAI,CAAC,4BAA4B,KAAK,EAAG,OAAM;AAAA,MAChD;AAAA,IACD;AAAA,EACD;AACD;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/worker-labels.ts"],"sourcesContent":["/**\n * Shared labelling for worker units across runner modes.\n *\n * Labels are how the server reconciles which workers exist after a restart:\n * there is no pid registry, the container/pod runtime is the source of truth.\n * Both the Docker and Kubernetes runners stamp these labels at start and read\n * them back during the adoption scan, so the keys and parse rules live here\n * rather than in a runtime-specific body.\n */\n\nexport const WORKER_LABEL_MANAGED_BY = \"leitwerk.dev/managed-by\";\nexport const WORKER_LABEL_COMPONENT = \"leitwerk.dev/component\";\nexport const WORKER_LABEL_INSTANCE_ID = \"leitwerk.dev/instance-id\";\nexport const WORKER_LABEL_WORKER_ID = \"leitwerk.dev/worker-id\";\nexport const WORKER_LABEL_SERVER_EPOCH = \"leitwerk.dev/server-epoch\";\n\nexport const WORKER_LABEL_MANAGED_BY_VALUE = \"leitwerk\";\nexport const WORKER_LABEL_COMPONENT_VALUE = \"worker\";\nexport const PROCESS_NAMESPACE_COMPONENT_VALUE = \"process-namespace\";\nexport const PROCESS_VOLUME_COMPONENT_VALUE = \"process-volume\";\nexport const PROCESS_SERVER_CA_COMPONENT_VALUE = \"server-ca\";\nexport const PROCESS_IMAGE_PULL_SECRET_COMPONENT_VALUE = \"image-pull-secret\";\nexport const EXPORT_HELPER_COMPONENT_VALUE = \"session-export-helper\";\nexport const EXPORT_HELPER_LABEL_EXPORT_ID = \"leitwerk.dev/export-id\";\n\nexport interface WorkerUnitIdentity {\n\tinstanceId: string;\n\tworkerId: string;\n\tserverEpoch: string;\n}\n\n/**\n * Builds the canonical label set for a worker unit. Extra labels are merged in\n * but can never override the managed identity keys.\n */\nexport function buildWorkerUnitLabels(\n\tidentity: WorkerUnitIdentity,\n\textra: Record<string, string> = {},\n): Record<string, string> {\n\treturn {\n\t\t...extra,\n\t\t[WORKER_LABEL_MANAGED_BY]: WORKER_LABEL_MANAGED_BY_VALUE,\n\t\t[WORKER_LABEL_COMPONENT]: WORKER_LABEL_COMPONENT_VALUE,\n\t\t[WORKER_LABEL_INSTANCE_ID]: identity.instanceId,\n\t\t[WORKER_LABEL_WORKER_ID]: identity.workerId,\n\t\t[WORKER_LABEL_SERVER_EPOCH]: identity.serverEpoch,\n\t};\n}\n\n/**\n * Builds labels for durable process-scoped resources (namespace/PVC). These\n * intentionally omit worker-id and server-epoch because the resources outlive a\n * specific worker lease and are not adoption targets.\n */\nexport function buildProcessResourceLabels(\n\targs: {\n\t\tinstanceId: string;\n\t\tcomponent:\n\t\t\t| typeof PROCESS_NAMESPACE_COMPONENT_VALUE\n\t\t\t| typeof PROCESS_VOLUME_COMPONENT_VALUE\n\t\t\t| typeof PROCESS_SERVER_CA_COMPONENT_VALUE\n\t\t\t| typeof PROCESS_IMAGE_PULL_SECRET_COMPONENT_VALUE;\n\t},\n\textra: Record<string, string> = {},\n): Record<string, string> {\n\treturn {\n\t\t...extra,\n\t\t[WORKER_LABEL_MANAGED_BY]: WORKER_LABEL_MANAGED_BY_VALUE,\n\t\t[WORKER_LABEL_COMPONENT]: args.component,\n\t\t[WORKER_LABEL_INSTANCE_ID]: args.instanceId,\n\t};\n}\n\n/** Selector for the two managed-by/component keys shared by every managed resource. */\nfunction managedResourceLabelSelector(component: string): Record<string, string> {\n\treturn {\n\t\t[WORKER_LABEL_MANAGED_BY]: WORKER_LABEL_MANAGED_BY_VALUE,\n\t\t[WORKER_LABEL_COMPONENT]: component,\n\t};\n}\n\nexport function managedProcessNamespaceLabelSelector(): Record<string, string> {\n\treturn managedResourceLabelSelector(PROCESS_NAMESPACE_COMPONENT_VALUE);\n}\n\nexport function buildExportHelperLabels(input: {\n\tinstanceId: string;\n\texportId: string;\n}): Record<string, string> {\n\treturn {\n\t\t[WORKER_LABEL_MANAGED_BY]: WORKER_LABEL_MANAGED_BY_VALUE,\n\t\t[WORKER_LABEL_COMPONENT]: EXPORT_HELPER_COMPONENT_VALUE,\n\t\t[WORKER_LABEL_INSTANCE_ID]: input.instanceId,\n\t\t[EXPORT_HELPER_LABEL_EXPORT_ID]: input.exportId,\n\t};\n}\n\nexport function managedExportHelperLabelSelector(): Record<string, string> {\n\treturn managedResourceLabelSelector(EXPORT_HELPER_COMPONENT_VALUE);\n}\n\n/** True when the labels identify an leitwerk-managed worker unit. */\nexport function isManagedWorkerUnitLabels(labels: Record<string, string>): boolean {\n\treturn (\n\t\tlabels[WORKER_LABEL_MANAGED_BY] === WORKER_LABEL_MANAGED_BY_VALUE &&\n\t\tlabels[WORKER_LABEL_COMPONENT] === WORKER_LABEL_COMPONENT_VALUE\n\t);\n}\n\n/**\n * Recovers the worker identity from a unit's labels, or `null` when the labels\n * do not describe a complete leitwerk-managed worker.\n */\nexport function parseWorkerUnitIdentity(labels: Record<string, string>): WorkerUnitIdentity | null {\n\tif (!isManagedWorkerUnitLabels(labels)) {\n\t\treturn null;\n\t}\n\tconst instanceId = labels[WORKER_LABEL_INSTANCE_ID];\n\tconst workerId = labels[WORKER_LABEL_WORKER_ID];\n\tconst serverEpoch = labels[WORKER_LABEL_SERVER_EPOCH];\n\tif (!instanceId || !workerId || !serverEpoch) {\n\t\treturn null;\n\t}\n\treturn { instanceId, workerId, serverEpoch };\n}\n\n/** Label selector for listing managed worker units in a runtime query. */\nexport function managedWorkerLabelSelector(): Record<string, string> {\n\treturn managedResourceLabelSelector(WORKER_LABEL_COMPONENT_VALUE);\n}\n"],"mappings":";AAUO,IAAM,0BAA0B;AAChC,IAAM,yBAAyB;AAC/B,IAAM,2BAA2B;AACjC,IAAM,yBAAyB;AAC/B,IAAM,4BAA4B;AAElC,IAAM,gCAAgC;AACtC,IAAM,+BAA+B;AACrC,IAAM,oCAAoC;AAC1C,IAAM,iCAAiC;AACvC,IAAM,oCAAoC;AAC1C,IAAM,4CAA4C;AAClD,IAAM,gCAAgC;AACtC,IAAM,gCAAgC;AAYtC,SAAS,sBACf,UACA,QAAgC,CAAC,GACR;AACzB,SAAO;AAAA,IACN,GAAG;AAAA,IACH,CAAC,uBAAuB,GAAG;AAAA,IAC3B,CAAC,sBAAsB,GAAG;AAAA,IAC1B,CAAC,wBAAwB,GAAG,SAAS;AAAA,IACrC,CAAC,sBAAsB,GAAG,SAAS;AAAA,IACnC,CAAC,yBAAyB,GAAG,SAAS;AAAA,EACvC;AACD;AAOO,SAAS,2BACf,MAQA,QAAgC,CAAC,GACR;AACzB,SAAO;AAAA,IACN,GAAG;AAAA,IACH,CAAC,uBAAuB,GAAG;AAAA,IAC3B,CAAC,sBAAsB,GAAG,KAAK;AAAA,IAC/B,CAAC,wBAAwB,GAAG,KAAK;AAAA,EAClC;AACD;AAGA,SAAS,6BAA6B,WAA2C;AAChF,SAAO;AAAA,IACN,CAAC,uBAAuB,GAAG;AAAA,IAC3B,CAAC,sBAAsB,GAAG;AAAA,EAC3B;AACD;AAEO,SAAS,uCAA+D;AAC9E,SAAO,6BAA6B,iCAAiC;AACtE;AAEO,SAAS,wBAAwB,OAGb;AAC1B,SAAO;AAAA,IACN,CAAC,uBAAuB,GAAG;AAAA,IAC3B,CAAC,sBAAsB,GAAG;AAAA,IAC1B,CAAC,wBAAwB,GAAG,MAAM;AAAA,IAClC,CAAC,6BAA6B,GAAG,MAAM;AAAA,EACxC;AACD;AAEO,SAAS,mCAA2D;AAC1E,SAAO,6BAA6B,6BAA6B;AAClE;AAGO,SAAS,0BAA0B,QAAyC;AAClF,SACC,OAAO,uBAAuB,MAAM,iCACpC,OAAO,sBAAsB,MAAM;AAErC;AAMO,SAAS,wBAAwB,QAA2D;AAClG,MAAI,CAAC,0BAA0B,MAAM,GAAG;AACvC,WAAO;AAAA,EACR;AACA,QAAM,aAAa,OAAO,wBAAwB;AAClD,QAAM,WAAW,OAAO,sBAAsB;AAC9C,QAAM,cAAc,OAAO,yBAAyB;AACpD,MAAI,CAAC,cAAc,CAAC,YAAY,CAAC,aAAa;AAC7C,WAAO;AAAA,EACR;AACA,SAAO,EAAE,YAAY,UAAU,YAAY;AAC5C;AAGO,SAAS,6BAAqD;AACpE,SAAO,6BAA6B,4BAA4B;AACjE;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/local-worker-runner.ts"],"sourcesContent":["import { type ChildProcess, execFile, spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { promisify } from \"node:util\";\nimport { createFilesystemProcessStateExporter } from \"./filesystem-process-state-exporter.js\";\nimport { UnitExitNotifier } from \"./runner-utils.js\";\nimport type {\n\tLocalStartWorkerInput,\n\tProcessStateExporter,\n\tStopWorkerOptions,\n\tWorkerExitInfo,\n\tWorkerRunner,\n\tWorkerUnit,\n\tWorkerUnitDescriptor,\n\tWorkerUnitRef,\n} from \"./types.js\";\n\nexport const DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER = \"@leitwerk-dev/worker/worker-entry\";\n\nexport interface LocalWorkerRunnerOptions {\n\t/** Command used to launch the worker. Defaults to `node`. */\n\tcommand?: string;\n\t/** Worker entry args. The default package subpath is resolved to the installed entry file. */\n\targs?: readonly string[];\n\t/** Working directory for the spawned worker. Defaults to the installed server package dir. */\n\tcwd?: string;\n\t/** Process storage roots used by the read-only session exporter. */\n\tprocessWorkspacesDir?: string;\n\ttreeFilesDir?: string;\n\t/** Explicit acknowledgement that Docker processes inherit host Docker authority. */\n\tallowHostDocker?: boolean;\n\t/** Test seam. Production uses node's spawn directly. */\n\tlocalWorkerSpawnImpl?: typeof spawn;\n\t/** Test seam for the shared host-Docker preflight. */\n\tdockerPreflightImpl?: (timeoutMs: number) => Promise<void>;\n}\n\n/** Verifies that the inherited Docker CLI context can reach its daemon. */\nexport async function preflightHostDocker(timeoutMs: number): Promise<void> {\n\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n\t\tthrow new Error(\"Docker preflight requires a positive startup timeout\");\n\t}\n\ttry {\n\t\tawait promisify(execFile)(\"docker\", [\"info\"], {\n\t\t\tenv: process.env,\n\t\t\ttimeout: timeoutMs,\n\t\t\tkillSignal: \"SIGKILL\",\n\t\t});\n\t} catch (error) {\n\t\tif (error && typeof error === \"object\" && \"killed\" in error && error.killed) {\n\t\t\tthrow new Error(`Docker preflight timed out after ${timeoutMs}ms`, { cause: error });\n\t\t}\n\t\tthrow error;\n\t}\n}\n\ninterface LocalWorkerUnitState {\n\tref: WorkerUnitRef;\n\tchild: ChildProcess;\n\tstatus: \"running\" | \"stopping\" | \"exited\";\n}\n\nlet localUnitCounter = 0;\n\nfunction nextUnitId(instanceId: string, workerId: string): string {\n\tlocalUnitCounter += 1;\n\treturn `local_${instanceId}_${workerId}_${localUnitCounter}`;\n}\n\nfunction findServerPackageDir(): string {\n\tlet current = path.dirname(fileURLToPath(import.meta.url));\n\twhile (true) {\n\t\tconst candidate = path.join(current, \"package.json\");\n\t\tif (existsSync(candidate)) return current;\n\t\tconst parent = path.dirname(current);\n\t\tif (parent === current) return process.cwd();\n\t\tcurrent = parent;\n\t}\n}\n\nfunction resolveDefaultWorkerEntryPath(): string {\n\treturn fileURLToPath(import.meta.resolve(DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER));\n}\n\nexport function resolveLocalWorkerSpawnArgs(args: readonly string[]): string[] {\n\treturn args[0] === DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER\n\t\t? [resolveDefaultWorkerEntryPath(), ...args.slice(1)]\n\t\t: [...args];\n}\n\nfunction exitInfo(code: number | null, signal: NodeJS.Signals | null): WorkerExitInfo {\n\treturn { exitCode: code, signal };\n}\n\n/**\n * Best-effort local development/test {@link WorkerRunner}.\n *\n * This runner implements the shared runner contract needed to start and stop a\n * local worker over the production WebSocket IPC path. It is not an isolation\n * boundary, has no restart adoption, and ignores image/resource profile semantics.\n * Docker and Kubernetes remain the contract-defining production runners.\n */\nexport function createLocalWorkerRunner(options: LocalWorkerRunnerOptions): {\n\trunner: WorkerRunner<LocalStartWorkerInput>;\n\texporter: ProcessStateExporter;\n} {\n\tconst command = options.command ?? \"node\";\n\tconst args = resolveLocalWorkerSpawnArgs(options.args ?? [DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER]);\n\tconst cwd = options.cwd ?? findServerPackageDir();\n\tconst localWorkerSpawnImpl = options.localWorkerSpawnImpl ?? spawn;\n\tconst dockerPreflightImpl = options.dockerPreflightImpl ?? preflightHostDocker;\n\tconst units = new Map<string, LocalWorkerUnitState>();\n\tconst exitNotifier = new UnitExitNotifier();\n\n\tfunction wrap(ref: WorkerUnitRef): WorkerUnit {\n\t\treturn exitNotifier.wrapUnit(ref, ref.unitId);\n\t}\n\n\tconst runner: WorkerRunner<LocalStartWorkerInput> = {\n\t\tasync start(input: LocalStartWorkerInput, observer): Promise<WorkerUnit> {\n\t\t\tobserver?.report(\"preparing_runtime\");\n\t\t\tif (input.docker) {\n\t\t\t\tif (options.allowHostDocker !== true) {\n\t\t\t\t\tthrow new Error(\"Docker-requiring processes need local_worker.allow_host_docker: true\");\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst configuredTimeoutMs = Number.parseInt(\n\t\t\t\t\t\tinput.env.LEITWERK_WORKER_STARTUP_TIMEOUT_MS ?? \"30000\",\n\t\t\t\t\t\t10,\n\t\t\t\t\t);\n\t\t\t\t\tconst deadlineMs = Number.parseInt(\n\t\t\t\t\t\tinput.env.LEITWERK_WORKER_STARTUP_DEADLINE_MS ?? \"\",\n\t\t\t\t\t\t10,\n\t\t\t\t\t);\n\t\t\t\t\tconst timeoutMs = Number.isFinite(deadlineMs)\n\t\t\t\t\t\t? Math.min(configuredTimeoutMs, deadlineMs - Date.now())\n\t\t\t\t\t\t: configuredTimeoutMs;\n\t\t\t\t\tif (timeoutMs <= 0)\n\t\t\t\t\t\tthrow new Error(\"Worker startup deadline expired before Docker preflight\");\n\t\t\t\t\tawait dockerPreflightImpl(timeoutMs);\n\t\t\t\t\tif (Date.now() >= deadlineMs) {\n\t\t\t\t\t\tthrow new Error(\"Worker startup deadline expired during Docker preflight\");\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow new Error(\"Local Docker preflight failed: Docker CLI or daemon is unavailable\", {\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst unitId = nextUnitId(input.instanceId, input.workerId);\n\t\t\tconst ref: WorkerUnitRef = { instanceId: input.instanceId, workerId: input.workerId, unitId };\n\t\t\tobserver?.report(\"starting_runtime\");\n\t\t\tconst child = localWorkerSpawnImpl(command, args, {\n\t\t\t\tcwd,\n\t\t\t\tstdio: [\"ignore\", \"inherit\", \"inherit\"],\n\t\t\t\tenv: {\n\t\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t\tObject.entries(process.env).filter(\n\t\t\t\t\t\t\t([key]) => !/(?:^|_)(?:TOKEN|API_KEY|PASSWORD|SECRET)$/.test(key),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t\t...input.env,\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst state: LocalWorkerUnitState = {\n\t\t\t\tref,\n\t\t\t\tchild,\n\t\t\t\tstatus: \"running\",\n\t\t\t};\n\t\t\tunits.set(unitId, state);\n\t\t\tchild.once(\"exit\", (code, signal) => {\n\t\t\t\tstate.status = \"exited\";\n\t\t\t\texitNotifier.fireExit(unitId, exitInfo(code, signal));\n\t\t\t});\n\t\t\tchild.once(\"error\", (error) => {\n\t\t\t\tstate.status = \"exited\";\n\t\t\t\texitNotifier.fireExit(unitId, {\n\t\t\t\t\texitCode: null,\n\t\t\t\t\tsignal: null,\n\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn wrap(ref);\n\t\t},\n\t\tasync stop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void> {\n\t\t\tconst state = units.get(ref.unitId);\n\t\t\tif (!state || state.status === \"exited\") return;\n\t\t\tstate.status = \"stopping\";\n\t\t\tconst child = state.child;\n\t\t\tconst exited = new Promise<void>((resolve) => child.once(\"exit\", () => resolve()));\n\t\t\tchild.kill(\"SIGTERM\");\n\t\t\tconst timedOut = await Promise.race([\n\t\t\t\texited.then(() => false),\n\t\t\t\tnew Promise<boolean>((resolve) => setTimeout(() => resolve(true), opts.graceMs)),\n\t\t\t]);\n\t\t\tif (timedOut) child.kill(\"SIGKILL\");\n\t\t},\n\t\tasync list(): Promise<WorkerUnitDescriptor[]> {\n\t\t\treturn [];\n\t\t},\n\t\tasync adopt(descriptor: WorkerUnitDescriptor): Promise<WorkerUnit> {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot adopt local worker ${descriptor.unitId}: local runner does not support adoption`,\n\t\t\t);\n\t\t},\n\t};\n\n\tconst processWorkspacesDir = path.resolve(\n\t\toptions.processWorkspacesDir ?? \"/tmp/leitwerk/workspaces\",\n\t);\n\tconst treeFilesDir = path.resolve(options.treeFilesDir ?? \"/tmp/leitwerk/trees\");\n\tconst exporter = createFilesystemProcessStateExporter({\n\t\tallowedRoots: [processWorkspacesDir, treeFilesDir],\n\t\tresolveSource: (instanceId) => ({\n\t\t\tworkspaceRoot: path.join(processWorkspacesDir, instanceId),\n\t\t\tsessionFile: path.join(treeFilesDir, `${instanceId}.jsonl`),\n\t\t}),\n\t});\n\treturn { runner, exporter };\n}\n"],"mappings":";;;;;;;;AAAA,SAA4B,UAAU,aAAa;AACnD,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAcnB,IAAM,uCAAuC;AAqBpD,eAAsB,oBAAoB,WAAkC;AAC3E,MAAI,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,GAAG;AAClD,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACvE;AACA,MAAI;AACH,UAAM,UAAU,QAAQ,EAAE,UAAU,CAAC,MAAM,GAAG;AAAA,MAC7C,KAAK,QAAQ;AAAA,MACb,SAAS;AAAA,MACT,YAAY;AAAA,IACb,CAAC;AAAA,EACF,SAAS,OAAO;AACf,QAAI,SAAS,OAAO,UAAU,YAAY,YAAY,SAAS,MAAM,QAAQ;AAC5E,YAAM,IAAI,MAAM,oCAAoC,SAAS,MAAM,EAAE,OAAO,MAAM,CAAC;AAAA,IACpF;AACA,UAAM;AAAA,EACP;AACD;AAQA,IAAI,mBAAmB;AAEvB,SAAS,WAAW,YAAoB,UAA0B;AACjE,sBAAoB;AACpB,SAAO,SAAS,UAAU,IAAI,QAAQ,IAAI,gBAAgB;AAC3D;AAEA,SAAS,uBAA+B;AACvC,MAAI,UAAU,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC;AACzD,SAAO,MAAM;AACZ,UAAM,YAAY,KAAK,KAAK,SAAS,cAAc;AACnD,QAAI,WAAW,SAAS,EAAG,QAAO;AAClC,UAAM,SAAS,KAAK,QAAQ,OAAO;AACnC,QAAI,WAAW,QAAS,QAAO,QAAQ,IAAI;AAC3C,cAAU;AAAA,EACX;AACD;AAEA,SAAS,gCAAwC;AAChD,SAAO,cAAc,YAAY,QAAQ,oCAAoC,CAAC;AAC/E;AAEO,SA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AAY,MAAM,KAAK,QAAQ,MAAM,QAAQ,CAAC,CAAC;AACjF,YAAM,KAAK,SAAS;AACpB,YAAM,WAAW,MAAM,QAAQ,KAAK;AAAA,QACnC,OAAO,KAAK,MAAM,KAAK;AAAA,QACvB,IAAI,QAAiB,CAAC,YAAY,WAAW,MAAM,QAAQ,IAAI,GAAG,KAAK,OAAO,CAAC;AAAA,MAChF,CAAC;AACD,UAAI,SAAU,OAAM,KAAK,SAAS;AAAA,IACnC;AAAA,IACA,MAAM,OAAwC;AAC7C,aAAO,CAAC;AAAA,IACT;AAAA,IACA,MAAM,MAAM,YAAuD;AAClE,YAAM,IAAI;AAAA,QACT,6BAA6B,WAAW,MAAM;AAAA,MAC/C;AAAA,IACD;AAAA,EACD;AAEA,QAAM,uBAAuB,KAAK;AAAA,IACjC,QAAQ,wBAAwB;AAAA,EACjC;AACA,QAAM,eAAe,KAAK,QAAQ,QAAQ,gBAAgB,qBAAqB;AAC/E,QAAM,WAAW,qCAAqC;AAAA,IACrD,cAAc,CAAC,sBAAsB,YAAY;AAAA,IACjD,eAAe,CAAC,gBAAgB;AAAA,MAC/B,eAAe,KAAK,KAAK,sBAAsB,UAAU;AAAA,MACzD,aAAa,KAAK,KAAK,cAAc,GAAG,UAAU,QAAQ;AAAA,IAC3D;AAAA,EACD,CAAC;AACD,SAAO,EAAE,QAAQ,SAAS;AAC3B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Readable } from \"node:stream\";\nimport type {\n\tLeitwerkTransferManifestV1,\n\tSessionTransferLimits,\n\tSessionTransferPreflight,\n\tSessionTransferPreflightReport,\n} from \"@leitwerk-dev/session-transfer\";\n\n/**\n * Runner API seams shared by worker run modes (Docker, Kubernetes, best-effort local).\n *\n * The seam is cut so the runtimes share everything except the runtime-specific\n * bodies of two interfaces. The IPC transport is deliberately *not* a runner\n * axis: the runner only injects connect env, the worker dials back over\n * WebSocket, and the existing `WorkerWebSocketIpcManager` binds the socket to\n * the lease. The supervisor stays the lease/lifecycle coordinator; the runner\n * only does runtime-specific work.\n */\n\n/**\n * Durable per-process storage handle.\n *\n * The server NEVER mounts or reads the volume contents. It learns tree and leaf\n * state over the protocol (the session-snapshot exchange), never by reading the\n * volume, which keeps every run mode symmetric.\n */\nexport interface VolumeRef {\n\tinstanceId: string;\n\t/** Runtime-specific identifier (host path, named volume, PVC name). */\n\tid: string;\n\t/** Path inside the worker container where the volume is mounted. */\n\tmountPath: string;\n\t/** Runtime-specific namespace/project for the volume (Kubernetes process namespace). */\n\tnamespace?: string;\n}\n\nexport interface ProcessVolumeRequirements {\n\t/** New Kubernetes PVC capacity. Existing volumes are unchanged; other runners ignore it. */\n\tsize?: string;\n\t/** Select storage compatible with a private Docker daemon. */\n\tdocker?: boolean;\n}\n\nexport type ProcessStateExportPreflight = SessionTransferPreflight;\nexport type ProcessStateExportHelperReport = SessionTransferPreflightReport;\n\n/** Server-owned, credential-scoped relay used by isolated export helpers. */\nexport interface ProcessStateExportHelperRelay {\n\treadonly exportId: string;\n\treadonly credential: string;\n\twaitForPreflight(signal?: AbortSignal): Promise<ProcessStateExportHelperReport>;\n\tactivateStream(): Readable;\n\tfail(error: Error): void;\n}\n\nexport interface PreparedProcessStateExport {\n\tmanifest: LeitwerkTransferManifestV1;\n\tpreflight: ProcessStateExportPreflight;\n\tstream(input: { signal?: AbortSignal }): Readable;\n}\n\n/** Purpose-specific read-only export seam. It never creates a worker lease. */\nexport interface ProcessStateExporter {\n\tprepare(input: {\n\t\tinstanceId: string;\n\t\tmanifest: LeitwerkTransferManifestV1;\n\t\tlimits: SessionTransferLimits;\n\t\tsignal?: AbortSignal;\n\t}): Promise<PreparedProcessStateExport>;\n\t/** Removes stale runner-specific export helpers after restart. */\n\treconcile(): Promise<void>;\n}\n\nexport interface ProcessStateExportHelperRelayProvider {\n\tcreate(input: {\n\t\tinstanceId: string;\n\t\tmanifest: LeitwerkTransferManifestV1;\n\t}): ProcessStateExportHelperRelay;\n}\n\nexport interface ProcessVolume {\n\t/** Idempotently provisions durable storage for a process instance. */\n\tensure(\n\t\tinstanceId: string,\n\t\trequirements?: ProcessVolumeRequirements,\n\t\tobserver?: WorkerStartObserver,\n\t): Promise<VolumeRef>;\n\t/** Retention cleanup only. Stopping a worker never calls this. */\n\trelease(instanceId: string): Promise<void>;\n\t/** Permanently deletes every runner-managed resource owned by a deleted process. */\n\tdeleteProcessResources(instanceId: string): Promise<void>;\n}\n\n/**\n * Output of runtime-profile selection. MVP resolves to a single configured\n * worker image; repository branch content must never select an image.\n */\nexport interface ResolvedWorkerImage {\n\t/** Fully qualified image reference, ideally digest-pinned. */\n\treference: string;\n}\n\nexport interface WorkerResourceLimits {\n\tcpu?: string;\n\tmemory?: string;\n}\n\nexport interface WorkerUnitRef {\n\tinstanceId: string;\n\tworkerId: string;\n\t/** Runtime-specific handle id (container id, pod name). */\n\tunitId: string;\n\t/** Runtime-specific namespace/project for the unit (Kubernetes process namespace). */\n\tnamespace?: string;\n}\n\nexport class WorkerStartDiagnosticError extends Error {\n\treadonly publicDiagnostic: string;\n\n\tconstructor(publicDiagnostic: string, cause?: unknown) {\n\t\tsuper(\"Worker runtime start failed\", { cause });\n\t\tthis.name = \"WorkerStartDiagnosticError\";\n\t\tthis.publicDiagnostic = publicDiagnostic;\n\t}\n}\n\nexport interface WorkerExitInfo {\n\t/** Process exit code when the runtime reports one. */\n\texitCode: number | null;\n\t/** Termination signal when the runtime reports one. */\n\tsignal: string | null;\n\t/** True when the runtime killed the unit for exceeding memory limits. */\n\toomKilled?: boolean;\n\t/** Human-readable reason surfaced by the runtime, if any. */\n\treason?: string;\n}\n\nexport interface WorkerUnit extends WorkerUnitRef {\n\t/** Require successful runtime removal before the supervisor permits replacement. */\n\treplacementHandoff?: \"stop-before-replacement\";\n\t/** Maps physical worker exit into the supervisor's existing failure paths. */\n\tonExit(listener: (info: WorkerExitInfo) => void): void;\n}\n\nexport interface WorkerUnitDescriptor extends WorkerUnitRef {\n\tobservedState?: \"running\" | \"pending\" | \"terminal\" | \"unknown\";\n}\n\ninterface StartWorkerInputBase {\n\tinstanceId: string;\n\tworkerId: string;\n\tserverEpoch: string;\n\t/** Runtime-profile selection output; MVP = single image. */\n\timage: ResolvedWorkerImage;\n\t/** Server URL, ids, connect token, `PI_CODING_AGENT_DIR`, etc. */\n\tenv: Record<string, string>;\n\t/** Start the image's private Docker daemon before the worker. */\n\tdocker: boolean;\n\tresources?: WorkerResourceLimits;\n\tresourceRequests?: WorkerResourceLimits;\n}\n\n/** Start input for the best-effort local runner, which uses configured host storage. */\nexport interface LocalStartWorkerInput extends StartWorkerInputBase {\n\trunnerKind: \"local\";\n\tvolume?: never;\n}\n\n/** Start input for isolated runners, whose durable process volume is mandatory. */\nexport interface IsolatedStartWorkerInput extends StartWorkerInputBase {\n\trunnerKind: \"isolated\";\n\tvolume: VolumeRef;\n}\n\nexport type StartWorkerInput = LocalStartWorkerInput | IsolatedStartWorkerInput;\n\nexport interface StopWorkerOptions {\n\t/** Grace period before forceful termination. The volume is always kept. */\n\tgraceMs: number;\n}\n\nexport type WorkerStartPhase = \"preparing_runtime\" | \"allocating_runtime\" | \"starting_runtime\";\n\nexport interface WorkerStartObserver {\n\tobserve?(\n\t\tobservation: Omit<\n\t\t\timport(\"@leitwerk-dev/domain\").StartupObservation,\n\t\t\t\"workerLeaseId\" | \"turnRecordId\"\n\t\t>,\n\t): void;\n\tshouldStop?(): boolean;\n\treport(phase: WorkerStartPhase): void;\n}\n\nexport interface WorkerRunner<TStartInput extends StartWorkerInput = StartWorkerInput> {\n\tstart(input: TStartInput, observer?: WorkerStartObserver): Promise<WorkerUnit>;\n\t/** Stops the unit but keeps the process volume for resume. */\n\tstop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void>;\n\t/** Adoption scan: lists labelled worker units. */\n\tlist(): Promise<WorkerUnitDescriptor[]>;\n\t/** Reconnects to a live unit discovered by {@link WorkerRunner.list}. */\n\tadopt(descriptor: WorkerUnitDescriptor, observer?: WorkerStartObserver): Promise<WorkerUnit>;\n}\n"],"mappings":";AAoHO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAC5C;AAAA,EAET,YAAY,kBAA0B,OAAiB;AACtD,UAAM,+BAA+B,EAAE,MAAM,CAAC;AAC9C,SAAK,OAAO;AACZ,SAAK,mBAAmB;AAAA,EACzB;AACD;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/session-transfer-helper.ts"],"sourcesContent":["import path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport {\n\tparseSessionTransferHelperSpec,\n\tprepareTransferArchive,\n} from \"@leitwerk-dev/session-transfer\";\n\nexport const SESSION_TRANSFER_HELPER_ENTRY_PATH =\n\t\"/app/packages/worker-runners/dist/session-transfer-helper-cli.js\";\nexport const SESSION_TRANSFER_HELPER_MOUNT_PATH = \"/state\";\n\ninterface HelperEnvironment {\n\texportId: string;\n\tcredential: string;\n\tserverUrl: URL;\n}\n\nfunction required(name: string): string {\n\tconst value = process.env[name]?.trim();\n\tif (!value) throw new Error(`Missing ${name}`);\n\treturn value;\n}\n\nfunction readEnvironment(): HelperEnvironment {\n\tconst serverUrl = new URL(required(\"LEITWERK_EXPORT_SERVER_URL\"));\n\tif (!/^https?:$/.test(serverUrl.protocol) || serverUrl.username || serverUrl.password) {\n\t\tthrow new Error(\"Invalid helper server URL\");\n\t}\n\treturn {\n\t\texportId: required(\"LEITWERK_EXPORT_ID\"),\n\t\tcredential: required(\"LEITWERK_EXPORT_CREDENTIAL\"),\n\t\tserverUrl,\n\t};\n}\n\nfunction helperUrl(environment: HelperEnvironment, suffix: string): URL {\n\treturn new URL(\n\t\t`/internal/session-transfer-exports/${encodeURIComponent(environment.exportId)}${suffix}`,\n\t\tenvironment.serverUrl,\n\t);\n}\n\nasync function helperFetch(\n\tenvironment: HelperEnvironment,\n\tsuffix: string,\n\tinit: RequestInit & { duplex?: \"half\" },\n): Promise<Response> {\n\tconst response = await fetch(helperUrl(environment, suffix), {\n\t\t...init,\n\t\tredirect: \"manual\",\n\t\theaders: {\n\t\t\t...init.headers,\n\t\t\tAuthorization: `Bearer ${environment.credential}`,\n\t\t},\n\t});\n\tif (response.status < 200 || response.status >= 300) {\n\t\tthrow new Error(`Helper request failed with HTTP ${response.status}`);\n\t}\n\treturn response;\n}\n\nasync function helperRequest(\n\tenvironment: HelperEnvironment,\n\tsuffix: string,\n\tinit: RequestInit & { duplex?: \"half\" },\n): Promise<void> {\n\tconst response = await helperFetch(environment, suffix, init);\n\tawait response.arrayBuffer();\n}\n\nasync function readHelperSpec(environment: HelperEnvironment) {\n\tconst response = await helperFetch(environment, \"/spec\", { method: \"GET\" });\n\treturn parseSessionTransferHelperSpec(await response.json());\n}\n\nexport async function runSessionTransferHelper(): Promise<void> {\n\tconst environment = readEnvironment();\n\tconst spec = await readHelperSpec(environment);\n\tconst workspaceRoot = path.join(SESSION_TRANSFER_HELPER_MOUNT_PATH, \"workspace\");\n\tconst sessionFile = path.join(SESSION_TRANSFER_HELPER_MOUNT_PATH, \"tree\", \"primary.jsonl\");\n\tconst prepared = await prepareTransferArchive({\n\t\tworkspaceRoot,\n\t\tsessionFile,\n\t\tmanifest: spec.manifest,\n\t\tlimits: spec.limits,\n\t});\n\tawait helperRequest(environment, \"/preflight\", {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({\n\t\t\tmanifest: prepared.manifest,\n\t\t\tpreflight: {\n\t\t\t\tentriesTotal: prepared.preflight.entriesTotal,\n\t\t\t\tlogicalBytesTotal: prepared.preflight.logicalBytesTotal,\n\t\t\t},\n\t\t}),\n\t});\n\tconst archive = prepared.stream({});\n\tawait helperRequest(environment, \"/stream\", {\n\t\tmethod: \"PUT\",\n\t\theaders: { \"Content-Type\": \"application/vnd.leitwerk.session-transfer+tar+zstd\" },\n\t\tbody: Readable.toWeb(archive) as ReadableStream,\n\t\tduplex: \"half\",\n\t});\n}\n"],"mappings":";AAAA,OA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,EAAE,QAAQ,MAAM,CAAC;AAC1E,SAAO,+BAA+B,MAAM,SAAS,KAAK,CAAC;AAC5D;AAEA,eAAsB,2BAA0C;AAC/D,QAAM,cAAc,gBAAgB;AACpC,QAAM,OAAO,MAAM,eAAe,WAAW;AAC7C,QAAM,gBAAgB,KAAK,KAAK,oCAAoC,WAAW;AAC/E,QAAM,cAAc,KAAK,KAAK,oCAAoC,QAAQ,eAAe;AACzF,QAAM,WAAW,MAAM,uBAAuB;AAAA,IAC7C;AAAA,IACA;AAAA,IACA,UAAU,KAAK;AAAA,IACf,QAAQ,KAAK;AAAA,EACd,CAAC;AACD,QAAM,cAAc,aAAa,cAAc;AAAA,IAC9C,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU;AAAA,MACpB,UAAU,SAAS;AAAA,MACnB,WAAW;AAAA,QACV,cAAc,SAAS,UAAU;AAAA,QACjC,mBAAmB,SAAS,UAAU;AAAA,MACvC;AAAA,IACD,CAAC;AAAA,EACF,CAAC;AACD,QAAM,UAAU,SAAS,OAAO,CAAC,CAAC;AAClC,QAAM,cAAc,aAAa,WAAW;AAAA,IAC3C,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,qDAAqD;AAAA,IAChF,MAAM,SAAS,MAAM,OAAO;AAAA,IAC5B,QAAQ;AAAA,EACT,CAAC;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/kubernetes-worker-runner.ts","../src/kubernetes-startup-sampler.ts","../src/kubernetes-volume-pool.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n\tcreateHelperProcessStateExporter,\n\texportHelperEnvironment,\n} from \"./helper-process-state-exporter.js\";\nimport type { KubernetesApiClient } from \"./kubernetes-api-client.js\";\nimport {\n\tbuildKubernetesDockerConfigJsonSecretManifest,\n\tbuildKubernetesExportHelperPodManifest,\n\tbuildKubernetesProcessNamespaceManifest,\n\tbuildKubernetesProcessPvcManifest,\n\tbuildKubernetesServerCaConfigMapManifest,\n\tbuildKubernetesWorkerPodManifest,\n\tKUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,\n\tKUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,\n\tKUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,\n\ttype KubernetesDockerPodSpecOptions,\n\ttype KubernetesPodSpecOptions,\n\ttype KubernetesProcessVolumeSpec,\n\tkubernetesExportHelperPodName,\n\tkubernetesProcessNamespaceName,\n\tkubernetesProcessPvcName,\n\tredactKubernetesDiagnostic,\n\tvolumeRefFromPvc,\n} from \"./kubernetes-manifests.js\";\nimport { sampleKubernetesStartup, startupReceipt } from \"./kubernetes-startup-sampler.js\";\nimport { createKubernetesVolumePool } from \"./kubernetes-volume-pool.js\";\nimport { UnitExitNotifier } from \"./runner-utils.js\";\nimport {\n\tSESSION_TRANSFER_HELPER_ENTRY_PATH,\n\tSESSION_TRANSFER_HELPER_MOUNT_PATH,\n} from \"./session-transfer-helper.js\";\nimport type {\n\tIsolatedStartWorkerInput,\n\tProcessStateExporter,\n\tProcessStateExportHelperRelayProvider,\n\tProcessVolume,\n\tStopWorkerOptions,\n\tWorkerRunner,\n\tWorkerUnit,\n\tWorkerUnitDescriptor,\n\tWorkerUnitRef,\n} from \"./types.js\";\nimport { WorkerStartDiagnosticError } from \"./types.js\";\nimport {\n\tmanagedExportHelperLabelSelector,\n\tmanagedProcessNamespaceLabelSelector,\n\tmanagedWorkerLabelSelector,\n\tparseWorkerUnitIdentity,\n\tWORKER_LABEL_COMPONENT,\n\tWORKER_LABEL_INSTANCE_ID,\n\tWORKER_LABEL_MANAGED_BY,\n\tWORKER_LABEL_MANAGED_BY_VALUE,\n} from \"./worker-labels.js\";\n\nconst KUBERNETES_START_DIAGNOSTIC_MAX_LENGTH = 2_048;\n\nfunction boundedKubernetesStartDiagnostic(\n\terror: unknown,\n\tsensitiveValues: readonly string[],\n): string {\n\tconst detail = error instanceof Error ? error.message : \"Kubernetes Pod admission failed\";\n\treturn redactKubernetesDiagnostic(detail, sensitiveValues).slice(\n\t\t0,\n\t\tKUBERNETES_START_DIAGNOSTIC_MAX_LENGTH,\n\t);\n}\n\nexport interface KubernetesWorkerRunnerOptions {\n\tpreProvision?: { count: number; onError?: () => void };\n\tclient: KubernetesApiClient;\n\t/** Prefix used to derive one Kubernetes namespace per process instance. */\n\tprocessNamespacePrefix: string;\n\tvolume: KubernetesProcessVolumeSpec;\n\t/** Storage and Pod wiring for process definitions that require private Docker. */\n\tdocker?: KubernetesDockerPodSpecOptions & { processStorageClassName: string };\n\t/** Maximum wait after deletion before replacement is rejected. */\n\tpodDisappearanceTimeoutMs?: number;\n\tpodDisappearancePollIntervalMs?: number;\n\t/** Test seam for bounded disappearance polling. */\n\tdelay?: (ms: number) => Promise<void>;\n\t/** Server-local CA bundle copied into each process namespace for worker TLS trust. */\n\tserverCaFile?: string;\n\t/** Namespace containing operator-managed source image-pull Secrets. */\n\tserverNamespace?: string;\n\t/** Docker registry Secrets copied into every process namespace. */\n\timagePullSecretCopies?: Array<{ sourceName: string; targetName: string }>;\n\tpod?: Omit<KubernetesPodSpecOptions, \"namespace\">;\n\t/** Stable internal URL used by PVC export helpers. */\n\tserverUrl?: string;\n\t/** Trusted image containing the bundled session-transfer helper entrypoint. */\n\texporterImage?: string;\n\t/** Pull policy for the trusted helper image. */\n\texporterImagePullPolicy?: string;\n\t/** Server-owned relay registry used by PVC export helpers. */\n\thelperRelays?: ProcessStateExportHelperRelayProvider;\n}\n\nexport function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOptions): {\n\trunner: WorkerRunner<IsolatedStartWorkerInput>;\n\tvolume: ProcessVolume;\n\texporter: ProcessStateExporter;\n\tvolumePool?: ReturnType<typeof createKubernetesVolumePool>;\n} {\n\tif (!options.serverUrl || !options.exporterImage || !options.helperRelays) {\n\t\tthrow new Error(\"Kubernetes transfer exporter is not configured\");\n\t}\n\tconst { client } = options;\n\tconst exporterServerUrl = options.serverUrl;\n\tconst exporterImage = options.exporterImage;\n\tconst helperRelays = options.helperRelays;\n\tconst serverCaFile = options.serverCaFile?.trim();\n\tconst namespaceForProcess = (instanceId: string) =>\n\t\tkubernetesProcessNamespaceName(instanceId, options.processNamespacePrefix);\n\tconst delay =\n\t\toptions.delay ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\tconst podDisappearanceTimeoutMs = options.podDisappearanceTimeoutMs ?? 30_000;\n\tconst podDisappearancePollIntervalMs = options.podDisappearancePollIntervalMs ?? 250;\n\n\tconst samplers = new Map<string, ReturnType<typeof sampleKubernetesStartup>>();\n\tconst volume: ProcessVolume = {\n\t\tasync ensure(instanceId, requirements, observer) {\n\t\t\tconst namespaceManifest = buildKubernetesProcessNamespaceManifest({\n\t\t\t\tinstanceId,\n\t\t\t\tprocessNamespacePrefix: options.processNamespacePrefix,\n\t\t\t});\n\t\t\tawait client.ensureNamespace(namespaceManifest);\n\t\t\tconst copySecrets = (options.imagePullSecretCopies ?? []).map(async (copy) => {\n\t\t\t\tconst dockerConfigJson = await client.getDockerConfigJsonSecret(\n\t\t\t\t\tcopy.sourceName,\n\t\t\t\t\toptions.serverNamespace ?? \"leitwerk-system\",\n\t\t\t\t);\n\t\t\t\tawait client.ensureDockerConfigJsonSecret(\n\t\t\t\t\tbuildKubernetesDockerConfigJsonSecretManifest({\n\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\t\t\tname: copy.targetName,\n\t\t\t\t\t\tdockerConfigJson,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t});\n\t\t\tconst workerServiceAccount = options.pod?.workerServiceAccount?.trim();\n\t\t\tconst manifest = buildKubernetesProcessPvcManifest({\n\t\t\t\tinstanceId,\n\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\tvolume: {\n\t\t\t\t\t...options.volume,\n\t\t\t\t\tsize: requirements?.size ?? options.volume.size,\n\t\t\t\t\t...(requirements?.docker && options.docker\n\t\t\t\t\t\t? { storageClassName: options.docker.processStorageClassName }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t});\n\t\t\tawait Promise.all([\n\t\t\t\t...copySecrets,\n\t\t\t\t...(serverCaFile\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tclient.ensureConfigMap(\n\t\t\t\t\t\t\t\tbuildKubernetesServerCaConfigMapManifest({\n\t\t\t\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\t\t\t\tnamespace: namespaceManifest.metadata.name,\n\t\t\t\t\t\t\t\t\tcaPem: readFileSync(serverCaFile, \"utf8\"),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t]\n\t\t\t\t\t: []),\n\t\t\t\t...(workerServiceAccount && workerServiceAccount !== \"default\"\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tclient.ensureServiceAccount(workerServiceAccount, namespaceManifest.metadata.name, {\n\t\t\t\t\t\t\t\t[WORKER_LABEL_MANAGED_BY]: WORKER_LABEL_MANAGED_BY_VALUE,\n\t\t\t\t\t\t\t\t[WORKER_LABEL_COMPONENT]: \"worker-service-account\",\n\t\t\t\t\t\t\t\t[WORKER_LABEL_INSTANCE_ID]: instanceId,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t]\n\t\t\t\t\t: []),\n\t\t\t\t(async () => {\n\t\t\t\t\tstartupReceipt(observer, \"pvc_requested\", {\n\t\t\t\t\t\tstorageClass: manifest.spec.storageClassName,\n\t\t\t\t\t});\n\t\t\t\t\tawait client.ensurePersistentVolumeClaim(manifest);\n\t\t\t\t\tstartupReceipt(observer, \"pvc_acknowledged\", {\n\t\t\t\t\t\tstorageClass: manifest.spec.storageClassName,\n\t\t\t\t\t});\n\t\t\t\t\tif (observer?.observe) {\n\t\t\t\t\t\tsamplers.get(instanceId)?.stop();\n\t\t\t\t\t\tsamplers.set(\n\t\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\t\tsampleKubernetesStartup(\n\t\t\t\t\t\t\t\tclient,\n\t\t\t\t\t\t\t\tobserver,\n\t\t\t\t\t\t\t\tmanifest.metadata.namespace,\n\t\t\t\t\t\t\t\tmanifest.metadata.name,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\t]);\n\t\t\treturn volumeRefFromPvc({\n\t\t\t\tinstanceId,\n\t\t\t\tpvcName: manifest.metadata.name,\n\t\t\t\tmountPath: options.volume.mountPath,\n\t\t\t\tnamespace: manifest.metadata.namespace,\n\t\t\t});\n\t\t},\n\t\tasync release(instanceId) {\n\t\t\tawait client.deletePersistentVolumeClaim(\n\t\t\t\tkubernetesProcessPvcName(instanceId, options.volume.namePrefix),\n\t\t\t\tnamespaceForProcess(instanceId),\n\t\t\t);\n\t\t},\n\t\tasync deleteProcessResources(instanceId) {\n\t\t\tsamplers.get(instanceId)?.stop();\n\t\t\tsamplers.delete(instanceId);\n\t\t\tawait client.deleteNamespace(namespaceForProcess(instanceId));\n\t\t},\n\t};\n\n\tconst exitNotifier = new UnitExitNotifier();\n\tconst unsubscribers = new Map<string, () => void>();\n\tconst disappearancePromises = new Map<string, Promise<void>>();\n\n\tfunction unitKey(namespace: string, unitId: string): string {\n\t\treturn `${namespace}/${unitId}`;\n\t}\n\n\tfunction deletePodAndWait(\n\t\tname: string,\n\t\tnamespace: string,\n\t\tgracePeriodSeconds: number,\n\t): Promise<void> {\n\t\tconst key = unitKey(namespace, name);\n\t\tconst existing = disappearancePromises.get(key);\n\t\tif (existing) return existing;\n\t\tconst operation = Promise.resolve()\n\t\t\t.then(async () => {\n\t\t\t\tconst deadline = Date.now() + podDisappearanceTimeoutMs;\n\t\t\t\tconst timeoutError = new Error(\n\t\t\t\t\t`Kubernetes worker Pod ${namespace}/${name} did not disappear within ${podDisappearanceTimeoutMs}ms; replacement was not started`,\n\t\t\t\t);\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tconst { signal } = controller;\n\t\t\t\tlet rejectTimeout!: (error: Error) => void;\n\t\t\t\tconst timedOut = new Promise<never>((_resolve, reject) => {\n\t\t\t\t\trejectTimeout = reject;\n\t\t\t\t});\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\tcontroller.abort(timeoutError);\n\t\t\t\t\trejectTimeout(timeoutError);\n\t\t\t\t}, podDisappearanceTimeoutMs);\n\t\t\t\tconst waitForDisappearance = async () => {\n\t\t\t\t\tawait client.deletePod(name, namespace, { gracePeriodSeconds, signal });\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\t\tif (Date.now() >= deadline) throw timeoutError;\n\t\t\t\t\t\tconst pod = await client.getPod(name, namespace, { signal });\n\t\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\t\tif (Date.now() >= deadline) throw timeoutError;\n\t\t\t\t\t\tif (!pod) return;\n\t\t\t\t\t\tawait delay(\n\t\t\t\t\t\t\tMath.min(podDisappearancePollIntervalMs, Math.max(0, deadline - Date.now())),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tawait Promise.race([waitForDisappearance(), timedOut]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (signal.aborted) throw timeoutError;\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => disappearancePromises.delete(key));\n\t\tdisappearancePromises.set(key, operation);\n\t\treturn operation;\n\t}\n\n\tfunction watchPod(\n\t\tunitId: string,\n\t\tnamespace: string,\n\t\tsensitiveValues: readonly string[] = [],\n\t): void {\n\t\tconst key = unitKey(namespace, unitId);\n\t\tif (unsubscribers.has(key)) return;\n\t\tconst unsubscribe = client.onPodExit(\n\t\t\tunitId,\n\t\t\tnamespace,\n\t\t\t(info) => {\n\t\t\t\texitNotifier.fireExit(key, info);\n\t\t\t\tunsubscribers.get(key)?.();\n\t\t\t\tunsubscribers.delete(key);\n\t\t\t},\n\t\t\t{ sensitiveValues },\n\t\t);\n\t\tunsubscribers.set(key, unsubscribe);\n\t}\n\n\tconst runner: WorkerRunner<IsolatedStartWorkerInput> = {\n\t\tasync start(input: IsolatedStartWorkerInput, observer): Promise<WorkerUnit> {\n\t\t\tobserver?.report(\"preparing_runtime\");\n\t\t\tif (input.docker && !options.docker) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Kubernetes Docker runtime is unavailable; configure kubernetes.docker completely\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst processNamespace = input.volume.namespace ?? namespaceForProcess(input.instanceId);\n\t\t\tconst manifest = buildKubernetesWorkerPodManifest(input, {\n\t\t\t\tnamespace: processNamespace,\n\t\t\t\t...(options.pod ?? {}),\n\t\t\t\t...(input.docker && options.docker ? { docker: options.docker } : {}),\n\t\t\t\t...(serverCaFile\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tserverCaConfigMap: {\n\t\t\t\t\t\t\t\tname: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,\n\t\t\t\t\t\t\t\tkey: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,\n\t\t\t\t\t\t\t\tmountPath: KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tobserver?.report(\"allocating_runtime\");\n\t\t\ttry {\n\t\t\t\tstartupReceipt(observer, \"pod_requested\", {\n\t\t\t\t\timage: input.image.reference,\n\t\t\t\t\t...input.resources,\n\t\t\t\t});\n\t\t\t\tawait client.createPod(manifest);\n\t\t\t\tstartupReceipt(observer, \"pod_acknowledged\");\n\t\t\t\tsamplers.get(input.instanceId)?.attachPod({\n\t\t\t\t\tname: manifest.metadata.name,\n\t\t\t\t\tworkerId: input.workerId,\n\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tsamplers.get(input.instanceId)?.stop();\n\t\t\t\tsamplers.delete(input.instanceId);\n\t\t\t\tthrow new WorkerStartDiagnosticError(\n\t\t\t\t\tboundedKubernetesStartDiagnostic(error, Object.values(input.env)),\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t}\n\t\t\tobserver?.report(\"starting_runtime\");\n\t\t\tconst ref: WorkerUnitRef = {\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tworkerId: input.workerId,\n\t\t\t\tunitId: manifest.metadata.name,\n\t\t\t\tnamespace: manifest.metadata.namespace,\n\t\t\t};\n\t\t\twatchPod(ref.unitId, ref.namespace ?? processNamespace, Object.values(input.env));\n\t\t\treturn exitNotifier.wrapUnit(ref, unitKey(ref.namespace ?? processNamespace, ref.unitId), {\n\t\t\t\treplacementHandoff: \"stop-before-replacement\",\n\t\t\t});\n\t\t},\n\t\tasync stop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void> {\n\t\t\tsamplers.get(ref.instanceId)?.stop();\n\t\t\tsamplers.delete(ref.instanceId);\n\t\t\tawait deletePodAndWait(\n\t\t\t\tref.unitId,\n\t\t\t\tref.namespace ?? namespaceForProcess(ref.instanceId),\n\t\t\t\tMath.max(0, Math.ceil(opts.graceMs / 1000)),\n\t\t\t);\n\t\t},\n\t\tasync list(): Promise<WorkerUnitDescriptor[]> {\n\t\t\tconst namespaces = await client.listNamespaces(managedProcessNamespaceLabelSelector());\n\t\t\tconst descriptors: WorkerUnitDescriptor[] = [];\n\t\t\tfor (const namespace of namespaces) {\n\t\t\t\tif (!namespace.name.startsWith(options.processNamespacePrefix)) continue;\n\t\t\t\tconst pods = await client.listPods(namespace.name, managedWorkerLabelSelector());\n\t\t\t\tfor (const pod of pods) {\n\t\t\t\t\tconst identity = parseWorkerUnitIdentity(pod.labels);\n\t\t\t\t\tif (!identity) continue;\n\t\t\t\t\tdescriptors.push({\n\t\t\t\t\t\tinstanceId: identity.instanceId,\n\t\t\t\t\t\tworkerId: identity.workerId,\n\t\t\t\t\t\tunitId: pod.name,\n\t\t\t\t\t\tnamespace: pod.namespace,\n\t\t\t\t\t\tobservedState:\n\t\t\t\t\t\t\tpod.phase === \"Failed\" || pod.phase === \"Succeeded\"\n\t\t\t\t\t\t\t\t? \"terminal\"\n\t\t\t\t\t\t\t\t: pod.phase === \"Pending\"\n\t\t\t\t\t\t\t\t\t? \"pending\"\n\t\t\t\t\t\t\t\t\t: pod.phase === \"Running\"\n\t\t\t\t\t\t\t\t\t\t? \"running\"\n\t\t\t\t\t\t\t\t\t\t: \"unknown\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn descriptors;\n\t\t},\n\t\tasync adopt(descriptor: WorkerUnitDescriptor, observer): Promise<WorkerUnit> {\n\t\t\tconst podNamespace = descriptor.namespace ?? namespaceForProcess(descriptor.instanceId);\n\t\t\tconst pod = await client.getPod(descriptor.unitId, podNamespace);\n\t\t\tconst identity = pod ? parseWorkerUnitIdentity(pod.labels) : null;\n\t\t\tif (\n\t\t\t\t!identity ||\n\t\t\t\tidentity.instanceId !== descriptor.instanceId ||\n\t\t\t\tidentity.workerId !== descriptor.workerId\n\t\t\t) {\n\t\t\t\tthrow new Error(`Cannot adopt worker pod ${descriptor.unitId}: labels changed`);\n\t\t\t}\n\t\t\tif (!pod || pod.phase === \"Failed\" || pod.phase === \"Succeeded\") {\n\t\t\t\tthrow new Error(`Cannot adopt worker pod ${descriptor.unitId}: not running`);\n\t\t\t}\n\t\t\tconst ref: WorkerUnitRef = {\n\t\t\t\tinstanceId: descriptor.instanceId,\n\t\t\t\tworkerId: descriptor.workerId,\n\t\t\t\tunitId: descriptor.unitId,\n\t\t\t\tnamespace: podNamespace,\n\t\t\t};\n\t\t\tif (observer?.observe && pod.pvcName) {\n\t\t\t\tsamplers.get(descriptor.instanceId)?.stop();\n\t\t\t\tconst sampler = sampleKubernetesStartup(client, observer, podNamespace, pod.pvcName);\n\t\t\t\tsampler.attachPod({ name: ref.unitId, workerId: ref.workerId, instanceId: ref.instanceId });\n\t\t\t\tsamplers.set(descriptor.instanceId, sampler);\n\t\t\t}\n\t\t\twatchPod(ref.unitId, podNamespace);\n\t\t\treturn exitNotifier.wrapUnit(ref, unitKey(podNamespace, ref.unitId), {\n\t\t\t\treplacementHandoff: \"stop-before-replacement\",\n\t\t\t});\n\t\t},\n\t};\n\n\tconst exporter = createHelperProcessStateExporter({\n\t\tvolume,\n\t\thelperRelays,\n\t\tasync launch(input) {\n\t\t\tconst namespace = input.volume.namespace ?? namespaceForProcess(input.instanceId);\n\t\t\tconst podName = kubernetesExportHelperPodName(input.instanceId, input.exportId);\n\t\t\tconst manifest = buildKubernetesExportHelperPodManifest(\n\t\t\t\t{\n\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\texportId: input.exportId,\n\t\t\t\t\timage: exporterImage,\n\t\t\t\t\tcommand: [\"node\", SESSION_TRANSFER_HELPER_ENTRY_PATH],\n\t\t\t\t\tenv: exportHelperEnvironment({\n\t\t\t\t\t\tserverUrl: exporterServerUrl,\n\t\t\t\t\t\texportId: input.exportId,\n\t\t\t\t\t\tcredential: input.credential,\n\t\t\t\t\t}),\n\t\t\t\t\tvolume: { ...input.volume, mountPath: SESSION_TRANSFER_HELPER_MOUNT_PATH },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tnamespace,\n\t\t\t\t\t...(options.pod ?? {}),\n\t\t\t\t\timagePullPolicy: options.exporterImagePullPolicy,\n\t\t\t\t\t...(serverCaFile\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tserverCaConfigMap: {\n\t\t\t\t\t\t\t\t\tname: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,\n\t\t\t\t\t\t\t\t\tkey: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,\n\t\t\t\t\t\t\t\t\tmountPath: KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t);\n\t\t\tawait client.createPod(manifest);\n\t\t\tconst exit = new Promise<{ exitCode: number | null; reason?: string }>((resolve) => {\n\t\t\t\tclient.onPodExit(podName, namespace, (info) =>\n\t\t\t\t\tresolve({ exitCode: info.exitCode, reason: info.reason }),\n\t\t\t\t);\n\t\t\t});\n\t\t\treturn {\n\t\t\t\twait: () => exit,\n\t\t\t\tremove: () => client.deletePod(podName, namespace, { gracePeriodSeconds: 0 }),\n\t\t\t};\n\t\t},\n\t\tasync reconcileHelpers() {\n\t\t\tconst namespaces = await client.listNamespaces(managedProcessNamespaceLabelSelector());\n\t\t\tfor (const namespace of namespaces) {\n\t\t\t\tconst helpers = await client.listPods(namespace.name, managedExportHelperLabelSelector());\n\t\t\t\tawait Promise.all(\n\t\t\t\t\thelpers.map((helper) =>\n\t\t\t\t\t\tclient.deletePod(helper.name, helper.namespace, { gracePeriodSeconds: 0 }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t});\n\n\tlet volumePool: ReturnType<typeof createKubernetesVolumePool> | undefined;\n\tif (options.preProvision) {\n\t\tif (!client.volumePool || !options.volume.storageClassName || !options.serverNamespace) {\n\t\t\tthrow new Error(\"Volume pre-provisioning requires an API, namespace and StorageClass\");\n\t\t}\n\t\tvolumePool = createKubernetesVolumePool({\n\t\t\tapi: client.volumePool,\n\t\t\tnamespace: options.serverNamespace,\n\t\t\tstorageClassName: options.volume.storageClassName,\n\t\t\tsize: options.volume.size,\n\t\t\taccessModes: options.volume.accessModes,\n\t\t\t...options.preProvision,\n\t\t\timage: exporterImage,\n\t\t\timagePullPolicy: options.exporterImagePullPolicy,\n\t\t\timagePullSecrets: (options.pod?.imagePullSecrets ?? []).map(\n\t\t\t\t(name) =>\n\t\t\t\t\toptions.imagePullSecretCopies?.find((copy) => copy.targetName === name)?.sourceName ??\n\t\t\t\t\tname,\n\t\t\t),\n\t\t\tnodeSelector: options.pod?.nodeSelector,\n\t\t\ttolerations: options.pod?.tolerations,\n\t\t});\n\t}\n\treturn { runner, volume, exporter, volumePool };\n}\n","import type { StartupMilestone, StartupObservation } from \"@leitwerk-dev/domain\";\nimport type { KubernetesApiClient } from \"./kubernetes-api-client.js\";\nimport type { WorkerStartObserver } from \"./types.js\";\nimport { parseWorkerUnitIdentity } from \"./worker-labels.js\";\nexport function startupReceipt(\n\tobserver: WorkerStartObserver | undefined,\n\tmilestone: StartupMilestone,\n\tmetadata: StartupObservation[\"metadata\"] = {},\n): void {\n\ttry {\n\t\tobserver?.observe?.({\n\t\t\tmilestone,\n\t\t\tobservedAt: new Date().toISOString(),\n\t\t\tsourceAt: null,\n\t\t\tsourceKind: \"server\",\n\t\t\tobjectUid: null,\n\t\t\tnotBefore: null,\n\t\t\tmetadata,\n\t\t});\n\t} catch {\n\t\t/* Observation cannot fail startup. */\n\t}\n}\n/** One asynchronous collection cycle per physical worker. Never awaited by lifecycle work. */\nexport function sampleKubernetesStartup(\n\tclient: KubernetesApiClient,\n\tobserver: WorkerStartObserver,\n\tnamespace: string,\n\tpvcName: string,\n) {\n\tlet pod: { name: string; workerId: string; instanceId: string } | undefined;\n\tlet podUid: string | undefined;\n\tlet pvcUid: string | undefined;\n\tlet lastUnbound: string | null = null;\n\tlet stopped = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet active: AbortController | undefined;\n\tlet failures = 0;\n\tconst seen = new Set<StartupMilestone>();\n\tconst deadline = Date.now() + 120_000;\n\tconst emit = (\n\t\tmilestone: StartupMilestone,\n\t\tobjectUid: string,\n\t\tsourceAt: string | null,\n\t\tmetadata: StartupObservation[\"metadata\"],\n\t\tsourceKind: StartupObservation[\"sourceKind\"] = \"kubernetes_status\",\n\t\tnotBefore: string | null = null,\n\t) => {\n\t\tif (\n\t\t\tstopped ||\n\t\t\tseen.has(milestone) ||\n\t\t\t(sourceAt !== null && !Number.isFinite(Date.parse(sourceAt)))\n\t\t)\n\t\t\treturn;\n\t\tobserver.observe?.({\n\t\t\tmilestone,\n\t\t\tobservedAt: new Date().toISOString(),\n\t\t\tsourceAt,\n\t\t\tobjectUid,\n\t\t\tsourceKind,\n\t\t\tnotBefore,\n\t\t\tmetadata: {\n\t\t\t\t...metadata,\n\t\t\t\t...(sourceAt !== null ? { precision: sourcePrecision(sourceAt) } : {}),\n\t\t\t},\n\t\t});\n\t\tseen.add(milestone);\n\t};\n\tconst stop = () => {\n\t\tstopped = true;\n\t\tif (timer) clearTimeout(timer);\n\t\tactive?.abort();\n\t};\n\tconst reportFailure = () => {\n\t\tif (!stopped && failures++ < 3)\n\t\t\tconsole.warn(\"Worker startup observation unavailable: Kubernetes collection failed\");\n\t};\n\tconst cycle = async () => {\n\t\tif (stopped || observer.shouldStop?.() || Date.now() >= deadline) {\n\t\t\tstop();\n\t\t\treturn;\n\t\t}\n\t\tactive = new AbortController();\n\t\tconst timeout = setTimeout(() => active?.abort(), 1500);\n\t\tconst signal = active.signal;\n\t\tconst collectPvc = async () => {\n\t\t\tif (!seen.has(\"pvc_bound\") && client.getPersistentVolumeClaim) {\n\t\t\t\tconst pvc = await client.getPersistentVolumeClaim(pvcName, namespace, { signal });\n\t\t\t\tif (pvc?.uid) {\n\t\t\t\t\tif (pvcUid && pvcUid !== pvc.uid) {\n\t\t\t\t\t\tstop();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tpvcUid = pvc.uid;\n\t\t\t\t\tif (pvc.phase === \"Bound\")\n\t\t\t\t\t\temit(\n\t\t\t\t\t\t\t\"pvc_bound\",\n\t\t\t\t\t\t\tpvc.uid,\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t{ storageClass: pvc.storageClass, precision: \"sampling_interval\" },\n\t\t\t\t\t\t\t\"kubernetes_status\",\n\t\t\t\t\t\t\tlastUnbound,\n\t\t\t\t\t\t);\n\t\t\t\t\telse lastUnbound = new Date().toISOString();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tconst collectPod = async () => {\n\t\t\tif (pod) {\n\t\t\t\tconst summary = await client.getPod(pod.name, namespace, { signal });\n\t\t\t\tif (!summary) {\n\t\t\t\t\tstop();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst identity = parseWorkerUnitIdentity(summary.labels);\n\t\t\t\tif (\n\t\t\t\t\t!identity ||\n\t\t\t\t\tidentity.workerId !== pod.workerId ||\n\t\t\t\t\tidentity.instanceId !== pod.instanceId ||\n\t\t\t\t\t(podUid && podUid !== summary.uid)\n\t\t\t\t) {\n\t\t\t\t\tstop();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (summary.uid) {\n\t\t\t\t\tpodUid = summary.uid;\n\t\t\t\t\tconst metadata = {\n\t\t\t\t\t\tnode: summary.node,\n\t\t\t\t\t\timageId: summary.imageId,\n\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\tpodName: pod.name,\n\t\t\t\t\t\t...summary.resources,\n\t\t\t\t\t};\n\t\t\t\t\tif (summary.createdAt) emit(\"pod_created\", podUid, summary.createdAt, metadata);\n\t\t\t\t\tif (summary.scheduledAt) emit(\"pod_scheduled\", podUid, summary.scheduledAt, metadata);\n\t\t\t\t\tif (summary.containerStartedAt)\n\t\t\t\t\t\temit(\"container_started\", podUid, summary.containerStartedAt, metadata);\n\t\t\t\t\tconst events = await client.listPodEvents(pod.name, namespace, { signal });\n\t\t\t\t\tfor (const event of events) {\n\t\t\t\t\t\tif (event.objectUid !== podUid || event.fieldPath !== \"spec.containers{worker}\")\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tconst at = event.eventTime || event.firstTimestamp;\n\t\t\t\t\t\tif (!at) continue;\n\t\t\t\t\t\tif (event.reason === \"Pulling\")\n\t\t\t\t\t\t\temit(\"image_pull_started\", podUid, at, metadata, \"kubernetes_event\");\n\t\t\t\t\t\tif (event.reason === \"Pulled\")\n\t\t\t\t\t\t\temit(\n\t\t\t\t\t\t\t\tevent.message?.includes(\"already present\") ? \"image_cached\" : \"image_pull_finished\",\n\t\t\t\t\t\t\t\tpodUid,\n\t\t\t\t\t\t\t\tat,\n\t\t\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\t\t\t\"kubernetes_event\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (summary.phase === \"Failed\" || summary.phase === \"Succeeded\") stop();\n\t\t\t}\n\t\t};\n\t\ttry {\n\t\t\tawait Promise.all([collectPvc().catch(reportFailure), collectPod().catch(reportFailure)]);\n\t\t\tif (\n\t\t\t\tseen.has(\"container_started\") &&\n\t\t\t\tseen.has(\"pod_scheduled\") &&\n\t\t\t\tseen.has(\"pvc_bound\") &&\n\t\t\t\t(seen.has(\"image_cached\") ||\n\t\t\t\t\t(seen.has(\"image_pull_started\") && seen.has(\"image_pull_finished\")))\n\t\t\t)\n\t\t\t\tstop();\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t\tactive = undefined;\n\t\t\tif (!stopped) {\n\t\t\t\ttimer = setTimeout(() => void cycle(), 250);\n\t\t\t\ttimer.unref?.();\n\t\t\t}\n\t\t}\n\t};\n\ttimer = setTimeout(() => void cycle(), 0);\n\ttimer.unref?.();\n\treturn {\n\t\tstop,\n\t\tattachPod(input: NonNullable<typeof pod>) {\n\t\t\tpod = input;\n\t\t},\n\t};\n}\n\nfunction sourcePrecision(timestamp: string): \"seconds\" | \"milliseconds\" | \"microseconds\" {\n\tconst digits = /\\.(\\d+)/.exec(timestamp)?.[1].length ?? 0;\n\treturn digits === 0 ? \"seconds\" : digits <= 3 ? \"milliseconds\" : \"microseconds\";\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { PoolObject, VolumePoolApi } from \"./kubernetes-volume-pool-api.js\";\n\nexport const POOL_LABEL = \"leitwerk.dev/volume-pool\";\nconst CLAIM_UID = \"leitwerk.dev/preparation-claim-uid\";\nconst CLAIM_NAME = \"leitwerk.dev/preparation-claim-name\";\nconst POLICY = \"leitwerk.dev/original-reclaim-policy\";\nconst TARGET_CLASS = \"leitwerk.dev/target-storage-class\";\nconst STATE = \"leitwerk.dev/volume-pool-state\";\nconst SIZE = \"leitwerk.dev/preparation-size\";\nconst MODES = \"leitwerk.dev/preparation-access-modes\";\n\nexport interface VolumePoolOptions {\n\tapi: VolumePoolApi;\n\tnamespace: string;\n\tcount: number;\n\tstorageClassName: string;\n\tsize: string;\n\taccessModes: string[];\n\timage: string;\n\timagePullPolicy?: string;\n\timagePullSecrets?: string[];\n\tnodeSelector?: Record<string, string>;\n\ttolerations?: unknown[];\n\tonError?: () => void;\n}\n\n/** Only the staging claim's UID authorizes rebinding; process claims are never recycled. */\nexport function createKubernetesVolumePool(options: VolumePoolOptions) {\n\tconst { api, namespace } = options;\n\tif (!Number.isSafeInteger(options.count) || options.count < 0)\n\t\tthrow new Error(\"Invalid volume pool count\");\n\tconst poolId = createHash(\"sha256\")\n\t\t.update(`${namespace}/${options.storageClassName}`)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 16);\n\tconst selector = `${POOL_LABEL}=${poolId}`;\n\tconst labels = {\n\t\t\"leitwerk.dev/managed-by\": \"leitwerk\",\n\t\t[POOL_LABEL]: poolId,\n\t\t\"leitwerk.dev/component\": \"volume-preparation\",\n\t};\n\tlet controller: AbortController | undefined;\n\tlet running: Promise<void> | undefined;\n\n\tfunction preparationPod(claim: PoolObject): PoolObject {\n\t\treturn {\n\t\t\tapiVersion: \"v1\",\n\t\t\tkind: \"Pod\",\n\t\t\tmetadata: {\n\t\t\t\tname: claim.metadata.name,\n\t\t\t\tnamespace,\n\t\t\t\tlabels,\n\t\t\t\townerReferences: [\n\t\t\t\t\t{\n\t\t\t\t\t\tapiVersion: \"v1\",\n\t\t\t\t\t\tkind: \"PersistentVolumeClaim\",\n\t\t\t\t\t\tname: claim.metadata.name,\n\t\t\t\t\t\tuid: claim.metadata.uid ?? \"\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\tspec: {\n\t\t\t\trestartPolicy: \"Never\",\n\t\t\t\tserviceAccountName: \"default\",\n\t\t\t\tautomountServiceAccountToken: false,\n\t\t\t\tnodeSelector: options.nodeSelector ?? {},\n\t\t\t\ttolerations: options.tolerations ?? [],\n\t\t\t\timagePullSecrets: (options.imagePullSecrets ?? []).map((name) => ({ name })),\n\t\t\t\tcontainers: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"prepare\",\n\t\t\t\t\t\timage: options.image,\n\t\t\t\t\t\timagePullPolicy: options.imagePullPolicy ?? \"IfNotPresent\",\n\t\t\t\t\t\tcommand: [\"node\", \"-e\", \"process.exit(0)\"],\n\t\t\t\t\t\tresources: {\n\t\t\t\t\t\t\trequests: { cpu: \"1m\", memory: \"32Mi\" },\n\t\t\t\t\t\t\tlimits: { cpu: \"100m\", memory: \"64Mi\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsecurityContext: {\n\t\t\t\t\t\t\tallowPrivilegeEscalation: false,\n\t\t\t\t\t\t\treadOnlyRootFilesystem: true,\n\t\t\t\t\t\t\tcapabilities: { drop: [\"ALL\"] },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tvolumeMounts: [{ name: \"volume\", mountPath: \"/volume\" }],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tvolumes: [{ name: \"volume\", persistentVolumeClaim: { claimName: claim.metadata.name } }],\n\t\t\t},\n\t\t};\n\t}\n\n\tasync function advanceVolume(pv: PoolObject, signal: AbortSignal): Promise<boolean> {\n\t\tconst annotations = pv.metadata.annotations ?? {};\n\t\tconst uid = annotations[CLAIM_UID];\n\t\tconst name = annotations[CLAIM_NAME];\n\t\tconst policy = annotations[POLICY];\n\t\tif (!uid || !name || ![\"Delete\", \"Retain\"].includes(policy))\n\t\t\tthrow new Error(\"Invalid prepared-volume ownership\");\n\t\tif (pv.metadata.deletionTimestamp) return false;\n\t\tconst claim = pv.spec.claimRef;\n\t\tif (claim && claim.uid !== uid) {\n\t\t\t// A process has consumed this PV, including if it was already released again.\n\t\t\tconst remainingLabels = { ...pv.metadata.labels };\n\t\t\tdelete remainingLabels[POOL_LABEL];\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: policy },\n\t\t\t\t\t{ op: \"add\", path: \"/metadata/labels\", value: remainingLabels },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tif (claim) {\n\t\t\tif (pv.spec.persistentVolumeReclaimPolicy !== \"Retain\")\n\t\t\t\tthrow new Error(\"Staging PV must be retained before release\");\n\t\t\tconst pod = await api.get(\"pods\", namespace, name, signal);\n\t\t\tif (pod) {\n\t\t\t\tif (\n\t\t\t\t\tpod.metadata.labels?.[POOL_LABEL] !== poolId ||\n\t\t\t\t\t!pod.metadata.ownerReferences?.some((owner) => owner.uid === uid)\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Preparation Pod ownership mismatch\");\n\t\t\t\tawait api.delete(\"pods\", namespace, pod, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst pvc = await api.get(\"persistentvolumeclaims\", namespace, name, signal);\n\t\t\tif (pvc) {\n\t\t\t\tif (pvc.metadata.uid !== uid) throw new Error(\"Preparation PVC ownership mismatch\");\n\t\t\t\tawait api.delete(\"persistentvolumeclaims\", namespace, pvc, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (pv.status?.phase === \"Released\") {\n\t\t\t\tawait api.patchVolume(\n\t\t\t\t\tpv,\n\t\t\t\t\t[\n\t\t\t\t\t\t{ op: \"test\", path: \"/spec/claimRef/uid\", value: uid },\n\t\t\t\t\t\t{ op: \"remove\", path: \"/spec/claimRef\" },\n\t\t\t\t\t],\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\t// Never restore Delete while the old Released status remains: a provisioner could reclaim it.\n\t\tif (pv.status?.phase === \"Available\" && annotations[STATE] !== \"ready\") {\n\t\t\tconst stagingClass = await api.getStorageClass(name, signal);\n\t\t\tif (stagingClass) {\n\t\t\t\tif (stagingClass.metadata.labels?.[POOL_LABEL] !== poolId)\n\t\t\t\t\tthrow new Error(\"Staging StorageClass ownership mismatch\");\n\t\t\t\tawait api.deleteStorageClass(stagingClass, signal);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst targetClass = annotations[TARGET_CLASS];\n\t\t\tif (!targetClass) throw new Error(\"Target StorageClass is missing\");\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: policy },\n\t\t\t\t\t{ op: \"add\", path: \"/spec/storageClassName\", value: targetClass },\n\t\t\t\t\t{ op: \"add\", path: \"/metadata/annotations\", value: { ...annotations, [STATE]: \"ready\" } },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\tannotations[STATE] !== \"ready\" ||\n\t\t\t(annotations[SIZE] === options.size &&\n\t\t\t\tannotations[MODES] === JSON.stringify(options.accessModes))\n\t\t);\n\t}\n\n\tasync function reconcile(signal: AbortSignal) {\n\t\tconst volumes = await api.list(\"persistentvolumes\", \"\", selector, signal);\n\t\tconst classes = await api.listStorageClasses(selector, signal);\n\t\tconst active = new Set<string>(classes.map((value) => value.metadata.name));\n\t\tfor (const pv of volumes) {\n\t\t\tif (await advanceVolume(pv, signal)) active.add(pv.metadata.annotations?.[CLAIM_NAME] ?? \"\");\n\t\t}\n\t\tconst claims = await api.list(\"persistentvolumeclaims\", namespace, selector, signal);\n\t\tfor (const claim of claims) {\n\t\t\tactive.add(claim.metadata.name);\n\t\t\tif (!claim.metadata.uid || claim.spec.storageClassName !== claim.metadata.name)\n\t\t\t\tthrow new Error(\"Invalid staging PVC identity\");\n\t\t\tif (\n\t\t\t\tclaim.metadata.deletionTimestamp ||\n\t\t\t\tvolumes.some((pv) => pv.metadata.annotations?.[CLAIM_UID] === claim.metadata.uid)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tconst pod = await api.get(\"pods\", namespace, claim.metadata.name, signal);\n\t\t\tif (!pod) {\n\t\t\t\tawait api.create(\"pods\", namespace, preparationPod(claim), signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tpod.metadata.labels?.[POOL_LABEL] !== poolId ||\n\t\t\t\t!pod.metadata.ownerReferences?.some((owner) => owner.uid === claim.metadata.uid)\n\t\t\t)\n\t\t\t\tthrow new Error(\"Preparation Pod ownership mismatch\");\n\t\t\tif (pod.status?.phase === \"Failed\") {\n\t\t\t\tawait api.delete(\"pods\", namespace, pod, signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (pod.status?.phase !== \"Succeeded\" || !claim.spec.volumeName) continue;\n\t\t\tconst pv = await api.get(\"persistentvolumes\", \"\", claim.spec.volumeName, signal);\n\t\t\tif (\n\t\t\t\t!pv ||\n\t\t\t\tpv.spec.claimRef?.uid !== claim.metadata.uid ||\n\t\t\t\tpv.metadata.ownerReferences?.length ||\n\t\t\t\tpv.metadata.deletionTimestamp\n\t\t\t)\n\t\t\t\tthrow new Error(\"Cannot safely retain staging volume\");\n\t\t\tif (pv.metadata.labels?.[POOL_LABEL]) throw new Error(\"PV already belongs to a pool\");\n\t\t\tconst policy = pv.spec.persistentVolumeReclaimPolicy;\n\t\t\tif (!policy || ![\"Delete\", \"Retain\"].includes(policy))\n\t\t\t\tthrow new Error(\"Unsupported reclaim policy\");\n\t\t\tawait api.patchVolume(\n\t\t\t\tpv,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\top: \"add\",\n\t\t\t\t\t\tpath: \"/metadata/labels\",\n\t\t\t\t\t\tvalue: { ...pv.metadata.labels, [POOL_LABEL]: poolId },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\top: \"add\",\n\t\t\t\t\t\tpath: \"/metadata/annotations\",\n\t\t\t\t\t\tvalue: {\n\t\t\t\t\t\t\t...pv.metadata.annotations,\n\t\t\t\t\t\t\t[CLAIM_UID]: claim.metadata.uid,\n\t\t\t\t\t\t\t[CLAIM_NAME]: claim.metadata.name,\n\t\t\t\t\t\t\t[POLICY]: policy,\n\t\t\t\t\t\t\t[STATE]: \"preparing\",\n\t\t\t\t\t\t\t[TARGET_CLASS]: options.storageClassName,\n\t\t\t\t\t\t\t[SIZE]: claim.metadata.annotations?.[SIZE],\n\t\t\t\t\t\t\t[MODES]: claim.metadata.annotations?.[MODES],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{ op: \"add\", path: \"/spec/persistentVolumeReclaimPolicy\", value: \"Retain\" },\n\t\t\t\t],\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\tfor (const stagingClass of classes) {\n\t\t\tconst name = stagingClass.metadata.name;\n\t\t\tif (\n\t\t\t\tstagingClass.metadata.deletionTimestamp ||\n\t\t\t\tclaims.some((claim) => claim.metadata.name === name) ||\n\t\t\t\tvolumes.some((pv) => pv.metadata.annotations?.[CLAIM_NAME] === name)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tawait api.create(\n\t\t\t\t\"persistentvolumeclaims\",\n\t\t\t\tnamespace,\n\t\t\t\t{\n\t\t\t\t\tapiVersion: \"v1\",\n\t\t\t\t\tkind: \"PersistentVolumeClaim\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tnamespace,\n\t\t\t\t\t\tlabels,\n\t\t\t\t\t\tannotations: {\n\t\t\t\t\t\t\t[SIZE]: stagingClass.metadata.annotations?.[SIZE] ?? \"\",\n\t\t\t\t\t\t\t[MODES]: stagingClass.metadata.annotations?.[MODES] ?? \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tspec: {\n\t\t\t\t\t\tstorageClassName: name,\n\t\t\t\t\t\taccessModes: JSON.parse(stagingClass.metadata.annotations?.[MODES] ?? \"null\"),\n\t\t\t\t\t\tvolumeMode: \"Filesystem\",\n\t\t\t\t\t\tresources: {\n\t\t\t\t\t\t\trequests: {\n\t\t\t\t\t\t\t\tstorage: stagingClass.metadata.annotations?.[SIZE],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\t\tif (active.size < options.count) {\n\t\t\tconst source = await api.getStorageClass(options.storageClassName, signal);\n\t\t\tif (!source || [\"kubernetes.io/no-provisioner\", \"manual\"].includes(source.provisioner))\n\t\t\t\tthrow new Error(\"Volume pre-provisioning requires a dynamic StorageClass\");\n\t\t\tfor (let i = active.size; i < options.count; i++) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t// A unique staging class prevents preparation PVCs from consuming the ready pool.\n\t\t\t\tawait api.createStorageClass(\n\t\t\t\t\t{\n\t\t\t\t\t\tapiVersion: \"storage.k8s.io/v1\",\n\t\t\t\t\t\tkind: \"StorageClass\",\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tname: `lw-volume-${randomUUID()}`,\n\t\t\t\t\t\t\tlabels,\n\t\t\t\t\t\t\tannotations: {\n\t\t\t\t\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t\t\t\t\tObject.entries(source.metadata.annotations ?? {}).filter(\n\t\t\t\t\t\t\t\t\t\t([key]) =>\n\t\t\t\t\t\t\t\t\t\t\t![\n\t\t\t\t\t\t\t\t\t\t\t\t\"storageclass.kubernetes.io/is-default-class\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"storageclass.beta.kubernetes.io/is-default-class\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"kubectl.kubernetes.io/last-applied-configuration\",\n\t\t\t\t\t\t\t\t\t\t\t].includes(key),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t[SIZE]: options.size,\n\t\t\t\t\t\t\t\t[MODES]: JSON.stringify(options.accessModes),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprovisioner: source.provisioner,\n\t\t\t\t\t\tparameters: source.parameters,\n\t\t\t\t\t\treclaimPolicy: source.reclaimPolicy,\n\t\t\t\t\t\tmountOptions: source.mountOptions,\n\t\t\t\t\t\tallowVolumeExpansion: source.allowVolumeExpansion,\n\t\t\t\t\t\tvolumeBindingMode: source.volumeBindingMode,\n\t\t\t\t\t\tallowedTopologies: source.allowedTopologies,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tpoolId,\n\t\treconcile,\n\t\tstart() {\n\t\t\tif (controller) return;\n\t\t\tcontroller = new AbortController();\n\t\t\tconst { signal } = controller;\n\t\t\trunning = (async () => {\n\t\t\t\twhile (!signal.aborted) {\n\t\t\t\t\tlet interval = 2_000;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait reconcile(signal);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tinterval = 30_000;\n\t\t\t\t\t\tif (!signal.aborted) options.onError?.();\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait delay(interval, undefined, { signal });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})();\n\t\t},\n\t\tasync stop() {\n\t\t\tcontroller?.abort();\n\t\t\tawait running;\n\t\t\tcontroller = undefined;\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;;;ACItB,SAAS,eACf,UACA,WACA,WAA2C,CAAC,GACrC;AACP,MAAI;AACH,cAAU,UAAU;AAAA,MACnB;AA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I,MAAM,qEAAqE;AAAA,IACtF;AACA,iBAAa,2BAA2B;AAAA,MACvC,KAAK,OAAO;AAAA,MACZ,WAAW,QAAQ;AAAA,MACnB,kBAAkB,QAAQ,OAAO;AAAA,MACjC,MAAM,QAAQ,OAAO;AAAA,MACrB,aAAa,QAAQ,OAAO;AAAA,MAC5B,GAAG,QAAQ;AAAA,MACX,OAAO;AAAA,MACP,iBAAiB,QAAQ;AAAA,MACzB,mBAAmB,QAAQ,KAAK,oBAAoB,CAAC,GAAG;AAAA,QACvD,CAAC,SACA,QAAQ,uBAAuB,KAAK,CAAC,SAAS,KAAK,eAAe,IAAI,GAAG,cACzE;AAAA,MACF;AAAA,MACA,cAAc,QAAQ,KAAK;AAAA,MAC3B,aAAa,QAAQ,KAAK;AAAA,IAC3B,CAAC;AAAA,EACF;AACA,SAAO,EAAE,QAAQ,QAAQ,UAAU,WAAW;AAC/C;","names":["pv","delay"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/runner-utils.ts"],"sourcesContent":["import type { WorkerExitInfo, WorkerUnit, WorkerUnitRef } from \"./types.js\";\n\n/**\n * Shared exit-notification machinery used by every {@link WorkerRunner}.\n *\n * Each runner implementation tracks physical unit exits and maps them to\n * `WorkerUnit.onExit` callbacks. This utility captures the identical map +\n * fire/wrap logic and leaves only the unit-keying to each runner.\n */\nexport class UnitExitNotifier {\n\tprivate readonly listeners = new Map<string, Array<(info: WorkerExitInfo) => void>>();\n\tprivate readonly exited = new Map<string, WorkerExitInfo>();\n\n\tonExit(key: string, listener: (info: WorkerExitInfo) => void): void {\n\t\tconst exit = this.exited.get(key);\n\t\tif (exit) {\n\t\t\tqueueMicrotask(() => listener(exit));\n\t\t\treturn;\n\t\t}\n\t\tconst list = this.listeners.get(key) ?? [];\n\t\tlist.push(listener);\n\t\tthis.listeners.set(key, list);\n\t}\n\n\tfireExit(key: string, info: WorkerExitInfo): void {\n\t\tif (this.exited.has(key)) return;\n\t\tthis.exited.set(key, info);\n\t\tconst list = this.listeners.get(key);\n\t\tif (!list) return;\n\t\tthis.listeners.delete(key);\n\t\tfor (const listener of list.splice(0)) listener(info);\n\t}\n\n\twrapUnit<T extends WorkerUnitRef>(\n\t\tref: T,\n\t\tkey: string,\n\t\toptions?: { replacementHandoff?: WorkerUnit[\"replacementHandoff\"] },\n\t): WorkerUnit {\n\t\treturn {\n\t\t\t...ref,\n\t\t\t...(options?.replacementHandoff ? { replacementHandoff: options.replacementHandoff } : {}),\n\t\t\tonExit: (listener) => this.onExit(key, listener),\n\t\t};\n\t}\n}\n"],"mappings":";AASO,IAAM,mBAAN,MAAuB;AAAA,EACZ,YAAY,oBAAI,IAAmD;AAAA,EACnE,SAAS,oBAAI,IAA4B;AAAA,EAE1D,OAAO,KAAa,UAAgD;AACnE,UAAM,OAAO,KAAK,OAAO,IAAI,GAAG;AAChC,QAAI,MAAM;AACT,qBAAe,MAAM,SAAS,IAAI,CAAC;AACnC;AAAA,IACD;AACA,UAAM,OAAO,KAAK,UAAU,IAAI,GAAG,KAAK,CAAC;AACzC,SAAK,KAAK,QAAQ;AAClB,SAAK,UAAU,IAAI,KAAK,IAAI;AAAA,EAC7B;AAAA,EAEA,SAAS,KAAa,MAA4B;AACjD,QAAI,KAAK,OAAO,IAAI,GAAG,EAAG;AAC1B,SAAK,OAAO,IAAI,KAAK,IAAI;AACzB,UAAM,OAAO,KAAK,UAAU,IAAI,GAAG;AACnC,QAAI,CAAC,KAAM;AACX,SAAK,UAAU,OAAO,GAAG;AACzB,eAAW,YAAY,KAAK,OAAO,CAAC,EAAG,UAAS,IAAI;AAAA,EACrD;AAAA,EAEA,SACC,KACA,KACA,SACa;AACb,WAAO;AAAA,MACN,GAAG;AAAA,MACH,GAAI,SAAS,qBAAqB,EAAE,oBAAoB,QAAQ,mBAAmB,IAAI,CAAC;AAAA,MACxF,QAAQ,CAAC,aAAa,KAAK,OAAO,KAAK,QAAQ;AAAA,IAChD;AAAA,EACD;AACD;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/docker-worker-runner.ts"],"sourcesContent":["import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n\tDockerContainerExit,\n\tDockerEngineClient,\n\tDockerMountSpec,\n} from \"./docker-engine-client.js\";\nimport { isDockerEngineNotFoundError } from \"./docker-engine-http-client.js\";\nimport { createFilesystemProcessStateExporter } from \"./filesystem-process-state-exporter.js\";\nimport {\n\tcreateHelperProcessStateExporter,\n\texportHelperEnvironment,\n} from \"./helper-process-state-exporter.js\";\nimport { UnitExitNotifier } from \"./runner-utils.js\";\nimport {\n\tSESSION_TRANSFER_HELPER_ENTRY_PATH,\n\tSESSION_TRANSFER_HELPER_MOUNT_PATH,\n} from \"./session-transfer-helper.js\";\nimport type {\n\tIsolatedStartWorkerInput,\n\tProcessStateExporter,\n\tProcessStateExportHelperRelayProvider,\n\tProcessVolume,\n\tStopWorkerOptions,\n\tWorkerExitInfo,\n\tWorkerRunner,\n\tWorkerUnit,\n\tWorkerUnitDescriptor,\n\tWorkerUnitRef,\n} from \"./types.js\";\nimport {\n\tbuildExportHelperLabels,\n\tbuildWorkerUnitLabels,\n\tmanagedExportHelperLabelSelector,\n\tmanagedWorkerLabelSelector,\n\tparseWorkerUnitIdentity,\n} from \"./worker-labels.js\";\n\nexport type DockerProcessVolumeMode = \"bind\" | \"named_volume\";\n\nexport interface DockerProcessVolumeOptions {\n\tmode: DockerProcessVolumeMode;\n\t/** Host root for per-process bind mounts (bind mode). */\n\thostRoot: string;\n\t/** Mount path injected into worker containers. */\n\tmountPath: string;\n\t/** Prefix for named volumes (named_volume mode). */\n\tnamedVolumePrefix?: string;\n}\n\nexport interface DockerWorkerRunnerOptions {\n\tengine: DockerEngineClient;\n\tvolume: DockerProcessVolumeOptions;\n\t/** Shared private network attached to every worker container. */\n\tdefaultNetwork: string;\n\t/** Exact isolation used for Docker-requiring processes. Omit to make them unavailable. */\n\tprivateDaemonIsolation?: \"privileged\" | \"sysbox-runc\";\n\t/** Host CA bundle mounted read-only into workers and export helpers. */\n\tserverCaFile?: string;\n\t/** Stable internal URL used by named-volume export helpers. */\n\tserverUrl?: string;\n\t/** Trusted image containing the bundled session-transfer helper entrypoint. */\n\texporterImage?: string;\n\t/** Server-owned relay registry used by named-volume export helpers. */\n\thelperRelays?: ProcessStateExportHelperRelayProvider;\n}\n\nconst DEFAULT_NAMED_VOLUME_PREFIX = \"leitwerk-process-\";\nconst NANO_CPUS_PER_CPU = 1_000_000_000;\nconst PRIVATE_DOCKER_ENV = \"LEITWERK_PRIVATE_DOCKER\";\nconst PROCESS_VOLUME_MOUNT_PATH_ENV = \"LEITWERK_PROCESS_VOLUME_MOUNT_PATH\";\nconst WORKER_SERVER_CA_MOUNT_PATH = \"/leitwerk/server-ca.pem\";\n\n/** Replaces characters Docker rejects in container names. */\nfunction sanitizeNameSegment(value: string): string {\n\tconst cleaned = value.replace(/[^a-zA-Z0-9_.-]/g, \"-\");\n\treturn cleaned.length > 0 ? cleaned : \"x\";\n}\n\nfunction containerName(instanceId: string, workerId: string): string {\n\treturn `leitwerk-worker-${sanitizeNameSegment(instanceId)}-${sanitizeNameSegment(workerId)}`;\n}\n\nfunction toEnvList(env: Record<string, string>): string[] {\n\treturn Object.entries(env).map(([key, value]) => `${key}=${value}`);\n}\n\nfunction parseCpuToNanoCpus(cpu: string | undefined): number | undefined {\n\tif (cpu === undefined) {\n\t\treturn undefined;\n\t}\n\tconst parsed = Number.parseFloat(cpu);\n\tif (!Number.isFinite(parsed) || parsed <= 0) {\n\t\treturn undefined;\n\t}\n\treturn Math.round(parsed * NANO_CPUS_PER_CPU);\n}\n\nconst MEMORY_SUFFIX_MULTIPLIERS: ReadonlyArray<[string, number]> = [\n\t[\"Gi\", 1024 ** 3],\n\t[\"Mi\", 1024 ** 2],\n\t[\"Ki\", 1024],\n\t[\"G\", 1000 ** 3],\n\t[\"M\", 1000 ** 2],\n\t[\"K\", 1000],\n\t[\"g\", 1024 ** 3],\n\t[\"m\", 1024 ** 2],\n\t[\"k\", 1024],\n\t[\"b\", 1],\n\t[\"B\", 1],\n];\n\nfunction parseMemoryToBytes(memory: string | undefined): number | undefined {\n\tif (memory === undefined) {\n\t\treturn undefined;\n\t}\n\tconst trimmed = memory.trim();\n\tfor (const [suffix, multiplier] of MEMORY_SUFFIX_MULTIPLIERS) {\n\t\tif (trimmed.endsWith(suffix)) {\n\t\t\tconst value = Number.parseFloat(trimmed.slice(0, -suffix.length));\n\t\t\tif (!Number.isFinite(value) || value <= 0) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn Math.round(value * multiplier);\n\t\t}\n\t}\n\tconst bytes = Number.parseInt(trimmed, 10);\n\treturn Number.isFinite(bytes) && bytes > 0 ? bytes : undefined;\n}\n\nfunction mapExit(info: DockerContainerExit): WorkerExitInfo {\n\treturn {\n\t\texitCode: Number.isFinite(info.statusCode) ? info.statusCode : null,\n\t\tsignal: info.signal ?? null,\n\t\t...(info.oomKilled !== undefined ? { oomKilled: info.oomKilled } : {}),\n\t\t...(info.error !== undefined ? { reason: info.error } : {}),\n\t};\n}\n\n/**\n * Docker Engine API {@link ProcessVolume} / {@link WorkerRunner}.\n *\n * Container-per-process, labelled for adoption, bind- or named-volume backed.\n * The server never reads the volume; it only injects the mount. Physical\n * container exits are observed via the engine's wait call and mapped into the\n * supervisor's existing failure paths through `onExit`.\n */\nexport function createDockerWorkerRunner(options: DockerWorkerRunnerOptions): {\n\trunner: WorkerRunner<IsolatedStartWorkerInput>;\n\tvolume: ProcessVolume;\n\texporter: ProcessStateExporter;\n} {\n\tif (\n\t\toptions.volume.mode === \"named_volume\" &&\n\t\t(!options.serverUrl || !options.exporterImage || !options.helperRelays)\n\t) {\n\t\tthrow new Error(\"Docker named-volume transfer exporter is not configured\");\n\t}\n\tconst { engine } = options;\n\tconst mountPath = options.volume.mountPath;\n\tconst namedVolumePrefix = options.volume.namedVolumePrefix ?? DEFAULT_NAMED_VOLUME_PREFIX;\n\tfunction volumeId(instanceId: string): string {\n\t\tif (options.volume.mode === \"named_volume\") {\n\t\t\treturn `${namedVolumePrefix}${instanceId}`;\n\t\t}\n\t\treturn path.join(options.volume.hostRoot, instanceId);\n\t}\n\n\tasync function releaseManagedStorage(instanceId: string): Promise<void> {\n\t\tif (options.volume.mode === \"named_volume\") {\n\t\t\tawait engine.removeVolume(volumeId(instanceId));\n\t\t}\n\t\t// Bind mounts are retained on the host filesystem; retention/GC of the\n\t\t// host directory is an operator concern, not a runner action.\n\t}\n\n\tconst volume: ProcessVolume = {\n\t\tasync ensure(instanceId) {\n\t\t\tconst id = volumeId(instanceId);\n\t\t\tif (options.volume.mode === \"named_volume\") {\n\t\t\t\tawait engine.ensureVolume(id);\n\t\t\t} else {\n\t\t\t\tmkdirSync(id, { recursive: true });\n\t\t\t}\n\t\t\treturn { instanceId, id, mountPath };\n\t\t},\n\t\trelease: releaseManagedStorage,\n\t\tdeleteProcessResources: releaseManagedStorage,\n\t};\n\n\tconst exitNotifier = new UnitExitNotifier();\n\tconst watched = new Set<string>();\n\tconst stopPromises = new Map<string, Promise<void>>();\n\n\tfunction stopAndRemove(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void> {\n\t\tconst existing = stopPromises.get(ref.unitId);\n\t\tif (existing) return existing;\n\t\tconst operation = Promise.resolve()\n\t\t\t.then(async () => {\n\t\t\t\tconst timeoutSeconds = Math.max(0, Math.ceil(opts.graceMs / 1000));\n\t\t\t\ttry {\n\t\t\t\t\tawait engine.stopContainer(ref.unitId, { timeoutSeconds });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!isDockerEngineNotFoundError(error)) throw error;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait engine.removeContainer(ref.unitId, { force: true });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!isDockerEngineNotFoundError(error)) throw error;\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => stopPromises.delete(ref.unitId));\n\t\tstopPromises.set(ref.unitId, operation);\n\t\treturn operation;\n\t}\n\n\tfunction applyServerCa(mounts: DockerMountSpec[], env: Record<string, string>): void {\n\t\tif (options.serverCaFile) {\n\t\t\tmounts.push({\n\t\t\t\tsource: options.serverCaFile,\n\t\t\t\ttarget: WORKER_SERVER_CA_MOUNT_PATH,\n\t\t\t\treadOnly: true,\n\t\t\t});\n\t\t\tenv.NODE_EXTRA_CA_CERTS = WORKER_SERVER_CA_MOUNT_PATH;\n\t\t}\n\t}\n\n\tfunction watchForExit(unitId: string): void {\n\t\tif (watched.has(unitId)) return;\n\t\twatched.add(unitId);\n\t\tengine\n\t\t\t.waitContainer(unitId)\n\t\t\t.then((exit) => exitNotifier.fireExit(unitId, mapExit(exit)))\n\t\t\t.catch(() =>\n\t\t\t\texitNotifier.fireExit(unitId, { exitCode: null, signal: null, reason: \"wait_failed\" }),\n\t\t\t)\n\t\t\t.finally(() => watched.delete(unitId));\n\t}\n\n\tconst runner: WorkerRunner<IsolatedStartWorkerInput> = {\n\t\tasync start(input: IsolatedStartWorkerInput, observer) {\n\t\t\tobserver?.report(\"preparing_runtime\");\n\t\t\tconst volume = input.volume;\n\t\t\tconst labels = buildWorkerUnitLabels({\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tworkerId: input.workerId,\n\t\t\t\tserverEpoch: input.serverEpoch,\n\t\t\t});\n\t\t\tconst mounts: DockerMountSpec[] = [{ source: volume.id, target: volume.mountPath }];\n\t\t\tconst env: Record<string, string> = {\n\t\t\t\t...input.env,\n\t\t\t\t[PROCESS_VOLUME_MOUNT_PATH_ENV]: volume.mountPath,\n\t\t\t};\n\t\t\tapplyServerCa(mounts, env);\n\t\t\tconst isolation = input.docker ? options.privateDaemonIsolation : undefined;\n\t\t\tif (input.docker && !isolation) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Cannot start Docker-requiring process ${input.instanceId}: docker.private_daemon is not configured`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.docker) env[PRIVATE_DOCKER_ENV] = \"1\";\n\t\t\tconst privileged = isolation === \"privileged\";\n\t\t\tconst sysbox = isolation === \"sysbox-runc\";\n\t\t\tobserver?.report(\"allocating_runtime\");\n\t\t\tconst { id } = await engine.createContainer({\n\t\t\t\tname: containerName(input.instanceId, input.workerId),\n\t\t\t\timage: input.image.reference,\n\t\t\t\tenv: toEnvList(env),\n\t\t\t\tlabels,\n\t\t\t\tmounts,\n\t\t\t\tnetworkMode: options.defaultNetwork,\n\t\t\t\tprivileged,\n\t\t\t\t...(sysbox ? { runtime: \"sysbox-runc\" } : {}),\n\t\t\t\tnanoCpus: parseCpuToNanoCpus(input.resources?.cpu),\n\t\t\t\tmemoryBytes: parseMemoryToBytes(input.resources?.memory),\n\t\t\t});\n\t\t\tobserver?.report(\"starting_runtime\");\n\t\t\tawait engine.startContainer(id);\n\t\t\tconst ref: WorkerUnitRef = {\n\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\tworkerId: input.workerId,\n\t\t\t\tunitId: id,\n\t\t\t};\n\t\t\twatchForExit(id);\n\t\t\treturn exitNotifier.wrapUnit(ref, ref.unitId, {\n\t\t\t\treplacementHandoff: \"stop-before-replacement\",\n\t\t\t});\n\t\t},\n\t\tasync stop(ref: WorkerUnitRef, opts: StopWorkerOptions) {\n\t\t\tawait stopAndRemove(ref, opts);\n\t\t\t// Container removal is the replacement handoff boundary. The process volume,\n\t\t\t// including private daemon state, remains available to the replacement.\n\t\t},\n\t\tasync list(): Promise<WorkerUnitDescriptor[]> {\n\t\t\tconst summaries = await engine.listContainers({\n\t\t\t\tlabels: managedWorkerLabelSelector(),\n\t\t\t});\n\t\t\tconst descriptors: WorkerUnitDescriptor[] = [];\n\t\t\tfor (const summary of summaries) {\n\t\t\t\tconst identity = parseWorkerUnitIdentity(summary.labels);\n\t\t\t\tif (!identity) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdescriptors.push({\n\t\t\t\t\tinstanceId: identity.instanceId,\n\t\t\t\t\tworkerId: identity.workerId,\n\t\t\t\t\tunitId: summary.id,\n\t\t\t\t\tobservedState: \"running\",\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn descriptors;\n\t\t},\n\t\tasync adopt(descriptor: WorkerUnitDescriptor): Promise<WorkerUnit> {\n\t\t\tconst inspect = await engine.inspectContainer(descriptor.unitId);\n\t\t\tconst identity = parseWorkerUnitIdentity(inspect.labels);\n\t\t\tif (\n\t\t\t\t!identity ||\n\t\t\t\tidentity.instanceId !== descriptor.instanceId ||\n\t\t\t\tidentity.workerId !== descriptor.workerId\n\t\t\t) {\n\t\t\t\tthrow new Error(`Cannot adopt worker unit ${descriptor.unitId}: labels changed`);\n\t\t\t}\n\t\t\tif (!inspect.running) {\n\t\t\t\tthrow new Error(`Cannot adopt worker unit ${descriptor.unitId}: not running`);\n\t\t\t}\n\t\t\tconst ref: WorkerUnitRef = {\n\t\t\t\tinstanceId: descriptor.instanceId,\n\t\t\t\tworkerId: descriptor.workerId,\n\t\t\t\tunitId: descriptor.unitId,\n\t\t\t};\n\t\t\twatchForExit(descriptor.unitId);\n\t\t\treturn exitNotifier.wrapUnit(ref, ref.unitId, {\n\t\t\t\treplacementHandoff: \"stop-before-replacement\",\n\t\t\t});\n\t\t},\n\t};\n\n\tconst exporterServerUrl = options.serverUrl ?? \"\";\n\tconst exporterImage = options.exporterImage ?? \"\";\n\tconst helperRelays = options.helperRelays as ProcessStateExportHelperRelayProvider;\n\tconst exporter =\n\t\toptions.volume.mode === \"bind\"\n\t\t\t? createFilesystemProcessStateExporter({\n\t\t\t\t\tallowedRoots: [options.volume.hostRoot],\n\t\t\t\t\tresolveSource: async (instanceId) => {\n\t\t\t\t\t\tconst { id } = await volume.ensure(instanceId);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tworkspaceRoot: path.join(id, \"workspace\"),\n\t\t\t\t\t\t\tsessionFile: path.join(id, \"tree\", \"primary.jsonl\"),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t: createHelperProcessStateExporter({\n\t\t\t\t\tvolume,\n\t\t\t\t\thelperRelays,\n\t\t\t\t\tasync launch(input) {\n\t\t\t\t\t\tconst mounts: DockerMountSpec[] = [\"workspace\", \"tree\"].map((volumeSubpath) => ({\n\t\t\t\t\t\t\tsource: input.volume.id,\n\t\t\t\t\t\t\ttarget: path.posix.join(SESSION_TRANSFER_HELPER_MOUNT_PATH, volumeSubpath),\n\t\t\t\t\t\t\treadOnly: true,\n\t\t\t\t\t\t\tvolumeSubpath,\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tconst env = exportHelperEnvironment({\n\t\t\t\t\t\t\tserverUrl: exporterServerUrl,\n\t\t\t\t\t\t\texportId: input.exportId,\n\t\t\t\t\t\t\tcredential: input.credential,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tapplyServerCa(mounts, env);\n\t\t\t\t\t\tconst created = await engine.createContainer({\n\t\t\t\t\t\t\tname: sanitizeNameSegment(input.name),\n\t\t\t\t\t\t\timage: exporterImage,\n\t\t\t\t\t\t\tcommand: [\"node\", SESSION_TRANSFER_HELPER_ENTRY_PATH],\n\t\t\t\t\t\t\tenv: toEnvList(env),\n\t\t\t\t\t\t\tlabels: buildExportHelperLabels({\n\t\t\t\t\t\t\t\tinstanceId: input.instanceId,\n\t\t\t\t\t\t\t\texportId: input.exportId,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tmounts,\n\t\t\t\t\t\t\tnetworkMode: options.defaultNetwork,\n\t\t\t\t\t\t\tprivileged: false,\n\t\t\t\t\t\t});\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait engine.startContainer(created.id);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait engine.removeContainer(created.id, { force: true });\n\t\t\t\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\t\t\t\tif (!isDockerEngineNotFoundError(cleanupError)) throw cleanupError;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\twait: async () => {\n\t\t\t\t\t\t\t\tconst exit = await engine.waitContainer(created.id);\n\t\t\t\t\t\t\t\treturn { exitCode: exit.statusCode, reason: exit.error };\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tremove: async () => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait engine.removeContainer(created.id, { force: true });\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tif (!isDockerEngineNotFoundError(error)) throw error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t\tasync reconcileHelpers() {\n\t\t\t\t\t\tconst helpers = await engine.listContainers({\n\t\t\t\t\t\t\tlabels: managedExportHelperLabelSelector(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\thelpers.map(async (helper) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait engine.removeContainer(helper.id, { force: true });\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tif (!isDockerEngineNotFoundError(error)) throw error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t});\n\treturn { runner, volume, exporter };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,OAAO,UAAU;AAkEjB,IAAM,8BAA8B;AACpC,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAC3B,IAAM,gCAAgC;AACtC,IAAM,8BAA8B;AAGpC,SAAS,oBAAoB,OAAuB;AACnD,QAAM,UAAU,MAAM,QAAQ,oBAAoB,GAAG;AACrD,SAAO,QAAQ,SAAS,IAAI,UAAU;AACvC;AAEA,SAAS,cAAc,YAAoB,UAA0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ACD,UAAI;AACH,cAAM,OAAO,eAAe,QAAQ,EAAE;AAAA,MACvC,SAAS,OAAO;AACf,YAAI;AACH,gBAAM,OAAO,gBAAgB,QAAQ,IAAI,EAAE,OAAO,KAAK,CAAC;AAAA,QACzD,SAAS,cAAc;AACtB,cAAI,CAAC,4BAA4B,YAAY,EAAG,OAAM;AAAA,QACvD;AACA,cAAM;AAAA,MACP;AACA,aAAO;AAAA,QACN,MAAM,YAAY;AACjB,gBAAM,OAAO,MAAM,OAAO,cAAc,QAAQ,EAAE;AAClD,iBAAO,EAAE,UAAU,KAAK,YAAY,QAAQ,KAAK,MAAM;AAAA,QACxD;AAAA,QACA,QAAQ,YAAY;AACnB,cAAI;AACH,kBAAM,OAAO,gBAAgB,QAAQ,IAAI,EAAE,OAAO,KAAK,CAAC;AAAA,UACzD,SAAS,OAAO;AACf,gBAAI,CAAC,4BAA4B,KAAK,EAAG,OAAM;AAAA,UAChD;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAAA,IACA,MAAM,mBAAmB;AACxB,YAAM,UAAU,MAAM,OAAO,eAAe;AAAA,QAC3C,QAAQ,iCAAiC;AAAA,MAC1C,CAAC;AACD,YAAM,QAAQ;AAAA,QACb,QAAQ,IAAI,OAAO,WAAW;AAC7B,cAAI;AACH,kBAAM,OAAO,gBAAgB,OAAO,IAAI,EAAE,OAAO,KAAK,CAAC;AAAA,UACxD,SAAS,OAAO;AACf,gBAAI,CAAC,4BAA4B,KAAK,EAAG,OAAM;AAAA,UAChD;AAAA,QACD,CAAC;AAAA,MACF;AAAA,IACD;AAAA,EACD,CAAC;AACJ,SAAO,EAAE,QAAQ,QAAQ,SAAS;AACnC;","names":["volume"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/kubernetes-manifests.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { DockerNetworkConfig } from \"@leitwerk-dev/worker-protocol\";\nimport type { IsolatedStartWorkerInput, VolumeRef, WorkerExitInfo } from \"./types.js\";\nimport {\n\tbuildExportHelperLabels,\n\tbuildProcessResourceLabels,\n\tbuildWorkerUnitLabels,\n\tPROCESS_IMAGE_PULL_SECRET_COMPONENT_VALUE,\n\tPROCESS_NAMESPACE_COMPONENT_VALUE,\n\tPROCESS_SERVER_CA_COMPONENT_VALUE,\n\tPROCESS_VOLUME_COMPONENT_VALUE,\n} from \"./worker-labels.js\";\n\nexport interface KubernetesProcessVolumeSpec {\n\tstorageClassName?: string;\n\tsize: string;\n\taccessModes: string[];\n\tmountPath: string;\n\tnamePrefix?: string;\n}\n\nexport interface KubernetesProcessNamespaceManifest {\n\tapiVersion: \"v1\";\n\tkind: \"Namespace\";\n\tmetadata: { name: string; labels: Record<string, string> };\n}\n\nexport interface KubernetesWorkerServerCaConfigMapSpec {\n\tname: string;\n\tkey: string;\n\tmountPath: string;\n}\n\nexport interface KubernetesDockerPodSpecOptions {\n\truntimeClassName: string;\n\thostUsers: boolean;\n\tnetwork?: DockerNetworkConfig;\n}\n\nexport interface KubernetesPodSpecOptions {\n\tnamespace: string;\n\tworkerServiceAccount?: string;\n\timagePullSecrets?: string[];\n\timagePullPolicy?: string;\n\tnodeSelector?: Record<string, string>;\n\tannotations?: Record<string, string>;\n\ttolerations?: unknown[];\n\thostAliases?: Array<{ ip: string; hostnames: string[] }>;\n\tserverCaConfigMap?: KubernetesWorkerServerCaConfigMapSpec;\n\t/** Trusted operator wiring used only when the process declares runtime.docker. */\n\tdocker?: KubernetesDockerPodSpecOptions;\n}\n\ninterface NamespacedManifest<Kind extends string> {\n\tapiVersion: \"v1\";\n\tkind: Kind;\n\tmetadata: { name: string; namespace: string; labels: Record<string, string> };\n}\n\nexport interface KubernetesPersistentVolumeClaimManifest\n\textends NamespacedManifest<\"PersistentVolumeClaim\"> {\n\tspec: {\n\t\taccessModes: string[];\n\t\tresources: { requests: { storage: string } };\n\t\tstorageClassName?: string;\n\t};\n}\n\nexport interface KubernetesConfigMapManifest extends NamespacedManifest<\"ConfigMap\"> {\n\tdata: Record<string, string>;\n}\n\nexport interface KubernetesDockerConfigJsonSecretManifest extends NamespacedManifest<\"Secret\"> {\n\ttype: \"kubernetes.io/dockerconfigjson\";\n\tdata: { \".dockerconfigjson\": string };\n}\n\nexport interface KubernetesPodEventSummary {\n\tobjectUid?: string;\n\tfieldPath?: string;\n\tfirstTimestamp?: string;\n\teventTime?: string;\n\ttype?: string;\n\treason?: string;\n\tmessage?: string;\n\tcount?: number;\n\tlastTimestamp?: string;\n}\n\nexport interface KubernetesPodManifest extends NamespacedManifest<\"Pod\"> {\n\tmetadata: NamespacedManifest<\"Pod\">[\"metadata\"] & { annotations?: Record<string, string> };\n\tspec: {\n\t\trestartPolicy: \"Never\";\n\t\truntimeClassName?: string;\n\t\thostUsers?: boolean;\n\t\tserviceAccountName?: string;\n\t\tnodeSelector?: Record<string, string>;\n\t\ttolerations?: unknown[];\n\t\thostAliases?: Array<{ ip: string; hostnames: string[] }>;\n\t\timagePullSecrets?: Array<{ name: string }>;\n\t\tautomountServiceAccountToken?: boolean;\n\t\tcontainers: Array<{\n\t\t\tname: string;\n\t\t\timage: string;\n\t\t\tcommand?: string[];\n\t\t\timagePullPolicy?: string;\n\t\t\tenv: Array<{ name: string; value: string }>;\n\t\t\tvolumeMounts: Array<{\n\t\t\t\tname: string;\n\t\t\t\tmountPath: string;\n\t\t\t\treadOnly?: boolean;\n\t\t\t\tsubPath?: string;\n\t\t\t}>;\n\t\t\tresources?: {\n\t\t\t\trequests?: Record<string, string>;\n\t\t\t\tlimits?: Record<string, string>;\n\t\t\t};\n\t\t}>;\n\t\tvolumes: Array<\n\t\t\t| { name: string; persistentVolumeClaim: { claimName: string } }\n\t\t\t| { name: string; configMap: { name: string; items: Array<{ key: string; path: string }> } }\n\t\t>;\n\t};\n}\n\nconst DNS_LABEL_MAX = 63;\nconst WORKER_VOLUME_NAME = \"process-state\";\nconst WORKER_SERVER_CA_VOLUME_NAME = \"server-ca\";\nexport const KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME = \"leitwerk-server-ca\";\nexport const KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY = \"server-ca.pem\";\nexport const KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH = \"/leitwerk/server-ca\";\nexport const KUBERNETES_WORKER_SERVER_CA_CERT_PATH = `${KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH}/${KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY}`;\n\nfunction safeKubernetesDnsName(value: string, maxLen = DNS_LABEL_MAX): string {\n\tconst cleaned = sanitizeKubernetesNameSegment(value);\n\tconst trimmed = cleaned.slice(0, maxLen).replace(/-+$/g, \"\");\n\treturn trimmed.length > 0 ? trimmed : \"x\";\n}\n\nexport function sanitizeKubernetesNameSegment(value: string): string {\n\tconst cleaned = value\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9-]/g, \"-\")\n\t\t.replace(/^-+|-+$/g, \"\");\n\treturn cleaned.length > 0 ? cleaned : \"x\";\n}\n\nexport function kubernetesWorkerPodName(instanceId: string, workerId: string): string {\n\treturn safeKubernetesDnsName(\n\t\t`leitwerk-worker-${sanitizeKubernetesNameSegment(instanceId)}-${sanitizeKubernetesNameSegment(workerId)}`,\n\t);\n}\n\nexport function kubernetesExportHelperPodName(instanceId: string, exportId: string): string {\n\tconst exportSegment = sanitizeKubernetesNameSegment(exportId);\n\tconst suffix = `-${exportSegment}`;\n\tconst instancePrefix = safeKubernetesDnsName(\n\t\t`leitwerk-export-${sanitizeKubernetesNameSegment(instanceId)}`,\n\t\tMath.max(1, DNS_LABEL_MAX - suffix.length),\n\t);\n\t// Keep the random export id at the end of the name. Truncating the full\n\t// prefix would otherwise make long instance ids produce colliding helper\n\t// names for different exports.\n\treturn safeKubernetesDnsName(`${instancePrefix}${suffix}`);\n}\n\nexport function kubernetesProcessPvcName(\n\tinstanceId: string,\n\tnamePrefix = \"leitwerk-process-\",\n): string {\n\treturn safeKubernetesDnsName(`${namePrefix}${sanitizeKubernetesNameSegment(instanceId)}`);\n}\n\nexport function kubernetesProcessNamespaceName(\n\tinstanceId: string,\n\tprocessNamespacePrefix = \"leitwerk-process-\",\n): string {\n\treturn safeKubernetesDnsName(\n\t\t`${processNamespacePrefix}${sanitizeKubernetesNameSegment(instanceId)}`,\n\t);\n}\n\nexport function buildKubernetesProcessNamespaceManifest(args: {\n\tinstanceId: string;\n\tprocessNamespacePrefix?: string;\n\textraLabels?: Record<string, string>;\n}): KubernetesProcessNamespaceManifest {\n\treturn {\n\t\tapiVersion: \"v1\",\n\t\tkind: \"Namespace\",\n\t\tmetadata: {\n\t\t\tname: kubernetesProcessNamespaceName(args.instanceId, args.processNamespacePrefix),\n\t\t\tlabels: buildProcessResourceLabels(\n\t\t\t\t{ instanceId: args.instanceId, component: PROCESS_NAMESPACE_COMPONENT_VALUE },\n\t\t\t\targs.extraLabels,\n\t\t\t),\n\t\t},\n\t};\n}\n\nfunction processResourceMetadata(\n\targs: { instanceId: string; namespace: string; extraLabels?: Record<string, string> },\n\tname: string,\n\tcomponent: Parameters<typeof buildProcessResourceLabels>[0][\"component\"],\n): NamespacedManifest<string>[\"metadata\"] {\n\treturn {\n\t\tname,\n\t\tnamespace: args.namespace,\n\t\tlabels: buildProcessResourceLabels(\n\t\t\t{ instanceId: args.instanceId, component },\n\t\t\targs.extraLabels,\n\t\t),\n\t};\n}\n\nexport function buildKubernetesProcessPvcManifest(args: {\n\tinstanceId: string;\n\tnamespace: string;\n\tvolume: KubernetesProcessVolumeSpec;\n\textraLabels?: Record<string, string>;\n}): KubernetesPersistentVolumeClaimManifest {\n\tconst spec: KubernetesPersistentVolumeClaimManifest[\"spec\"] = {\n\t\taccessModes: [...args.volume.accessModes],\n\t\tresources: { requests: { storage: args.volume.size } },\n\t};\n\tif (args.volume.storageClassName?.trim()) {\n\t\tspec.storageClassName = args.volume.storageClassName;\n\t}\n\treturn {\n\t\tapiVersion: \"v1\",\n\t\tkind: \"PersistentVolumeClaim\",\n\t\tmetadata: processResourceMetadata(\n\t\t\targs,\n\t\t\tkubernetesProcessPvcName(args.instanceId, args.volume.namePrefix),\n\t\t\tPROCESS_VOLUME_COMPONENT_VALUE,\n\t\t),\n\t\tspec,\n\t};\n}\n\nexport function buildKubernetesServerCaConfigMapManifest(args: {\n\tinstanceId: string;\n\tnamespace: string;\n\tcaPem: string;\n\tname?: string;\n\tkey?: string;\n\textraLabels?: Record<string, string>;\n}): KubernetesConfigMapManifest {\n\treturn {\n\t\tapiVersion: \"v1\",\n\t\tkind: \"ConfigMap\",\n\t\tmetadata: processResourceMetadata(\n\t\t\targs,\n\t\t\targs.name ?? KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,\n\t\t\tPROCESS_SERVER_CA_COMPONENT_VALUE,\n\t\t),\n\t\tdata: { [args.key ?? KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY]: args.caPem },\n\t};\n}\n\nexport function buildKubernetesDockerConfigJsonSecretManifest(args: {\n\tinstanceId: string;\n\tnamespace: string;\n\tname: string;\n\tdockerConfigJson: string;\n\textraLabels?: Record<string, string>;\n}): KubernetesDockerConfigJsonSecretManifest {\n\treturn {\n\t\tapiVersion: \"v1\",\n\t\tkind: \"Secret\",\n\t\tmetadata: processResourceMetadata(args, args.name, PROCESS_IMAGE_PULL_SECRET_COMPONENT_VALUE),\n\t\ttype: \"kubernetes.io/dockerconfigjson\",\n\t\tdata: { \".dockerconfigjson\": args.dockerConfigJson },\n\t};\n}\n\nfunction envList(env: Record<string, string>): Array<{ name: string; value: string }> {\n\treturn Object.entries(env)\n\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t.map(([name, value]) => ({ name, value }));\n}\n\nfunction resources(\n\tinput: IsolatedStartWorkerInput,\n): KubernetesPodManifest[\"spec\"][\"containers\"][number][\"resources\"] {\n\tconst result: NonNullable<ReturnType<typeof resources>> = {};\n\tfor (const [kind, values] of [\n\t\t[\"limits\", { cpu: input.resources?.cpu, memory: input.resources?.memory }],\n\t\t[\"requests\", input.resourceRequests],\n\t] as const) {\n\t\tconst entries = Object.entries(values ?? {}).filter(([, value]) => value);\n\t\tif (entries.length) result[kind] = Object.fromEntries(entries);\n\t}\n\treturn Object.keys(result).length ? result : undefined;\n}\n\nfunction podManifest(\n\tname: string,\n\tvolume: VolumeRef,\n\tlabels: Record<string, string>,\n\toptions: KubernetesPodSpecOptions,\n\tcontainer: KubernetesPodManifest[\"spec\"][\"containers\"][number],\n\tspec: Partial<KubernetesPodManifest[\"spec\"]> = {},\n): KubernetesPodManifest {\n\treturn {\n\t\tapiVersion: \"v1\",\n\t\tkind: \"Pod\",\n\t\tmetadata: {\n\t\t\tname,\n\t\t\tnamespace: volume.namespace ?? options.namespace,\n\t\t\tlabels,\n\t\t\t...(options.annotations && Object.keys(options.annotations).length > 0\n\t\t\t\t? { annotations: { ...options.annotations } }\n\t\t\t\t: {}),\n\t\t},\n\t\tspec: {\n\t\t\trestartPolicy: \"Never\",\n\t\t\t...(options.workerServiceAccount?.trim()\n\t\t\t\t? { serviceAccountName: options.workerServiceAccount }\n\t\t\t\t: {}),\n\t\t\t...(options.imagePullSecrets?.length\n\t\t\t\t? { imagePullSecrets: options.imagePullSecrets.map((name) => ({ name })) }\n\t\t\t\t: {}),\n\t\t\t...(options.nodeSelector && Object.keys(options.nodeSelector).length > 0\n\t\t\t\t? { nodeSelector: { ...options.nodeSelector } }\n\t\t\t\t: {}),\n\t\t\t...(options.tolerations?.length ? { tolerations: [...options.tolerations] } : {}),\n\t\t\t...(options.hostAliases?.length\n\t\t\t\t? {\n\t\t\t\t\t\thostAliases: options.hostAliases.map(({ ip, hostnames }) => ({\n\t\t\t\t\t\t\tip,\n\t\t\t\t\t\t\thostnames: [...hostnames],\n\t\t\t\t\t\t})),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...spec,\n\t\t\tcontainers: [container],\n\t\t\tvolumes: processStateVolumes(volume.id, options.serverCaConfigMap),\n\t\t},\n\t};\n}\n\nfunction processStateVolumes(\n\tclaimName: string,\n\tca: KubernetesWorkerServerCaConfigMapSpec | undefined,\n): KubernetesPodManifest[\"spec\"][\"volumes\"] {\n\treturn [\n\t\t{ name: WORKER_VOLUME_NAME, persistentVolumeClaim: { claimName } },\n\t\t...(ca\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: WORKER_SERVER_CA_VOLUME_NAME,\n\t\t\t\t\t\tconfigMap: { name: ca.name, items: [{ key: ca.key, path: ca.key }] },\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t];\n}\n\nfunction processStateContainerConfig(\n\tenv: Record<string, string>,\n\tmountPath: string,\n\texportOnly: boolean,\n\tca: KubernetesWorkerServerCaConfigMapSpec | undefined,\n): Pick<KubernetesPodManifest[\"spec\"][\"containers\"][number], \"env\" | \"volumeMounts\"> {\n\treturn {\n\t\tenv: envList(ca ? { ...env, NODE_EXTRA_CA_CERTS: `${ca.mountPath}/${ca.key}` } : env),\n\t\tvolumeMounts: [\n\t\t\t...(exportOnly\n\t\t\t\t? [\"workspace\", \"tree\"].map((subPath) => ({\n\t\t\t\t\t\tname: WORKER_VOLUME_NAME,\n\t\t\t\t\t\tmountPath: path.posix.join(mountPath, subPath),\n\t\t\t\t\t\tsubPath,\n\t\t\t\t\t\treadOnly: true,\n\t\t\t\t\t}))\n\t\t\t\t: [{ name: WORKER_VOLUME_NAME, mountPath }]),\n\t\t\t...(ca\n\t\t\t\t? [{ name: WORKER_SERVER_CA_VOLUME_NAME, mountPath: ca.mountPath, readOnly: true }]\n\t\t\t\t: []),\n\t\t],\n\t};\n}\n\nexport function buildKubernetesExportHelperPodManifest(\n\tinput: {\n\t\tinstanceId: string;\n\t\texportId: string;\n\t\timage: string;\n\t\tcommand: string[];\n\t\tenv: Record<string, string>;\n\t\tvolume: VolumeRef;\n\t},\n\toptions: KubernetesPodSpecOptions,\n): KubernetesPodManifest {\n\treturn podManifest(\n\t\tkubernetesExportHelperPodName(input.instanceId, input.exportId),\n\t\tinput.volume,\n\t\tbuildExportHelperLabels({ instanceId: input.instanceId, exportId: input.exportId }),\n\t\toptions,\n\t\t{\n\t\t\tname: \"session-export-helper\",\n\t\t\timage: input.image,\n\t\t\tcommand: [...input.command],\n\t\t\t...processStateContainerConfig(\n\t\t\t\tinput.env,\n\t\t\t\tinput.volume.mountPath,\n\t\t\t\ttrue,\n\t\t\t\toptions.serverCaConfigMap,\n\t\t\t),\n\t\t\t...(options.imagePullPolicy ? { imagePullPolicy: options.imagePullPolicy } : {}),\n\t\t},\n\t\t{ automountServiceAccountToken: false },\n\t);\n}\n\nexport function buildKubernetesWorkerPodManifest(\n\tinput: IsolatedStartWorkerInput,\n\toptions: KubernetesPodSpecOptions,\n): KubernetesPodManifest {\n\tconst volume = input.volume;\n\tconst labels = buildWorkerUnitLabels({\n\t\tinstanceId: input.instanceId,\n\t\tworkerId: input.workerId,\n\t\tserverEpoch: input.serverEpoch,\n\t});\n\tconst containerResources = resources(input);\n\tconst ca = options.serverCaConfigMap;\n\tconst trustedDockerEnv = input.docker\n\t\t? {\n\t\t\t\t...input.env,\n\t\t\t\tDOCKER_HOST: \"unix:///var/run/docker.sock\",\n\t\t\t\tLEITWERK_PRIVATE_DOCKER: \"1\",\n\t\t\t\tLEITWERK_PROCESS_VOLUME_MOUNT_PATH: volume.mountPath,\n\t\t\t\t...(options.docker?.network\n\t\t\t\t\t? { LEITWERK_DOCKER_NETWORK: JSON.stringify(options.docker.network) }\n\t\t\t\t\t: {}),\n\t\t\t}\n\t\t: input.env;\n\tconst container: KubernetesPodManifest[\"spec\"][\"containers\"][number] = {\n\t\tname: \"worker\",\n\t\timage: input.image.reference,\n\t\t...processStateContainerConfig(trustedDockerEnv, volume.mountPath, false, ca),\n\t\t...(options.imagePullPolicy ? { imagePullPolicy: options.imagePullPolicy } : {}),\n\t\t...(containerResources ? { resources: containerResources } : {}),\n\t};\n\treturn podManifest(\n\t\tkubernetesWorkerPodName(input.instanceId, input.workerId),\n\t\tvolume,\n\t\tlabels,\n\t\toptions,\n\t\tcontainer,\n\t\tinput.docker && options.docker\n\t\t\t? { runtimeClassName: options.docker.runtimeClassName, hostUsers: options.docker.hostUsers }\n\t\t\t: {},\n\t);\n}\n\nconst KUBERNETES_DIAGNOSTIC_MAX_LENGTH = 2_048;\n\nexport function redactKubernetesDiagnostic(\n\tvalue: string,\n\tsensitiveValues: readonly string[] = [],\n): string {\n\tlet redacted = value;\n\tfor (const sensitiveValue of sensitiveValues) {\n\t\tif (sensitiveValue.length >= 8) redacted = redacted.replaceAll(sensitiveValue, \"<redacted>\");\n\t}\n\treturn redacted;\n}\n\nfunction boundedDiagnostic(value: string, sensitiveValues: readonly string[] = []): string {\n\tconst redacted = redactKubernetesDiagnostic(value, sensitiveValues);\n\treturn redacted.length <= KUBERNETES_DIAGNOSTIC_MAX_LENGTH\n\t\t? redacted\n\t\t: `${redacted.slice(0, KUBERNETES_DIAGNOSTIC_MAX_LENGTH - 1)}…`;\n}\n\nfunction formatPodEvent(\n\tevent: KubernetesPodEventSummary,\n\tsensitiveValues: readonly string[],\n): string | null {\n\tconst pieces: string[] = [];\n\tif (event.type?.trim()) pieces.push(event.type.trim());\n\tif (event.reason?.trim()) pieces.push(event.reason.trim());\n\tif (event.count !== undefined && event.count > 1) pieces.push(`x${event.count}`);\n\tconst prefix = pieces.join(\" \");\n\tconst message = event.message?.trim();\n\tif (!prefix && !message) return null;\n\treturn boundedDiagnostic(\n\t\tmessage ? `${prefix ? `${prefix}: ` : \"\"}${message}` : prefix,\n\t\tsensitiveValues,\n\t);\n}\n\nexport function formatKubernetesPodDiagnostics(\n\tevents: readonly KubernetesPodEventSummary[] | undefined,\n\tlimit = 3,\n\tsensitiveValues: readonly string[] = [],\n): string | undefined {\n\tconst formatted = (events ?? [])\n\t\t.map((event) => formatPodEvent(event, sensitiveValues))\n\t\t.filter((entry): entry is string => entry !== null)\n\t\t.slice(0, limit);\n\treturn formatted.length > 0\n\t\t? boundedDiagnostic(`Kubernetes events: ${formatted.join(\" | \")}`, sensitiveValues)\n\t\t: undefined;\n}\n\nexport function mapKubernetesPodExit(args: {\n\tphase?: string;\n\treason?: string;\n\texitCode?: number | null;\n\tsignal?: string | null;\n\toomKilled?: boolean;\n\tterminationMessage?: string;\n\tevents?: readonly KubernetesPodEventSummary[];\n\tsensitiveValues?: readonly string[];\n}): WorkerExitInfo {\n\tconst sensitiveValues = args.sensitiveValues ?? [];\n\tconst baseReason = args.reason ?? args.phase;\n\tconst startupDiagnostic = args.terminationMessage?.trim()\n\t\t? `Runtime startup: ${boundedDiagnostic(args.terminationMessage.trim(), sensitiveValues)}`\n\t\t: undefined;\n\tconst diagnostics = formatKubernetesPodDiagnostics(args.events, 3, sensitiveValues);\n\tconst reason = boundedDiagnostic(\n\t\t[baseReason, startupDiagnostic, diagnostics].filter(Boolean).join(\"; \"),\n\t\tsensitiveValues,\n\t);\n\treturn {\n\t\texitCode: args.exitCode ?? null,\n\t\tsignal: args.signal ?? null,\n\t\t...(args.oomKilled !== undefined ? { oomKilled: args.oomKilled } : {}),\n\t\t...(reason ? { reason } : {}),\n\t};\n}\n\nexport function volumeRefFromPvc(args: {\n\tinstanceId: string;\n\tpvcName: string;\n\tmountPath: string;\n\tnamespace?: string;\n}): VolumeRef {\n\treturn {\n\t\tinstanceId: args.instanceId,\n\t\tid: args.pvcName,\n\t\tmountPath: args.mountPath,\n\t\t...(args.namespace ? { namespace: args.namespace } : {}),\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAAA,OAAO,UAAU;AA6HjB,IAAM,gBAAgB;AACtB,IAAM,qBAAqB;AAC3B,IAAM,+BAA+B;AAC9B,IAAM,8CAA8C;AACpD,IAAM,6CAA6C;AACnD,IAAM,yCAAyC;AAC/C,IAAM,wCAAwC,GAAG,sCAAsC,IAAI,0CAA0C;AAE5I,SAAS,sBAAsB,OAAe,SAAS,eAAuB;AAC7E,QAAM,UAAU,8BAA8B,KAAK;AACnD,QAAM,UAAU,QAAQ,MAAM,GAAG,MAAM,EAAE,QAAQ,QAAQ,EAAE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