miravo 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +1 -1
  2. package/console-dist/assets/activity-DsWeRq4h.js +1 -0
  3. package/console-dist/assets/api-4AqKvsm9.js +1 -0
  4. package/console-dist/assets/arrow-right-Ea_UhTNi.js +1 -0
  5. package/console-dist/assets/arrow-up-down-DFSjzzl2.js +1 -0
  6. package/console-dist/assets/blueprint-card-classes-DBFCDy0M.js +1 -0
  7. package/console-dist/assets/box-C1WaoOMF.js +1 -0
  8. package/console-dist/assets/card-BjeP32PN.js +1 -0
  9. package/console-dist/assets/catalog-BJzyzbLR.js +1 -0
  10. package/console-dist/assets/catalog-DKjEm-c4.js +1 -0
  11. package/console-dist/assets/catalog-template-icons-BrUeHaCY.js +1 -0
  12. package/console-dist/assets/checkbox-DZlJXTE4.js +1 -0
  13. package/console-dist/assets/chunk-OE4NN4TA-CEjpfhS6.js +3 -0
  14. package/console-dist/assets/combobox-BGnuCYxO.js +1 -0
  15. package/console-dist/assets/control-CPhvwx9o.js +1 -0
  16. package/console-dist/assets/control-Cg2up9NA.js +1 -0
  17. package/console-dist/assets/copy-button-WkbNkMcd.js +1 -0
  18. package/console-dist/assets/createLucideIcon-Bwxw859K.js +1 -0
  19. package/console-dist/assets/deploy-tab-JeWDwPoZ.js +1 -0
  20. package/console-dist/assets/dist-BhbDML0a.js +1 -0
  21. package/console-dist/assets/dist-Cy8XTNFT.js +2 -0
  22. package/console-dist/assets/download-DQ6NH16U.js +1 -0
  23. package/console-dist/assets/engine-store-CrLnz692.js +1 -0
  24. package/console-dist/assets/events-CXm29Ok4.js +1 -0
  25. package/console-dist/assets/events-D01IxhnP.js +1 -0
  26. package/console-dist/assets/fleet-CfxbKXt9.js +1 -0
  27. package/console-dist/assets/fleet-lotMGVqe.js +1 -0
  28. package/console-dist/assets/format-kXTonpDJ.js +1 -0
  29. package/console-dist/assets/gauge-Ci8zNZlk.js +1 -0
  30. package/console-dist/assets/get-error-message-3Q5Q-2G5.js +1 -0
  31. package/console-dist/assets/index-CVPKSDvJ.js +12 -0
  32. package/console-dist/assets/index-DJkgDeun.css +2 -0
  33. package/console-dist/assets/input-BWEQFptx.js +1 -0
  34. package/console-dist/assets/instance-detail-C5IVwuh3.js +1 -0
  35. package/console-dist/assets/label-uephX5ZG.js +1 -0
  36. package/console-dist/assets/layers-CUsLQ1fq.js +1 -0
  37. package/console-dist/assets/login-C3RJli0m.js +126 -0
  38. package/console-dist/assets/models-B_UioWQ5.js +1 -0
  39. package/console-dist/assets/models-_IPlPiZ7.js +1 -0
  40. package/console-dist/assets/not-found-B8gAm08S.js +1 -0
  41. package/console-dist/assets/platform-targets-R3T-4eJ7.js +1 -0
  42. package/console-dist/assets/platforms-BWh0BQ3Y.js +1 -0
  43. package/console-dist/assets/platforms-DStNbtVc.js +1 -0
  44. package/console-dist/assets/proxy-CsnYqnPp.js +9 -0
  45. package/console-dist/assets/query-keys-BvtE7BMs.js +1 -0
  46. package/console-dist/assets/radio-CoHegOv5.js +1 -0
  47. package/console-dist/assets/rolldown-runtime-COnpUsM8.js +1 -0
  48. package/console-dist/assets/select-CeO4vP0G.js +1 -0
  49. package/console-dist/assets/select-display-items-CIzY8953.js +1 -0
  50. package/console-dist/assets/server-D9Kfn8fQ.js +1 -0
  51. package/console-dist/assets/shallow-6lGjQhtJ.js +1 -0
  52. package/console-dist/assets/tags-CiXOIHtY.js +4 -0
  53. package/console-dist/assets/tags-FQCXIxrP.js +1 -0
  54. package/console-dist/assets/tooltip-HGLF366Q.js +1 -0
  55. package/console-dist/assets/transition-nav-link-Df4Rk6vV.js +1 -0
  56. package/console-dist/assets/transition-types-CPlGtM8w.js +1 -0
  57. package/console-dist/assets/triangle-alert-adNk_sea.js +1 -0
  58. package/console-dist/assets/use-platform-stream-DGbK1k2L.js +2 -0
  59. package/console-dist/assets/use-transition-navigate-CCpcWXB0.js +2 -0
  60. package/console-dist/assets/validation-Blvud9_O.js +1 -0
  61. package/console-dist/assets/vendor-charts-CAZdaPlq.js +60 -0
  62. package/console-dist/assets/vendor-table-wd8JuMmT.js +4 -0
  63. package/console-dist/assets/vendor-ui-ByahnaY0.js +1 -0
  64. package/console-dist/index.html +70 -2
  65. package/package.json +9 -8
  66. package/src/__tests__/integration/executable-methods-runner.ts +7 -6
  67. package/src/__tests__/integration/executable-methods.integration.ts +214 -122
  68. package/src/__tests__/integration/opcua-concurrent-clients.integration.ts +314 -0
  69. package/src/commands/adapter.ts +180 -7
  70. package/src/commands/apply.test.ts +62 -0
  71. package/src/commands/apply.ts +216 -0
  72. package/src/commands/cleanup.test.ts +34 -0
  73. package/src/commands/cleanup.ts +201 -0
  74. package/src/commands/export.test.ts +51 -0
  75. package/src/commands/export.ts +404 -0
  76. package/src/commands/fork.ts +2 -2
  77. package/src/commands/inject.ts +2 -2
  78. package/src/commands/load.ts +1 -1
  79. package/src/commands/logs.ts +13 -15
  80. package/src/commands/models.test.ts +1 -1
  81. package/src/commands/models.ts +1 -1
  82. package/src/commands/pause.ts +3 -3
  83. package/src/commands/platforms.test.ts +186 -0
  84. package/src/commands/platforms.ts +371 -0
  85. package/src/commands/remove.ts +1 -1
  86. package/src/commands/reset.ts +2 -2
  87. package/src/commands/spawn.ts +2 -2
  88. package/src/commands/speed.ts +2 -2
  89. package/src/commands/start/adapter-config.ts +157 -0
  90. package/src/commands/start/catalog-le-dt.test.ts +50 -0
  91. package/src/commands/start/catalog-le-dt.ts +187 -0
  92. package/src/commands/start/catalog-model-schema.ts +89 -0
  93. package/src/commands/start/catalog-template-detail.ts +54 -0
  94. package/src/commands/start/daemon.ts +255 -0
  95. package/src/commands/start/display.ts +150 -0
  96. package/src/commands/start/engine-setup.ts +247 -0
  97. package/src/commands/start/events.ts +126 -0
  98. package/src/commands/start/index.ts +897 -0
  99. package/src/commands/start/protocol-plans.ts +239 -0
  100. package/src/commands/start/template-loader.ts +197 -0
  101. package/src/commands/start/template-resolver.ts +185 -0
  102. package/src/commands/start/types.ts +73 -0
  103. package/src/commands/start.test.ts +137 -16
  104. package/src/commands/status.ts +1 -1
  105. package/src/commands/stop.ts +19 -8
  106. package/src/commands/templates.test.ts +1 -1
  107. package/src/commands/templates.ts +1 -3
  108. package/src/index.ts +11 -3
  109. package/src/lib/admin-auth.ts +157 -0
  110. package/src/lib/admin-client.test.ts +31 -15
  111. package/src/lib/admin-client.ts +106 -6
  112. package/src/lib/admin-platform-routes.ts +1017 -0
  113. package/src/lib/admin-platform-stream.test.ts +434 -0
  114. package/src/lib/admin-platform-stream.ts +788 -0
  115. package/src/lib/admin-responses.ts +211 -0
  116. package/src/lib/admin-server.test.ts +274 -55
  117. package/src/lib/admin-server.ts +387 -248
  118. package/src/lib/auth-store.ts +87 -0
  119. package/src/lib/daemon-registry.ts +12 -14
  120. package/src/lib/le/le-apply.test.ts +591 -0
  121. package/src/lib/le/le-apply.ts +832 -0
  122. package/src/lib/le/le-auth.ts +89 -0
  123. package/src/lib/le/le-cleanup.test.ts +168 -0
  124. package/src/lib/le/le-cleanup.ts +399 -0
  125. package/src/lib/le/le-cli-helpers.ts +77 -0
  126. package/src/lib/le/le-client.ts +184 -0
  127. package/src/lib/le/le-concurrency.test.ts +157 -0
  128. package/src/lib/le/le-concurrency.ts +78 -0
  129. package/src/lib/le/le-connection-test.ts +42 -0
  130. package/src/lib/le/le-devicehub-properties.test.ts +53 -0
  131. package/src/lib/le/le-devicehub-properties.ts +33 -0
  132. package/src/lib/le/le-devicehub.ts +213 -0
  133. package/src/lib/le/le-digital-twins.ts +285 -0
  134. package/src/lib/le/le-drivers.ts +23 -0
  135. package/src/lib/le/le-endpoint.ts +40 -0
  136. package/src/lib/le/le-environments.test.ts +73 -0
  137. package/src/lib/le/le-environments.ts +156 -0
  138. package/src/lib/le/le-markers.ts +87 -0
  139. package/src/lib/le/le-plan.test.ts +26 -0
  140. package/src/lib/le/le-plan.ts +109 -0
  141. package/src/lib/le/le-platform-operations.test.ts +198 -0
  142. package/src/lib/le/le-platform-operations.ts +340 -0
  143. package/src/lib/le/le-static-model-schema.ts +78 -0
  144. package/src/lib/le/le-static-planner.test.ts +255 -0
  145. package/src/lib/le/le-static-planner.ts +442 -0
  146. package/src/lib/le/le-template-exporter.test.ts +527 -0
  147. package/src/lib/le/le-template-exporter.ts +459 -0
  148. package/src/lib/le/le-value-types.ts +23 -0
  149. package/src/lib/mqtt-client.ts +1 -2
  150. package/src/lib/resolve-simulation.ts +1 -6
  151. package/src/lib/session-store.ts +110 -0
  152. package/src/lib/shutdown.test.ts +184 -2
  153. package/src/lib/shutdown.ts +104 -34
  154. package/src/lib/template-category.ts +3 -3
  155. package/src/lib/template-locator.ts +8 -2
  156. package/src/lib/ws-hub.ts +72 -46
  157. package/src/logger.ts +39 -14
  158. package/src/output.ts +3 -0
  159. package/console-dist/assets/index-C3XMYq26.css +0 -2
  160. package/console-dist/assets/index-hUJSpKtB.js +0 -119
  161. package/src/commands/start.ts +0 -2023
