-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy pathhost-kernel.ts
More file actions
1168 lines (1103 loc) · 42.3 KB
/
Copy pathhost-kernel.ts
File metadata and controls
1168 lines (1103 loc) · 42.3 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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { randomUUID } from 'node:crypto';
import { arch as osArch, homedir, release as osRelease } from 'node:os';
import { collapseHomePath } from '@maka/core/diagnostic-log';
import {
assertInteractiveRootOwner,
authenticateInteractiveRootOwner,
type InteractiveRootOwner,
} from '@maka/storage/root-authority';
import { bindStateRootComposition } from '@maka/storage/state-root-composition';
import { removeHostRegistration, writeHostRegistration } from '../control/registration.js';
import {
decodeClientFrame,
encodeProtocolMessage,
HOST_OPERATION_SPECS,
negotiateProtocol,
RUNTIME_HOST_COMPATIBILITY_EPOCH,
RUNTIME_HOST_PROTOCOL_VERSION,
RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION,
requireHostGeneration,
type ClientHello,
type HostOperationErrorCode,
type HostHandshakeResult,
type HostActivitySnapshot,
type HostLifecycleState,
type HostRegistration,
type HostStatusResult,
type RequestFrame,
} from '../protocol/index.js';
import type { RuntimeHostMessageTransport } from '../transport/message-transport.js';
import {
RuntimeHostConnectionSession,
type ConnectionOperationLease,
} from './connection-session.js';
import {
composeOperationHandlers,
createUnavailableDomainOperationHandlers,
type DomainOperationHandlerMap,
type OperationResidency,
type OperationHandlerMap,
} from './operation-dispatcher.js';
import {
issueAccessCredential,
acknowledgeCollaborationTurnRequest,
createCollaborationTurnRequest,
decideCollaborationTurnRequest,
withdrawCollaborationTurnRequest,
finalizeAccessCredential,
prepareCollaborationInvitation,
queryCollaborationTurnRequests,
prepareAccessCredential,
prepareAccessCredentialRotation,
replaceAccessCredential,
revokeAccessCredential,
revokeAccessPrincipal,
revokeAccessCredentialRotation,
revokeCollaborationGrant,
revokeCollaborationPrincipal,
type RuntimeHostAccessAuthority,
} from './access-authority.js';
import type { RuntimeHostConnectionAuthority } from './connection-authority.js';
import type { SessionContinuityService } from './session-continuity-service.js';
import type { ClientCapabilityService } from './client-capability-service.js';
import type { HostChangeFeed } from './host-change-feed.js';
import { runtimeHostLogBuffer } from '../process-diagnostics.js';
import {
type HostCompositionDescriptor,
type RuntimeHostCompositionSource,
} from './host-composition.js';
import {
startLocalRuntimeHostListenerSet,
type RuntimeHostListenerConnection,
type RuntimeHostListenerSet,
type RuntimeHostListenerSetFactory,
} from './listener-set.js';
import { HostResidencyRegistry } from './host-residency-registry.js';
import type { PeerMeshNode } from '../peer-mesh/node.js';
import { createPeerMeshOperationHandlers } from './peer-mesh-authority.js';
import { createHostResourceCollector } from './host-resource-collector.js';
const DEFAULT_IDLE_GRACE_MS = 30_000;
const DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000;
const DEFAULT_SHUTDOWN_GRACE_MS = 10_000;
const SHUTDOWN_HANDSHAKE_GRACE_MS = 1_000;
const SHUTDOWN_OPERATION_GRACE_MS = 1_000;
const INITIAL_CONNECTION_DEADLINE_DEFERRAL_LIMIT = 3;
const HOST_PROTOCOL = {
min: RUNTIME_HOST_PROTOCOL_VERSION,
max: RUNTIME_HOST_PROTOCOL_VERSION,
} as const;
export type RuntimeHostResidency = OperationResidency;
export class RuntimeHostProcessTerminationRequiredError extends Error {
readonly code = 'process_termination_required';
constructor(readonly shutdownGraceMs: number) {
super(`Runtime Host did not shut down within ${shutdownGraceMs} ms`);
this.name = 'RuntimeHostProcessTerminationRequiredError';
}
}
export interface RuntimeHostCompositionContext {
owner: InteractiveRootOwner;
hostEpoch: string;
acquireResidency(label: string): RuntimeHostResidency;
/** Irreversible fail-stop latch; normal residency still uses acquireResidency(). */
retainUntilProcessExit(): void;
requestDrain(): void;
sessionAccessAuthority?: Pick<
RuntimeHostAccessAuthority,
| 'activeSessionGrant'
| 'activeSessionGrantForPrincipal'
| 'approvedTurnAccessRequests'
| 'completeTurnAccessRequest'
| 'subscribeGrantRevocations'
| 'subscribeApprovedTurnAccessRequests'
>;
waitForResidencies?(): Promise<void>;
waitForResidenciesExcept?(excludedLabel: string): Promise<void>;
}
export interface RuntimeHostComposition {
readonly handlers: DomainOperationHandlerMap;
readonly moduleIds?: readonly string[];
readonly continuity?: SessionContinuityService;
readonly clientCapabilities?: ClientCapabilityService;
readonly hostChanges?: HostChangeFeed;
releaseConnection?(connectionId: string): void;
beginDrain(): void;
recover(): Promise<void>;
close(): Promise<void>;
}
export type RuntimeHostCompositionFactory = (
context: RuntimeHostCompositionContext,
) => Promise<RuntimeHostComposition>;
interface RuntimeHostKernelCommonOptions {
owner: InteractiveRootOwner;
handshakeTimeoutMs?: number;
shutdownGraceMs?: number;
composition: RuntimeHostCompositionSource;
listenerSetFactory?: RuntimeHostListenerSetFactory;
accessAuthority?: RuntimeHostAccessAuthority;
peerMesh?: PeerMeshNode;
/** Ephemeral launch gate used until a supervised Candidate durably commits. */
initialClientAdmission?: {
isClientAdmitted(clientInstanceId: string): boolean;
};
}
export type RuntimeHostLifecycleMode = 'ephemeral' | 'service';
export type RuntimeHostKernelOptions = RuntimeHostKernelCommonOptions &
(
| {
lifecycleMode?: 'ephemeral';
initialConnectionTimeoutMs?: number;
idleGraceMs?: number;
generation?: string;
}
| {
lifecycleMode: 'service';
initialConnectionTimeoutMs?: never;
idleGraceMs?: never;
generation?: never;
}
);
type RuntimeHostLifecycle =
| {
readonly kind: 'ephemeral';
readonly initialConnectionTimeoutMs: number;
readonly idleGraceMs: number;
}
| { readonly kind: 'service' };
export class RuntimeHostKernel {
readonly hostEpoch = randomUUID();
readonly closed: Promise<void>;
readonly #options: RuntimeHostKernelOptions;
readonly #createdAt = new Date().toISOString();
readonly #handshakingTransports = new Set<RuntimeHostMessageTransport>();
readonly #acceptedTransports = new Set<RuntimeHostMessageTransport>();
readonly #connectionSessions = new Set<RuntimeHostConnectionSession>();
readonly #transportAuthorities = new Map<
RuntimeHostMessageTransport,
RuntimeHostListenerConnection['authority']
>();
readonly #operationDrainWaiters = new Set<() => void>();
readonly #residencies = new HostResidencyRegistry();
readonly #resourceCollector = createHostResourceCollector();
readonly #lifecycle: RuntimeHostLifecycle;
readonly #handshakeTimeoutMs: number;
readonly #shutdownGraceMs: number;
#listeners: RuntimeHostListenerSet | undefined;
#state: HostLifecycleState = 'starting';
#hasAcceptedConnection = false;
#activeOperations = 0;
#activeCommandOperations = 0;
#retainedUntilProcessExit = false;
#composition: RuntimeHostComposition | undefined;
#compositionDrainBegun = false;
#compositionStartup: Promise<void> | undefined;
#operationHandlers: OperationHandlerMap;
#idleTimer: NodeJS.Timeout | undefined;
#initialConnectionDeadline: NodeJS.Timeout | undefined;
#initialConnectionDeadlineDeferrals = 0;
#shutdownRequested = false;
#shutdownReason: 'retirement' | undefined;
#shutdownTask: Promise<void> | undefined;
#shutdownDeadlineTimer: NodeJS.Timeout | undefined;
#terminationRequired: RuntimeHostProcessTerminationRequiredError | undefined;
#resolveClosed!: () => void;
#rejectClosed!: (error: unknown) => void;
readonly #unsubscribeAccessRevocations: (() => void) | undefined;
readonly #unsubscribeSessionGrantRevocations: (() => void) | undefined;
private constructor(options: RuntimeHostKernelOptions) {
this.#lifecycle = normalizeLifecycle(options);
if (options.generation !== undefined) requireHostGeneration(options.generation);
assertDuration(
options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS,
'handshakeTimeoutMs',
1,
);
assertDuration(options.shutdownGraceMs ?? DEFAULT_SHUTDOWN_GRACE_MS, 'shutdownGraceMs', 1);
this.#handshakeTimeoutMs = options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;
this.#shutdownGraceMs = options.shutdownGraceMs ?? DEFAULT_SHUTDOWN_GRACE_MS;
this.#options = options;
this.#unsubscribeAccessRevocations = options.accessAuthority?.subscribeRevocations(
(credentialId) => this.#revokeCredentialConnections(credentialId),
);
this.#unsubscribeSessionGrantRevocations = options.accessAuthority?.subscribeGrantRevocations(
(grant) => {
if (grant.kind === 'session_observation') {
this.#composition?.hostChanges?.publishSessionCatalogAndCloseScope(
grant.sessionId,
grant.principalId,
);
}
},
);
this.#operationHandlers = this.#createOperationHandlers(
createUnavailableDomainOperationHandlers(),
);
this.closed = new Promise((resolve, reject) => {
this.#resolveClosed = resolve;
this.#rejectClosed = reject;
});
}
static async start(options: RuntimeHostKernelOptions): Promise<RuntimeHostKernel> {
const owner = authenticateInteractiveRootOwner(options.owner);
let host: RuntimeHostKernel | undefined;
try {
host = new RuntimeHostKernel(options);
await host.#start();
return host;
} catch (error) {
if (host) {
if (host.#listeners) {
host.#requestDrain();
try {
await host.closed;
} catch (shutdownError) {
throw new AggregateError(
[error, shutdownError],
'Runtime Host startup failed and shutdown did not complete cleanly',
{ cause: error },
);
}
} else {
await host.#abortStartup();
}
} else {
await options.accessAuthority?.close().catch(() => undefined);
await owner.close();
}
throw error;
}
}
get state(): HostLifecycleState {
return this.#state;
}
get shutdownReason(): 'retirement' | undefined {
return this.#shutdownReason;
}
get endpoint(): string {
if (!this.#listeners) throw new Error('Runtime Host has not started listening');
return this.#listeners.localEndpoint;
}
get rootId(): string {
return this.#options.owner.capability.rootId;
}
get connectionCount(): number {
return this.#acceptedTransports.size;
}
get websocketEndpoints(): readonly string[] {
return this.#listeners?.websocketEndpoints ?? [];
}
get peerListeners(): RuntimeHostListenerSet['peerListeners'] {
return this.#listeners?.peerListeners ?? [];
}
get compositionDescriptor(): HostCompositionDescriptor {
return this.#options.composition.descriptor;
}
close(): Promise<void> {
this.#requestDrain();
return this.closed;
}
#requestDrain(): void {
if (!this.#shutdownRequested) {
this.#shutdownRequested = true;
this.#cancelIdle();
this.#cancelInitialConnectionDeadline();
this.#armShutdownDeadline();
this.#beginCompositionDrain();
}
this.#commitRequestedShutdownIfQuiescent();
}
async #start(): Promise<void> {
await assertInteractiveRootOwner(this.#options.owner);
await bindStateRootComposition(this.#options.owner.lease, this.compositionDescriptor.id);
this.#listeners = await (this.#options.listenerSetFactory ?? startLocalRuntimeHostListenerSet)({
rootId: this.#options.owner.capability.rootId,
hostEpoch: this.hostEpoch,
accept: (connection) => this.#accept(connection),
isReady: () => this.#state === 'ready' && !this.#shutdownRequested,
});
await this.#publishRegistration();
this.#state = 'recovering';
await this.#publishRegistration();
let settleCompositionStartup!: () => void;
this.#compositionStartup = new Promise((resolve) => {
settleCompositionStartup = resolve;
});
// Armed only once #compositionStartup is assigned: a deadline that fired
// earlier would drive #closeResources past an undefined startup await and
// let shutdown complete without closing the composition created below.
this.#armInitialConnectionDeadline();
const compositionStartup = (async () => {
try {
this.#composition = await this.#options.composition.create({
owner: this.#options.owner,
hostEpoch: this.hostEpoch,
acquireResidency: (label) => this.#acquireResidency(label),
retainUntilProcessExit: () => this.#retainUntilProcessExit(),
requestDrain: () => this.#requestDrain(),
...(this.#options.accessAuthority
? { sessionAccessAuthority: this.#options.accessAuthority }
: {}),
waitForResidencies: () => this.#waitForResidencies(),
waitForResidenciesExcept: (excludedLabel) =>
this.#waitForResidenciesExcept(excludedLabel),
});
for (const session of this.#connectionSessions) session.attachGlobalChanges();
if (this.#shutdownRequested) this.#beginCompositionDrain();
this.#operationHandlers = this.#createOperationHandlers(this.#composition.handlers);
await this.#composition.recover();
} finally {
settleCompositionStartup();
}
})();
await Promise.race([compositionStartup, this.closed]);
if (this.#shutdownRequested) {
this.#commitRequestedShutdownIfQuiescent();
return;
}
this.#state = 'ready';
await this.#publishRegistration();
this.#scheduleIdleIfNeeded();
}
#accept(connection: RuntimeHostListenerConnection): void {
const { transport } = connection;
this.#transportAuthorities.set(transport, connection.authority);
this.#handshakingTransports.add(transport);
void this.#serveConnection(connection).finally(() => {
this.#handshakingTransports.delete(transport);
this.#transportAuthorities.delete(transport);
});
}
async #serveConnection(connection: RuntimeHostListenerConnection): Promise<void> {
const { authority, transport } = connection;
let transportReleased = false;
let connectionId: string | undefined;
const releaseTransport = () => {
if (!connectionId || transportReleased) return;
transportReleased = true;
this.#releaseConnection(transport);
};
try {
const frame = decodeClientFrame(await transport.read(this.#handshakeTimeoutMs));
if (!('kind' in frame) || frame.kind !== 'hello') {
throw new Error('First Runtime Host frame must be a hello');
}
const result = await this.#admitHandshake(frame, transport, authority);
connectionId = result.kind === 'accepted' ? result.connectionId : undefined;
await transport.write(encodeProtocolMessage(result));
if (result.kind !== 'accepted') {
transport.closeAfterFlush();
return;
}
const session = new RuntimeHostConnectionSession({
transport,
connection: {
hostEpoch: this.hostEpoch,
connectionId: result.connectionId,
clientInstanceId: frame.clientInstanceId,
authority,
},
resolveHandlers: () => this.#operationHandlers,
resolveContinuity: () => this.#composition?.continuity,
resolveClientCapabilities: () => this.#composition?.clientCapabilities,
resolveHostChanges: () => this.#composition?.hostChanges,
resolveSharedSessionId: () =>
this.#options.accessAuthority?.activeSessionGrantForPrincipal(
authority.principalId,
'session_observation',
)?.sessionId,
beginOperation: (request) => this.#beginOperation(request),
onTeardown: releaseTransport,
});
this.#connectionSessions.add(session);
try {
await session.run();
} finally {
this.#connectionSessions.delete(session);
}
} catch {
transport.abort();
} finally {
try {
if (connectionId) this.#composition?.releaseConnection?.(connectionId);
} finally {
releaseTransport();
}
}
}
async #admitHandshake(
hello: ClientHello,
transport: RuntimeHostMessageTransport,
authority: RuntimeHostConnectionAuthority,
): Promise<HostHandshakeResult> {
const admittedState = await this.#readAdmissionState();
if (!admittedState) {
return {
kind: 'draining',
hostEpoch: this.hostEpoch,
compositionId: this.compositionDescriptor.id,
compositionRevision: this.compositionDescriptor.revision,
};
}
const initialClientAdmission = this.#options.initialClientAdmission;
if (
initialClientAdmission &&
!initialClientAdmission.isClientAdmitted(hello.clientInstanceId)
) {
return {
kind: 'draining',
hostEpoch: this.hostEpoch,
compositionId: this.compositionDescriptor.id,
compositionRevision: this.compositionDescriptor.revision,
};
}
if (authority.clientInstanceId && authority.clientInstanceId !== hello.clientInstanceId) {
throw new Error('Runtime Host access credential belongs to another Client');
}
if (
authority.principalKind === 'remote_owner' &&
authority.clientInstanceId === undefined &&
this.#options.accessAuthority?.hasActiveBoundClientIdentity(
authority.principalId,
hello.clientInstanceId,
)
) {
throw new Error('Runtime Host Client identity is bound to another access credential');
}
const selectedProtocol = negotiateProtocol(
{ min: hello.protocolMin, max: hello.protocolMax },
HOST_PROTOCOL,
);
const generationMismatch =
this.#lifecycle.kind === 'ephemeral' &&
hello.generation !== undefined &&
hello.generation !== this.#options.generation;
if (generationMismatch && hello.takeover?.expectedHostEpoch === this.hostEpoch) {
if (authority.principalKind === 'local_owner' && this.#isTrueIdle()) {
this.#requestDrain();
return {
kind: 'draining',
hostEpoch: this.hostEpoch,
compositionId: this.compositionDescriptor.id,
compositionRevision: this.compositionDescriptor.revision,
};
}
}
if (
selectedProtocol === undefined ||
hello.compatibilityEpoch !== RUNTIME_HOST_COMPATIBILITY_EPOCH ||
hello.compositionId !== this.compositionDescriptor.id ||
generationMismatch
) {
return {
kind: 'incompatible',
hostEpoch: this.hostEpoch,
protocolMin: HOST_PROTOCOL.min,
protocolMax: HOST_PROTOCOL.max,
compatibilityEpoch: RUNTIME_HOST_COMPATIBILITY_EPOCH,
compositionId: this.compositionDescriptor.id,
compositionRevision: this.compositionDescriptor.revision,
...(this.#options.generation === undefined ? {} : { generation: this.#options.generation }),
state: admittedState,
replacement:
this.#lifecycle.kind === 'ephemeral' && this.#isTrueIdle()
? 'wait_for_idle_exit'
: 'blocked_by_residency',
...(generationMismatch && authority.principalKind === 'local_owner'
? { activity: this.#activitySnapshot() }
: {}),
};
}
this.#hasAcceptedConnection = true;
this.#cancelInitialConnectionDeadline();
this.#acceptedTransports.add(transport);
this.#handshakingTransports.delete(transport);
this.#cancelIdle();
return {
kind: 'accepted',
rootId: this.#options.owner.capability.rootId,
hostEpoch: this.hostEpoch,
connectionId: randomUUID(),
selectedProtocol,
compatibilityEpoch: RUNTIME_HOST_COMPATIBILITY_EPOCH,
compositionId: this.compositionDescriptor.id,
compositionRevision: this.compositionDescriptor.revision,
state: admittedState,
};
}
#releaseConnection(transport: RuntimeHostMessageTransport): void {
if (!this.#acceptedTransports.delete(transport)) {
throw new Error('Runtime Host connection residency underflow');
}
this.#settleLifecycleAfterWork();
}
#revokeCredentialConnections(credentialId: string): void {
for (const [transport, authority] of this.#transportAuthorities) {
if (authority.credentialId === credentialId) transport.abort();
}
}
async #beginOperation(
frame: RequestFrame,
): Promise<ConnectionOperationLease | HostOperationErrorCode> {
if (!(await this.#readAdmissionState())) return 'host_draining';
if (
HOST_OPERATION_SPECS[frame.operation].availability !== 'bootstrap' &&
this.#state !== 'ready'
) {
return 'host_not_ready';
}
this.#activeOperations += 1;
const command = HOST_OPERATION_SPECS[frame.operation].mode === 'command';
if (command) this.#activeCommandOperations += 1;
this.#cancelIdle();
let sealed = false;
let finished = false;
const seal = () => {
if (sealed) return;
sealed = true;
if (command) {
if (this.#activeCommandOperations === 0) {
throw new Error('Runtime Host command operation residency underflow');
}
this.#activeCommandOperations -= 1;
this.#settleLifecycleAfterWork();
}
};
return {
acquireResidency: () => {
if (sealed || finished) throw new Error('Runtime Host operation lease has ended');
return this.#acquireResidency(`operation.${frame.operation}`);
},
seal,
finish: () => {
if (finished) throw new Error('Runtime Host operation lease already ended');
finished = true;
seal();
this.#finishOperation();
},
};
}
async #hasLiveOwnerOrDrain(): Promise<boolean> {
if (this.#isDraining()) return false;
try {
await assertInteractiveRootOwner(this.#options.owner);
} catch {
void this.#commitShutdown().catch(() => undefined);
return false;
}
return !this.#isDraining();
}
async #readAdmissionState(): Promise<Exclude<HostLifecycleState, 'draining'> | undefined> {
if (this.#shutdownRequested || this.#isDraining()) return undefined;
if (!(await this.#hasLiveOwnerOrDrain())) return undefined;
const state = this.#state;
return this.#shutdownRequested || state === 'draining' ? undefined : state;
}
#isDraining(): boolean {
return this.#state === 'draining';
}
#finishOperation(): void {
if (this.#activeOperations === 0) throw new Error('Runtime Host operation residency underflow');
this.#activeOperations -= 1;
if (this.#activeOperations === 0) {
for (const resolve of this.#operationDrainWaiters) resolve();
this.#operationDrainWaiters.clear();
}
this.#settleLifecycleAfterWork();
}
#acquireResidency(label: string): RuntimeHostResidency {
const residency = this.#residencies.acquire(label);
this.#cancelIdle();
return {
release: () => {
residency.release();
this.#settleLifecycleAfterWork();
},
};
}
#retainUntilProcessExit(): void {
if (this.#retainedUntilProcessExit) return;
this.#retainedUntilProcessExit = true;
this.#residencies.acquire('process-retention');
this.#cancelIdle();
}
#createOperationHandlers(domainHandlers: DomainOperationHandlerMap): OperationHandlerMap {
return composeOperationHandlers(
{
'host.status': async () => ({
ok: true,
result: this.#statusSnapshot(),
}),
'host.diagnostics.query': async () => ({
ok: true,
result: {
...this.#statusSnapshot(),
compositionModules: this.#composition?.moduleIds ?? [],
residencies: this.#residencies.snapshot(),
protocolVersion: RUNTIME_HOST_PROTOCOL_VERSION,
compatibilityEpoch: RUNTIME_HOST_COMPATIBILITY_EPOCH,
pid: process.pid,
processUptimeSeconds: Math.max(0, Math.floor(process.uptime())),
nodeVersion: process.versions.node,
platform: process.platform,
arch: osArch(),
osRelease: osRelease(),
logs: runtimeHostLogBuffer
.snapshot()
.map((entry) => collapseHomePath(entry, homedir(), process.platform)),
},
}),
'host.resources.query': async () => ({
ok: true,
result: await this.#resourceCollector.snapshot(this.hostEpoch),
}),
'host.upgrade.prepare': async (input) => {
if (input.expectedHostEpoch !== this.hostEpoch) {
return {
ok: false,
error: {
code: 'operation_conflict',
message: 'Runtime Host identity changed before upgrade drain',
},
};
}
if (!input.allowInterruptActiveTasks && this.#hasUpgradeBlockingActivity()) {
return { ok: true, result: { kind: 'active_tasks' } };
}
this.#shutdownReason = 'retirement';
this.#requestDrain();
return { ok: true, result: { kind: 'prepared', pid: process.pid } };
},
'access.credential.issue': async (input) =>
this.#settleAccessCredentialMutation(
issueAccessCredential(this.#options.accessAuthority, input),
),
'access.credential.replace': async (input) =>
this.#settleAccessCredentialMutation(
replaceAccessCredential(this.#options.accessAuthority, input),
),
'access.credential.prepare': async (input) =>
this.#settleAccessCredentialMutation(
prepareAccessCredential(this.#options.accessAuthority, input),
),
'access.credential.revoke': async (input) =>
this.#settleAccessCredentialMutation(
revokeAccessCredential(this.#options.accessAuthority, input),
),
'access.principal.revoke': async (input) =>
this.#settleAccessCredentialMutation(
revokeAccessPrincipal(this.#options.accessAuthority, input),
),
'access.credential.rotation.prepare': async (input) =>
this.#settleAccessCredentialMutation(
prepareAccessCredentialRotation(this.#options.accessAuthority, input),
),
'access.credential.rotation.revoke': async (input) =>
this.#settleAccessCredentialMutation(
revokeAccessCredentialRotation(this.#options.accessAuthority, input),
),
'access.credential.finalize': async (_input, context) =>
this.#settleAccessCredentialMutation(
finalizeAccessCredential(
this.#options.accessAuthority,
context.credentialId,
context.clientInstanceId,
context.credentialClientInstanceId,
),
),
'collaboration.invitation.prepare': async (input) =>
this.#settleAccessCredentialMutation(
prepareCollaborationInvitation(this.#options.accessAuthority, this.rootId, input),
),
'collaboration.access.query': async (input) =>
this.#options.accessAuthority
? {
ok: true,
result: this.#options.accessAuthority.queryCollaborationAccess(input),
}
: {
ok: false,
error: {
code: 'operation_unavailable',
message: 'Runtime Host collaboration authority is unavailable',
},
},
'collaboration.grant.revoke': async (input) =>
this.#settleAccessCredentialMutation(
revokeCollaborationGrant(this.#options.accessAuthority, input),
),
'collaboration.principal.revoke': async (input) =>
this.#settleAccessCredentialMutation(
revokeCollaborationPrincipal(this.#options.accessAuthority, input.principalId),
),
'collaboration.turn-request.create': async (input, context) =>
this.#settleAccessCredentialMutation(
createCollaborationTurnRequest(this.#options.accessAuthority, context.principal, input),
),
'collaboration.turn-request.query': async (input, context) =>
queryCollaborationTurnRequests(
this.#options.accessAuthority,
{
principalId: context.principal,
principalKind: context.principalKind,
},
input,
),
'collaboration.turn-request.acknowledge': async (input, context) =>
this.#settleAccessCredentialMutation(
acknowledgeCollaborationTurnRequest(
this.#options.accessAuthority,
context.principal,
input,
),
),
'collaboration.turn-request.withdraw': async (input, context) =>
this.#settleAccessCredentialMutation(
withdrawCollaborationTurnRequest(
this.#options.accessAuthority,
context.principal,
input,
),
),
'collaboration.turn-request.decide': async (input, context) =>
this.#settleAccessCredentialMutation(
decideCollaborationTurnRequest(this.#options.accessAuthority, context.principal, input),
),
},
createPeerMeshOperationHandlers(this.#options.peerMesh, {
requestDrain: () => this.#requestDrain(),
}),
domainHandlers,
);
}
async #settleAccessCredentialMutation<
T extends {
readonly ok: boolean;
readonly error?: { readonly code: string };
},
>(operation: Promise<T>): Promise<T> {
const outcome = await operation;
if (!outcome.ok && outcome.error?.code === 'commit_outcome_unknown') {
this.#requestDrain();
}
return outcome;
}
#statusSnapshot(): HostStatusResult {
const peer = this.peerListeners[0];
return {
hostEpoch: this.hostEpoch,
compositionId: this.compositionDescriptor.id,
compositionRevision: this.compositionDescriptor.revision,
state: this.#state,
connections: this.#acceptedTransports.size,
activeOperations: this.#activeOperations,
activeResidencies: this.#residencies.activeCount,
...(peer
? {
peerEndpoint: peer.reachability,
}
: {}),
};
}
#activitySnapshot(): HostActivitySnapshot {
return {
connections: this.#acceptedTransports.size,
activeOperations: this.#activeOperations,
processUptimeSeconds: Math.max(0, Math.floor(process.uptime())),
residencies: this.#residencies.snapshot(),
};
}
#hasUpgradeBlockingActivity(): boolean {
// The request's own accepted transport is expected. Any other live
// connection arrived after discovery or remained attached and therefore
// requires explicit interruption authority before retirement.
if (this.#acceptedTransports.size > 1) return true;
if (this.#activeCommandOperations > 1) return true;
return this.#residencies.snapshot().some(({ label }) => label !== 'process-retention');
}
#beginCompositionDrain(): void {
if (!this.#composition || this.#compositionDrainBegun) return;
this.#compositionDrainBegun = true;
this.#composition.beginDrain();
}
#waitForOperations(): Promise<void> {
if (this.#activeOperations === 0) return Promise.resolve();
return new Promise((resolve) => this.#operationDrainWaiters.add(resolve));
}
#waitForResidencies(): Promise<void> {
return this.#residencies.waitForEmpty();
}
#waitForResidenciesExcept(excludedLabel: string): Promise<void> {
return this.#residencies.waitForEmptyExcept(excludedLabel);
}
#scheduleIdleIfNeeded(): void {
if (this.#lifecycle.kind === 'service') return;
if (this.#shutdownRequested) return;
// One timer authority per lifecycle phase: until the first connection is
// accepted, only #initialConnectionDeadline governs (it defers under an
// in-flight handshake, which #isTrueIdle() cannot see); afterwards the
// idle timer owns the idleGraceMs exit.
if (!this.#hasAcceptedConnection) return;
if (!this.#isTrueIdle() || this.#idleTimer) return;
this.#idleTimer = setTimeout(() => {
this.#idleTimer = undefined;
if (!this.#isTrueIdle()) return;
void this.#commitShutdown().catch(() => undefined);
}, this.#lifecycle.idleGraceMs);
}
#isTrueIdle(): boolean {
return (
this.#state === 'ready' &&
this.#acceptedTransports.size === 0 &&
this.#activeOperations === 0 &&
this.#residencies.activeCount === 0
);
}
// The idle timer only arms once the kernel reaches true idle, so a
// composition startup that never settles or a residency held from boot
// would keep an ephemeral candidate that no Client ever reached alive
// forever. This deadline bounds the wait for the first accepted connection
// independently of composition progress. A handshake in flight defers it by
// the handshake budget instead of draining under a connecting Client, but
// only a bounded number of times: connections enter the handshaking set
// before their first hello byte, so a reconnect loop that never completes a
// handshake must not push the deadline out indefinitely.
#armInitialConnectionDeadline(delayMs?: number): void {
if (this.#lifecycle.kind !== 'ephemeral') return;
if (this.#hasAcceptedConnection || this.#shutdownRequested) return;
this.#initialConnectionDeadline = setTimeout(() => {
this.#initialConnectionDeadline = undefined;
if (this.#hasAcceptedConnection || this.#shutdownRequested) return;
if (
this.#handshakingTransports.size > 0 &&
this.#initialConnectionDeadlineDeferrals < INITIAL_CONNECTION_DEADLINE_DEFERRAL_LIMIT
) {
this.#initialConnectionDeadlineDeferrals += 1;
this.#armInitialConnectionDeadline(this.#handshakeTimeoutMs);
return;
}
this.#requestDrain();
}, delayMs ?? this.#lifecycle.initialConnectionTimeoutMs);
}
#cancelInitialConnectionDeadline(): void {
if (!this.#initialConnectionDeadline) return;
clearTimeout(this.#initialConnectionDeadline);
this.#initialConnectionDeadline = undefined;
}
#cancelIdle(): void {
if (!this.#idleTimer) return;
clearTimeout(this.#idleTimer);
this.#idleTimer = undefined;
}
#settleLifecycleAfterWork(): void {
if (this.#shutdownRequested) {
this.#commitRequestedShutdownIfQuiescent();
return;
}
this.#scheduleIdleIfNeeded();
}
#commitRequestedShutdownIfQuiescent(): void {
if (this.#activeCommandOperations !== 0) return;
void this.#commitShutdown().catch(() => undefined);
}
#commitShutdown(): Promise<void> {
if (this.#terminationRequired) return this.closed;
if (!this.#shutdownTask) {
if (!this.#shutdownRequested) {
this.#shutdownRequested = true;
this.#armShutdownDeadline();
this.#beginCompositionDrain();
}
this.#state = 'draining';
this.#cancelIdle();
this.#cancelInitialConnectionDeadline();
this.#shutdownTask = this.#closeResources();
void this.#shutdownTask.then(
() => {
this.#clearShutdownDeadline();
if (!this.#terminationRequired) this.#resolveClosed();
},
(error: unknown) => {
this.#clearShutdownDeadline();
if (!this.#terminationRequired) this.#rejectClosed(error);
},
);
}
return this.closed;
}
#armShutdownDeadline(): void {