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/servers/sync-fs.ts
Views: 687
1
/*
2
Start sync-fs websocket endpoint.
3
4
This listens for connections then streams and extracts a tarball.
5
6
This is how all the real data gets sent back and forth for
7
@cocalc/sync-fs.
8
*/
9
10
import { join } from "node:path";
11
import type { Server } from "http";
12
import { getLogger } from "@cocalc/project/logger";
13
import { WebSocketServer } from "ws";
14
import { parse } from "url";
15
import recvFiles from "@cocalc/sync-fs/lib/recv-files";
16
import sendFiles from "@cocalc/sync-fs/lib/send-files";
17
18
const logger = getLogger("cocalc:project:server:sync-fs");
19
20
export default function initSyncFs(server: Server, basePath: string): void {
21
initReceive(server, basePath);
22
initSend(server, basePath);
23
}
24
25
function initReceive(server, basePath) {
26
const path = join(basePath, ".smc", "sync-fs", "recv");
27
logger.info(`Initializing syncfs-recv server`, path);
28
29
const wss = new WebSocketServer({ noServer: true });
30
wss.on("connection", (ws) => {
31
logger.debug("syncfs-recv server: got new connection");
32
ws.once("message", (mesg) => {
33
// logger.debug("syncfs-recv server: received args", mesg);
34
const args = JSON.parse(mesg.toString());
35
logger.debug("parse", args);
36
recvFiles({ ws, args, HOME: process.env.HOME });
37
});
38
});
39
40
server.on("upgrade", (request, socket, head) => {
41
const { pathname } = parse(request.url ?? "");
42
if (pathname === path) {
43
logger.info("creating new syncfs-recv handler");
44
wss.handleUpgrade(request, socket, head, (ws) => {
45
wss.emit("connection", ws, request);
46
});
47
}
48
});
49
}
50
51
function initSend(server, basePath) {
52
const path = join(basePath, ".smc", "sync-fs", "send");
53
logger.info(`Initializing syncfs-send server`, path);
54
const wss = new WebSocketServer({ noServer: true });
55
56
wss.on("connection", (ws) => {
57
logger.debug("syncfs-send server: got new connection");
58
ws.once("message", (mesg) => {
59
// logger.debug("syncfs-send server: received", mesg);
60
const args = JSON.parse(mesg.toString());
61
logger.debug("parse", args);
62
sendFiles({ ws, args, HOME: process.env.HOME });
63
});
64
});
65
66
server.on("upgrade", (request, socket, head) => {
67
const { pathname } = parse(request.url ?? "");
68
if (pathname === path) {
69
logger.info("creating new syncfs-recv handler");
70
wss.handleUpgrade(request, socket, head, (ws) => {
71
wss.emit("connection", ws, request);
72
});
73
}
74
});
75
}
76
77