Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/conat/service/terminal.ts
1452 views
1
/*
2
Service for controlling a terminal served from a project/compute server.
3
*/
4
5
import {
6
createServiceClient,
7
createServiceHandler,
8
type ConatService,
9
} from "./typed";
10
11
export type { ConatService };
12
13
export const SIZE_TIMEOUT_MS = 45000;
14
15
// API that runs under Node.js in linux:
16
17
interface TerminalApi {
18
create: (opts: {
19
env?: { [key: string]: string };
20
command?: string;
21
args?: string[];
22
cwd?: string;
23
ephemeral?: boolean;
24
}) => Promise<{ success: "ok"; note?: string; ephemeral?: boolean }>;
25
26
write: (data: string) => Promise<void>;
27
28
restart: () => Promise<void>;
29
30
cwd: () => Promise<string | undefined>;
31
32
kill: () => Promise<void>;
33
34
size: (opts: {
35
rows: number;
36
cols: number;
37
browser_id: string;
38
kick?: boolean;
39
}) => Promise<void>;
40
41
// sent from browser to project when this client is leaving.
42
close: (browser_id: string) => Promise<void>;
43
}
44
45
export function createTerminalClient({ project_id, termPath }) {
46
return createServiceClient<TerminalApi>({
47
project_id,
48
path: termPath,
49
service: "terminal-server",
50
timeout: 3000,
51
});
52
}
53
54
export type TerminalServiceApi = ReturnType<typeof createTerminalClient>;
55
56
export function createTerminalServer({
57
project_id,
58
termPath,
59
impl,
60
}: {
61
project_id: string;
62
termPath: string;
63
impl;
64
}): ConatService {
65
return createServiceHandler<TerminalApi>({
66
project_id,
67
path: termPath,
68
service: "terminal-server",
69
description: "Terminal service.",
70
impl,
71
});
72
}
73
74
// API that runs in the browser:
75
76
export interface TerminalBrowserApi {
77
// command is used for things like "open foo.txt" in the terminal.
78
command: (mesg) => Promise<void>;
79
80
// used for kicking all but the specified user out:
81
kick: (sender_browser_id: string) => Promise<void>;
82
83
// tell browser to change its size
84
size: (opts: { rows: number; cols: number }) => Promise<void>;
85
}
86
87
export function createBrowserClient({ project_id, termPath }) {
88
return createServiceClient<TerminalBrowserApi>({
89
project_id,
90
path: termPath,
91
service: "terminal-browser",
92
});
93
}
94
95
export function createBrowserService({
96
project_id,
97
termPath,
98
impl,
99
}: {
100
project_id: string;
101
termPath: string;
102
impl: TerminalBrowserApi;
103
}): ConatService {
104
return createServiceHandler<TerminalBrowserApi>({
105
project_id,
106
path: termPath,
107
service: "terminal-browser",
108
description: "Browser Terminal service.",
109
all: true,
110
impl,
111
});
112
}
113
114