Path: blob/master/src/packages/project/conat/connection.ts
1447 views
/*1Create a connection to a conat server authenticated as a project or compute2server, via an api key or the project secret token.3*/45import { apiKey, conatServer } from "@cocalc/backend/data";6import { secretToken } from "@cocalc/project/data";7import { connect, type Client } from "@cocalc/conat/core/client";8import {9API_COOKIE_NAME,10PROJECT_SECRET_COOKIE_NAME,11PROJECT_ID_COOKIE_NAME,12} from "@cocalc/backend/auth/cookie-names";13import { inboxPrefix } from "@cocalc/conat/names";14import { setConatClient } from "@cocalc/conat/client";15import { compute_server_id, project_id } from "@cocalc/project/data";16import { version as ourVersion } from "@cocalc/util/smc-version";17import { getLogger } from "@cocalc/project/logger";18import { initHubApi } from "@cocalc/conat/hub/api";19import { delay } from "awaiting";2021const logger = getLogger("conat:connection");2223const VERSION_CHECK_INTERVAL = 2 * 60000;2425let cache: Client | null = null;26export function connectToConat(options?): Client {27if (cache != null) {28return cache;29}30let Cookie;31if (apiKey) {32Cookie = `${API_COOKIE_NAME}=${apiKey}`;33} else {34Cookie = `${PROJECT_SECRET_COOKIE_NAME}=${secretToken}; ${PROJECT_ID_COOKIE_NAME}=${project_id}`;35}36cache = connect({37address: conatServer,38inboxPrefix: inboxPrefix({ project_id }),39extraHeaders: { Cookie },40...options,41});4243versionCheckLoop(cache);4445return cache!;46}4748export function init() {49setConatClient({50conat: connectToConat,51project_id,52compute_server_id,53getLogger,54});55}56init();5758async function callHub({59client,60service = "api",61name,62args = [],63timeout,64}: {65client: Client;66service?: string;67name: string;68args: any[];69timeout?: number;70}) {71const subject = `hub.project.${project_id}.${service}`;72try {73const data = { name, args };74const resp = await client.request(subject, data, { timeout });75return resp.data;76} catch (err) {77err.message = `${err.message} - callHub: subject='${subject}', name='${name}', `;78throw err;79}80}8182async function versionCheckLoop(client) {83const hub = initHubApi((opts) => callHub({ ...opts, client }));84while (true) {85try {86const { version } = await hub.system.getCustomize(["version"]);87logger.debug("versionCheckLoop: ", { ...version, ourVersion });88if (version != null) {89const requiredVersion = compute_server_id90? (version.min_compute_server ?? 0)91: (version.min_project ?? 0);92if ((ourVersion ?? 0) < requiredVersion) {93logger.debug(94`ERROR: our CoCalc version ${ourVersion} is older than the required version ${requiredVersion}. \n\n** TERMINATING DUE TO VERSION BEING TOO OLD!!**\n\n`,95);96setTimeout(() => process.exit(1), 10);97}98}99} catch (err) {100logger.debug(`WARNING: problem getting version info from hub -- ${err}`);101}102await delay(VERSION_CHECK_INTERVAL);103}104}105106107