|
| 1 | +import type { PublicRuntimeConfig } from 'nuxt/schema' |
| 2 | +import type { NitroApp } from 'nitropack/types' |
| 3 | +import { consola } from 'consola' |
| 4 | +import * as v from 'valibot' |
| 5 | + |
| 6 | +interface Cursor { |
| 7 | + x: number |
| 8 | + y: number |
| 9 | + peerId: string |
| 10 | + avatar_url?: string |
| 11 | + login?: string |
| 12 | +} |
| 13 | + |
| 14 | +const logger = consola.create({}).withTag('WS') |
| 15 | +const topicPageSchema = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.startsWith('page:')) |
| 16 | + |
| 17 | +function myPerformantWS() { |
| 18 | + let nitroApp: NitroApp |
| 19 | + let config: PublicRuntimeConfig['ws'] |
| 20 | + |
| 21 | + function getConfig() { |
| 22 | + if (config) return config |
| 23 | + return config = useRuntimeConfig().public.ws as PublicRuntimeConfig['ws'] |
| 24 | + } |
| 25 | + function getNitroApp() { |
| 26 | + if (nitroApp) return nitroApp |
| 27 | + return nitroApp = useNitroApp() |
| 28 | + } |
| 29 | + |
| 30 | + return defineWebSocketHandler({ |
| 31 | + async open(peer) { |
| 32 | + const config = getConfig() |
| 33 | + const nitroHooks = getNitroApp().hooks |
| 34 | + |
| 35 | + // Automatically subscribe to internal and default topics |
| 36 | + config.topics!.internals!.forEach(topic => peer.subscribe(topic)) |
| 37 | + config.topics!.defaults!.forEach(topic => peer.subscribe(topic)) |
| 38 | + |
| 39 | + // Setup notification hooks |
| 40 | + nitroHooks.hook('ws:publish', (...messages) => { |
| 41 | + for (const { topic, payload } of messages) { |
| 42 | + if (!topic || !payload) continue |
| 43 | + peer.publish(topic, JSON.stringify({ topic, payload }), { compress: true }) |
| 44 | + } |
| 45 | + }) |
| 46 | + |
| 47 | + logger.log('New connection:', peer.id) |
| 48 | + // Update peer with data from storage |
| 49 | + peer.topics.forEach(async (topic) => { |
| 50 | + const payload = await useStorage('ws').getItem(topic) |
| 51 | + if (payload) |
| 52 | + peer.send(JSON.stringify({ topic, payload }), { compress: true }) |
| 53 | + }) |
| 54 | + |
| 55 | + // Send `_internal` communications |
| 56 | + peer.send(JSON.stringify({ |
| 57 | + topic: '_internal', |
| 58 | + payload: { |
| 59 | + connectionId: peer.id, |
| 60 | + }, |
| 61 | + }), { compress: true }) |
| 62 | + |
| 63 | + // Update everyone's session metadata |
| 64 | + const payload = JSON.stringify({ topic: 'session', payload: { users: peer.peers.size } }) |
| 65 | + peer.send(payload, { compress: true }) |
| 66 | + peer.publish('session', payload, { compress: true }) |
| 67 | + }, |
| 68 | + |
| 69 | + async message(peer, message) { |
| 70 | + // Validate channel subscription/unsubscription or cursor update |
| 71 | + const validated = await wsSafeValidateMessage( |
| 72 | + v.union([ |
| 73 | + topicSubUnsub(topicPageSchema), |
| 74 | + topicPublish( |
| 75 | + v.object({ x: v.number(), y: v.number() }), |
| 76 | + topicPageSchema, |
| 77 | + ), |
| 78 | + ]), |
| 79 | + message, |
| 80 | + ) |
| 81 | + // If validation failed, fail silently |
| 82 | + if (validated.issues) return |
| 83 | + const parsedMessage = validated.value |
| 84 | + |
| 85 | + const storage = useStorage('ws') |
| 86 | + |
| 87 | + if (parsedMessage.type === 'subscribe') { |
| 88 | + peer.subscribe(parsedMessage.topic) |
| 89 | + const cursors = await storage.getItem<Cursor[]>(parsedMessage.topic) || [] |
| 90 | + |
| 91 | + if (cursors) |
| 92 | + peer.send(JSON.stringify({ |
| 93 | + topic: parsedMessage.topic, |
| 94 | + payload: cursors, |
| 95 | + }), { compress: true }) |
| 96 | + |
| 97 | + return |
| 98 | + } |
| 99 | + else if (parsedMessage.type === 'unsubscribe') { |
| 100 | + peer.unsubscribe(parsedMessage.topic) |
| 101 | + const cursors = await storage.getItem<Cursor[]>(parsedMessage.topic) |
| 102 | + |
| 103 | + if (cursors) { |
| 104 | + // Remove this peer's cursor from the array |
| 105 | + const updatedCursors = cursors.filter(cursor => cursor.peerId !== peer.id) |
| 106 | + |
| 107 | + // Update storage and notify other peers |
| 108 | + await storage.setItem(parsedMessage.topic, updatedCursors) |
| 109 | + peer.publish(parsedMessage.topic, JSON.stringify({ |
| 110 | + topic: parsedMessage.topic, |
| 111 | + payload: updatedCursors, |
| 112 | + }), { compress: true }) |
| 113 | + } |
| 114 | + |
| 115 | + return |
| 116 | + } |
| 117 | + else if (parsedMessage.type === 'publish') { |
| 118 | + const cursors: Cursor[] = await storage.getItem<Cursor[]>(parsedMessage.topic) || [] |
| 119 | + |
| 120 | + // Find and update existing cursor or add new one |
| 121 | + const cursorIndex = cursors.findIndex(cursor => cursor.peerId === peer.id) |
| 122 | + const updatedCursor: Cursor = { |
| 123 | + x: parsedMessage.payload.x, |
| 124 | + y: parsedMessage.payload.y, |
| 125 | + peerId: peer.id, |
| 126 | + // TODO: Add avatar_url and login |
| 127 | + } |
| 128 | + |
| 129 | + if (cursorIndex >= 0) { |
| 130 | + cursors[cursorIndex] = updatedCursor |
| 131 | + } |
| 132 | + else { |
| 133 | + cursors.push(updatedCursor) |
| 134 | + } |
| 135 | + |
| 136 | + await storage.setItem(parsedMessage.topic, cursors) |
| 137 | + peer.publish(parsedMessage.topic, JSON.stringify({ |
| 138 | + topic: parsedMessage.topic, |
| 139 | + payload: cursors, |
| 140 | + }), { compress: true }) |
| 141 | + } |
| 142 | + }, |
| 143 | + |
| 144 | + async close(peer, details) { |
| 145 | + logger.log('Connection closed:', peer.id, details.code, details.reason) |
| 146 | + |
| 147 | + peer.publish( |
| 148 | + 'session', |
| 149 | + JSON.stringify({ topic: 'session', payload: { users: peer.peers.size } }), |
| 150 | + { compress: true }, |
| 151 | + ) |
| 152 | + |
| 153 | + // Remove the user from all active cursors |
| 154 | + const storage = useStorage('ws') |
| 155 | + |
| 156 | + // Clean up cursor data from all topics this peer was subscribed to |
| 157 | + for (const topic of peer.topics) { |
| 158 | + if (topic.startsWith('page:')) { |
| 159 | + const cursors = await storage.getItem<Cursor[]>(topic) |
| 160 | + if (cursors) { |
| 161 | + const updatedCursors = cursors.filter(cursor => cursor.peerId !== peer.id) |
| 162 | + await storage.setItem(topic, updatedCursors) |
| 163 | + |
| 164 | + // Notify remaining peers |
| 165 | + peer.publish(topic, JSON.stringify({ |
| 166 | + topic, |
| 167 | + payload: updatedCursors, |
| 168 | + }), { compress: true }) |
| 169 | + } |
| 170 | + } |
| 171 | + } |
| 172 | + }, |
| 173 | + |
| 174 | + error(peer, error) { |
| 175 | + logger.error('Peer', peer.id, 'connection error:', error) |
| 176 | + }, |
| 177 | + }) |
| 178 | +} |
| 179 | + |
| 180 | +export default myPerformantWS() |
0 commit comments