|
| 1 | +module.exports = function(postgres, a, b) { |
| 2 | + const listeners = new Map() |
| 3 | + |
| 4 | + let connection |
| 5 | + |
| 6 | + return async function subscribe(event, fn) { |
| 7 | + event = parseEvent(event) |
| 8 | + |
| 9 | + const options = typeof a === 'string' ? b : a || {} |
| 10 | + options.max = 1 |
| 11 | + options.connection = { |
| 12 | + ...options.connection, |
| 13 | + replication: 'database' |
| 14 | + } |
| 15 | + |
| 16 | + const sql = postgres(a, b) |
| 17 | + |
| 18 | + !connection && (subscribe.sql = sql, connection = init(sql, options.publications)) |
| 19 | + |
| 20 | + const fns = listeners.has(event) |
| 21 | + ? listeners.get(event).add(fn) |
| 22 | + : listeners.set(event, new Set([fn])) |
| 23 | + |
| 24 | + const unsubscribe = () => { |
| 25 | + fns.delete(fn) |
| 26 | + fns.size === 0 && listeners.delete(event) |
| 27 | + } |
| 28 | + |
| 29 | + return connection.then(() => ({ unsubscribe })) |
| 30 | + } |
| 31 | + |
| 32 | + async function init(sql, publications = 'alltables') { |
| 33 | + if (!publications) |
| 34 | + throw new Error('Missing publication names') |
| 35 | + |
| 36 | + const slot = 'postgresjs_' + Math.random().toString(36).slice(2) |
| 37 | + const [x] = await sql.unsafe( |
| 38 | + `CREATE_REPLICATION_SLOT ${ slot } TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` |
| 39 | + ) |
| 40 | + |
| 41 | + const stream = sql.unsafe( |
| 42 | + `START_REPLICATION SLOT ${ slot } LOGICAL ${ |
| 43 | + x.consistent_point |
| 44 | + } (proto_version '1', publication_names '${ publications }')` |
| 45 | + ).writable() |
| 46 | + |
| 47 | + const state = { |
| 48 | + lsn: Buffer.concat(x.consistent_point.split('/').map(x => Buffer.from(('00000000' + x).slice(-8), 'hex'))) |
| 49 | + } |
| 50 | + |
| 51 | + stream.on('data', data) |
| 52 | + |
| 53 | + function data(x) { |
| 54 | + if (x[0] === 0x77) |
| 55 | + parse(x.slice(25), state, sql.options.parsers, handle) |
| 56 | + else if (x[0] === 0x6b && x[17]) |
| 57 | + pong() |
| 58 | + } |
| 59 | + |
| 60 | + function handle(a, b) { |
| 61 | + const path = b.relation.schema + '.' + b.relation.table |
| 62 | + call('*', a, b) |
| 63 | + call('*:' + path, a, b) |
| 64 | + b.relation.keys.length && call('*:' + path + '=' + b.relation.keys.map(x => a[x.name]), a, b) |
| 65 | + call(b.command, a, b) |
| 66 | + call(b.command + ':' + path, a, b) |
| 67 | + b.relation.keys.length && call(b.command + ':' + path + '=' + b.relation.keys.map(x => a[x.name]), a, b) |
| 68 | + } |
| 69 | + |
| 70 | + function pong() { |
| 71 | + const x = Buffer.alloc(34) |
| 72 | + x[0] = 'r'.charCodeAt(0) |
| 73 | + x.fill(state.lsn, 1) |
| 74 | + x.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2000, 0, 1)) * BigInt(1000), 25) |
| 75 | + stream.write(x) |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + function call(x, a, b) { |
| 80 | + listeners.has(x) && listeners.get(x).forEach(fn => fn(a, b, x)) |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +function Time(x) { |
| 85 | + return new Date(Date.UTC(2000, 0, 1) + Number(x / BigInt(1000))) |
| 86 | +} |
| 87 | + |
| 88 | +function parse(x, state, parsers, handle) { |
| 89 | + const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc) |
| 90 | + |
| 91 | + Object.entries({ |
| 92 | + R: x => { // Relation |
| 93 | + let i = 1 |
| 94 | + const r = state[x.readInt32BE(i)] = { |
| 95 | + schema: String(x.slice(i += 4, i = x.indexOf(0, i))) || 'pg_catalog', |
| 96 | + table: String(x.slice(i + 1, i = x.indexOf(0, i + 1))), |
| 97 | + columns: Array(x.readInt16BE(i += 2)), |
| 98 | + keys: [] |
| 99 | + } |
| 100 | + i += 2 |
| 101 | + |
| 102 | + let columnIndex = 0 |
| 103 | + , column |
| 104 | + |
| 105 | + while (i < x.length) { |
| 106 | + column = r.columns[columnIndex++] = { |
| 107 | + key: x[i++], |
| 108 | + name: String(x.slice(i, i = x.indexOf(0, i))), |
| 109 | + type: x.readInt32BE(i += 1), |
| 110 | + parser: parsers[x.readInt32BE(i)], |
| 111 | + atttypmod: x.readInt32BE(i += 4) |
| 112 | + } |
| 113 | + |
| 114 | + column.key && r.keys.push(column) |
| 115 | + i += 4 |
| 116 | + } |
| 117 | + }, |
| 118 | + Y: () => { /* noop */ }, // Type |
| 119 | + O: () => { /* noop */ }, // Origin |
| 120 | + B: x => { // Begin |
| 121 | + state.date = Time(x.readBigInt64BE(9)) |
| 122 | + state.lsn = x.slice(1, 9) |
| 123 | + }, |
| 124 | + I: x => { // Insert |
| 125 | + let i = 1 |
| 126 | + const relation = state[x.readInt32BE(i)] |
| 127 | + const row = {} |
| 128 | + tuples(x, row, relation.columns, i += 7) |
| 129 | + |
| 130 | + handle(row, { |
| 131 | + command: 'insert', |
| 132 | + relation |
| 133 | + }) |
| 134 | + }, |
| 135 | + D: x => { // Delete |
| 136 | + let i = 1 |
| 137 | + const relation = state[x.readInt32BE(i)] |
| 138 | + i += 4 |
| 139 | + const key = x[i] === 75 |
| 140 | + const row = key || x[i] === 79 |
| 141 | + ? {} |
| 142 | + : null |
| 143 | + |
| 144 | + tuples(x, row, key ? relation.keys : relation.columns, i += 3) |
| 145 | + |
| 146 | + handle(row, { |
| 147 | + command: 'delete', |
| 148 | + relation, |
| 149 | + key |
| 150 | + }) |
| 151 | + }, |
| 152 | + U: x => { // Update |
| 153 | + let i = 1 |
| 154 | + const relation = state[x.readInt32BE(i)] |
| 155 | + i += 4 |
| 156 | + const key = x[i] === 75 |
| 157 | + const old = key || x[i] === 79 |
| 158 | + ? {} |
| 159 | + : null |
| 160 | + |
| 161 | + old && (i = tuples(x, old, key ? relation.keys : relation.columns, ++i)) |
| 162 | + |
| 163 | + const row = {} |
| 164 | + i = tuples(x, row, relation.columns, i += 3) |
| 165 | + |
| 166 | + handle(row, { |
| 167 | + command: 'update', |
| 168 | + relation, |
| 169 | + key, |
| 170 | + old |
| 171 | + }) |
| 172 | + }, |
| 173 | + T: () => { /* noop */ }, // Truncate, |
| 174 | + C: () => { /* noop */ } // Commit |
| 175 | + }).reduce(char, {})[x[0]](x) |
| 176 | +} |
| 177 | + |
| 178 | +function tuples(x, row, columns, xi) { |
| 179 | + let type |
| 180 | + , column |
| 181 | + |
| 182 | + for (let i = 0; i < columns.length; i++) { |
| 183 | + type = x[xi++] |
| 184 | + column = columns[i] |
| 185 | + row[column.name] = type === 110 // n |
| 186 | + ? null |
| 187 | + : type === 117 // u |
| 188 | + ? undefined |
| 189 | + : column.parser === undefined |
| 190 | + ? x.toString('utf8', xi + 4, xi += 4 + x.readInt32BE(xi)) |
| 191 | + : column.parser.array === true |
| 192 | + ? column.parser(x.toString('utf8', xi + 5, xi += 4 + x.readInt32BE(xi))) |
| 193 | + : column.parser(x.toString('utf8', xi + 4, xi += 4 + x.readInt32BE(xi))) |
| 194 | + } |
| 195 | + |
| 196 | + return xi |
| 197 | +} |
| 198 | + |
| 199 | +function parseEvent(x) { |
| 200 | + const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || [] |
| 201 | + |
| 202 | + if (!xs) |
| 203 | + throw new Error('Malformed subscribe pattern: ' + x) |
| 204 | + |
| 205 | + const [, command, path, key] = xs |
| 206 | + |
| 207 | + return (command || '*') |
| 208 | + + (path ? ':' + (path.indexOf('.') === -1 ? 'public.' + path : path) : '') |
| 209 | + + (key ? '=' + key : '') |
| 210 | +} |
0 commit comments