|
|
|
@ -14,12 +14,20 @@ await sender.bind(`tcp://127.0.0.1:5557`);
|
|
|
|
|
const receiver = new Pull();
|
|
|
|
|
await receiver.bind(`tcp://127.0.0.1:5558`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const clients: Record<string, FastifyReply> = {};
|
|
|
|
|
const generateId = () => nanoid(32);
|
|
|
|
|
|
|
|
|
|
let updates: Update[] = [];
|
|
|
|
|
let doc = Text.of(["foo"]);
|
|
|
|
|
const rooms: Record<string, WebSocket[]> = {};
|
|
|
|
|
//let updates: Update[] = [];
|
|
|
|
|
//let doc = Text.of(["foo"]);
|
|
|
|
|
|
|
|
|
|
type Room = {
|
|
|
|
|
sockets: WebSocket[];
|
|
|
|
|
updates: Update[];
|
|
|
|
|
doc: Text;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const rooms: Record<string, Room> = {};
|
|
|
|
|
|
|
|
|
|
function send(socket: WebSocket, requestId: number, payload: unknown) {
|
|
|
|
|
const response = {
|
|
|
|
@ -52,31 +60,35 @@ fastify.register(async function (fastify: Fastify) {
|
|
|
|
|
},
|
|
|
|
|
(socket, request) => {
|
|
|
|
|
const { roomId } = request.params;
|
|
|
|
|
let liveClients = rooms[roomId];
|
|
|
|
|
if(!liveClients){
|
|
|
|
|
liveClients = [];
|
|
|
|
|
rooms[roomId] = liveClients;
|
|
|
|
|
let room = rooms[roomId];
|
|
|
|
|
if(!room){
|
|
|
|
|
room = {
|
|
|
|
|
sockets: [],
|
|
|
|
|
updates: [],
|
|
|
|
|
doc: Text.of([''])
|
|
|
|
|
};
|
|
|
|
|
rooms[roomId] = room;
|
|
|
|
|
}
|
|
|
|
|
liveClients.push(socket);
|
|
|
|
|
room.sockets.push(socket);
|
|
|
|
|
socket.on("message", message => {
|
|
|
|
|
const data = JSON.parse(message.toString());
|
|
|
|
|
const requestId = data._request;
|
|
|
|
|
|
|
|
|
|
if (data.type === "pullUpdates") {
|
|
|
|
|
send(socket, requestId, updates.slice(data.version));
|
|
|
|
|
send(socket, requestId, room.updates.slice(data.version));
|
|
|
|
|
} else if (data.type === "pushUpdates") {
|
|
|
|
|
let received = data.updates.map((json: any) => ({
|
|
|
|
|
clientID: json.clientID,
|
|
|
|
|
changes: ChangeSet.fromJSON(json.changes),
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
if (data.version != updates.length) {
|
|
|
|
|
received = rebaseUpdates(received, updates.slice(data.version));
|
|
|
|
|
if (data.version != room.updates.length) {
|
|
|
|
|
received = rebaseUpdates(received, room.updates.slice(data.version));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (let update of received) {
|
|
|
|
|
updates.push(update);
|
|
|
|
|
doc = update.changes.apply(doc);
|
|
|
|
|
room.updates.push(update);
|
|
|
|
|
room.doc = update.changes.apply(room.doc);
|
|
|
|
|
}
|
|
|
|
|
send(
|
|
|
|
|
socket,
|
|
|
|
@ -87,7 +99,7 @@ fastify.register(async function (fastify: Fastify) {
|
|
|
|
|
})),
|
|
|
|
|
);
|
|
|
|
|
} else if (data.type == "getDocument") {
|
|
|
|
|
send(socket, requestId, { version: updates.length, doc: doc.toString() });
|
|
|
|
|
send(socket, requestId, { version: room.updates.length, doc: room.doc.toString() });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|