import { readFile } from "node:fs/promises";
import { abspath } from "@cocalc/backend/misc_node";
type Type = "sage";
const { SMC } = process.env;
function port_file(type: Type): string {
return `${SMC}/${type}_server/${type}_server.port`;
}
const ports: { [type in Type]?: number } = {};
export async function get_port(type: Type): Promise<number> {
const val = ports[type];
if (val != null) {
return val;
} else {
const content = await readFile(abspath(port_file(type)));
try {
const val = parseInt(content.toString());
ports[type] = val;
return val;
} catch (e) {
throw new Error(`${type}_server port file corrupted`);
}
}
}
export function forget_port(type: Type) {
if (ports[type] != null) {
delete ports[type];
}
}