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/browser-websocket/server.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
/*
7
Create the Primus realtime socket server
8
*/
9
10
import { join } from "node:path";
11
import { Router } from "express";
12
import { Server } from "http";
13
import Primus from "primus";
14
import type { PrimusWithChannels } from "@cocalc/terminal";
15
16
// We are NOT using UglifyJS because it can easily take 3 blocking seconds of cpu
17
// during project startup to save 100kb -- it just isn't worth it. Obviously, it
18
// would be optimal to build this one and for all into the project image. TODO.
19
//const UglifyJS = require("uglify-js");
20
import { init_websocket_api } from "./api";
21
22
import { getLogger } from "@cocalc/project/logger";
23
24
export default function init(server: Server, basePath: string): Router {
25
const winston = getLogger("websocket-server");
26
const opts = {
27
pathname: join(basePath, ".smc", "ws"),
28
transformer: "websockets",
29
} as const;
30
winston.info(`Initializing primus websocket server at "${opts.pathname}"...`);
31
const primus = new Primus(server, opts) as PrimusWithChannels;
32
33
// add multiplex to Primus so we have channels.
34
primus.plugin("multiplex", require("@cocalc/primus-multiplex"));
35
36
/* Add responder plugin, which adds a 'request' event to sparks,
37
spark.on("request", (data, done) => { done({'thanks for':data}) })
38
and
39
primus.writeAndWait({event:'foo'}, (response) => console.log("got", response))
40
See: https://github.com/swissmanu/primus-responder
41
*/
42
primus.plugin("responder", require("@cocalc/primus-responder"));
43
44
init_websocket_api(primus);
45
46
const router = Router();
47
const library: string = primus.library();
48
// See note above.
49
//UglifyJS.minify(primus.library()).code;
50
51
router.get("/.smc/primus.js", (_, res) => {
52
winston.debug("serving up primus.js to a specific client");
53
res.send(library);
54
});
55
winston.info(
56
`waiting for clients to request primus.js (length=${library.length})...`,
57
);
58
59
return router;
60
}
61
62