Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
230 lines (200 loc) · 5.77 KB
/
Copy pathserver.ts
File metadata and controls
230 lines (200 loc) · 5.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import { WebSocketServer, WebSocket } from "ws";
import Redis from "ioredis";
import type { SerializedEditorState } from "lexical";
import {
isPeerMessage,
isSyncMessageClient,
} from "@mortenson/lexical-collab-stream";
import type {
PeerMessage,
SyncMessageClient,
SyncMessageServer,
} from "@mortenson/lexical-collab-stream";
import parseArgs from "minimist";
// @todo: run real webserver and have this be in path, or put in every message
// @todo: also put the lastId the client saw in a query param or something
const defaultDocumentId = "documentId";
// The number of messages every stream
const STREAM_COUNT = "10";
// The time between stream reads per client in milliseconds
const STREAM_DELAY_MS = 250;
// The max length of the stream. Set this to a low number to test desync.
const STREAM_MAXLEN = "10000";
console.log("Connecting to Redis...");
const redis = new Redis();
await redis.ping();
console.log("Connected to Redis!");
const args = parseArgs(process.argv.slice(2));
if (args["wipe"]) {
await redis.del(`streams:${defaultDocumentId}`);
await redis.del(`documents:${defaultDocumentId}`);
console.log("Wiped default document from Redis");
}
const wss = new WebSocketServer({ port: 9045, host: "127.0.0.1" });
console.log("Serving websockets on 127.0.0.1:9045");
// Redis operations
type RedisDocument = {
editorState: SerializedEditorState;
lastId: string;
};
// In my head this helps with race conditions, I don't really want to wait for
// a client to give me a document.
let defaultRedisDocument: RedisDocument = {
lastId: "0",
editorState: {
root: {
children: [],
direction: null,
format: "",
indent: 0,
type: "root",
version: 1,
},
},
};
const getDocument = async (documentId: string): Promise<RedisDocument> => {
const document = await redis.get(`documents:${documentId}`);
if (document !== null) {
return JSON.parse(document);
}
return defaultRedisDocument;
};
const setDocument = (
documentId: string,
document: RedisDocument,
): Promise<"OK"> => {
return redis.set(`documents:${documentId}`, JSON.stringify(document));
};
type RedisStreamChunk = {
messages: PeerMessage[];
lastId: string;
firstId: string;
};
const readStreamChunk = async (
documentId: string,
lastId: string,
count: string,
): Promise<null | RedisStreamChunk> => {
const results = await redis.xread(
"COUNT",
count,
"STREAMS",
`streams:${documentId}`,
lastId,
);
if (!results) {
return null;
}
const [_, messagesRaw] = results[0];
const messages: PeerMessage[] = [];
messagesRaw.forEach(([id, messageRaw]) => {
const message: PeerMessage = JSON.parse(messageRaw[1]);
if (!isPeerMessage(message)) {
console.error(`Redis contains non-peer message: ${messageRaw[1]}`);
return;
}
message.streamId = id;
messages.push(message);
});
return {
messages: messages,
lastId: messagesRaw[messagesRaw.length - 1][0],
firstId: messagesRaw[0][0],
};
};
const addtoStream = async (
documentId: string,
message: PeerMessage,
): Promise<string | null> => {
return redis.xadd(
`streams:${documentId}`,
"MAXLEN",
"~",
STREAM_MAXLEN,
"*",
"message",
JSON.stringify(message),
);
};
// Websocket operations
const sendMessage = (ws: WebSocket, message: SyncMessageServer) => {
ws.send(JSON.stringify(message));
};
const sendInitMessage = async (ws: WebSocket, documentId: string) => {
const document = await getDocument(documentId);
const chunk = await readStreamChunk(documentId, "0", "1");
sendMessage(ws, {
type: "init",
editorState: document.editorState,
lastId: document.lastId,
firstId: chunk?.firstId,
});
};
const delay = (time: number) => new Promise((res) => setTimeout(res, time));
const listenForMessage = async (
ws: WebSocket,
documentId: string,
lastId: string,
) => {
// Prevent infinite looping on closed messages.
if (ws.readyState === ws.CLOSED) {
return;
}
const chunk = await readStreamChunk(documentId, lastId, STREAM_COUNT);
if (!chunk || chunk.messages.length === 0) {
await delay(STREAM_DELAY_MS);
await listenForMessage(ws, documentId, lastId);
return;
}
sendMessage(ws, {
type: "peer-chunk",
messages: chunk.messages,
});
await delay(STREAM_DELAY_MS);
await listenForMessage(ws, documentId, chunk.lastId);
};
wss.on("connection", (ws) => {
ws.on("error", (error) => {
console.error(error);
ws.close();
});
ws.on("message", (data, isBinary) => {
const str = data.toString();
if (isBinary) {
console.error(`Unexpected binary message: ${str}`);
return;
}
const clientMessage: SyncMessageClient = JSON.parse(data.toString());
if (!isSyncMessageClient(clientMessage)) {
console.error(`Client sent non-client message: ${str}`);
return;
}
// Some messages are not meant to be broadcast
// @todo Probably should make this clear in types
switch (clientMessage.type) {
// Begin streaming when client is ready.
case "init-received":
listenForMessage(ws, defaultDocumentId, clientMessage.lastId);
return;
// Persist document from whatever client wants us to (YOLO).
case "persist-document":
setDocument(defaultDocumentId, {
editorState: clientMessage.editorState,
lastId: clientMessage.lastId,
});
return;
case "peer-chunk":
clientMessage.messages.forEach((message) => {
if (!isPeerMessage(message)) {
console.error(
`Client sent a non-peer message, possibly trying to spoof other clients: ${message}`,
);
return;
}
addtoStream(defaultDocumentId, message);
});
return;
}
});
sendInitMessage(ws, defaultDocumentId);
});