Repository navigation
Expand file tree
/
Copy pathlease-registry.ts
More file actions
630 lines (588 loc) · 22.8 KB
/
Copy pathlease-registry.ts
File metadata and controls
630 lines (588 loc) · 22.8 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
import type { DeviceLease } from '@agent-device/contracts/device';
import type { HumanControlHold, HumanControlHoldScope } from '@agent-device/contracts/client';
import type { LeaseBackend } from '@agent-device/kernel/contracts';
import { AppError } from '@agent-device/kernel/errors';
import {
ProviderSessionOwnershipRegistry,
type ProviderSessionOwnership,
} from './provider-session-ownership.ts';
import {
type AdmissionRequest,
type AllocateLeaseRequest,
type HeartbeatLeaseRequest,
type ReleaseLeaseRequest,
type LeaseRegistryOptions,
type NormalizedAllocateLeaseRequest,
createLeaseTtlResolver,
normalizeAllocateLeaseRequest,
createDeviceLease,
deviceLeaseBusyError,
hasAllocatedScope,
normalizeLeaseId,
normalizeRequiredLeaseId,
normalizeLeaseAdmissionRequest,
assertLeaseOwnerScope,
assertLeaseScopeMatch,
leaseDeviceBindingKey,
leaseOwnTtlMs,
leaseRunBindingKey,
} from './lease-registry-scope.ts';
import { DeviceMutationDrain } from './device/device-mutation-drain.ts';
import {
type LeaseWorkPass,
type LeaseWorkWanted,
LeaseInFlightWorkRegistry,
} from './lease-in-flight-work.ts';
import {
type HumanControlAuthority,
type HumanControlHoldInput,
normalizeHumanControlHoldId,
parseHumanControlHoldInput,
cloneHumanControlHold,
humanControlActiveError,
} from './human-control-contract.ts';
type OwnedHumanControlHold = { hold: HumanControlHold; ownerLeaseId?: string };
export class LeaseRegistry {
private readonly holdsByDevice = new Map<string, Map<string, OwnedHumanControlHold>>();
private readonly mutations = new DeviceMutationDrain();
private readonly inFlightWork = new LeaseInFlightWorkRegistry();
private readonly leases = new Map<string, DeviceLease>();
private readonly runBindings = new Map<string, string>();
private readonly deviceBindings = new Map<string, string>();
/** The inactivity window the host chose for each lease it allocated; a tenant cannot exceed it. */
private readonly hostTtlMsByLeaseId = new Map<string, number>();
private readonly macOsAppTenantIds = new Set<string>();
private readonly maxActiveSimulatorLeases: number;
private readonly resolveLeaseTtlMs: ReturnType<typeof createLeaseTtlResolver>;
private readonly now: () => number;
private readonly onLeaseExpired?: (lease: DeviceLease) => void;
private readonly providerSessionOwnership: ProviderSessionOwnershipRegistry;
constructor(options: LeaseRegistryOptions = {}) {
this.maxActiveSimulatorLeases = Number.isInteger(options.maxActiveSimulatorLeases)
? Math.max(0, Number(options.maxActiveSimulatorLeases))
: 0;
this.resolveLeaseTtlMs = createLeaseTtlResolver(options);
this.now = options.now ?? (() => Date.now());
this.onLeaseExpired = options.onLeaseExpired;
this.providerSessionOwnership = new ProviderSessionOwnershipRegistry({
now: this.now,
retentionMs: options.providerSessionRetentionMs,
});
}
allocateLease(request: AllocateLeaseRequest): DeviceLease {
const chosenLeaseId =
request.leaseId === undefined ? undefined : normalizeRequiredLeaseId(request.leaseId);
const normalized = normalizeAllocateLeaseRequest(request);
this.cleanupExpiredLeases();
const leaseTtlMs = this.resolveLeaseTtlMs(normalized.ttlMs);
this.assertHumanControlAdmission(normalized);
const existingLease = this.refreshExistingRunBinding(normalized, leaseTtlMs);
if (existingLease) return existingLease;
if (chosenLeaseId && this.leases.has(chosenLeaseId)) {
throw new AppError('INVALID_ARGS', 'Lease id already names an active lease.', {
reason: 'LEASE_ID_IN_USE',
});
}
this.assertDeviceAvailable(normalized);
this.enforceCapacity(normalized.backend);
const lease = {
...createDeviceLease(normalized, leaseTtlMs, this.now()),
...(chosenLeaseId ? { leaseId: chosenLeaseId } : {}),
};
this.leases.set(lease.leaseId, lease);
this.bindLease(lease);
return { ...lease };
}
/**
* Host administration: allocates the lease `leaseId` with exactly this scope, or renews it when
* it already holds this scope. A tenant never reaches this; it is how a host pins the device a
* client may use, so an existing lease with another scope is refused rather than rewritten.
*/
putHostLease(leaseId: string, request: AllocateLeaseRequest): DeviceLease {
const id = normalizeRequiredLeaseId(leaseId);
const normalized = normalizeAllocateLeaseRequest(request);
this.cleanupExpiredLeases();
const leaseTtlMs = this.resolveLeaseTtlMs(normalized.ttlMs);
const existing = this.leases.get(id);
if (existing) {
if (!hasAllocatedScope(existing, normalized)) {
throw new AppError('INVALID_ARGS', 'Lease id already names a lease with another scope.', {
reason: 'LEASE_SCOPE_MISMATCH',
});
}
this.hostTtlMsByLeaseId.set(id, leaseTtlMs);
return this.refreshLease(existing, leaseTtlMs);
}
this.assertHumanControlAdmission(normalized);
this.assertDeviceAvailable(normalized);
if (normalized.backend === 'macos-app') this.macOsAppTenantIds.add(normalized.tenantId);
if (this.runBindings.has(leaseRunBindingKey(normalized))) {
throw new AppError('DEVICE_IN_USE', 'This tenant run already holds a lease for the device.', {
reason: 'DEVICE_LEASE_BUSY',
});
}
this.enforceCapacity(normalized.backend);
const lease = { ...createDeviceLease(normalized, leaseTtlMs, this.now()), leaseId: id };
this.leases.set(lease.leaseId, lease);
this.hostTtlMsByLeaseId.set(id, leaseTtlMs);
this.bindLease(lease);
return { ...lease };
}
private refreshExistingRunBinding(
request: NormalizedAllocateLeaseRequest,
leaseTtlMs: number,
): DeviceLease | undefined {
const bindingKey = leaseRunBindingKey(request);
const existingId = this.runBindings.get(bindingKey);
if (!existingId) return undefined;
const existingLease = this.leases.get(existingId);
if (!existingLease) {
this.runBindings.delete(bindingKey);
return undefined;
}
if (existingLease.clientId === request.clientId) {
return this.refreshLease(
request.retainOnClose ? { ...existingLease, retainOnClose: true } : existingLease,
leaseTtlMs,
);
}
if (existingLease.deviceKey) {
throw deviceLeaseBusyError(existingLease);
}
assertLeaseScopeMatch(existingLease, request);
return this.refreshLease(existingLease, leaseTtlMs);
}
/**
* Extends a lease's life. A request naming a `ttlMs` asks for that inactivity window; one naming
* none renews for the window the lease already carries, the way protected work renews for its
* existing one (ADR 0007). Resolving an absent `ttlMs` to the registry default instead would
* shorten a lease every time a caller heartbeats without repeating its allocation TTL — which is
* what an admitted request does, and what expired the lease paying for a device mid-upload (#2946).
*/
heartbeatLease(request: HeartbeatLeaseRequest): DeviceLease {
const leaseId = normalizeRequiredLeaseId(request.leaseId);
this.cleanupExpiredLeases();
const lease = this.getActiveLease(leaseId);
assertLeaseOwnerScope(lease, request);
assertLeaseScopeMatch(lease, request);
const requestedTtlMs =
request.ttlMs === undefined ? leaseOwnTtlMs(lease) : this.resolveLeaseTtlMs(request.ttlMs);
const hostTtlMs = this.hostTtlMsByLeaseId.get(leaseId);
return this.refreshLease(
lease,
hostTtlMs === undefined ? requestedTtlMs : Math.min(requestedTtlMs, hostTtlMs),
);
}
/**
* Protects a lease while an admitted request works on its device. A lease renews
* when a request is admitted and never again while that request runs, so without
* this the slowest command in a session expired the lease that was paying for
* the device and tore the session down under the client still waiting for it
* (#2509). Releasing a still-wanted pass renews the lease the way releasing a
* human-control hold does; a pass whose request was cancelled protects nothing.
* `wanted` is how the caller reports that its client is still waiting.
*/
retainLeaseWork(lease: Pick<DeviceLease, 'leaseId'>, wanted: LeaseWorkWanted): LeaseWorkPass {
const pass = this.inFlightWork.retain(lease.leaseId, wanted);
return {
leaseId: pass.leaseId,
release: () => {
const renewed = pass.release();
if (renewed) this.refreshProtectedLease(lease.leaseId, this.now());
return renewed;
},
};
}
releaseLease(request: ReleaseLeaseRequest): { released: boolean; lease?: DeviceLease } {
const lease = this.getLease(request);
if (!lease) {
return { released: false };
}
this.leases.delete(lease.leaseId);
this.unbindLease(lease);
this.inFlightWork.forget(lease.leaseId);
return { released: true, lease };
}
/**
* Reads a releasable lease without committing its removal. Callers with an
* external provider use this to release the remote resource first, so a
* transient provider failure leaves the local lease available for retry.
*/
getLease(request: ReleaseLeaseRequest): DeviceLease | undefined {
const leaseId = normalizeRequiredLeaseId(request.leaseId);
this.cleanupExpiredLeases();
const lease = this.leases.get(leaseId);
if (!lease) return undefined;
assertLeaseOwnerScope(lease, request);
assertLeaseScopeMatch(lease, request);
return { ...lease };
}
assertLeaseAdmission(request: AdmissionRequest): void {
const scope = normalizeLeaseAdmissionRequest(request);
this.cleanupExpiredLeases();
assertLeaseScopeMatch(this.getActiveLease(scope.leaseId), scope);
}
/** Whether this daemon ever allocated `tenantId` a `macos-app` lease, released or not. */
hasHeldMacOsAppLease(tenantId: string): boolean {
return this.macOsAppTenantIds.has(tenantId);
}
/** The backend of the active lease `leaseId` names, read without an owner check. */
findActiveLeaseBackend(leaseId: string): LeaseBackend | undefined {
const id = normalizeLeaseId(leaseId);
if (!id) return undefined;
this.cleanupExpiredLeases();
return this.leases.get(id)?.backend;
}
/**
* Whether a `retainOnClose` lease is still inside its own window. A human-control hold or admitted
* work can keep a past-due lease registered, but only the lease's `expiresAt` bounds how long it
* keeps an idle daemon alive.
*/
hasRetainedLeases(): boolean {
const now = this.now();
return this.listActiveLeases().some(
(lease) => lease.retainOnClose === true && lease.expiresAt > now,
);
}
listActiveLeases(): DeviceLease[] {
this.cleanupExpiredLeases();
return Array.from(this.leases.values()).map((entry) => ({ ...entry }));
}
recordProviderSession(
lease: Pick<DeviceLease, 'leaseId' | 'tenantId' | 'leaseProvider' | 'expiresAt'>,
providerSessionId: string,
): void {
this.cleanupExpiredLeases();
const releasedAt = lease.expiresAt <= this.now() ? lease.expiresAt : undefined;
this.providerSessionOwnership.record(lease, providerSessionId);
if (!this.leases.has(lease.leaseId)) {
this.providerSessionOwnership.markLeaseReleased(lease, releasedAt);
}
}
resolveProviderSession(params: {
provider?: string;
providerSessionId?: string;
tenantId?: string;
}): ProviderSessionOwnership | undefined {
this.cleanupExpiredLeases();
return this.providerSessionOwnership.resolve(params);
}
listHumanControlHolds(authority: HumanControlAuthority): HumanControlHold[] {
this.cleanupExpiredLeases();
const key =
authority.kind === 'lease'
? leaseDeviceBindingKey(this.requireHumanControlLease(authority.leaseId))
: undefined;
const holds = [...this.holdsByDevice.entries()]
.filter(([deviceKey]) => key === undefined || key === deviceKey)
.flatMap(([, entries]) =>
[...entries.values()].map(({ hold }) => cloneHumanControlHold(hold)),
);
return holds.sort((left, right) => left.id.localeCompare(right.id));
}
async putHumanControlHold(
authority: HumanControlAuthority,
rawId: string,
rawInput: HumanControlHoldInput,
signal?: AbortSignal,
): Promise<HumanControlHold> {
signal?.throwIfAborted();
const id = normalizeHumanControlHoldId(rawId);
const input = parseHumanControlHoldInput(rawInput);
this.cleanupExpiredLeases();
const scope = this.resolveHumanControlScope(authority, input);
const key = leaseDeviceBindingKey(scope)!;
const existing = this.findHumanControlHold(id);
if (existing) {
this.assertHoldAuthority(authority, existing);
if (leaseDeviceBindingKey(existing.hold.scope) !== key) {
throw new AppError('INVALID_ARGS', 'Release a hold before changing its device scope.');
}
}
const now = this.now();
const pending: OwnedHumanControlHold = {
...(authority.kind === 'lease' ? { ownerLeaseId: authority.leaseId } : {}),
hold: {
id,
scope,
state: 'activating',
...(input.reason ? { reason: input.reason } : {}),
createdAt: existing?.hold.createdAt ?? now,
updatedAt: now,
},
};
const holds = this.holdsByDevice.get(key) ?? new Map<string, OwnedHumanControlHold>();
this.holdsByDevice.set(key, holds);
holds.set(id, pending);
return await this.activateHumanControlHold(key, pending, input.ttlMs, signal);
}
private async activateHumanControlHold(
key: string,
pending: OwnedHumanControlHold,
ttlMs: number | undefined,
signal?: AbortSignal,
): Promise<HumanControlHold> {
const holds = this.holdsByDevice.get(key)!;
const { id } = pending.hold;
try {
await this.mutations.wait(key, signal);
signal?.throwIfAborted();
if (holds.get(id) !== pending) {
throw new AppError(
'COMMAND_FAILED',
'Human-control hold changed before activation completed.',
{ holdId: id },
);
}
const activatedAt = this.now();
pending.hold = {
...pending.hold,
state: 'active',
updatedAt: activatedAt,
...(ttlMs === undefined ? {} : { expiresAt: activatedAt + ttlMs }),
};
this.refreshHeldLease(key, activatedAt);
return cloneHumanControlHold(pending.hold);
} catch (error) {
if (holds.get(id) === pending) this.deleteHumanControlHold(key, id);
throw error;
}
}
removeHumanControlHold(
authority: HumanControlAuthority,
rawId: string,
): HumanControlHold | undefined {
const id = normalizeHumanControlHoldId(rawId);
this.cleanupExpiredLeases();
const existing = this.findHumanControlHold(id);
if (!existing) return undefined;
this.assertHoldAuthority(authority, existing);
const key = leaseDeviceBindingKey(existing.hold.scope)!;
this.deleteHumanControlHold(key, id);
return cloneHumanControlHold(existing.hold);
}
private deleteHumanControlHold(key: string, id: string): void {
const holds = this.holdsByDevice.get(key)!;
holds.delete(id);
if (holds.size === 0) {
this.holdsByDevice.delete(key);
this.refreshHeldLease(key, this.now());
}
}
assertHumanControlAdmission(
scope: Pick<DeviceLease, 'backend' | 'leaseProvider' | 'deviceKey'>,
): void {
this.expireHumanControlHolds();
const key = leaseDeviceBindingKey(scope);
const entry =
key === undefined ? undefined : this.holdsByDevice.get(key)?.values().next().value;
if (entry) throw humanControlActiveError(entry.hold);
}
async runDeviceMutation<T>(lease: DeviceLease | undefined, task: () => Promise<T>): Promise<T> {
if (!lease) return await task();
this.cleanupExpiredLeases();
const activeLease = this.getActiveLease(lease.leaseId);
this.assertHumanControlAdmission(activeLease);
const key = leaseDeviceBindingKey(activeLease);
return key === undefined ? await task() : await this.mutations.run(key, task);
}
private requireHumanControlLease(leaseId: string): DeviceLease & { deviceKey: string } {
const lease = this.getActiveLease(leaseId);
if (!lease.deviceKey) {
throw new AppError(
'UNSUPPORTED_OPERATION',
'Human control requires a device-scoped remote lease.',
);
}
return { ...lease, deviceKey: lease.deviceKey };
}
private resolveHumanControlScope(
authority: HumanControlAuthority,
input: HumanControlHoldInput,
): HumanControlHoldScope {
if (authority.kind === 'host') {
if (!input.scope)
throw new AppError('INVALID_ARGS', 'Host human control requires a lease device scope.');
return input.scope;
}
if (input.scope) {
throw new AppError(
'INVALID_ARGS',
'Lease-owner human control uses the admitted lease device; do not supply scope.',
);
}
const lease = this.requireHumanControlLease(authority.leaseId);
return {
backend: lease.backend,
leaseProvider: lease.leaseProvider,
deviceKey: lease.deviceKey,
};
}
private assertHoldAuthority(
authority: HumanControlAuthority,
entry: OwnedHumanControlHold,
): void {
if (authority.kind === 'host') return;
const lease = this.requireHumanControlLease(authority.leaseId);
if (
entry.ownerLeaseId !== lease.leaseId ||
leaseDeviceBindingKey(lease) !== leaseDeviceBindingKey(entry.hold.scope)
) {
throw new AppError(
'UNAUTHORIZED',
'Human-control hold does not belong to the admitted lease.',
{ reason: 'LEASE_SCOPE_MISMATCH' },
);
}
}
private findHumanControlHold(id: string): OwnedHumanControlHold | undefined {
for (const holds of this.holdsByDevice.values()) {
const entry = holds.get(id);
if (entry) return entry;
}
return undefined;
}
private hasHumanControl(lease: DeviceLease): boolean {
const key = leaseDeviceBindingKey(lease);
return key !== undefined && this.holdsByDevice.has(key);
}
/**
* What keeps a past-due lease alive: a human holding the device, or an admitted
* request still working on it while its client still wants the result.
*/
private isLeaseProtected(lease: DeviceLease, now: number): boolean {
return (
lease.expiresAt > now ||
this.hasHumanControl(lease) ||
this.inFlightWork.isDeferred(lease.leaseId)
);
}
private expireHumanControlHolds(): void {
const now = this.now();
for (const [key, holds] of this.holdsByDevice) {
let releasedAt = 0;
for (const [id, { hold }] of holds) {
if (hold.expiresAt === undefined || hold.expiresAt > now) continue;
releasedAt = Math.max(releasedAt, hold.expiresAt);
holds.delete(id);
}
if (holds.size === 0) {
this.holdsByDevice.delete(key);
this.refreshHeldLease(key, releasedAt);
}
}
}
private refreshHeldLease(key: string, at: number): void {
this.refreshProtectedLease(this.deviceBindings.get(key), at);
}
/**
* The one rule for a device resource that stops holding a lease: the lease is
* renewed for its own TTL from the instant the resource let go, never from a
* later sweep, so work nobody waited for cannot revive an abandoned lease.
*/
private refreshProtectedLease(leaseId: string | undefined, at: number): void {
const lease = leaseId ? this.leases.get(leaseId) : undefined;
if (lease) {
this.refreshLease(lease, leaseOwnTtlMs(lease), Math.max(at, lease.heartbeatAt));
}
}
consumeExpiredLeases(): DeviceLease[] {
this.expireHumanControlHolds();
const now = this.now();
const expired: DeviceLease[] = [];
for (const lease of this.leases.values()) {
if (this.isLeaseProtected(lease, now)) continue;
this.leases.delete(lease.leaseId);
this.unbindLease(lease, lease.expiresAt);
const expiredLease = { ...lease };
expired.push(expiredLease);
this.onLeaseExpired?.(expiredLease);
}
return expired;
}
consumeExpiredLease(leaseId: string): DeviceLease | undefined {
this.expireHumanControlHolds();
const normalizedLeaseId = normalizeLeaseId(leaseId);
if (!normalizedLeaseId) return undefined;
const lease = this.leases.get(normalizedLeaseId);
if (!lease || this.isLeaseProtected(lease, this.now())) {
return undefined;
}
this.leases.delete(lease.leaseId);
this.unbindLease(lease, lease.expiresAt);
const expiredLease = { ...lease };
this.onLeaseExpired?.(expiredLease);
return expiredLease;
}
private cleanupExpiredLeases(): void {
this.consumeExpiredLeases();
}
private enforceCapacity(backend: LeaseBackend): void {
if (backend !== 'ios-simulator') return;
if (this.maxActiveSimulatorLeases <= 0) return;
const activeSimulatorLeases = Array.from(this.leases.values()).filter(
(lease) => lease.backend === 'ios-simulator',
).length;
if (activeSimulatorLeases < this.maxActiveSimulatorLeases) return;
throw new AppError('DEVICE_IN_USE', 'No simulator lease capacity available', {
reason: 'LEASE_CAPACITY_EXCEEDED',
activeLeases: activeSimulatorLeases,
maxActiveLeases: this.maxActiveSimulatorLeases,
backend,
hint: 'Retry after releasing another simulator lease.',
});
}
private getActiveLease(leaseId: string): DeviceLease {
const lease = this.leases.get(leaseId);
if (lease) return lease;
throw new AppError('UNAUTHORIZED', 'Lease is not active', {
reason: 'LEASE_NOT_FOUND',
});
}
private refreshLease(lease: DeviceLease, ttlMs: number, now = this.now()): DeviceLease {
const updated: DeviceLease = {
...lease,
heartbeatAt: now,
expiresAt: now + ttlMs,
};
this.leases.set(updated.leaseId, updated);
this.bindLease(updated);
return { ...updated };
}
private bindLease(lease: DeviceLease): void {
this.runBindings.set(leaseRunBindingKey(lease), lease.leaseId);
const deviceBindingKey = leaseDeviceBindingKey(lease);
if (deviceBindingKey) {
this.deviceBindings.set(deviceBindingKey, lease.leaseId);
}
}
private unbindLease(lease: DeviceLease, releasedAt = this.now()): void {
this.hostTtlMsByLeaseId.delete(lease.leaseId);
this.runBindings.delete(leaseRunBindingKey(lease));
const deviceBindingKey = leaseDeviceBindingKey(lease);
if (deviceBindingKey) {
this.deviceBindings.delete(deviceBindingKey);
}
this.providerSessionOwnership.markLeaseReleased(lease, releasedAt);
}
private assertDeviceAvailable(params: {
backend: LeaseBackend;
leaseProvider?: string;
deviceKey?: string;
}): void {
const deviceBindingKey = leaseDeviceBindingKey({
backend: params.backend,
leaseProvider: params.leaseProvider,
deviceKey: params.deviceKey,
});
if (!deviceBindingKey) return;
const activeLeaseId = this.deviceBindings.get(deviceBindingKey);
if (!activeLeaseId) return;
const activeLease = this.leases.get(activeLeaseId);
if (!activeLease) {
this.deviceBindings.delete(deviceBindingKey);
return;
}
throw deviceLeaseBusyError(activeLease);
}
}