@@ -0,0 +1,788 @@
1
+ /**
2
+ * SSE streaming handlers for platform apply/cleanup operations.
3
+ *
4
+ * Emits server-sent events as resources are created/updated/deleted,
5
+ * giving the console real-time progress feedback.
6
+ */
7
+
8
+ import type { EventLog } from "@miravo/core";
9
+ import { colors } from "consola/utils";
10
+ import { platformLog } from "../logger.ts";
11
+ import { formatDuration } from "../output.ts";
12
+ import {
13
+ DEFAULT_APPLY_SCOPE,
14
+ DEFAULT_CLEANUP_SCOPE,
15
+ PlatformCleanupBodySchema,
16
+ resolveApplyContext,
17
+ } from "./admin-platform-routes.ts";
18
+ import type { ResourceProgress } from "./le/le-apply.ts";
19
+ import { buildApplyPlan, executePlan } from "./le/le-apply.ts";
20
+ import { buildCleanupPlan, executeCleanup } from "./le/le-cleanup.ts";
21
+ import { extractTemplateId } from "./le/le-cli-helpers.ts";
22
+ import { LEClient } from "./le/le-client.ts";
23
+ import { formatThrownError } from "./le/le-concurrency.ts";
24
+ import { LEDeviceHub } from "./le/le-devicehub.ts";
25
+ import { LEDigitalTwins } from "./le/le-digital-twins.ts";
26
+ import { DEFAULT_PLATFORM_ID, getEnvironment, touchEnvironment } from "./le/le-environments.ts";
27
+ import type { ApplyPlan } from "./le/le-plan.ts";
28
+ import {
29
+ appendPlatformOperation,
30
+ createPlatformOperationTracker,
31
+ } from "./le/le-platform-operations.ts";
32
+ import { createCatalog, resolveTemplateIdentifier } from "./template-locator.ts";
33
+
34
+ // --- Active operation registry ---
35
+
36
+ const activeOperations = new Map<string, AbortController>();
37
+
38
+ /** Cancel an in-progress streaming operation. Returns true if found and aborted. */
39
+ export function cancelOperation(operationId: string): boolean {
40
+ const ac = activeOperations.get(operationId);
41
+ if (!ac) return false;
42
+ ac.abort();
43
+ return true;
44
+ }
45
+
46
+ // --- SSE helpers ---
47
+
48
+ type SSESend = (event: string, data: unknown) => void;
49
+
50
+ function createSSEResponse(handler: (send: SSESend) => Promise<void>): Response {
51
+ return new Response(
52
+ new ReadableStream({
53
+ async start(controller) {
54
+ const encoder = new TextEncoder();
55
+ const send: SSESend = (event, data) => {
56
+ try {
57
+ controller.enqueue(
58
+ encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
59
+ );
60
+ } catch {
61
+ // Ignore errors if the stream controller is already closed (e.g., client disconnected)
62
+ }
63
+ };
64
+ try {
65
+ await handler(send);
66
+ } catch (err) {
67
+ const msg = err instanceof Error ? err.message : String(err);
68
+ send("error", { message: msg });
69
+ } finally {
70
+ try {
71
+ controller.close();
72
+ } catch {
73
+ // Ignore if already closed
74
+ }
75
+ }
76
+ },
77
+ }),
78
+ {
79
+ headers: {
80
+ "Content-Type": "text/event-stream",
81
+ "Cache-Control": "no-cache",
82
+ Connection: "keep-alive",
83
+ },
84
+ },
85
+ );
86
+ }
87
+
88
+ // --- Apply stream ---
89
+
90
+ export function handleApplyStream(body: unknown, eventLog?: EventLog | undefined): Response {
91
+ return createSSEResponse(async (send) => {
92
+ const ctx = await resolveApplyContext(body);
93
+ if (ctx instanceof Response) {
94
+ const errorBody = (await ctx.json()) as { message?: string; error?: string };
95
+ send("error", { message: errorBody.message ?? "Request validation failed." });
96
+ return;
97
+ }
98
+
99
+ touchEnvironment(ctx.req.environmentId).catch(() => {});
100
+
101
+ const operationId = crypto.randomUUID();
102
+ const startTime = performance.now();
103
+ const startedAt = Date.now();
104
+
105
+ const scope = ctx.req.scope ?? DEFAULT_APPLY_SCOPE;
106
+ const ac = new AbortController();
107
+ activeOperations.set(operationId, ac);
108
+
109
+ let totalAppliedCount = 0;
110
+ let totalFailedCount = 0;
111
+ let currentPlan: ApplyPlan | undefined;
112
+
113
+ const maxAttempts = 3;
114
+ let attempt = 0;
115
+ const finalActivityLogs: Parameters<NonNullable<EventLog>["pushExternal"]>[0][] = [];
116
+ const tracker = createPlatformOperationTracker({
117
+ operationId,
118
+ operationType: "apply",
119
+ templateId: ctx.templateId,
120
+ environmentId: ctx.req.environmentId,
121
+ environmentLabel: ctx.env.label,
122
+ hostname: ctx.env.hostname,
123
+ scope,
124
+ filters: { area: ctx.req.area, line: ctx.req.line, instance: ctx.req.instance },
125
+ startedAt,
126
+ });
127
+
128
+ try {
129
+ while (attempt < maxAttempts) {
130
+ attempt++;
131
+
132
+ try {
133
+ const planOpts = {
134
+ templateId: ctx.templateId,
135
+ targetHost: ctx.env.hostname,
136
+ sourceHostname: ctx.env.sourceHostname,
137
+ scope,
138
+ filters: { area: ctx.req.area, line: ctx.req.line, instance: ctx.req.instance },
139
+ ifUnmanaged: ctx.req.ifUnmanaged ?? "fail",
140
+ dryRun: false,
141
+ };
142
+
143
+ const { plan, snapshot } = await buildApplyPlan(ctx.hub, ctx.dt, ctx.desired, planOpts);
144
+ currentPlan = plan;
145
+
146
+ const totalPlanned = plan.entries.length;
147
+ const phaseTotals = computePhaseTotals(plan.entries);
148
+
149
+ send("started", {
150
+ operationId,
151
+ type: "apply",
152
+ template: ctx.req.template,
153
+ model: ctx.req.model,
154
+ environment: ctx.env.label,
155
+ totalPlanned,
156
+ attempt,
157
+ maxAttempts,
158
+ });
159
+
160
+ platformLog.start(
161
+ `apply ${colors.bold(ctx.templateId)} ${colors.dim("\u2192")} ${colors.cyan(ctx.env.label)} · ${colors.bold(String(totalPlanned))} planned`,
162
+ );
163
+
164
+ let currentPhase = "";
165
+ const applyOpts = {
166
+ ...planOpts,
167
+ onResourceComplete: (progress: ResourceProgress) => {
168
+ if (progress.status === "success") {
169
+ totalAppliedCount++;
170
+ } else {
171
+ totalFailedCount++;
172
+ }
173
+
174
+ tracker.onResourceComplete(progress);
175
+ if (progress.phase !== currentPhase) {
176
+ currentPhase = progress.phase;
177
+ send("phase", {
178
+ operationId,
179
+ phase: currentPhase,
180
+ total: phaseTotals.get(currentPhase) ?? 0,
181
+ });
182
+ }
183
+ send("resource", {
184
+ operationId,
185
+ phase: progress.phase,
186
+ name: progress.name,
187
+ action: progress.action,
188
+ status: progress.status,
189
+ ...(progress.error ? { error: progress.error } : {}),
190
+ index: progress.index,
191
+ of: progress.of,
192
+ });
193
+
194
+ finalActivityLogs.push({
195
+ type: "platform:resource",
196
+ operationId,
197
+ operationType: "apply",
198
+ templateId: ctx.templateId,
199
+ environmentLabel: ctx.env.label,
200
+ hostname: ctx.env.hostname,
201
+ phase: progress.phase,
202
+ resourceType: progress.resourceType,
203
+ resourceName: progress.name,
204
+ action: progress.action,
205
+ status: progress.status,
206
+ ...(progress.error ? { error: progress.error } : {}),
207
+ });
208
+ },
209
+ };
210
+
211
+ const blockers = plan.entries.filter((e) => e.action === "blocked");
212
+ if (blockers.length > 0) {
213
+ const duration = Math.round(performance.now() - startTime);
214
+ const completedAt = Date.now();
215
+ platformLog.warn(
216
+ `apply blocked · ${colors.yellow(String(blockers.length))} blocked · ${formatDuration(duration)}`,
217
+ );
218
+
219
+ const blockerIndices = new Map<string, number>();
220
+ for (const b of blockers) {
221
+ const idx = (blockerIndices.get(b.resourceType) ?? 0) + 1;
222
+ blockerIndices.set(b.resourceType, idx);
223
+
224
+ applyOpts.onResourceComplete({
225
+ phase: b.resourceType,
226
+ resourceType: b.resourceType,
227
+ name: b.name,
228
+ action: b.action,
229
+ status: "failed",
230
+ error:
231
+ "blockReason" in b && typeof b.blockReason === "string"
232
+ ? b.blockReason
233
+ : "Resource is blocked",
234
+ index: idx,
235
+ of: phaseTotals.get(b.resourceType) ?? blockers.length,
236
+ });
237
+ }
238
+
239
+ send("complete", {
240
+ operationId,
241
+ applied: totalAppliedCount,
242
+ failed: totalFailedCount,
243
+ duration,
244
+ plan,
245
+ });
246
+ for (const log of finalActivityLogs) {
247
+ eventLog?.pushExternal(log);
248
+ }
249
+ eventLog?.pushExternal({
250
+ type: "platform:operation",
251
+ operationId,
252
+ operationType: "apply",
253
+ templateId: ctx.templateId,
254
+ environmentLabel: ctx.env.label,
255
+ hostname: ctx.env.hostname,
256
+ applied: totalAppliedCount,
257
+ failed: totalFailedCount,
258
+ duration,
259
+ });
260
+ await appendPlatformOperation(
261
+ tracker.finalize({
262
+ successCount: totalAppliedCount,
263
+ failedCount: totalFailedCount,
264
+ blockedCount: blockers.length,
265
+ completedAt,
266
+ }),
267
+ ).catch(() => {});
268
+ return;
269
+ }
270
+
271
+ const result = await executePlan(
272
+ ctx.hub,
273
+ ctx.dt,
274
+ plan,
275
+ ctx.desired,
276
+ { ...applyOpts, signal: ac.signal },
277
+ snapshot,
278
+ );
279
+ const duration = Math.round(performance.now() - startTime);
280
+ const completedAt = Date.now();
281
+
282
+ if (ac.signal.aborted) {
283
+ platformLog.info(
284
+ `apply cancelled · ${colors.green(String(totalAppliedCount))} applied · ${formatDuration(duration)}`,
285
+ );
286
+ send("cancelled", {
287
+ operationId,
288
+ applied: totalAppliedCount,
289
+ failed: totalFailedCount,
290
+ duration,
291
+ plan: result.plan,
292
+ });
293
+ for (const log of finalActivityLogs) {
294
+ eventLog?.pushExternal(log);
295
+ }
296
+ await appendPlatformOperation(
297
+ tracker.finalize({
298
+ successCount: totalAppliedCount,
299
+ failedCount: totalFailedCount,
300
+ completedAt,
301
+ error: "Cancelled",
302
+ }),
303
+ ).catch(() => {});
304
+ return;
305
+ }
306
+
307
+ if (result.failed > 0 && attempt < maxAttempts) {
308
+ platformLog.warn(
309
+ `apply attempt ${attempt} finished with ${colors.yellow(String(result.failed))} errors, retrying in 3s...`,
310
+ );
311
+ send("retrying", {
312
+ operationId,
313
+ attempt,
314
+ maxAttempts,
315
+ delayMs: 3000,
316
+ error: `Attempt ${attempt} finished with ${result.failed} errors`,
317
+ });
318
+ await Bun.sleep(3000);
319
+ continue;
320
+ }
321
+
322
+ if (result.failed > 0) {
323
+ platformLog.warn(
324
+ `apply done · ${colors.green(String(totalAppliedCount))} created · ${colors.yellow(String(totalFailedCount))} failed · ${formatDuration(duration)}`,
325
+ );
326
+ } else {
327
+ platformLog.success(
328
+ `apply done · ${colors.bold(String(totalAppliedCount))} created · ${formatDuration(duration)}`,
329
+ );
330
+ }
331
+
332
+ send("complete", {
333
+ operationId,
334
+ applied: totalAppliedCount,
335
+ failed: totalFailedCount,
336
+ duration,
337
+ plan: result.plan,
338
+ });
339
+
340
+ for (const log of finalActivityLogs) {
341
+ eventLog?.pushExternal(log);
342
+ }
343
+ eventLog?.pushExternal({
344
+ type: "platform:operation",
345
+ operationId,
346
+ operationType: "apply",
347
+ templateId: ctx.templateId,
348
+ environmentLabel: ctx.env.label,
349
+ hostname: ctx.env.hostname,
350
+ applied: totalAppliedCount,
351
+ failed: totalFailedCount,
352
+ duration,
353
+ });
354
+ await appendPlatformOperation(
355
+ tracker.finalize({
356
+ successCount: totalAppliedCount,
357
+ failedCount: totalFailedCount,
358
+ completedAt,
359
+ ...(result.error ? { error: result.error } : {}),
360
+ }),
361
+ ).catch(() => {});
362
+ return;
363
+ } catch (err) {
364
+ const duration = Math.round(performance.now() - startTime);
365
+ const completedAt = Date.now();
366
+
367
+ if (ac.signal.aborted || (err instanceof Error && err.name === "AbortError")) {
368
+ platformLog.info(
369
+ `apply cancelled · ${colors.green(String(totalAppliedCount))} applied · ${formatDuration(duration)}`,
370
+ );
371
+ send("cancelled", {
372
+ operationId,
373
+ applied: totalAppliedCount,
374
+ failed: totalFailedCount,
375
+ duration,
376
+ plan: currentPlan ?? {
377
+ sourceMode: "static",
378
+ targetHost: ctx.env.hostname,
379
+ scope: [],
380
+ filters: {},
381
+ entries: [],
382
+ },
383
+ });
384
+ for (const log of finalActivityLogs) {
385
+ eventLog?.pushExternal(log);
386
+ }
387
+ await appendPlatformOperation(
388
+ tracker.finalize({
389
+ successCount: totalAppliedCount,
390
+ failedCount: totalFailedCount,
391
+ completedAt,
392
+ error: "Cancelled",
393
+ }),
394
+ ).catch(() => {});
395
+ return;
396
+ }
397
+
398
+ const message = formatThrownError(err);
399
+
400
+ if (attempt < maxAttempts) {
401
+ platformLog.warn(`apply attempt ${attempt} failed: ${message}, retrying in 3s...`);
402
+ send("retrying", {
403
+ operationId,
404
+ attempt,
405
+ maxAttempts,
406
+ delayMs: 3000,
407
+ error: message,
408
+ });
409
+ await Bun.sleep(3000);
410
+ continue;
411
+ }
412
+
413
+ platformLog.error(`apply failed · ${message}`);
414
+ for (const log of finalActivityLogs) {
415
+ eventLog?.pushExternal(log);
416
+ }
417
+ await appendPlatformOperation(
418
+ tracker.finalize({
419
+ successCount: totalAppliedCount,
420
+ failedCount: totalFailedCount || 1,
421
+ completedAt,
422
+ error: message,
423
+ }),
424
+ ).catch(() => {});
425
+ throw err;
426
+ }
427
+ }
428
+ } finally {
429
+ activeOperations.delete(operationId);
430
+ }
431
+ });
432
+ }
433
+
434
+ // --- Cleanup stream ---
435
+
436
+ export function handleCleanupStream(body: unknown, eventLog?: EventLog | undefined): Response {
437
+ return createSSEResponse(async (send) => {
438
+ const parsed = PlatformCleanupBodySchema.safeParse(body);
439
+ if (!parsed.success) {
440
+ send("error", { message: parsed.error.issues.map((i) => i.message).join("; ") });
441
+ return;
442
+ }
443
+ const req = parsed.data;
444
+
445
+ const env = await getEnvironment(req.environmentId);
446
+ if (!env) {
447
+ send("error", { message: "Environment not found." });
448
+ return;
449
+ }
450
+ if (env.platformId !== DEFAULT_PLATFORM_ID) {
451
+ send("error", {
452
+ message: `Environment "${env.label}" uses unsupported platform "${env.platformId}".`,
453
+ });
454
+ return;
455
+ }
456
+
457
+ touchEnvironment(req.environmentId).catch(() => {});
458
+
459
+ const allManaged = req.allManaged ?? false;
460
+ if (!allManaged && !req.template) {
461
+ send("error", { message: "Provide 'template' or set 'allManaged: true'." });
462
+ return;
463
+ }
464
+
465
+ const operationId = crypto.randomUUID();
466
+ const startTime = performance.now();
467
+ const startedAt = Date.now();
468
+
469
+ const client = new LEClient({ hostname: env.hostname, apiToken: env.apiToken });
470
+ const hub = new LEDeviceHub(client);
471
+ const dt = new LEDigitalTwins(client);
472
+ await client.checkAuth();
473
+
474
+ let templateId = "all-managed";
475
+ if (!allManaged && req.template) {
476
+ const catalog = createCatalog();
477
+ const templatePath = await resolveTemplateIdentifier(req.template, catalog);
478
+ templateId = extractTemplateId(templatePath);
479
+ }
480
+
481
+ const scope = req.scope ?? DEFAULT_CLEANUP_SCOPE;
482
+ const ac = new AbortController();
483
+ activeOperations.set(operationId, ac);
484
+
485
+ let totalDeletedCount = 0;
486
+ let totalFailedCount = 0;
487
+ let currentPlan: ApplyPlan | undefined;
488
+
489
+ const maxAttempts = 3;
490
+ let attempt = 0;
491
+ const finalActivityLogs: Parameters<NonNullable<EventLog>["pushExternal"]>[0][] = [];
492
+ const tracker = createPlatformOperationTracker({
493
+ operationId,
494
+ operationType: "cleanup",
495
+ templateId,
496
+ environmentId: req.environmentId,
497
+ environmentLabel: env.label,
498
+ hostname: env.hostname,
499
+ scope,
500
+ filters: { area: req.area, line: req.line, instance: req.instance },
501
+ startedAt,
502
+ });
503
+
504
+ try {
505
+ while (attempt < maxAttempts) {
506
+ attempt++;
507
+
508
+ try {
509
+ const basePlanOpts = {
510
+ templateId,
511
+ targetHost: env.hostname,
512
+ scope,
513
+ filters: { area: req.area, line: req.line, instance: req.instance },
514
+ allManaged,
515
+ dryRun: false,
516
+ };
517
+
518
+ const planResult = await buildCleanupPlan(hub, dt, basePlanOpts);
519
+ currentPlan = planResult.plan;
520
+ const totalPlanned = planResult.plan.entries.length;
521
+ const phaseTotals = computePhaseTotals(planResult.plan.entries);
522
+
523
+ send("started", {
524
+ operationId,
525
+ type: "cleanup",
526
+ template: req.template,
527
+ environment: env.label,
528
+ totalPlanned,
529
+ attempt,
530
+ maxAttempts,
531
+ });
532
+
533
+ platformLog.start(
534
+ `cleanup ${colors.bold(templateId)} ${colors.dim("\u2192")} ${colors.cyan(env.label)} · ${colors.bold(String(totalPlanned))} planned`,
535
+ );
536
+
537
+ let currentPhase = "";
538
+ const cleanupOpts = {
539
+ ...basePlanOpts,
540
+ onResourceComplete: (progress: ResourceProgress) => {
541
+ if (progress.status === "success") {
542
+ totalDeletedCount++;
543
+ } else {
544
+ totalFailedCount++;
545
+ }
546
+
547
+ tracker.onResourceComplete(progress);
548
+ if (progress.phase !== currentPhase) {
549
+ currentPhase = progress.phase;
550
+ send("phase", {
551
+ operationId,
552
+ phase: currentPhase,
553
+ total: phaseTotals.get(currentPhase) ?? 0,
554
+ });
555
+ }
556
+ send("resource", {
557
+ operationId,
558
+ phase: progress.phase,
559
+ name: progress.name,
560
+ action: progress.action,
561
+ status: progress.status,
562
+ ...(progress.error ? { error: progress.error } : {}),
563
+ index: progress.index,
564
+ of: progress.of,
565
+ });
566
+
567
+ finalActivityLogs.push({
568
+ type: "platform:resource",
569
+ operationId,
570
+ operationType: "cleanup",
571
+ templateId,
572
+ environmentLabel: env.label,
573
+ hostname: env.hostname,
574
+ phase: progress.phase,
575
+ resourceType: progress.resourceType,
576
+ resourceName: progress.name,
577
+ action: progress.action,
578
+ status: progress.status,
579
+ ...(progress.error ? { error: progress.error } : {}),
580
+ });
581
+ },
582
+ };
583
+
584
+ if (planResult.plan.entries.length === 0) {
585
+ const duration = Math.round(performance.now() - startTime);
586
+ const completedAt = Date.now();
587
+ platformLog.info(`cleanup done · nothing to remove · ${formatDuration(duration)}`);
588
+ send("complete", {
589
+ operationId,
590
+ deleted: totalDeletedCount,
591
+ failed: totalFailedCount,
592
+ duration,
593
+ plan: planResult.plan,
594
+ });
595
+ for (const log of finalActivityLogs) {
596
+ eventLog?.pushExternal(log);
597
+ }
598
+ eventLog?.pushExternal({
599
+ type: "platform:operation",
600
+ operationId,
601
+ operationType: "cleanup",
602
+ templateId,
603
+ environmentLabel: env.label,
604
+ hostname: env.hostname,
605
+ applied: totalDeletedCount,
606
+ failed: totalFailedCount,
607
+ duration,
608
+ });
609
+ await appendPlatformOperation(
610
+ tracker.finalize({
611
+ successCount: totalDeletedCount,
612
+ failedCount: totalFailedCount,
613
+ completedAt,
614
+ }),
615
+ ).catch(() => {});
616
+ return;
617
+ }
618
+
619
+ const result = await executeCleanup(hub, dt, planResult, {
620
+ ...cleanupOpts,
621
+ signal: ac.signal,
622
+ });
623
+ const duration = Math.round(performance.now() - startTime);
624
+ const completedAt = Date.now();
625
+
626
+ if (ac.signal.aborted) {
627
+ platformLog.info(
628
+ `cleanup cancelled · ${colors.green(String(totalDeletedCount))} deleted · ${formatDuration(duration)}`,
629
+ );
630
+ send("cancelled", {
631
+ operationId,
632
+ deleted: totalDeletedCount,
633
+ failed: totalFailedCount,
634
+ duration,
635
+ plan: result.plan,
636
+ });
637
+ for (const log of finalActivityLogs) {
638
+ eventLog?.pushExternal(log);
639
+ }
640
+ await appendPlatformOperation(
641
+ tracker.finalize({
642
+ successCount: totalDeletedCount,
643
+ failedCount: totalFailedCount,
644
+ completedAt,
645
+ error: "Cancelled",
646
+ }),
647
+ ).catch(() => {});
648
+ return;
649
+ }
650
+
651
+ if (result.failed > 0 && attempt < maxAttempts) {
652
+ platformLog.warn(
653
+ `cleanup attempt ${attempt} finished with ${colors.yellow(String(result.failed))} errors, retrying in 3s...`,
654
+ );
655
+ send("retrying", {
656
+ operationId,
657
+ attempt,
658
+ maxAttempts,
659
+ delayMs: 3000,
660
+ error: `Attempt ${attempt} finished with ${result.failed} errors`,
661
+ });
662
+ await Bun.sleep(3000);
663
+ continue;
664
+ }
665
+
666
+ if (result.failed > 0) {
667
+ platformLog.warn(
668
+ `cleanup done · ${colors.green(String(totalDeletedCount))} deleted · ${colors.yellow(String(totalFailedCount))} failed · ${formatDuration(duration)}`,
669
+ );
670
+ } else {
671
+ platformLog.success(
672
+ `cleanup done · ${colors.bold(String(totalDeletedCount))} deleted · ${formatDuration(duration)}`,
673
+ );
674
+ }
675
+
676
+ send("complete", {
677
+ operationId,
678
+ deleted: totalDeletedCount,
679
+ failed: totalFailedCount,
680
+ duration,
681
+ plan: result.plan,
682
+ });
683
+
684
+ for (const log of finalActivityLogs) {
685
+ eventLog?.pushExternal(log);
686
+ }
687
+ eventLog?.pushExternal({
688
+ type: "platform:operation",
689
+ operationId,
690
+ operationType: "cleanup",
691
+ templateId,
692
+ environmentLabel: env.label,
693
+ hostname: env.hostname,
694
+ applied: totalDeletedCount,
695
+ failed: totalFailedCount,
696
+ duration,
697
+ });
698
+ await appendPlatformOperation(
699
+ tracker.finalize({
700
+ successCount: totalDeletedCount,
701
+ failedCount: totalFailedCount,
702
+ completedAt,
703
+ ...(result.error ? { error: result.error } : {}),
704
+ }),
705
+ ).catch(() => {});
706
+ return;
707
+ } catch (err) {
708
+ const duration = Math.round(performance.now() - startTime);
709
+ const completedAt = Date.now();
710
+
711
+ if (ac.signal.aborted || (err instanceof Error && err.name === "AbortError")) {
712
+ platformLog.info(
713
+ `cleanup cancelled · ${colors.green(String(totalDeletedCount))} deleted · ${formatDuration(duration)}`,
714
+ );
715
+ send("cancelled", {
716
+ operationId,
717
+ deleted: totalDeletedCount,
718
+ failed: totalFailedCount,
719
+ duration,
720
+ plan: currentPlan ?? {
721
+ sourceMode: "static",
722
+ targetHost: env.hostname,
723
+ scope: [],
724
+ filters: {},
725
+ entries: [],
726
+ },
727
+ });
728
+ for (const log of finalActivityLogs) {
729
+ eventLog?.pushExternal(log);
730
+ }
731
+ await appendPlatformOperation(
732
+ tracker.finalize({
733
+ successCount: totalDeletedCount,
734
+ failedCount: totalFailedCount,
735
+ completedAt,
736
+ error: "Cancelled",
737
+ }),
738
+ ).catch(() => {});
739
+ return;
740
+ }
741
+
742
+ const message = formatThrownError(err);
743
+
744
+ if (attempt < maxAttempts) {
745
+ platformLog.warn(`cleanup attempt ${attempt} failed: ${message}, retrying in 3s...`);
746
+ send("retrying", {
747
+ operationId,
748
+ attempt,
749
+ maxAttempts,
750
+ delayMs: 3000,
751
+ error: message,
752
+ });
753
+ await Bun.sleep(3000);
754
+ continue;
755
+ }
756
+
757
+ platformLog.error(`cleanup failed · ${message}`);
758
+ for (const log of finalActivityLogs) {
759
+ eventLog?.pushExternal(log);
760
+ }
761
+ await appendPlatformOperation(
762
+ tracker.finalize({
763
+ successCount: totalDeletedCount,
764
+ failedCount: totalFailedCount || 1,
765
+ completedAt,
766
+ error: message,
767
+ }),
768
+ ).catch(() => {});
769
+ throw err;
770
+ }
771
+ }
772
+ } finally {
773
+ activeOperations.delete(operationId);
774
+ }
775
+ });
776
+ }
777
+
778
+ // --- Shared helpers ---
779
+
780
+ function computePhaseTotals(
781
+ entries: readonly { action: string; resourceType: string }[],
782
+ ): Map<string, number> {
783
+ const totals = new Map<string, number>();
784
+ for (const entry of entries) {
785
+ totals.set(entry.resourceType, (totals.get(entry.resourceType) ?? 0) + 1);
786
+ }
787
+ return totals;
788
+ }