CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/project/port_manager.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2023 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { readFile } from "node:fs/promises";
7
8
import { abspath } from "@cocalc/backend/misc_node";
9
10
type Type = "sage";
11
12
/*
13
The port_manager manages the ports for the various servers.
14
15
It reads the port from memory or from disk and returns it.
16
*/
17
18
const { SMC } = process.env;
19
20
function port_file(type: Type): string {
21
return `${SMC}/${type}_server/${type}_server.port`;
22
}
23
24
// a local cache
25
const ports: { [type in Type]?: number } = {};
26
27
export async function get_port(type: Type): Promise<number> {
28
const val = ports[type];
29
if (val != null) {
30
return val;
31
} else {
32
const content = await readFile(abspath(port_file(type)));
33
try {
34
const val = parseInt(content.toString());
35
ports[type] = val;
36
return val;
37
} catch (e) {
38
throw new Error(`${type}_server port file corrupted`);
39
}
40
}
41
}
42
43
export function forget_port(type: Type) {
44
if (ports[type] != null) {
45
delete ports[type];
46
}
47
}
48
49