Repository navigation
Expand file tree
/
Copy pathlease-owner.ts
More file actions
242 lines (224 loc) · 8.44 KB
/
Copy pathlease-owner.ts
File metadata and controls
242 lines (224 loc) · 8.44 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
import type { DeviceLease, LeaseLifecycleContext } from '@agent-device/contracts/device';
import { errorMessage } from '@agent-device/kernel/errors';
import type { RevylPlatform } from './device.ts';
import {
isRevylSessionGone,
REVYL_STOP_REQUEST_BUDGET_MS,
type RevylClient,
} from './revyl-client.ts';
import {
startRevylSession,
stopRevylSession,
type RevylRentedSession,
type RevylSession,
type RevylStart,
} from './revyl-session.ts';
import type { RevylStartRequest } from './session-allocation.ts';
import { revylSessionIdForLease } from './session-identity.ts';
const CREATE_ANSWER_BUDGET_MS = 120_000;
// Allow the HTTP stop's complete request/retry budget plus a 5 s settlement margin.
const STOP_ANSWER_BUDGET_MS = REVYL_STOP_REQUEST_BUDGET_MS + 5_000;
export type RevylStopOutcome = Readonly<{
session: RevylRentedSession;
data?: Record<string, unknown>;
}> &
(Readonly<{ cleanup: 'confirmed' }> | Readonly<{ cleanup: 'uncertain'; failure: string }>);
type RevylUncertainStop = Extract<RevylStopOutcome, { cleanup: 'uncertain' }>;
type RevylConfirmedStop = Extract<RevylStopOutcome, { cleanup: 'confirmed' }>;
type StopWork = Readonly<{ pending: Promise<RevylStopOutcome> }>;
type RevylLeaseState =
| { phase: 'starting'; rented?: RevylRentedSession }
| { phase: 'ready'; session: RevylSession }
| {
phase: 'stopping';
disposal: Promise<RevylStopOutcome | undefined>;
rented?: RevylRentedSession;
stop?: StopWork;
}
| { phase: 'stop-failed'; outcome: RevylUncertainStop; stop?: StopWork }
| { phase: 'closed'; outcome?: RevylConfirmedStop };
export class RevylLeaseOwner {
private state: RevylLeaseState = { phase: 'starting' };
readonly creation: Promise<RevylStart>;
private readonly client: RevylClient;
readonly lease: DeviceLease;
readonly request: RevylStartRequest;
private readonly closed: () => void;
constructor(
client: RevylClient,
lease: DeviceLease,
platform: RevylPlatform,
request: RevylStartRequest,
context: LeaseLifecycleContext | undefined,
closed: () => void,
) {
this.client = client;
this.lease = lease;
this.request = request;
this.closed = closed;
// The microtask starts only after the runtime publishes this owner in its map.
this.creation = Promise.resolve().then(async () => {
let result: RevylStart;
try {
result = await startRevylSession(
client,
lease,
{
platform,
appUrl: request.appUrl,
deviceModel: request.deviceModel,
osVersion: request.osVersion,
...(context?.signal === undefined ? {} : { signal: context.signal }),
...(context?.deadline === undefined ? {} : { deadline: context.deadline }),
},
(rented) => this.recordRent(rented),
);
} catch (error) {
result = {
status: 'failed',
error,
rented: { sessionId: revylSessionIdForLease(lease.leaseId) },
};
}
if (this.state.phase === 'starting') {
if (result.status === 'ready') this.state = { phase: 'ready', session: result.session };
else if (result.rented === undefined) this.close();
else this.recordRent(result.rented);
}
return result;
});
void this.creation
.then(async (result) => {
if (result.status === 'failed' && result.rented !== undefined) await this.endFailedStart();
})
.catch(() => undefined);
}
get session(): RevylSession | undefined {
return this.state.phase === 'ready' ? this.state.session : undefined;
}
get releasing(): boolean {
return this.state.phase !== 'starting' && this.state.phase !== 'ready';
}
private recordRent(rented: RevylRentedSession): void {
const state = this.state;
if (state.phase === 'starting' || state.phase === 'stopping') state.rented = rented;
else if (state.phase === 'stop-failed')
this.state = { ...state, outcome: { ...state.outcome, session: rented } };
}
endFailedStart(): Promise<RevylStopOutcome | undefined> {
return this.state.phase === 'stop-failed' ? Promise.resolve(this.state.outcome) : this.end();
}
end(): Promise<RevylStopOutcome | undefined> {
const previous = this.state;
if (previous.phase === 'closed') return Promise.resolve(previous.outcome);
if (previous.phase === 'stopping') return previous.disposal;
const stop = previous.phase === 'stop-failed' ? previous.stop : undefined;
const rented =
previous.phase === 'starting'
? previous.rented
: previous.phase === 'ready'
? previous.session
: previous.outcome.session;
const disposal = Promise.resolve().then(async () => await this.dispose());
this.state = {
phase: 'stopping',
disposal,
...(rented === undefined ? {} : { rented }),
...(stop === undefined ? {} : { stop }),
};
return disposal;
}
private async dispose(): Promise<RevylStopOutcome | undefined> {
const created = await withinBudget(this.creation, CREATE_ANSWER_BUDGET_MS);
if (created === undefined) {
const outcome = this.uncertain('Revyl start has not answered within its disposal budget.');
this.state = { phase: 'stop-failed', outcome };
// No stop can confirm absence before the create answers. Its eventual answer re-enters the same owner.
void this.creation.then(async () => await this.end()).catch(() => undefined);
return outcome;
}
const target =
created.status === 'ready'
? { runId: created.session.runId, sessionId: created.session.sessionId }
: created.rented;
if (target === undefined) {
this.close();
return undefined;
}
const data = created.status === 'ready' ? allocationResult(created.session) : undefined;
const state = this.state;
if (state.phase !== 'stopping') throw new TypeError('Revyl disposal lost its owner');
const pending = state.stop?.pending ?? this.stop(target, data);
const stop = { pending };
state.stop = stop;
const outcome = await withinBudget(pending, STOP_ANSWER_BUDGET_MS);
if (outcome === undefined) {
const uncertain = {
...this.uncertain('Revyl stop has not answered within its disposal budget.'),
...(data === undefined ? {} : { data }),
};
this.state = { phase: 'stop-failed', outcome: uncertain, stop };
// A late confirmation closes the owner; a late refusal leaves the same session available for retry.
void pending
.then((late) => {
if (this.state.phase === 'stop-failed' && this.state.stop === stop) this.finish(late);
})
.catch(() => undefined);
return uncertain;
}
this.finish(outcome);
return outcome;
}
private async stop(
target: RevylRentedSession,
data?: Record<string, unknown>,
): Promise<RevylStopOutcome> {
const result = { session: target, ...(data === undefined ? {} : { data }) };
try {
await stopRevylSession(this.client, target.sessionId);
return { ...result, cleanup: 'confirmed' };
} catch (error) {
return isRevylSessionGone(error)
? { ...result, cleanup: 'confirmed' }
: { ...result, cleanup: 'uncertain', failure: errorMessage(error) };
}
}
private uncertain(failure: string): RevylUncertainStop {
const state = this.state;
const target = state.phase === 'stopping' ? state.rented : undefined;
return {
cleanup: 'uncertain',
session: target ?? { sessionId: revylSessionIdForLease(this.lease.leaseId) },
failure,
};
}
private finish(outcome: RevylStopOutcome): void {
if (outcome.cleanup === 'confirmed') this.close(outcome);
else this.state = { phase: 'stop-failed', outcome };
}
private close(outcome?: RevylConfirmedStop): void {
this.state = { phase: 'closed', ...(outcome === undefined ? {} : { outcome }) };
this.closed();
}
}
async function withinBudget<T>(work: Promise<T>, budgetMs: number): Promise<T | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
work,
new Promise<undefined>((resolve) => {
timer = setTimeout(() => resolve(undefined), budgetMs);
timer.unref();
}),
]);
} finally {
if (timer !== undefined) clearTimeout(timer);
}
}
export function allocationResult(session: RevylSession): Record<string, unknown> {
return {
revylRunId: session.runId,
providerSessionId: session.sessionId,
device: session.device,
};
}