-
Notifications
You must be signed in to change notification settings - Fork 118
/
index.js
353 lines (304 loc) · 8.74 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
const mysql = require('mysql');
const util = require('util');
const EventEmitter = require('events').EventEmitter;
const initBinlogClass = require('./lib/sequence/binlog');
const ConnectionConfigMap = {
'Connection': obj => obj.config,
'Pool': obj => obj.config.connectionConfig,
};
const TableInfoQueryTemplate = 'SELECT ' +
'COLUMN_NAME, COLLATION_NAME, CHARACTER_SET_NAME, ' +
'COLUMN_COMMENT, COLUMN_TYPE ' +
'FROM information_schema.columns ' + "WHERE table_schema='%s' AND table_name='%s'";
function ZongJi(dsn) {
EventEmitter.call(this);
this._options({});
this._filters({});
this.ctrlCallbacks = [];
this.tableMap = {};
this.ready = false;
this.useChecksum = false;
this._establishConnection(dsn);
}
util.inherits(ZongJi, EventEmitter);
// dsn - can be one instance of Connection or Pool / object / url string
ZongJi.prototype._establishConnection = function(dsn) {
const createConnection = (options) => {
let connection = mysql.createConnection(options);
connection.on('error', this.emit.bind(this, 'error'));
connection.on('unhandledError', this.emit.bind(this, 'error'));
// don't need to call connection.connect() here
// we use implicitly established connection
// see https://github.com/mysqljs/mysql#establishing-connections
return connection;
};
const configFunc = ConnectionConfigMap[dsn.constructor.name];
let binlogDsn;
if (typeof dsn === 'object' && configFunc) {
// dsn is a pool or connection object
let conn = dsn; // reuse as ctrlConnection
this.ctrlConnection = conn;
this.ctrlConnectionOwner = false;
binlogDsn = Object.assign({}, configFunc(conn));
}
if (!binlogDsn) {
// assuming that the object passed is the connection settings
this.ctrlConnectionOwner = true;
this.ctrlConnection = createConnection(dsn);
binlogDsn = dsn;
}
this.connection = createConnection(binlogDsn);
};
ZongJi.prototype._isChecksumEnabled = function(next) {
const SelectChecksumParamSql = 'select @@GLOBAL.binlog_checksum as checksum';
const SetChecksumSql = 'set @master_binlog_checksum=@@global.binlog_checksum';
const query = (conn, sql) => {
return new Promise(
(resolve, reject) => {
conn.query(sql, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
}
);
};
let checksumEnabled = true;
query(this.ctrlConnection, SelectChecksumParamSql)
.then(rows => {
if (rows[0].checksum === 'NONE') {
checksumEnabled = false;
}
if (checksumEnabled) {
return query(this.connection, SetChecksumSql);
}
})
.catch(err => {
if (err.toString().match(/ER_UNKNOWN_SYSTEM_VARIABLE/)) {
checksumEnabled = false;
// a simple query to open this.connection
return query(this.connection, 'SELECT 1');
}
else {
next(err);
}
})
.then(() => {
next(null, checksumEnabled);
});
};
ZongJi.prototype._findBinlogEnd = function(next) {
this.ctrlConnection.query('SHOW BINARY LOGS', (err, rows) => {
if (err) {
// Errors should be emitted
next(err);
}
else {
next(null, rows.length > 0 ? rows[rows.length - 1] : null);
}
});
};
ZongJi.prototype._fetchTableInfo = function(tableMapEvent, next) {
const sql = util.format(TableInfoQueryTemplate,
tableMapEvent.schemaName, tableMapEvent.tableName);
this.ctrlConnection.query(sql, (err, rows) => {
if (err) {
// Errors should be emitted
this.emit('error', err);
// This is a fatal error, no additional binlog events will be
// processed since next() will never be called
return;
}
if (rows.length === 0) {
this.emit('error', new Error(
'Insufficient permissions to access: ' +
tableMapEvent.schemaName + '.' + tableMapEvent.tableName));
// This is a fatal error, no additional binlog events will be
// processed since next() will never be called
return;
}
this.tableMap[tableMapEvent.tableId] = {
columnSchemas: rows,
parentSchema: tableMapEvent.schemaName,
tableName: tableMapEvent.tableName
};
next();
});
};
// #_options will reset all the options.
ZongJi.prototype._options = function({
serverId,
filename,
position,
startAtEnd,
}) {
this.options = {
serverId,
filename,
position,
startAtEnd,
};
};
// #_filters will reset all the filters.
ZongJi.prototype._filters = function({
includeEvents,
excludeEvents,
includeSchema,
excludeSchema,
}) {
this.filters = {
includeEvents,
excludeEvents,
includeSchema,
excludeSchema,
};
};
ZongJi.prototype.get = function(name) {
let result;
if (typeof name === 'string') {
result = this.options[name];
}
else if (Array.isArray(name)) {
result = name.reduce(
(acc, cur) => {
acc[cur] = this.options[cur];
return acc;
},
{}
);
}
return result;
};
// @options contains a list options
// - `serverId` unique identifier
// - `filename`, `position` the position of binlog to beigin with
// - `startAtEnd` if true, will update filename / postion automatically
// - `includeEvents`, `excludeEvents`, `includeSchema`, `exludeSchema` filter different binlog events bubbling
ZongJi.prototype.start = function(options = {}) {
this._options(options);
this._filters(options);
const testChecksum = (resolve, reject) => {
this._isChecksumEnabled((err, checksumEnabled) => {
if (err) {
reject(err);
}
else {
this.useChecksum = checksumEnabled;
resolve();
}
});
};
const findBinlogEnd = (resolve, reject) => {
this._findBinlogEnd((err, result) => {
if (err) {
return reject(err);
}
if (result) {
this._options(
Object.assign({}, options, {
filename: result.Log_name,
position: result.File_size,
})
);
}
resolve();
});
};
const binlogHandler = (error, event) => {
if (error) {
return this.emit('error', error);
}
// Do not emit events that have been filtered out
if (event === undefined || event._filtered === true) return;
switch (event.getTypeName()) {
case 'TableMap': {
const tableMap = this.tableMap[event.tableId];
if (!tableMap) {
this.connection.pause();
this._fetchTableInfo(event, () => {
// merge the column info with metadata
event.updateColumnInfo();
this.emit('binlog', event);
this.connection.resume();
});
return;
}
break;
}
case 'Rotate':
if (this.options.filename !== event.binlogName) {
this.options.filename = event.binlogName;
}
break;
}
this.options.position = event.nextPosition;
this.emit('binlog', event);
};
let promises = [new Promise(testChecksum)];
if (this.options.startAtEnd) {
promises.push(new Promise(findBinlogEnd));
}
Promise.all(promises)
.then(() => {
this.BinlogClass = initBinlogClass(this);
this.ready = true;
this.emit('ready');
this.connection._protocol._enqueue(
new this.BinlogClass(binlogHandler)
);
})
.catch(err => {
this.emit('error', err);
});
};
ZongJi.prototype.stop = function() {
// Binary log connection does not end with destroy()
this.connection.destroy();
this.ctrlConnection.query(
'KILL ' + this.connection.threadId,
() => {
if (this.ctrlConnectionOwner) {
this.ctrlConnection.destroy();
}
this.emit('stopped');
}
);
};
// It includes every events by default.
ZongJi.prototype._skipEvent = function(name) {
const includes = this.filters.includeEvents;
const excludes = this.filters.excludeEvents;
let included = (includes === undefined) ||
(Array.isArray(includes) && (includes.indexOf(name) > -1));
let excluded = Array.isArray(excludes) && (excludes.indexOf(name) > -1);
return excluded || !included;
};
// It doesn't skip any schema by default.
ZongJi.prototype._skipSchema = function(database, table) {
const includes = this.filters.includeSchema;
const excludes = this.filters.excludeSchema || {};
let included = (includes === undefined) ||
(
(database in includes) &&
(
includes[database] === true ||
(
Array.isArray(includes[database]) &&
includes[database].indexOf(table) > -1
)
)
);
let excluded = (database in excludes) &&
(
excludes[database] === true ||
(
Array.isArray(excludes[database]) &&
excludes[database].indexOf(table) > -1
)
);
return excluded || !included;
};
module.exports = ZongJi;