Repository navigation
Expand file tree
/
Copy pathplatform-runtime-gateway.ts
More file actions
377 lines (360 loc) · 13.3 KB
/
Copy pathplatform-runtime-gateway.ts
File metadata and controls
377 lines (360 loc) · 13.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
import type { ProviderDeviceRuntime } from '@agent-device/contracts/device';
import {
type DeviceBinding,
type DeviceBindingRequest,
type DeviceRuntimeGateway,
type RuntimeOwnerRef,
providerRuntimeOwner,
runtimeOwnerKey,
sameRuntimeOwner,
} from '@agent-device/contracts/platform-runtime';
import type {
PlatformRuntimeHost,
PlatformRuntimeModule,
PlatformRuntimeOperations,
PlatformRuntimeOwner,
PlatformRuntimeProviderModule,
} from '@agent-device/contracts/platform-runtime-operations';
import {
createFullyUnavailablePlatformRuntimeFacts,
createUnavailablePlatformRuntimeBinding,
createUnavailablePlatformRuntimeFacts,
} from '@agent-device/contracts/platform-runtime-unavailable';
import { runStartupRecoveryFence } from '@agent-device/contracts/startup-recovery-fence';
import {
deviceIdentity,
deviceShape,
sameDeviceIdentity,
sameDeviceShape,
type DeviceInfo,
type Platform,
} from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
export type PlatformRuntimeProviderRegistration = Readonly<{
runtime: ProviderDeviceRuntime;
module: PlatformRuntimeProviderModule;
}>;
export function createComposedPlatformRuntimeGateway(options: {
modules: ReadonlyMap<Platform, PlatformRuntimeModule>;
loadHost: () => Promise<PlatformRuntimeHost>;
providerRuntimes?: readonly ProviderDeviceRuntime[];
providerModules?: readonly PlatformRuntimeProviderRegistration[];
}): DeviceRuntimeGateway<PlatformRuntimeOperations> {
const providersByOwner = new Map<string, PlatformRuntimeProviderRegistration>();
const modulesByRuntime = new Map<ProviderDeviceRuntime, PlatformRuntimeProviderModule>();
for (const registration of options.providerModules ?? []) {
const { runtime, module } = registration;
const key = runtimeOwnerKey(module.owner);
if (module.owner.provider !== runtime.provider) {
throw runtimeContractError(`Provider platform runtime metadata is invalid: ${key}`);
}
if (providersByOwner.has(key)) {
throw runtimeContractError(`Duplicate platform runtime owner: ${key}`);
}
if (modulesByRuntime.has(runtime)) {
throw runtimeContractError(`Duplicate platform module registration for ${runtime.provider}`);
}
providersByOwner.set(key, registration);
modulesByRuntime.set(runtime, module);
}
const localLoads = new Map<Platform, Promise<PlatformRuntimeOwner>>();
const providerLoads = new Map<PlatformRuntimeProviderModule, Promise<PlatformRuntimeOwner>>();
const loadedOwners = new Map<string, PlatformRuntimeOwner>();
let closing: Promise<void> | undefined;
const ensureOpen = () => {
if (closing) {
throw new AppError('COMMAND_FAILED', 'Platform runtime gateway is shut down', {
reason: 'runtime-gateway-shut-down',
});
}
};
let hostLoad: Promise<PlatformRuntimeHost> | undefined;
const loadHost = async () => {
hostLoad ??= options.loadHost();
try {
return await hostLoad;
} catch (error) {
hostLoad = undefined;
throw error;
}
};
// Which durable resources exist is the host's composition problem; the gateway only owns the
// once-per-process shape of each phase and keeps the host load lazy.
let lifecycleDetach: Promise<readonly string[]> | undefined;
let lifecycleFinalize: Promise<readonly string[]> | undefined;
const applicationLifecycle = Object.freeze({
recoverStartupResources: async (input: Readonly<{ stateDir: string }>) => {
await runStartupRecoveryFence(input.stateDir, async () => {
await (await loadHost()).applicationResources.recoverStartupResources(input);
});
},
detachForDaemonShutdown: async () => {
lifecycleDetach ??= loadHost().then(
async (host) => await host.applicationResources.detachForDaemonShutdown(),
);
return await lifecycleDetach;
},
finalizeDaemonShutdown: async () => {
lifecycleFinalize ??= loadHost().then(
async (host) => await host.applicationResources.finalizeDaemonShutdown(),
);
return await lifecycleFinalize;
},
});
const registerOwner = (owner: PlatformRuntimeOwner) => {
const key = runtimeOwnerKey(owner.owner);
const existing = loadedOwners.get(key);
if (existing && existing !== owner) {
throw runtimeContractError(`Duplicate platform runtime owner: ${key}`);
}
loadedOwners.set(key, owner);
return owner;
};
const loadLocal = async (family: Platform) => {
ensureOpen();
const existing = localLoads.get(family);
if (existing) return await existing;
const module = options.modules.get(family);
if (!module) throw runtimeContractError(`Missing platform runtime module for ${family}`);
if (module.family !== family) {
throw runtimeContractError(
`Platform runtime module registered for ${family} declares ${module.family}`,
);
}
const pending = loadHost().then(async (host) => {
const owner = await module.loadRuntime(host);
if (owner.owner.kind !== 'local-family' || owner.owner.family !== family) {
throw runtimeContractError(
`Platform runtime module for ${family} returned a different local owner`,
);
}
return registerOwner(owner);
});
localLoads.set(family, pending);
try {
return await pending;
} catch (error) {
if (localLoads.get(family) === pending) localLoads.delete(family);
throw error;
}
};
const loadProvider = async (module: PlatformRuntimeProviderModule) => {
ensureOpen();
const existing = providerLoads.get(module);
if (existing) return await existing;
const pending = loadHost().then(async (host) => {
const owner = await module.loadRuntime(host);
if (!sameRuntimeOwner(owner.owner, module.owner)) {
throw runtimeContractError(
'Provider platform runtime returned a different advertised owner',
);
}
return registerOwner(owner);
});
providerLoads.set(module, pending);
try {
return await pending;
} catch (error) {
if (providerLoads.get(module) === pending) providerLoads.delete(module);
throw error;
}
};
return Object.freeze({
applicationLifecycle,
inspectFacts: async (device) => {
ensureOpen();
const provider = selectOrdinaryProvider(options.providerRuntimes, device);
let owner: PlatformRuntimeOwner;
if (provider) {
const module = modulesByRuntime.get(provider);
if (!module) return unavailableProviderFacts(provider, device);
owner = await loadProvider(module);
} else {
owner = await loadLocal(device.platform);
}
ensureOpen();
return await inspectAndValidate(owner, device);
},
bind: async (request) => {
ensureOpen();
let owner: PlatformRuntimeOwner;
if (request.intent.kind === 'exact-owner') {
owner = await selectExactOwner(
request.intent.owner,
providersByOwner,
loadProvider,
loadLocal,
);
} else {
const provider = selectOrdinaryProvider(options.providerRuntimes, request.device);
if (provider) {
const module = modulesByRuntime.get(provider);
if (!module) return unavailableProviderBinding(provider, request.device);
owner = await loadProvider(module);
} else {
owner = await loadLocal(request.device.platform);
}
}
ensureOpen();
return await bindAndValidate(owner, request);
},
shutdown: () =>
(closing ??= Promise.resolve().then(async () => {
const outcomes = await Promise.all(
[...localLoads.values(), ...providerLoads.values()].map((load) =>
load.then(
async (owner) => {
try {
await owner.shutdown();
} catch (error) {
return { owner: owner.owner, error };
}
},
() => undefined,
),
),
);
loadedOwners.clear();
localLoads.clear();
providerLoads.clear();
const [first, ...rest] = outcomes.filter((outcome) => outcome !== undefined);
if (first) {
const { createPlatformRuntimeShutdownError } =
await import('@agent-device/contracts/platform-runtime-shutdown');
throw createPlatformRuntimeShutdownError([first, ...rest]);
}
})),
});
}
function selectOrdinaryProvider(
runtimes: readonly ProviderDeviceRuntime[] | undefined,
device: DeviceInfo,
): ProviderDeviceRuntime | undefined {
const matching = (runtimes ?? []).filter((runtime) => runtime.ownsDevice(device));
if (matching.length > 1) {
throw runtimeContractError('Multiple provider runtimes claim the selected device');
}
return matching[0];
}
async function inspectAndValidate(owner: PlatformRuntimeOwner, device: DeviceInfo) {
const facts = await owner.inspectFacts(device);
if (!factsMatchDeviceOwner(device, owner.owner, facts)) {
throw runtimeContractError('Platform runtime facts do not match the selected device and owner');
}
return facts;
}
async function bindAndValidate(
owner: PlatformRuntimeOwner,
request: DeviceBindingRequest,
): Promise<DeviceBinding<PlatformRuntimeOperations>> {
const binding = await owner.bind(request);
const failure = bindingContractFailure(owner, binding, request);
if (!failure) return binding;
let cleanupError: string | undefined;
try {
await binding[Symbol.asyncDispose]();
} catch (error) {
cleanupError = error instanceof Error ? error.message : String(error);
}
throw runtimeContractError(failure, cleanupError);
}
function bindingContractFailure(
selected: PlatformRuntimeOwner,
binding: DeviceBinding<PlatformRuntimeOperations>,
request: DeviceBindingRequest,
): string | undefined {
if (!sameRuntimeOwner(binding.owner, selected.owner)) {
return 'Platform binding returned a different owner than the selected runtime';
}
if (!matchesRequestedOwner(binding.owner, request)) {
return 'Exact platform binding returned a different persisted owner';
}
if (!sameDeviceIdentity(deviceIdentity(binding.device), deviceIdentity(request.device))) {
return 'Platform binding returned a different device identity';
}
if (!factsMatchBindingIdentity(binding)) {
return 'Platform binding facts do not match its device and owner';
}
return undefined;
}
function matchesRequestedOwner(owner: RuntimeOwnerRef, request: DeviceBindingRequest): boolean {
return request.intent.kind !== 'exact-owner' || sameRuntimeOwner(owner, request.intent.owner);
}
function factsMatchBindingIdentity(binding: DeviceBinding<PlatformRuntimeOperations>): boolean {
return factsMatchDeviceOwner(binding.device, binding.owner, binding.facts);
}
function factsMatchDeviceOwner(
device: DeviceInfo,
owner: RuntimeOwnerRef,
facts: DeviceBinding<PlatformRuntimeOperations>['facts'],
): boolean {
return (
sameDeviceShape(facts.device, deviceShape(device)) &&
providerModeMatchesOwner(facts.device.providerMode, owner)
);
}
function providerModeMatchesOwner(
mode: DeviceBinding<PlatformRuntimeOperations>['facts']['device']['providerMode'],
owner: RuntimeOwnerRef,
): boolean {
switch (owner.kind) {
case 'local-family':
return mode === 'local' || mode === 'transport-composed';
case 'provider-runtime':
return mode === 'provider-runtime';
}
}
async function selectExactOwner(
ref: RuntimeOwnerRef,
providersByOwner: ReadonlyMap<string, PlatformRuntimeProviderRegistration>,
loadProvider: (module: PlatformRuntimeProviderModule) => Promise<PlatformRuntimeOwner>,
loadLocal: (family: Platform) => Promise<PlatformRuntimeOwner>,
): Promise<PlatformRuntimeOwner> {
switch (ref.kind) {
case 'local-family': {
const owner = await loadLocal(ref.family);
if (sameRuntimeOwner(owner.owner, ref)) return owner;
throw ownerUnavailable(ref);
}
case 'provider-runtime': {
const registration = providersByOwner.get(runtimeOwnerKey(ref));
if (registration) return await loadProvider(registration.module);
throw ownerUnavailable(ref);
}
}
}
/** Missing provider modules must fail closed per operation, never via a shared lifecycle bucket. */
const UNSUPPORTED_PROVIDER_MODE = Object.freeze({
available: false,
reason: 'unsupported-provider-mode',
} as const);
function unavailableProviderBinding(
runtime: ProviderDeviceRuntime,
device: DeviceInfo,
): DeviceBinding<PlatformRuntimeOperations> {
const owner = providerRuntimeOwner(runtime.provider, 'default');
return createUnavailablePlatformRuntimeBinding(
device,
owner,
createFullyUnavailablePlatformRuntimeFacts(UNSUPPORTED_PROVIDER_MODE),
);
}
function unavailableProviderFacts(runtime: ProviderDeviceRuntime, device: DeviceInfo) {
return createUnavailablePlatformRuntimeFacts(
device,
providerRuntimeOwner(runtime.provider, 'default'),
createFullyUnavailablePlatformRuntimeFacts(UNSUPPORTED_PROVIDER_MODE),
);
}
function ownerUnavailable(owner: RuntimeOwnerRef): AppError {
return new AppError('UNSUPPORTED_OPERATION', 'The exact platform runtime owner is unavailable.', {
reason: 'owner-unavailable',
owner: runtimeOwnerKey(owner),
});
}
function runtimeContractError(message: string, cleanupError?: string): AppError {
return new AppError('COMMAND_FAILED', message, {
reason: 'runtime-contract-invalid',
...(cleanupError ? { cleanupError } : {}),
});
}