Repository navigation
Expand file tree
/
Copy patharf.ts
More file actions
427 lines (423 loc) · 16.8 KB
/
Copy patharf.ts
File metadata and controls
427 lines (423 loc) · 16.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
import {
ARF_METHOD_NOT_FOUND,
ARF_TIMEOUT,
ArfRpcError,
arfRequest,
checkArfSession,
} from '../arf';
import { ArfAttachConnection, ArfEvent } from '../arfAttach';
import { BackendEvent, InspectionRequest } from '../backend';
import { MAX_MESSAGE_BYTES, object, Submission } from '../protocol';
import { RuntimeProcess } from './process';
import { rString } from './rCode';
import { ArfOutput } from './arfOutput';
import {
ArfHandlerApi,
CallLimits,
InspectionCalls,
inspectionCallsAvailable,
parseHandlerApi,
} from './arfInspection';
/** Topic that sess publishes before running submitted code under arf. */
const STARTED_TOPIC = 'vscode-r.interactive.started';
/**
* Longest line accepted on the attach connection. A handler's result is
* limited to MAX_MESSAGE_BYTES before it is sent as a JSON string, which can
* escape every character once more.
*/
const MAX_ATTACH_LINE_BYTES = 8 * MAX_MESSAGE_BYTES;
/** The submission sent to arf, and arf's execution ID once known. */
interface Execution {
submission: string;
id?: number;
interruptRequested: boolean;
}
export class Arf {
readonly process: RuntimeProcess;
ready = false;
private abort = new AbortController();
private started = false;
private attach?: ArfAttachConnection;
private attaching?: Promise<Record<string, unknown>>;
private handlerApi?: ArfHandlerApi;
private inspections = new InspectionCalls((selector, args, limits) =>
this.callHandler(selector, args, limits),
);
private sessionId?: string;
private execution?: Execution;
private failure?: Error;
private stopping?: Promise<void>;
constructor(
private command: string,
private directory: string,
private endpoint: string | undefined,
adopted: boolean,
private emit: (event: BackendEvent) => void,
private token: string,
private event: (message: Record<string, unknown>, channel: string) => void,
) {
this.process = new RuntimeProcess(adopted, emit);
}
markStarted(): void {
this.started = true;
}
/**
* `expose` is the R expression that arf evaluates, after the R profiles,
* to publish handlers. It applies only when this adapter starts arf.
*/
async start(bootstrap: string, env: NodeJS.ProcessEnv, expose?: string): Promise<void> {
if (!this.process.adopted) {
const output = new Map(
['stdout', 'stderr'].map((channel) => [
channel,
new ArfOutput(
this.token,
(text) => {
if (text) {
this.emit({ type: 'stream', text, channel });
}
},
(message) => this.event(message, channel),
),
]),
);
this.endpoint = await new Promise<string>((resolve, reject) => {
let readiness = '';
const timer = setTimeout(
() => reject(new Error('arf did not report its IPC endpoint')),
30000,
);
const child = this.process.launch(
this.command,
['headless', '--json', ...(expose ? ['--ipc-expose', expose] : [])],
this.directory,
env,
(text, channel) => {
if (channel === 'stdout' && !this.endpoint) {
readiness += text;
let newline: number;
while (!this.endpoint && (newline = readiness.indexOf('\n')) >= 0) {
const line = readiness.slice(0, newline);
readiness = readiness.slice(newline + 1);
let info: Record<string, unknown> | undefined;
try {
info = object(JSON.parse(line));
} catch {
/* Profiles can print before readiness. */
}
if (typeof info?.socket_path === 'string') {
this.endpoint = info.socket_path;
clearTimeout(timer);
resolve(this.endpoint);
} else {
this.emit({ type: 'stream', text: line + '\n', channel });
}
}
if (this.endpoint || readiness.length > 65536) {
if (readiness) {
output.get(channel)!.push(readiness);
}
readiness = '';
}
} else {
try {
output.get(channel)!.push(text);
} catch (error) {
this.emit({ type: 'unavailable', message: String(error) });
}
}
},
);
child.once('error', (error) => {
clearTimeout(timer);
reject(error);
});
child.once('exit', () => {
clearTimeout(timer);
reject(new Error('arf exited during startup'));
});
});
}
if (!this.endpoint) {
throw new Error('Missing arf endpoint');
}
// Subscribe before submitting anything so that no started event is missed.
const metadata = await this.connect();
checkArfSession(metadata);
// The published table must match the selectors that inspection calls.
if (!this.process.adopted && !this.callsInspection()) {
throw new Error('arf did not publish the R Interactive inspection handlers');
}
this.emit({
type: 'provider',
data: {
provider: this.process.adopted ? 'arf-existing' : 'arf',
policy: metadata.ipc_policy,
},
});
// Visible evaluation respects arf's advertised IPC policy, including bootstrap.
const result = object(
await arfRequest(
this.endpoint,
'evaluate',
{ code: bootstrap, visible: true },
30000,
this.abort.signal,
),
);
// A missing or unknown status is not a successful bootstrap.
if (result.status !== 'ok') {
const detail =
typeof result.error === 'string' && result.error
? result.error
: typeof result.stderr === 'string' && result.stderr.trim()
? result.stderr.trim()
: `status ${JSON.stringify(result.status ?? null)}`;
throw new Error(`Interactive bootstrap failed in arf: ${detail}`);
}
}
/** Attaches, or joins an attach that is already in progress. */
private connect(): Promise<Record<string, unknown>> {
return (this.attaching ??= this.attachOnce().finally(() => {
this.attaching = undefined;
}));
}
private async attachOnce(): Promise<Record<string, unknown>> {
const { connection, result } = await ArfAttachConnection.open(this.endpoint!, {
subscribe: [STARTED_TOPIC],
client: { name: 'vscode-R Interactive' },
maxLineBytes: MAX_ATTACH_LINE_BYTES,
onEvent: (event) => this.arfEvent(event),
});
if (this.sessionId !== undefined && result.sessionId !== this.sessionId) {
connection.close();
throw new Error('The arf endpoint now belongs to a different session');
}
if (this.abort.signal.aborted) {
connection.close();
throw new Error('arf adapter was disposed');
}
this.sessionId = result.sessionId;
this.attach = connection;
this.handlerApi = parseHandlerApi(result.session);
return result.session;
}
/** The attach connection, reattaching to the same session if it was lost. */
private async attached(): Promise<ArfAttachConnection> {
if (!this.attach || this.attach.closed) {
await this.connect();
}
return this.attach!;
}
/**
* Whether inspection uses handler calls, which stop at their execution
* deadline, rather than the sess socket, which cannot be interrupted.
*/
callsInspection(): boolean {
return inspectionCallsAvailable(this.handlerApi);
}
/** Runs an inspection as a handler call with the request's execution deadline. */
inspect(request: InspectionRequest): Promise<unknown> {
return this.inspections.request(request);
}
private async callHandler(
selector: string,
args: string,
limits: CallLimits,
): Promise<unknown> {
// A long-lived connection drops a call that has not started when it
// closes, so disposal does not leave inspections queued in R.
const connection = await this.attached();
return connection.request(
'call',
{
handler: selector,
args,
queue_timeout_ms: limits.queue,
execution_timeout_ms: limits.execution,
},
{ timeout: limits.transport, signal: this.abort.signal },
);
}
dispose(): void {
this.abort.abort();
this.inspections.close(new Error('R session was disposed'));
this.attach?.close();
this.process.dispose();
}
/** Called once sess reports that a submission finished. */
finished(submission: string): void {
if (this.execution?.submission === submission) {
this.execution = undefined;
}
}
async interrupt(): Promise<void> {
const execution = this.execution;
if (!execution) {
// Inspection is stopped by its execution deadline, not by this request.
throw new Error('No submitted code is running');
}
execution.interruptRequested = true;
if (execution.id !== undefined) {
await this.sendInterrupt(execution);
} else if (this.attach?.closed) {
throw new Error(
'Cannot interrupt: the connection to arf was lost before the execution started',
);
}
// Otherwise the request is sent once arf reports the execution ID.
}
private async sendInterrupt(execution: Execution): Promise<void> {
if (this.execution !== execution || execution.id === undefined) {
return;
}
// Acceptance only registers the request; sess reports the outcome. A
// rejection means the execution already ended, which races with Stop.
await arfRequest(this.endpoint!, 'interrupt', { execution_id: execution.id }, 5000);
}
/** Records arf's execution ID for a submission, from its reply or its started event. */
private register(submission: unknown, id: unknown): void {
const execution = this.execution;
if (!execution || execution.submission !== submission) {
return;
}
if (!Number.isSafeInteger(id) || (id as number) < 0) {
this.fail(new Error('arf reported an invalid execution ID'));
return;
}
if (execution.id === undefined) {
execution.id = id as number;
if (execution.interruptRequested) {
void this.sendInterrupt(execution).catch((error: Error) =>
this.emit({ type: 'error', message: error.message }),
);
}
} else if (execution.id !== id) {
this.fail(new Error('arf reported conflicting execution IDs for one submission'));
}
}
private arfEvent(event: ArfEvent): void {
if (event.topic !== STARTED_TOPIC) {
return;
}
const data = event.data;
const submission =
data && typeof data === 'object' ? (data as Record<string, unknown>).id : undefined;
this.register(submission, event.execution);
}
private fail(error: Error): void {
this.failure ??= error;
this.emit({ type: 'unavailable', message: error.message });
}
stop(force = false): Promise<void> {
return (this.stopping ??= this.stopRuntime(force).finally(() => {
this.stopping = undefined;
}));
}
private async stopRuntime(force: boolean): Promise<void> {
if (!this.process.alive()) {
this.process.markExited();
return;
}
if (force) {
await this.kill(undefined, 0);
return;
}
if (!this.endpoint) {
if (this.process.adopted) {
throw new Error('The arf endpoint is unknown');
}
await this.kill('SIGTERM', 3000);
return;
}
try {
await arfRequest(this.endpoint, 'shutdown', {}, 5000);
} catch (error) {
if (
this.process.adopted &&
error instanceof ArfRpcError &&
error.code === ARF_METHOD_NOT_FOUND
) {
// An interactive arf rejects shutdown; stop it as a terminal would.
await this.kill('SIGTERM', 3000);
return;
}
if (!this.process.adopted) {
// The managed process is ours even if its IPC no longer answers.
await this.kill('SIGTERM', 3000);
return;
}
throw error;
}
// Acceptance only starts shutdown, and running R code may delay it.
await this.kill(undefined, 5000);
}
/** Sends `first`, waits up to `grace` ms, then kills; resolves after a confirmed exit. */
private async kill(first: NodeJS.Signals | undefined, grace: number): Promise<void> {
if (first) {
this.process.send(first);
}
if (await this.process.waitForExit(grace)) {
return;
}
this.process.send('SIGKILL');
if (!(await this.process.waitForExit(2000))) {
throw new Error('R has not exited after Stop');
}
}
async dispatch(submission: Submission): Promise<void> {
if (this.failure) {
throw this.failure;
}
// The previous execution has finished, so attaching again loses no
// state; the session must still be the same arf process.
await this.attached();
const code = `sess:::interactive_execute(${rString(submission.id)}, ${rString(submission.code)}, jsonlite::fromJSON(${rString(JSON.stringify(submission.source ?? null))}, simplifyVector=FALSE))`;
this.started = false;
this.execution = { submission: submission.id, interruptRequested: false };
// Managed sessions use send to avoid arf's unbounded evaluation capture.
// R's ordered events establish the outcome even if arf's reply times out.
let result: Record<string, unknown>;
try {
result = object(
await arfRequest(
this.endpoint!,
this.process.adopted ? 'evaluate' : 'user_input',
{ code, visible: true, timeout_ms: 86400000 },
0,
this.abort.signal,
),
);
} catch (error) {
// A server timeout does not cancel R. Keep accepting its event stream.
// Other transport failures remain ambiguous and must block dispatch.
if (
!this.process.adopted &&
this.started &&
error instanceof ArfRpcError &&
error.code === ARF_TIMEOUT
) {
return;
}
if (!this.started) {
this.finished(submission.id);
}
throw error;
}
this.register(submission.id, result.execution_id);
if (this.process.adopted) {
for (const channel of ['stdout', 'stderr']) {
if (typeof result[channel] === 'string' && result[channel]) {
this.emit({ type: 'stream', text: result[channel], channel });
}
}
}
if (result.error || result.accepted === false) {
throw new Error(
typeof result.error === 'string'
? result.error
: 'arf rejected Interactive execution',
);
}
}
}