Repository navigation
Expand file tree
/
Copy patharf.ts
More file actions
790 lines (784 loc) · 32.9 KB
/
Copy patharf.ts
File metadata and controls
790 lines (784 loc) · 32.9 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
import { setTimeout as delay } from 'timers/promises';
import {
ARF_METHOD_NOT_FOUND,
ARF_TIMEOUT,
ArfRpcError,
arfRequest,
checkArfSession,
discoverArf,
withRegistryEnvironment,
} from '../arf';
import { ArfAttachConnection, ArfEvent } from '../arfAttach';
import {
BackendEvent,
DispatchNotSentError,
InspectionRequest,
StopRefusedError,
} from '../backend';
import { ArfRegistryEnvironment, 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;
/** For an adopted session, the attach connection that sent the code. */
connection?: ArfAttachConnection;
}
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>;
private disposing?: Promise<void>;
private readiness?: Promise<string>;
/**
* Set when the configured executable launched arf as another process,
* whose exit closing therefore cannot confirm.
*/
private launchedElsewhere?: Error;
/**
* Set when a Stop found that the endpoint no longer reaches this session:
* code is then sent only after a new connection reaches it again.
*/
private reverify = false;
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,
/** The adopted arf process that discovery confirmed. */
private expected: { sessionId?: string; pid?: number } = {},
/** Where the arf CLI lists an adopted session again, if not `directory`. */
private discoveryDirectory = directory,
/**
* The registry selection that listed the adopted session. The agent's
* own environment, as under tmux, need not select the same registry.
*/
private registry?: ArfRegistryEnvironment,
) {
this.process = new RuntimeProcess(adopted, emit);
// The first attach must then reach the same arf as the probe did.
this.sessionId = expected.sessionId;
}
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(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.readiness = 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') {
clearTimeout(timer);
const pid = info.pid;
if (
typeof pid !== 'number' ||
!Number.isSafeInteger(pid) ||
pid <= 0
) {
reject(new Error('arf did not report its PID'));
break;
}
if (!this.process.ownsPid(pid)) {
// Signals and the exit that closing waits for
// must concern arf itself.
this.launchedElsewhere = new Error(
`${this.command} started arf as another process (PID ${pid}), which may still be running. ` +
'Set r.interactive.arfPath to arf itself, or to a script that replaces itself with arf using exec.',
);
reject(this.launchedElsewhere);
break;
}
this.endpoint = info.socket_path;
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'));
});
});
this.endpoint = await this.readiness;
}
this.abort.signal.throwIfAborted();
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,
},
});
}
/** Read the running R installation and its current library order, including changes before adoption. */
async rEnvironment(): Promise<{ libraryPaths: string[]; rHome?: string }> {
const deadline = Date.now() + 30000;
for (;;) {
const timeout = Math.max(1, Math.min(15000, deadline - Date.now()));
// The attach connection reached the verified session; a new
// connection to its socket path could reach another arf.
const attach = await this.attached();
const session = object(
await attach.request('session', {}, { timeout, signal: this.abort.signal }),
);
const libraries = session.r && object(session.r).lib_paths;
if (
Array.isArray(libraries) &&
libraries.length &&
libraries.every((p: unknown): p is string => typeof p === 'string' && p.length > 0)
) {
return {
libraryPaths: libraries,
rHome: typeof session.r_home === 'string' ? session.r_home : undefined,
};
}
const reason =
typeof session.r_unavailable_reason === 'string'
? session.r_unavailable_reason
: 'arf returned no library paths';
// An adopted R may still be evaluating the user's previous command.
// arf then returns a successful response containing only its own metadata.
if (
!this.process.adopted ||
session.r !== null ||
!/busy evaluating|pending|timed out collecting R session information/i.test(
reason,
) ||
Date.now() + 250 >= deadline
) {
throw new Error(`Could not read R library paths for jgd: ${reason}`);
}
await delay(250, undefined, { signal: this.abort.signal });
}
}
async bootstrap(code: string): Promise<void> {
// Visible evaluation respects arf's advertised IPC policy, including
// bootstrap. It goes over the attach connection, which reached the
// verified arf, rather than a new connection to its socket path, which
// a restarted arf can serve by then.
const attach = await this.attached();
const result = object(
await attach.request(
'evaluate',
{ code, visible: true },
{ timeout: 30000, signal: 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>> {
try {
return await this.attachTo(this.endpoint!);
} catch (error) {
const session = await this.relocated();
if (!session) {
throw error;
}
return session;
}
}
/**
* Attaches to the adopted session at the socket path it now lists. arf
* registers a new path when IPC restarts in the same process, as after
* `:ipc stop` and `:ipc start`, and keeps its PID and session ID.
*/
private async relocated(): Promise<Record<string, unknown> | undefined> {
return this.atListedPath(async (endpoint, timeout) => {
// The attach checks the session ID before the path is used.
const session = await this.attachTo(endpoint, timeout);
this.endpoint = endpoint;
return session;
});
}
/**
* Lists the adopted session again and returns what `open` returns for the
* first other socket path listed for its PID, within `deadline` if given.
* `open` must verify the session at that path.
*/
private async atListedPath<T>(
open: (endpoint: string, timeout: number | undefined) => Promise<T>,
deadline?: number,
): Promise<T | undefined> {
const pid = this.expected.pid;
if (!this.process.adopted || this.sessionId === undefined || pid === undefined) {
return undefined;
}
const remaining = (): number | undefined =>
deadline === undefined ? undefined : deadline - Date.now();
if ((remaining() ?? 1) <= 0) {
return undefined;
}
const discovery = await discoverArf(
this.command,
this.discoveryDirectory,
this.registry ? withRegistryEnvironment(process.env, this.registry) : process.env,
undefined,
Math.min(remaining() ?? Infinity, 5000),
);
if (!discovery.available) {
return undefined;
}
for (const listed of discovery.sessions) {
if (listed.pid !== pid || listed.socket_path === this.endpoint) {
continue;
}
const timeout = remaining();
if (timeout !== undefined && timeout <= 0) {
break;
}
try {
return await open(listed.socket_path, timeout);
} catch {
// Another listed path may reach the session.
}
}
return undefined;
}
private async attachTo(endpoint: string, timeout?: number): Promise<Record<string, unknown>> {
const { connection, result } = await ArfAttachConnection.open(endpoint, {
timeout,
subscribe: [STARTED_TOPIC],
client: { name: 'vscode-R Interactive' },
maxLineBytes: MAX_ATTACH_LINE_BYTES,
onEvent: (event) => this.arfEvent(event),
});
if (!this.sameSession(result) || !this.startedArf(result)) {
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;
}
/** Whether an attach reached the arf session that this adapter serves, as far as it is known. */
private sameSession(result: { sessionId: string; session: Record<string, unknown> }): boolean {
return (
(this.sessionId === undefined || result.sessionId === this.sessionId) &&
(this.expected.pid === undefined || result.session.pid === this.expected.pid)
);
}
/**
* Whether an attach reply comes from the arf that was started. The first
* attach records the session ID, so it must not accept a session that has
* taken over the socket path.
*/
private startedArf(result: { session: Record<string, unknown> }): boolean {
return this.process.adopted || this.process.ownsPid(result.session.pid);
}
/** A separate attach connection that reaches the same arf session as before. */
/**
* Reaching the session, including finding it at another socket path,
* takes at most 5 s, which Stop's client timeout allows for.
*/
private async verifiedConnection(): Promise<ArfAttachConnection> {
const deadline = Date.now() + 5000;
try {
return await this.openVerified(this.endpoint!, deadline);
} catch (error) {
// After IPC restarts, the attach connection has closed and the
// session may listen at another socket path, which listing finds.
// A live attach connection means the session did not move. The
// connection found there is Stop's own; the attach connection
// stays with dispatch, which finds the path again itself.
const moved =
this.process.adopted && (!this.attach || this.attach.closed)
? await this.atListedPath(
(endpoint) => this.openVerified(endpoint, deadline),
deadline,
)
: undefined;
if (!moved) {
throw error;
}
return moved;
}
}
private async openVerified(endpoint: string, deadline: number): Promise<ArfAttachConnection> {
const { connection, result } = await ArfAttachConnection.open(endpoint, {
subscribe: [],
client: { name: 'vscode-R Interactive' },
timeout: Math.max(1, deadline - Date.now()),
maxLineBytes: MAX_ATTACH_LINE_BYTES,
onEvent: () => undefined,
});
if (!this.sameSession(result) || !this.startedArf(result)) {
connection.close();
throw new Error('The arf endpoint now belongs to a different session');
}
return connection;
}
/** 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(): Promise<void> {
return (this.disposing ??= this.disposeRuntime());
}
private async disposeRuntime(): Promise<void> {
this.abort.abort();
this.inspections.close(new Error('R session was disposed'));
this.attach?.close();
try {
if (!this.process.adopted) {
await (this.stopping ?? this.stopManaged(false, 1000, 3000));
}
} finally {
this.process.dispose();
}
if (this.launchedElsewhere) {
throw this.launchedElsewhere;
}
}
/** 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 ((execution.connection ?? 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.
// An adopted execution is interrupted on the connection that started
// it: its ID belongs to that arf, which the socket path may no longer
// reach.
const params = { execution_id: execution.id };
if (!execution.connection) {
await arfRequest(this.endpoint!, 'interrupt', params, 5000);
return;
}
if (execution.connection.closed) {
throw new Error('Cannot interrupt: the connection to arf that runs the code was lost');
}
await execution.connection.request('interrupt', params, { timeout: 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.disposing ?? this.stopRuntime(force)).finally(() => {
this.stopping = undefined;
}));
}
private async stopRuntime(force: boolean): Promise<void> {
if (!this.process.alive()) {
this.process.markExited();
return;
}
if (this.process.adopted) {
await this.stopAdopted(force);
return;
}
await this.stopManaged(force, 5000, 5000);
}
private async stopManaged(
force: boolean,
requestTimeout: number,
grace: number,
): Promise<void> {
if (!this.process.alive()) {
this.process.markExited();
return;
}
if (force) {
await this.kill(undefined, 0);
return;
}
// Readiness comes after arf has installed its signal handler and started IPC.
// Allow a closing agent a brief chance to reach a child still starting up.
const deadline = Date.now() + requestTimeout;
if (!this.endpoint && this.readiness) {
const timer = new AbortController();
try {
await Promise.race([
this.readiness.catch(() => undefined),
delay(Math.min(1000, requestTimeout), undefined, { signal: timer.signal }),
]);
} finally {
timer.abort();
}
}
let accepted = false;
if (this.endpoint && this.process.alive()) {
let connection: ArfAttachConnection | undefined;
try {
// Verify the child even if the original attachment is gone or startup failed.
connection = await this.openVerified(this.endpoint, deadline);
const result = object(
await connection.request(
'shutdown',
{},
{
timeout: Math.max(1, deadline - Date.now()),
},
),
);
accepted = result.accepted === true;
} catch {
// A missing or unresponsive endpoint is handled below.
} finally {
connection?.close();
}
}
if (accepted) {
await this.kill(undefined, grace);
} else if (process.platform !== 'win32') {
await this.kill('SIGTERM', 3000);
} else {
// Windows signals forcibly terminate. A lost IPC response may still
// mean shutdown was accepted, so allow the child time to exit.
await this.kill(undefined, this.endpoint ? grace : 0);
}
}
/**
* An adopted arf is only asked to shut down. Its process is never
* terminated: an interactive arf would not restore its terminal or finish
* R's exit, and its PID may have been reused.
*/
private async stopAdopted(force: boolean): Promise<void> {
if (force) {
throw new StopRefusedError('An attached arf session cannot be stopped forcibly');
}
if (!this.endpoint) {
throw new StopRefusedError('The arf endpoint is unknown');
}
// Shut down only the adopted arf: a socket path can be bound by another
// session while the adopted R is still alive. A new connection is
// verified first, so that a failure to reach arf is known to have
// sent nothing, as when IPC is stopped while R keeps running.
let connection: ArfAttachConnection;
try {
connection = await this.verifiedConnection();
} catch (error) {
this.reverify = true;
throw new StopRefusedError(
`arf could not receive the shutdown request: ${error instanceof Error ? error.message : String(error)}`,
);
}
try {
await connection.request('shutdown', {}, { timeout: 5000 });
} catch (error) {
if (error instanceof ArfRpcError && error.code === ARF_METHOD_NOT_FOUND) {
throw new StopRefusedError(
'This arf session runs in a terminal and cannot be stopped from VS Code. End R in the terminal that started arf.',
);
}
if (error instanceof ArfRpcError) {
throw new StopRefusedError(
`arf did not accept the shutdown request: ${error.message}`,
);
}
// Without an answer, arf may or may not have accepted it.
throw error;
} finally {
connection.close();
}
// Acceptance only starts shutdown, and running R code may delay it.
// The process monitor reports a later exit.
if (!(await this.process.waitForExit(5000))) {
throw new Error('arf accepted the shutdown request but has not exited yet');
}
}
/** 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('Managed arf has not exited after forced termination');
}
}
async dispatch(submission: Submission, signal?: AbortSignal): 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.
let connection: ArfAttachConnection;
try {
if (this.reverify) {
// The next attach verifies the session again.
this.attach?.close();
}
connection = await this.attached();
this.reverify = false;
} catch (error) {
throw new DispatchNotSentError(
`arf could not be reached: ${error instanceof Error ? error.message : String(error)}`,
);
}
if (this.process.adopted && connection.closed) {
// The request would be rejected before it is written.
throw new DispatchNotSentError(
`arf could not be reached: ${connection.closed.message}`,
);
}
const code = `sess:::interactive_execute(${rString(submission.id)}, ${rString(submission.code)}, jsonlite::fromJSON(${rString(JSON.stringify(submission.source ?? null))}, simplifyVector=FALSE))`;
// Nothing awaits from here until the request is written.
if (signal?.aborted) {
throw new DispatchNotSentError('The code was cancelled before it was sent');
}
this.started = false;
this.execution = {
submission: submission.id,
interruptRequested: false,
connection: this.process.adopted ? connection : undefined,
};
// 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.
// An adopted session is evaluated on the attach connection that reached
// it, as a new connection to its socket path can reach another arf.
const params = { code, visible: true, timeout_ms: 86400000 };
let result: Record<string, unknown>;
try {
result = object(
this.process.adopted
? await connection.request('evaluate', params, { signal: this.abort.signal })
: await arfRequest(this.endpoint!, 'user_input', params, 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);
}
const errno = (error as NodeJS.ErrnoException).code;
if (errno === 'ENOENT' || errno === 'ECONNREFUSED') {
// The connection was never opened, so nothing was sent. The
// endpoint was gone, so another session may serve it next.
this.reverify = true;
throw new DispatchNotSentError(`arf could not be reached: ${String(error)}`);
}
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',
);
}
}
}