Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/conat/project/project-info.ts
1452 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import type { ProjectInfo } from "@cocalc/util/types/project-info/types";
7
export type { ProjectInfo };
8
import { getLogger } from "@cocalc/conat/client";
9
import { projectSubject } from "@cocalc/conat/names";
10
import { conat } from "@cocalc/conat/client";
11
12
const SERVICE_NAME = "project-info";
13
const logger = getLogger("project:project-info");
14
15
interface Api {
16
get: () => Promise<ProjectInfo | null>;
17
}
18
19
export async function get({
20
project_id,
21
compute_server_id = 0,
22
}: {
23
project_id: string;
24
compute_server_id?: number;
25
}) {
26
const c = await conat();
27
const subject = getSubject({ project_id, compute_server_id });
28
return await c.call(subject).get();
29
}
30
31
function getSubject({ project_id, compute_server_id }) {
32
return projectSubject({
33
project_id,
34
compute_server_id,
35
service: SERVICE_NAME,
36
});
37
}
38
39
export function createService(opts: {
40
infoServer;
41
project_id: string;
42
compute_server_id: number;
43
}) {
44
return new ProjectInfoService(opts);
45
}
46
47
class ProjectInfoService {
48
private infoServer?;
49
private service?;
50
private readonly subject: string;
51
info?: ProjectInfo | null = null;
52
53
constructor({ infoServer, project_id, compute_server_id }) {
54
logger.debug("register");
55
this.subject = getSubject({ project_id, compute_server_id });
56
// initializing project info server + reacting when it has something to say
57
this.infoServer = infoServer;
58
this.infoServer.start();
59
this.infoServer.on("info", this.saveInfo);
60
this.createService();
61
}
62
63
private saveInfo = (info) => {
64
this.info = info;
65
};
66
67
private createService = async () => {
68
logger.debug("started project info service ", { subject: this.subject });
69
const client = await conat();
70
this.service = await client.service<Api>(this.subject, {
71
get: async () => this.info ?? null,
72
});
73
};
74
75
close = (): void => {
76
if (this.infoServer == null) {
77
return;
78
}
79
logger.debug("close");
80
this.infoServer?.removeListener("info", this.saveInfo);
81
delete this.infoServer;
82
this.service?.close();
83
delete this.service;
84
}
85
}
86
87