|
| 1 | +import { Adapter, Room } from "socket.io-adapter"; |
| 2 | +import type { WebSocket } from "uWebSockets.js"; |
| 3 | +import type { Socket } from "./socket.js"; |
| 4 | +import { createReadStream, statSync } from "fs"; |
| 5 | +import debugModule from "debug"; |
| 6 | + |
| 7 | +const debug = debugModule("socket.io:adapter-uws"); |
| 8 | + |
| 9 | +const SEPARATOR = "\x1f"; // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text |
| 10 | + |
| 11 | +const { addAll, del, broadcast } = Adapter.prototype; |
| 12 | + |
| 13 | +export function patchAdapter(app /* : TemplatedApp */) { |
| 14 | + Adapter.prototype.addAll = function (id, rooms) { |
| 15 | + const isNew = !this.sids.has(id); |
| 16 | + addAll.call(this, id, rooms); |
| 17 | + const socket: Socket = this.nsp.sockets.get(id); |
| 18 | + if (!socket) { |
| 19 | + return; |
| 20 | + } |
| 21 | + if (socket.conn.transport.name === "websocket") { |
| 22 | + subscribe(this.nsp.name, socket, isNew, rooms); |
| 23 | + return; |
| 24 | + } |
| 25 | + if (isNew) { |
| 26 | + socket.conn.on("upgrade", () => { |
| 27 | + const rooms = this.sids.get(id); |
| 28 | + subscribe(this.nsp.name, socket, isNew, rooms); |
| 29 | + }); |
| 30 | + } |
| 31 | + }; |
| 32 | + |
| 33 | + Adapter.prototype.del = function (id, room) { |
| 34 | + del.call(this, id, room); |
| 35 | + const socket: Socket = this.nsp.sockets.get(id); |
| 36 | + if (socket && socket.conn.transport.name === "websocket") { |
| 37 | + // @ts-ignore |
| 38 | + const sessionId = socket.conn.id; |
| 39 | + // @ts-ignore |
| 40 | + const websocket: WebSocket = socket.conn.transport.socket; |
| 41 | + const topic = `${this.nsp.name}${SEPARATOR}${room}`; |
| 42 | + debug("unsubscribe connection %s from topic %s", sessionId, topic); |
| 43 | + websocket.unsubscribe(topic); |
| 44 | + } |
| 45 | + }; |
| 46 | + |
| 47 | + Adapter.prototype.broadcast = function (packet, opts) { |
| 48 | + const useFastPublish = opts.rooms.size <= 1 && opts.except!.size === 0; |
| 49 | + if (!useFastPublish) { |
| 50 | + broadcast.call(this, packet, opts); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + const flags = opts.flags || {}; |
| 55 | + const basePacketOpts = { |
| 56 | + preEncoded: true, |
| 57 | + volatile: flags.volatile, |
| 58 | + compress: flags.compress, |
| 59 | + }; |
| 60 | + |
| 61 | + packet.nsp = this.nsp.name; |
| 62 | + const encodedPackets = this.encoder.encode(packet); |
| 63 | + |
| 64 | + const topic = |
| 65 | + opts.rooms.size === 0 |
| 66 | + ? this.nsp.name |
| 67 | + : `${this.nsp.name}${SEPARATOR}${opts.rooms.keys().next().value}`; |
| 68 | + debug("fast publish to %s", topic); |
| 69 | + |
| 70 | + // fast publish for clients connected with WebSocket |
| 71 | + encodedPackets.forEach((encodedPacket) => { |
| 72 | + const isBinary = typeof encodedPacket !== "string"; |
| 73 | + // "4" being the message type in the Engine.IO protocol, see https://github.com/socketio/engine.io-protocol |
| 74 | + app.publish( |
| 75 | + topic, |
| 76 | + isBinary ? encodedPacket : "4" + encodedPacket, |
| 77 | + isBinary |
| 78 | + ); |
| 79 | + }); |
| 80 | + |
| 81 | + this.apply(opts, (socket) => { |
| 82 | + if (socket.conn.transport.name !== "websocket") { |
| 83 | + // classic publish for clients connected with HTTP long-polling |
| 84 | + for (let i = 0; i < encodedPackets.length; i++) { |
| 85 | + socket.client.writeToEngine(encodedPackets[i], basePacketOpts); |
| 86 | + } |
| 87 | + } |
| 88 | + }); |
| 89 | + }; |
| 90 | +} |
| 91 | + |
| 92 | +function subscribe( |
| 93 | + namespaceName: string, |
| 94 | + socket: Socket, |
| 95 | + isNew: boolean, |
| 96 | + rooms: Set<Room> |
| 97 | +) { |
| 98 | + // @ts-ignore |
| 99 | + const sessionId = socket.conn.id; |
| 100 | + // @ts-ignore |
| 101 | + const websocket: WebSocket = socket.conn.transport.socket; |
| 102 | + if (isNew) { |
| 103 | + debug("subscribe connection %s to topic %s", sessionId, namespaceName); |
| 104 | + websocket.subscribe(namespaceName); |
| 105 | + } |
| 106 | + rooms.forEach((room) => { |
| 107 | + const topic = `${namespaceName}${SEPARATOR}${room}`; // '#' can be used as wildcard |
| 108 | + debug("subscribe connection %s to topic %s", sessionId, topic); |
| 109 | + websocket.subscribe(topic); |
| 110 | + }); |
| 111 | +} |
| 112 | + |
| 113 | +export function restoreAdapter() { |
| 114 | + Adapter.prototype.addAll = addAll; |
| 115 | + Adapter.prototype.del = del; |
| 116 | + Adapter.prototype.broadcast = broadcast; |
| 117 | +} |
| 118 | + |
| 119 | +const toArrayBuffer = (buffer: Buffer) => { |
| 120 | + const { buffer: arrayBuffer, byteOffset, byteLength } = buffer; |
| 121 | + return arrayBuffer.slice(byteOffset, byteOffset + byteLength); |
| 122 | +}; |
| 123 | + |
| 124 | +// imported from https://github.com/kolodziejczak-sz/uwebsocket-serve |
| 125 | +export function serveFile(res /* : HttpResponse */, filepath: string) { |
| 126 | + const { size } = statSync(filepath); |
| 127 | + const readStream = createReadStream(filepath); |
| 128 | + const destroyReadStream = () => !readStream.destroyed && readStream.destroy(); |
| 129 | + |
| 130 | + const onError = (error: Error) => { |
| 131 | + destroyReadStream(); |
| 132 | + throw error; |
| 133 | + }; |
| 134 | + |
| 135 | + const onDataChunk = (chunk: Buffer) => { |
| 136 | + const arrayBufferChunk = toArrayBuffer(chunk); |
| 137 | + |
| 138 | + const lastOffset = res.getWriteOffset(); |
| 139 | + const [ok, done] = res.tryEnd(arrayBufferChunk, size); |
| 140 | + |
| 141 | + if (!done && !ok) { |
| 142 | + readStream.pause(); |
| 143 | + |
| 144 | + res.onWritable((offset) => { |
| 145 | + const [ok, done] = res.tryEnd( |
| 146 | + arrayBufferChunk.slice(offset - lastOffset), |
| 147 | + size |
| 148 | + ); |
| 149 | + |
| 150 | + if (!done && ok) { |
| 151 | + readStream.resume(); |
| 152 | + } |
| 153 | + |
| 154 | + return ok; |
| 155 | + }); |
| 156 | + } |
| 157 | + }; |
| 158 | + |
| 159 | + res.onAborted(destroyReadStream); |
| 160 | + readStream |
| 161 | + .on("data", onDataChunk) |
| 162 | + .on("error", onError) |
| 163 | + .on("end", destroyReadStream); |
| 164 | +} |
0 commit comments