-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBootstrap.ts
More file actions
700 lines (625 loc) · 19.6 KB
/
Bootstrap.ts
File metadata and controls
700 lines (625 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
/**
* @module Effect/Bootstrap
* @description
* Bootstrap orchestration for Cocoon Extension Host using Effect-TS.
* Coordinates initialization stages for the extension host system.
*
* Bootstrap Stages:
* 1. Environment Detection
* 2. Configuration Loading
* 3. gRPC Connection to Mountain
* 4. Module Interceptor Setup
* 5. Extension Registry Initialization
* 6. Health Checks
*/
import { createConnection } from "node:net";
import { Context, Duration, Effect, Layer, Schedule } from "effect";
import { CocoonDevLog } from "../Services/DevLog.js";
import LandFixLog from "../Utility/LandFixLog.js";
import { ExtensionTag } from "./Extension.js";
import { HealthTag } from "./Health.js";
import { ModuleInterceptorTag } from "./ModuleInterceptor.js";
import { MountainClientTag } from "./MountainClient.js";
import { RPCServerTag } from "./RPCServer.js";
import { TelemetryTag, withSpan } from "./Telemetry.js";
/**
* Fast TCP port probe - returns true if a client socket can ESTABLISH (not
* just send SYN) inside `TimeoutMs`. Used as Stage 3's pre-flight so we only
* attempt the expensive gRPC handshake once Mountain's listener is live.
* Cheap: one socket, one timeout, no retries.
*/
const ProbeTcp = (
Host: string,
Port: number,
TimeoutMs: number,
): Effect.Effect<boolean, never> =>
Effect.async<boolean, never>((Resume) => {
let Settled = false;
const Settle = (Value: boolean) => {
if (Settled) return;
Settled = true;
try {
Socket.destroy();
} catch {}
Resume(Effect.succeed(Value));
};
const Socket = createConnection({ host: Host, port: Port });
const Timer = setTimeout(() => Settle(false), TimeoutMs);
Socket.once("connect", () => {
clearTimeout(Timer);
Settle(true);
});
Socket.once("error", () => {
clearTimeout(Timer);
Settle(false);
});
return Effect.sync(() => {
clearTimeout(Timer);
try {
Socket.destroy();
} catch {}
});
});
// ============================================================================
// TYPES
// ============================================================================
export interface BootstrapOptions {
readonly debugMode?: boolean;
readonly verboseLogging?: boolean;
readonly enablePerformanceTracking?: boolean;
readonly skipHealthCheck?: boolean;
}
export interface StageResult {
readonly stageName: string;
readonly success: boolean;
readonly duration: number;
readonly error: Error | undefined;
}
export interface BootstrapResult {
readonly success: boolean;
readonly totalDuration: number;
readonly stages: ReadonlyArray<StageResult>;
readonly error: Error | undefined;
}
export interface BootstrapService {
readonly run: (
options?: BootstrapOptions,
) => Effect.Effect<BootstrapResult, never>;
}
// ============================================================================
// SERVICE TAG
// ============================================================================
export class BootstrapTag extends Context.Tag("Cocoon/Bootstrap")<
BootstrapTag,
BootstrapService
>() {}
// ============================================================================
// STAGE EFFECTS
// ============================================================================
const stage1_Environment = withSpan(
"stage1_environment",
Effect.gen(function* () {
const telemetry = yield* TelemetryTag;
const StageStart = Date.now();
CocoonDevLog("bootstrap-stage", "[Bootstrap] stage=Environment event=start");
telemetry.log(
"info",
"[Cocoon Bootstrap] Stage 1: Detecting environment...",
);
const nodeVersion = process.version;
const platform = process.platform;
const arch = process.arch;
telemetry.log(
"info",
`[Cocoon Bootstrap] Node.js ${nodeVersion} on ${platform}/${arch}`,
);
CocoonDevLog(
"bootstrap-stage",
`[Bootstrap] stage=Environment event=ok node=${nodeVersion} platform=${platform}/${arch} duration_ms=${Date.now() - StageStart}`,
);
return {
stageName: "Environment",
success: true as boolean,
duration: 0,
error: undefined,
} satisfies StageResult;
}),
);
const stage2_Configuration = withSpan(
"stage2_configuration",
Effect.gen(function* () {
const telemetry = yield* TelemetryTag;
const StageStart = Date.now();
CocoonDevLog(
"bootstrap-stage",
"[Bootstrap] stage=Configuration event=start",
);
telemetry.log(
"info",
"[Cocoon Bootstrap] Stage 2: Loading configuration...",
);
// Real bootstrap configuration comes in through the environment -
// Mountain spawns Cocoon with `MOUNTAIN_GRPC_PORT`, `COCOON_GRPC_PORT`,
// `LAND_DEV_LOG`, `NODE_ENV`, etc. Extension-host settings arrive later
// via `InitializeExtensionHost`. Here we:
// (a) parse + validate the bootstrap env vars once,
// (b) report each resolved value via telemetry so a pasted log makes
// misconfiguration obvious, and
// (c) attach the parsed block to `globalThis.__cocoonBootstrapConfig`
// so downstream stages / handlers can read without re-parsing.
const ParsePort = (
Raw: string | undefined,
Fallback: number,
): number => {
if (Raw === undefined) return Fallback;
const Value = parseInt(Raw, 10);
return Number.isFinite(Value) && Value > 0 && Value < 65536
? Value
: Fallback;
};
const ResolvedConfig = {
MountainPort: ParsePort(process.env["MOUNTAIN_GRPC_PORT"], 50051),
CocoonPort: ParsePort(process.env["COCOON_GRPC_PORT"], 50052),
NodeEnv: process.env["NODE_ENV"] ?? "production",
DevLog: process.env["LAND_DEV_LOG"] ?? "",
DebugFlag: process.env["TAURI_ENV_DEBUG"] === "true",
};
(
globalThis as unknown as {
__cocoonBootstrapConfig?: typeof ResolvedConfig;
}
).__cocoonBootstrapConfig = ResolvedConfig;
LandFixLog.Info(
"Bootstrap",
`Configuration resolved: MountainPort=${ResolvedConfig.MountainPort} CocoonPort=${ResolvedConfig.CocoonPort} NodeEnv=${ResolvedConfig.NodeEnv} DevLog=${ResolvedConfig.DevLog || "<unset>"} TauriDebug=${ResolvedConfig.DebugFlag}`,
);
telemetry.log("info", "[Cocoon Bootstrap] Configuration loaded");
CocoonDevLog(
"bootstrap-stage",
`[Bootstrap] stage=Configuration event=ok mountain_port=${ResolvedConfig.MountainPort} cocoon_port=${ResolvedConfig.CocoonPort} node_env=${ResolvedConfig.NodeEnv} duration_ms=${Date.now() - StageStart}`,
);
return {
stageName: "Configuration",
success: true as boolean,
duration: 0,
error: undefined,
} satisfies StageResult;
}),
);
/**
* Stage 3 tuning - exposed as constants so a future test harness can override.
* Total worst-case duration before we give up: probe 15× + connect retry up to
* `MountainConnectMaxAttempts`. With 250 ms probe + 500 ms initial backoff
* doubling to 5 s cap, 15 attempts covers the 5-8 s Mountain startup window
* observed in every rebuild so far with generous headroom.
*/
const MountainProbeTimeoutMs = 250;
const MountainProbeMaxAttempts = 15;
const MountainProbeDelayMs = 200;
const MountainConnectMaxAttempts = 20;
const stage3_MountainConnection = withSpan(
"stage3_mountain_connection",
Effect.gen(function* () {
const telemetry = yield* TelemetryTag;
const mountainClient = yield* MountainClientTag;
telemetry.log(
"info",
"[Cocoon Bootstrap] Stage 3: Connecting to Mountain...",
);
// Connect to Mountain's gRPC server (MountainService on port 50051).
// Mountain sets MOUNTAIN_GRPC_PORT env var when spawning Cocoon.
const MountainPort = parseInt(
process.env["MOUNTAIN_GRPC_PORT"] || "50051",
10,
);
const MountainHost = "localhost";
// Pre-flight: wait for the TCP listener to come up before attempting
// the gRPC handshake. Without this, the first `mountainClient.connect`
// attempt races Mountain's boot and reports a hard ConnectionError
// before the in-client retry loop (SendRequestWithRetry) can recover.
let ProbeAttempt = 0;
let Listening = false;
while (ProbeAttempt < MountainProbeMaxAttempts && !Listening) {
ProbeAttempt++;
Listening = yield* ProbeTcp(
MountainHost,
MountainPort,
MountainProbeTimeoutMs,
);
if (Listening) {
LandFixLog.Info(
"Bootstrap",
`Mountain TCP port ${MountainHost}:${MountainPort} listening after ${ProbeAttempt} probe(s)`,
);
break;
}
yield* Effect.sleep(Duration.millis(MountainProbeDelayMs));
}
if (!Listening) {
LandFixLog.Warn(
"Bootstrap",
`Mountain TCP port ${MountainHost}:${MountainPort} unreachable after ${MountainProbeMaxAttempts} probes; attempting connect anyway`,
);
}
// Attempt the gRPC connect with exponential backoff. Schedule.exponential
// doubles each delay from 500 ms; Schedule.recurs caps total attempts.
// On every recur, log the failure so a pasted terminal log surfaces the
// cause without having to re-run with a verbose flag.
const AttemptRef = { value: 0 };
const Connect = Effect.gen(function* () {
AttemptRef.value++;
yield* mountainClient.connect({
host: MountainHost,
port: MountainPort,
});
}).pipe(
Effect.tapError((Failure) =>
Effect.sync(() => {
const Message =
Failure instanceof Error
? Failure.message
: String(Failure);
LandFixLog.Warn(
"Bootstrap",
`MountainConnection attempt ${AttemptRef.value}/${MountainConnectMaxAttempts} failed: ${Message}`,
);
}),
),
Effect.retry(
Schedule.exponential(Duration.millis(500)).pipe(
Schedule.union(Schedule.spaced(Duration.seconds(5))),
Schedule.intersect(
Schedule.recurs(MountainConnectMaxAttempts - 1),
),
),
),
);
yield* Connect;
const version = yield* mountainClient.version;
LandFixLog.Info(
"Bootstrap",
`MountainConnection OK (v${version}) after ${AttemptRef.value} attempt(s), probe settled after ${ProbeAttempt}`,
);
telemetry.log(
"info",
`[Cocoon Bootstrap] Connected to Mountain (v${version})`,
);
return {
stageName: "MountainConnection",
success: true as boolean,
duration: 0,
error: undefined,
} satisfies StageResult;
}),
);
const stage4_ModuleInterceptor = withSpan(
"stage4_module_interceptor",
Effect.gen(function* () {
const telemetry = yield* TelemetryTag;
const moduleInterceptor = yield* ModuleInterceptorTag;
telemetry.log(
"info",
"[Cocoon Bootstrap] Stage 4: Setting up module interceptor...",
);
// Initialize module interceptor service
yield* moduleInterceptor.initialize;
// Install module interceptor into Node.js module system
yield* moduleInterceptor.install;
telemetry.log(
"info",
"[Cocoon Bootstrap] Module interceptor installed successfully",
);
return {
stageName: "ModuleInterceptor",
success: true as boolean,
duration: 0,
error: undefined,
} satisfies StageResult;
}),
);
const stage5_RPCServer = withSpan(
"stage5_rpc_server",
Effect.gen(function* () {
const telemetry = yield* TelemetryTag;
const rpcServer = yield* RPCServerTag;
telemetry.log(
"info",
"[Cocoon Bootstrap] Stage 5: Starting gRPC server...",
);
// Start gRPC server for Mountain ← Cocoon communication.
// Port from env var (set by Mountain) or default 50052.
const CocoonPort = parseInt(
process.env["COCOON_GRPC_PORT"] || "50052",
10,
);
console.log(
`[Cocoon Bootstrap] Stage 5: Starting gRPC on port ${CocoonPort}`,
);
yield* rpcServer.start({
host: "0.0.0.0",
port: CocoonPort,
});
telemetry.log("info", "[Cocoon Bootstrap] gRPC server started");
return {
stageName: "RPCServer",
success: true as boolean,
duration: 0,
error: undefined,
} satisfies StageResult;
}),
);
const stage6_Extensions = withSpan(
"stage6_extensions",
Effect.gen(function* () {
const telemetry = yield* TelemetryTag;
const extension = yield* ExtensionTag;
telemetry.log(
"info",
"[Cocoon Bootstrap] Stage 6: Initializing extensions...",
);
// Get all extensions
const extensions = yield* extension.getAll;
telemetry.log(
"info",
`[Cocoon Bootstrap] Found ${extensions.length} extensions`,
);
// Parallel activation with bounded concurrency (8) and per-extension
// error isolation - one bad activate must not abort the stage. Sequential
// for-loops used to serialise activations behind any slow I/O inside an
// extension's activate callback (file reads, LSP launches). Effect.forEach
// runs up to 8 concurrently and collects all successes; failures log and
// fall through.
const EligibleExtensions = extensions.filter(
(Ext) => Ext.manifest.enabled,
);
const ActivationAttempts = yield* Effect.forEach(
EligibleExtensions,
(Ext) =>
extension.activate(Ext.id).pipe(
Effect.map(() => ({ Id: Ext.id, Ok: true as const })),
Effect.catchAll((Failure) => {
const Message =
Failure instanceof Error
? Failure.message
: String(Failure);
telemetry.log(
"warn",
`[Cocoon Bootstrap] Extension ${Ext.id} activation failed: ${Message}`,
);
return Effect.succeed({
Id: Ext.id,
Ok: false as const,
Error: Message,
});
}),
),
{ concurrency: 8 },
);
const Successful = ActivationAttempts.filter((R) => R.Ok).length;
const FailedCount = ActivationAttempts.length - Successful;
const activeCount = yield* extension.getActiveCount;
telemetry.log(
"info",
`[Cocoon Bootstrap] Activated ${activeCount} extensions (${Successful} this stage, ${FailedCount} failed)`,
);
return {
stageName: "Extensions",
success: true as boolean,
duration: 0,
error: undefined,
} satisfies StageResult;
}),
);
const stage7_HealthCheck = withSpan(
"stage7_healthcheck",
Effect.gen(function* () {
const telemetry = yield* TelemetryTag;
const health = yield* HealthTag;
telemetry.log(
"info",
"[Cocoon Bootstrap] Stage 7: Running health checks...",
);
const systemHealth = yield* health.checkAllServices();
telemetry.log(
"info",
`[Cocoon Bootstrap] Health check result: ${systemHealth.overallStatus}`,
);
if (systemHealth.overallStatus === "unhealthy") {
telemetry.log(
"error",
"[Cocoon Bootstrap] Some services are unhealthy!",
);
}
return {
stageName: "HealthCheck",
success: systemHealth.overallStatus !== "unhealthy",
duration: 0,
error: undefined,
} satisfies StageResult;
}),
);
// ============================================================================
// BOOTSTRAP IMPLEMENTATION
// ============================================================================
const makeBootstrap = (): BootstrapService => ({
run: (options) =>
Effect.gen(function* () {
const telemetry = yield* TelemetryTag;
const startTime = Date.now();
const { skipHealthCheck = false, debugMode = false } =
options ?? {};
telemetry.log(
"info",
"[Cocoon Bootstrap] ===============================================",
);
telemetry.log(
"info",
"[Cocoon Bootstrap] Cocoon Extension Host Bootstrap",
);
telemetry.log(
"info",
`[Cocoon Bootstrap] Debug mode: ${debugMode}`,
);
telemetry.log(
"info",
"[Cocoon Bootstrap] ===============================================",
);
const stages: Array<[string, unknown]> = [
["Environment", stage1_Environment],
["Configuration", stage2_Configuration],
["MountainConnection", stage3_MountainConnection],
["ModuleInterceptor", stage4_ModuleInterceptor],
["RPCServer", stage5_RPCServer],
["Extensions", stage6_Extensions],
...(skipHealthCheck
? []
: ([["HealthCheck", stage7_HealthCheck]] as Array<
[string, unknown]
>)),
];
const results: StageResult[] = [];
for (const [StageName, stage] of stages) {
const stageStartTime = Date.now();
// Wrap each stage in Effect.catchAllCause to survive fiber failures.
// JavaScript try/catch does NOT catch Effect fiber failures.
const SafeStage = Effect.suspend(() => stage as any).pipe(
Effect.catchAllCause((Cause) => {
const Message = String(Cause).slice(0, 300);
process.stdout.write(
`[LandFix:Bootstrap] Stage "${StageName}" failed (continuing): ${Message}\n`,
);
return Effect.succeed({
stageName: StageName,
success: false as boolean,
duration: Date.now() - stageStartTime,
error: new Error(Message),
} satisfies StageResult);
}),
);
const result = yield* SafeStage as any;
if (result?.success === false) {
process.stdout.write(
`[LandFix:Bootstrap] Stage "${StageName}" reported failure: ${(result as { error?: { message?: string } }).error?.message ?? "<no message>"}\n`,
);
} else {
process.stdout.write(
`[LandFix:Bootstrap] Stage "${StageName}" OK in ${Date.now() - stageStartTime}ms\n`,
);
}
results.push({
...result,
duration: Date.now() - stageStartTime,
});
}
const endTime = Date.now();
const totalDuration = endTime - startTime;
const allSuccess = results.every((r) => r.success);
telemetry.log(
"info",
"[Cocoon Bootstrap] ===============================================",
);
telemetry.log(
"info",
`[Cocoon Bootstrap] ${allSuccess ? "✓ Bootstrap completed successfully" : "✗ Bootstrap failed"}`,
);
telemetry.log(
"info",
`[Cocoon Bootstrap] Total duration: ${totalDuration}ms`,
);
telemetry.log(
"info",
"[Cocoon Bootstrap] ===============================================",
);
if (!allSuccess) {
const failedStages = results.filter((r) => !r.success);
telemetry.log("error", "[Cocoon Bootstrap] Failed stages:");
for (const failed of failedStages) {
telemetry.log(
"error",
`[Cocoon Bootstrap] - ${failed.stageName}: ${failed.error?.message || "Unknown error"}`,
);
}
}
return {
success: allSuccess,
totalDuration,
stages: results,
error: allSuccess ? undefined : new Error("Bootstrap failed"),
} satisfies BootstrapResult;
}),
});
// ============================================================================
// LAYERS
// ============================================================================
export const BootstrapLive = Layer.effect(
BootstrapTag,
Effect.succeed(makeBootstrap()),
);
// ============================================================================
// MOCK FOR TESTING
// ============================================================================
export const makeMockBootstrap = (): BootstrapService => ({
run: (options) =>
Effect.gen(function* () {
yield* Effect.sleep("1 millis");
return {
success: true,
totalDuration: 1,
stages: [
{
stageName: "Environment",
success: true,
duration: 0,
error: undefined,
},
{
stageName: "Configuration",
success: true,
duration: 0,
error: undefined,
},
{
stageName: "MountainConnection",
success: true,
duration: 0,
error: undefined,
},
{
stageName: "RPCServer",
success: true,
duration: 0,
error: undefined,
},
{
stageName: "Extensions",
success: true,
duration: 0,
error: undefined,
},
...(options?.skipHealthCheck
? []
: [
{
stageName: "HealthCheck",
success: true,
duration: 0,
error: undefined,
},
]),
],
error: undefined,
} satisfies BootstrapResult;
}),
});
export const BootstrapMock = Layer.effect(
BootstrapTag,
Effect.succeed(makeMockBootstrap()),
);
// ============================================================================
// CONVENIENCE EXPORTS
// ============================================================================
export const runBootstrap = (options?: BootstrapOptions) =>
Effect.gen(function* () {
const bootstrap = yield* BootstrapTag;
return yield* bootstrap.run(options);
}).pipe(Effect.provide(BootstrapLive));