mycdc/mycdc.js

442 lines
11 KiB
JavaScript
Raw Normal View History

require('require-yaml');
require('colors');
const fs = require('fs');
const path = require('path');
2022-10-21 14:36:49 +00:00
const ZongJi = require('./zongji');
const mysql = require('mysql2/promise');
2022-10-23 19:46:07 +00:00
const amqp = require('amqplib');
2022-10-21 14:36:49 +00:00
const allEvents = [
'writerows',
'updaterows',
'deleterows'
];
2022-10-21 14:36:49 +00:00
2022-10-24 06:01:43 +00:00
module.exports = class MyCDC {
constructor() {
2022-10-21 14:37:35 +00:00
this.running = false;
this.filename = null;
this.position = null;
this.schemaMap = new Map();
this.queues = {};
}
2022-10-21 14:37:35 +00:00
async start() {
2022-11-06 12:00:55 +00:00
const defaultConfig = require('./config/producer.yml');
const conf = this.conf = Object.assign({}, defaultConfig);
const localPath = path.join(__dirname, 'config/producer.local.yml');
if (fs.existsSync(localPath)) {
const localConfig = require(localPath);
2022-11-06 12:00:55 +00:00
Object.assign(conf, localConfig);
}
2022-11-06 12:00:55 +00:00
this.queuesConf = require('./config/queues.yml');
2022-11-06 12:00:55 +00:00
const queues = this.queuesConf;
for (const queueName in queues) {
const includeSchema = queues[queueName].includeSchema;
for (const schemaName in includeSchema) {
let tableMap = this.schemaMap.get(schemaName);
if (!tableMap) {
tableMap = new Map();
this.schemaMap.set(schemaName, tableMap);
}
const schema = includeSchema[schemaName];
for (const tableName in schema) {
const table = schema[tableName];
//if (typeof table !== 'object') continue;
let tableInfo = tableMap.get(tableName);
if (!tableInfo) {
tableInfo = {
queues: new Map(),
events: new Map(),
columns: false,
fk: 'id'
};
tableMap.set(tableName, tableInfo);
}
tableInfo.queues.set(queueName, table);
const events = table.events || allEvents;
for (const event of events) {
let eventInfo = tableInfo.events.get(event);
if (!eventInfo) {
eventInfo = [];
tableInfo.events.set(event, eventInfo);
}
eventInfo.push(queueName);
}
const columns = table.columns;
if (columns) {
if (tableInfo.columns === false)
tableInfo.columns = new Set();
if (tableInfo.columns !== true)
for (const column of columns)
tableInfo.columns.add(column);
} else
tableInfo.columns = true;
if (table.id)
tableInfo.id = table.id;
2022-10-21 14:36:49 +00:00
}
this.schemaMap.set(schemaName, tableMap);
2022-10-21 14:36:49 +00:00
}
}
const includeSchema = {};
for (const [schemaName, tableMap] of this.schemaMap)
includeSchema[schemaName] = Array.from(tableMap.keys());
2022-10-21 14:36:49 +00:00
2022-10-23 19:46:07 +00:00
this.opts = {
includeEvents: [
'rotate',
'tablemap',
'writerows',
'updaterows',
'deleterows'
],
2022-10-21 14:37:35 +00:00
includeSchema
};
2022-10-23 19:46:07 +00:00
2022-11-06 12:00:55 +00:00
if (conf.testMode)
2022-10-23 19:46:07 +00:00
console.log('Test mode enabled, just logging queries to console.');
console.log('Starting process.');
await this.init();
console.log('Process started.');
}
async stop() {
console.log('Stopping process.');
await this.end();
console.log('Process stopped.');
}
async init() {
2022-11-06 12:00:55 +00:00
const conf = this.conf;
this.debug('MyCDC', 'Initializing.');
2022-10-23 19:46:07 +00:00
this.onErrorListener = err => this.onError(err);
// DB connection
2022-11-06 12:00:55 +00:00
this.db = await mysql.createConnection(conf.db);
2022-10-23 19:46:07 +00:00
this.db.on('error', this.onErrorListener);
// RabbitMQ
2022-11-06 12:00:55 +00:00
this.publisher = await amqp.connect(conf.amqp);
const channel = this.channel = await this.publisher.createChannel();
2022-11-06 12:00:55 +00:00
for (const tableMap of this.schemaMap.values()) {
for (const tableName of tableMap.keys()) {
await channel.assertExchange(tableName, 'headers', {
2022-11-06 12:00:55 +00:00
durable: true
});
}
}
for (const queueName in this.queuesConf) {
const options = conf.deleteNonEmpty ? {} : {ifEmpty: true};
await channel.deleteQueue(queueName, {options});
await channel.assertQueue(queueName, {
durable: true
});
const includeSchema = this.queuesConf[queueName].includeSchema;
for (const schemaName in includeSchema) {
const schema = includeSchema[schemaName];
for (const tableName in schema) {
const table = schema[tableName];
const events = table.events || allEvents;
for (const event of events) {
let args;
if (event === 'updaterows' && table.columns) {
args = {'x-match': 'any'};
table.columns.map(c => args[c] = true);
} else
args = {'z-event': event};
await channel.bindQueue(queueName, tableName, '', args);
}
}
}
}
2022-10-23 19:46:07 +00:00
// Zongji
2022-11-06 12:00:55 +00:00
const zongji = new ZongJi(conf.db);
2022-10-23 19:46:07 +00:00
this.zongji = zongji;
this.onBinlogListener = evt => this.onBinlog(evt);
zongji.on('binlog', this.onBinlogListener);
2022-10-21 14:37:35 +00:00
const [res] = await this.db.query(
'SELECT `logName`, `position` FROM `binlogQueue` WHERE code = ?',
2022-11-06 12:00:55 +00:00
[conf.code]
2022-10-21 14:37:35 +00:00
);
if (res.length) {
const [row] = res;
this.filename = row.logName;
this.position = row.position;
this.isFlushed = true;
2022-10-23 19:46:07 +00:00
Object.assign(this.opts, {
2022-10-21 14:37:35 +00:00
filename: this.filename,
position: this.position
});
} else
2022-10-23 19:46:07 +00:00
this.opts.startAtEnd = true;
2022-10-21 14:36:49 +00:00
2022-10-23 19:46:07 +00:00
this.debug('Zongji', 'Starting.');
await new Promise((resolve, reject) => {
const onReady = () => {
zongji.off('error', onError);
resolve();
};
const onError = err => {
this.zongji = null;
zongji.off('ready', onReady);
zongji.off('binlog', this.onBinlogListener);
reject(err);
}
2022-10-21 14:36:49 +00:00
2022-10-23 19:46:07 +00:00
zongji.once('ready', onReady);
zongji.once('error', onError);
zongji.start(this.opts);
});
this.debug('Zongji', 'Started.');
2022-10-21 14:37:35 +00:00
2022-10-23 19:46:07 +00:00
this.zongji.on('error', this.onErrorListener);
2022-10-21 14:37:35 +00:00
2022-10-23 19:46:07 +00:00
this.flushInterval = setInterval(
2022-11-06 12:00:55 +00:00
() => this.flushQueue(), conf.flushInterval * 1000);
2022-10-23 19:46:07 +00:00
this.pingInterval = setInterval(
2022-11-06 12:00:55 +00:00
() => this.connectionPing(), conf.pingInterval * 1000);
2022-10-23 19:46:07 +00:00
// Summary
this.running = true;
this.debug('MyCDC', 'Initialized.');
2022-10-21 14:37:35 +00:00
}
2022-10-23 19:46:07 +00:00
async end(silent) {
const zongji = this.zongji;
if (!zongji) return;
this.debug('MyCDC', 'Ending.');
2022-10-23 19:46:07 +00:00
// Zongji
2022-10-21 14:37:35 +00:00
clearInterval(this.flushInterval);
clearInterval(this.pingInterval);
2022-10-23 19:46:07 +00:00
zongji.off('binlog', this.onBinlogListener);
zongji.off('error', this.onErrorListener);
this.zongji = null;
this.running = false;
2022-10-21 14:37:35 +00:00
2022-10-23 19:46:07 +00:00
this.debug('Zongji', 'Stopping.');
// FIXME: Cannot call Zongji.stop(), it doesn't wait to end connection
zongji.connection.destroy(() => {
console.log('zongji.connection.destroy');
});
await new Promise(resolve => {
2022-11-06 12:00:55 +00:00
zongji.ctrlConnection.query('KILL ?', [zongji.connection.threadId],
2022-10-23 19:46:07 +00:00
err => {
2022-11-06 12:00:55 +00:00
if (err && err.code !== 'ER_NO_SUCH_THREAD' && !silent)
2022-10-23 19:46:07 +00:00
console.error(err);
resolve();
});
});
zongji.ctrlConnection.destroy(() => {
console.log('zongji.ctrlConnection.destroy');
});
zongji.emit('stopped');
this.debug('Zongji', 'Stopped.');
2022-10-21 14:37:35 +00:00
2022-10-23 19:46:07 +00:00
// RabbitMQ
2022-10-21 14:37:35 +00:00
2022-10-23 19:46:07 +00:00
await this.publisher.close();
2022-10-21 14:37:35 +00:00
2022-10-23 19:46:07 +00:00
// DB connection
this.db.off('error', this.onErrorListener);
// FIXME: mysql2/promise bug, db.end() ends process
this.db.on('error', () => {});
try {
await this.db.end();
} catch (err) {
if (!silent)
console.error(err);
}
// Summary
this.debug('MyCDC', 'Ended.');
2022-10-21 14:37:35 +00:00
}
2022-10-23 19:46:07 +00:00
async tryRestart() {
try {
await this.init();
console.log('Process restarted.');
} catch(err) {
setTimeout(() => this.tryRestart(), 30);
}
2022-10-21 14:37:35 +00:00
}
async onError(err) {
console.log(`Error: ${err.code}: ${err.message}`);
2022-10-23 19:46:07 +00:00
try {
await this.end(true);
} catch(e) {}
2022-10-21 14:37:35 +00:00
switch (err.code) {
case 'PROTOCOL_CONNECTION_LOST':
case 'ECONNRESET':
2022-10-23 19:46:07 +00:00
console.log('Trying to restart process.');
await this.tryRestart();
2022-10-21 14:37:35 +00:00
break;
default:
process.exit();
2022-10-21 14:36:49 +00:00
}
2022-10-21 14:37:35 +00:00
}
2022-10-21 14:36:49 +00:00
2022-10-21 14:37:35 +00:00
onBinlog(evt) {
//evt.dump();
const eventName = evt.getEventName();
2022-11-06 12:00:55 +00:00
let position = evt.nextPosition;
2022-10-21 14:37:35 +00:00
2022-11-06 12:00:55 +00:00
switch (eventName) {
case 'rotate':
2022-10-21 14:37:35 +00:00
this.filename = evt.binlogName;
2022-11-06 12:00:55 +00:00
position = evt.position;
console.log(`[${eventName}] filename: ${this.filename}`, `position: ${this.position}, nextPosition: ${evt.nextPosition}`);
break;
case 'writerows':
case 'deleterows':
case 'updaterows':
this.onRowEvent(evt, eventName);
break;
2022-10-21 14:36:49 +00:00
}
2022-10-21 14:37:35 +00:00
2022-11-06 12:00:55 +00:00
this.position = position;
this.isFlushed = false;
2022-11-06 12:00:55 +00:00
}
onRowEvent(evt, eventName) {
2022-10-21 14:37:35 +00:00
const table = evt.tableMap[evt.tableId];
2022-11-06 12:00:55 +00:00
const tableName = table.tableName;
2022-10-21 14:37:35 +00:00
const tableMap = this.schemaMap.get(table.parentSchema);
if (!tableMap) return;
2022-11-06 12:00:55 +00:00
const tableInfo = tableMap.get(tableName);
2022-10-21 14:37:35 +00:00
if (!tableInfo) return;
2022-11-06 12:00:55 +00:00
const queues = tableInfo.events.get(eventName);
if (!queues) return;
2022-10-21 14:37:35 +00:00
2022-11-06 12:00:55 +00:00
const isUpdate = eventName === 'updaterows';
let rows;
let cols;
2022-11-06 12:00:55 +00:00
if (isUpdate) {
rows = [];
cols = new Set();
let columns = tableInfo.columns === true
? Object.keys(evt.rows[0].after)
: tableInfo.columns.keys();
2022-10-23 19:46:07 +00:00
2022-11-06 12:00:55 +00:00
for (const row of evt.rows) {
let nColsChanged = 0;
const after = row.after;
for (const col of columns) {
2022-11-06 12:00:55 +00:00
if (after[col] !== undefined
&& !equals(after[col], row.before[col])) {
nColsChanged++;
cols.add(col);
}
}
if (nColsChanged)
rows.push(row);
}
} else
rows = evt.rows;
2022-11-06 12:00:55 +00:00
if (!rows || !rows.length) return;
2022-11-06 12:00:55 +00:00
const data = {
eventName,
table: tableName,
schema: table.parentSchema,
rows
};
let headers = {};
headers['z-event'] = eventName;
2022-11-06 12:00:55 +00:00
if (isUpdate) {
for (const col of cols)
headers[col] = true;
data.cols = Array.from(cols);
2022-10-21 14:36:49 +00:00
}
2022-10-21 14:37:35 +00:00
2022-11-06 12:00:55 +00:00
const options = {
persistent: true,
headers
};
2022-11-06 12:00:55 +00:00
const jsonData = JSON.stringify(data);
this.channel.publish(tableName, '',
Buffer.from(jsonData), options);
2022-11-06 12:00:55 +00:00
if (this.debug) {
// console.debug(data, options);
2022-11-06 12:00:55 +00:00
console.debug('Queued:'.blue,
`${tableName}(${rows.length}) [${eventName}]`);
2022-10-21 14:36:49 +00:00
}
}
2022-10-21 14:37:35 +00:00
async flushQueue() {
if (this.isFlushed) return;
const {filename, position} = this;
this.debug('Flush', `filename: ${filename}, position: ${position}`);
const replaceQuery =
'REPLACE INTO `binlogQueue` SET `code` = ?, `logName` = ?, `position` = ?';
if (!this.conf.testMode)
await this.db.query(replaceQuery, [this.conf.code, filename, position]);
2022-10-23 19:46:07 +00:00
this.isFlushed = true;
2022-10-21 14:36:49 +00:00
}
2022-10-21 14:37:35 +00:00
async connectionPing() {
2022-10-23 19:46:07 +00:00
this.debug('Ping', 'Sending ping to database.');
// FIXME: Should Zongji.connection be pinged?
await new Promise((resolve, reject) => {
this.zongji.ctrlConnection.ping(err => {
if (err) return reject(err);
resolve();
});
})
2022-10-21 14:37:35 +00:00
await this.db.ping();
2022-10-21 14:36:49 +00:00
}
2022-10-23 19:46:07 +00:00
debug(namespace, message) {
2022-11-06 12:00:55 +00:00
if (this.conf.debug)
2022-10-23 19:46:07 +00:00
console.debug(`${namespace}:`.blue, message.yellow);
}
2022-10-21 14:37:35 +00:00
}
function equals(a, b) {
if (a === b)
return true;
const type = typeof a;
if (a == null || b == null || type !== typeof b)
return false;
if (type === 'object' && a.constructor === b.constructor) {
if (a instanceof Date)
return a.getTime() === b.getTime();
}
return false;
}