-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanual.js
584 lines (466 loc) · 12.9 KB
/
manual.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
const path = require('path');
const fs = require('fs');
const log = require('inspc');
const express = require('express');
const isObject = require('nlab/isObject');
const isArray = require('nlab/isArray');
const yaml = require('js-yaml');
const {safeDump} = yaml;
require('dotenv-up')(
{
override: false,
deep: 1,
},
true,
'manual'
);
const fixturesTool = require('./test/lr-tree-model/tree-fixtures');
const host = process.env.HOST;
const port = process.env.PORT;
const {Router} = express;
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server); // io
app.use(express.static('.'));
app.use(express.urlencoded({extended: false}));
app.use(express.json());
const knex = require('./src');
knex.init(require('./test/lr-tree-model/config'));
const fixtures = fixturesTool({
// yamlFile: path.resolve(__dirname, './test/lr-tree-model/tree-fixture-sm.yml'),
yamlFile: path.resolve(__dirname, './test/lr-tree-model/tree-fixture-server-test-set.yml'),
knex,
});
const emit = require('./test/lr-tree-model/io')({
io,
});
io.on('connection', (socket) => {
const mtree = knex().model.tree;
function enrich(data) {
if (isArray(data)) {
return data.map((a) => enrich(a));
}
if (isObject(data)) {
return Object.keys(data).reduce((acc, key) => {
acc[key] = enrich(data[key]);
return acc;
}, {});
}
if (typeof data === 'number' || data === null) {
return {
d: data,
v: true,
};
}
return data;
}
function check(list, k = 1, p = '', pid = false, level = 1, operation = {}) {
if (Array.isArray(list)) {
let ii = 0;
for (let i = 0, l = list.length, t, key; i < l; i += 1) {
t = list[i];
if (t.id.d === operation.sourceId) {
t.operation = 'source';
}
if (t.id.d === operation.parentId) {
t.operation = 'parent';
}
let wrong = !(t.sort.d > 0);
if (t.sort.d < 0) {
t.sort.n = true;
}
key = p ? `${p}.${t.id.d}` : t.id.d;
if (t.sort.d > 0 && t.l.d !== k) {
t.l.v = wrong;
}
if (t.sort.d > 0) {
k += 1;
ii += 1;
}
if (Array.isArray(t.children)) {
k = check(t.children, k, key, t.id.d, level + 1, operation);
}
if (t.r.d !== k) {
t.r.v = wrong;
}
if (pid && t.pid.d !== pid) {
t.pid.v = wrong;
}
if (t.level.d !== level) {
t.level.v = wrong;
}
if (t.sort.d !== ii) {
t.sort.v = wrong;
}
if (t.sort.d > 0) {
k += 1;
}
}
}
return k;
}
const checkIntegrity = (function () {
return async (operation) => {
const data = await mtree.treeCheckIntegrity('t.title');
const enriched = enrich(JSON.parse(JSON.stringify(data.tree)));
const checked = JSON.parse(JSON.stringify(enriched));
check(checked, 1, '', false, 1, operation);
emit('tobrowser', {
old: data,
checked,
});
};
})();
console.log('connect..');
socket.on('reset', async (data) => {
try {
const tmp = await fixtures.reset(data);
if (tmp) {
const {operation} = tmp;
if (operation) {
return await checkIntegrity(operation);
}
}
await checkIntegrity();
} catch (e) {
log.dump({
reset_error: e,
});
emit('setstate', {
valid: false,
invalidMsg: e.message,
});
}
});
socket.on('onDelete', async (id) => {
try {
const data = await mtree.treeDelete(id);
await checkIntegrity();
} catch (e) {
log.dump({
delete_error: e,
});
emit('setstate', {
valid: false,
invalidMsg: e.message,
});
}
});
socket.on('onAdd', async (data) => {
const {title, targetId, method, n, extra = {}} = data;
log.dump(
{
onAdd_params: data,
},
3
);
try {
await knex().transaction(async (trx) => {
const sourceId = await mtree.insert(trx, {
title,
});
switch (method) {
case 'treeCreateBefore':
case 'treeCreateAfter':
await mtree[method](trx, {
sourceId,
targetId,
});
break;
case 'treeCreateAsNthChild':
const params = {
sourceId,
parentId: targetId,
};
if (n) {
params.nOneIndexed = n;
}
await mtree.treeCreateAsNthChild(trx, params);
break;
default:
throw new Error(`Method unknown '${method}'`);
}
});
log.dump('inserted');
await checkIntegrity();
} catch (e) {
log.dump(
{
method,
add_error: e,
},
6
);
emit('setstate', {
valid: false,
invalidMsg: e.message,
});
}
});
socket.on('onPaste', async (data) => {
const {sourceId, targetId, method, n, extra = {}} = data;
try {
// await knex().transaction(async trx => {
const trx = false;
switch (method) {
case 'treeMoveBefore':
case 'treeMoveAfter':
await mtree[method](trx, {
sourceId,
targetId,
// strict: true,
});
break;
case 'treeMoveToNthChild':
const params = {
sourceId,
parentId: targetId,
// gate: true,
// strict: true,
};
if (n) {
params.nOneIndexed = n;
}
await mtree.treeMoveToNthChild(trx, params);
break;
default:
throw new Error(`Method unknown '${method}'`);
}
// });
log.dump('inserted');
await checkIntegrity();
} catch (e) {
log.dump(
{
method,
add_error: e,
},
6
);
emit('setstate', {
valid: false,
invalidMsg: e.message,
});
}
});
socket.on('fix', async () => {
try {
await mtree.treeFix();
await checkIntegrity();
} catch (e) {
log.dump({
fix_error: e,
});
emit('setstate', {
valid: false,
invalidMsg: e.message,
});
}
});
socket.on('check', async () => {
try {
await checkIntegrity();
} catch (e) {
log.dump({
check_error: e,
});
emit('setstate', {
valid: false,
invalidMsg: e.message,
});
}
});
(function () {
const toYml = (function () {
function level(data, operation) {
if (isArray(data)) {
return data.map((a) => level(a, operation));
}
if (isObject(data)) {
const d = {};
if (data.id === operation.sourceId) {
d.operation = 'source';
}
if (data.id === operation.parentId) {
d.operation = 'parent';
}
if (data.title) {
d.title = data.title;
}
if (data.children) {
d.children = level(data.children, operation);
}
return d;
}
return data;
}
return function (data, operation) {
try {
const yml = {
operation,
root: level(data.tree, operation)[0],
};
return safeDump(yml);
} catch (e) {
return `catch: toYaml: ` + (e + '');
}
};
})();
socket.on('start', async (on) => {
// log.dump('start', on, ' wtf?');
try {
const man = knex().model.tree;
await knex().transaction(async (trx) => {
const source = await man.queryOne(
trx,
`SELECT * FROM :table: t WHERE t.tlevel > 1 ORDER BY rand() LIMIT 1 FOR UPDATE`
);
// const source = await man.queryOne(trx, `
// (
// SELECT *, '1' origin
// FROM tree t
// WHERE
// (t.tr - t.tl < 2)
// AND (SELECT (tt.tr - tt.tl) diff FROM tree tt WHERE tt.tl = (t.tr + 1) FOR update) < 2
// AND (SELECT (ttt.tr - ttt.tl) diff FROM tree ttt WHERE ttt.tr = (t.tl - 1) FOR update) < 2
// ORDER BY rand()
// )
// UNION
// (
// SELECT *, '2' origin FROM tree FOR update
// )
// ORDER BY origin, RAND()
// LIMIT 1
// `);
if (!source) {
return log.dump({
start_error_l1: 'source not found',
});
}
const logic = async () => {
const countOnTheFirstLevel = await man.queryColumn(
trx,
`select count(*) from :table: t where t.tlevel = 2`
);
let target;
if (countOnTheFirstLevel < 4) {
target = await man.queryOne(trx, `select * from :table: t where t.tlevel = 1 limit 1 FOR UPDATE`);
} else {
target = await man.queryOne(
trx,
`select * FROM tree t where t.tlevel > 1 AND not (t.tl >= :l AND t.tr <= :r) ORDER BY RAND() LIMIT 1 FOR UPDATE`,
{
l: source.tl,
r: source.tr,
}
);
// target = await man.queryOne(trx, `
// (
// SELECT *, '1' origin
// FROM tree t
// where t.tlevel > 1
// AND not (t.tl >= :l AND t.tr <= :r)
// AND (t.tr - t.tl) < 2
// ORDER BY RAND()
// ) UNION (
// SELECT *, '2' origin FROM tree ORDER BY RAND()
// )
// ORDER BY origin, RAND()
// LIMIT 1
// `, {
// l: source.tl,
// r: source.tr,
// });
}
// log.dump({
// t: 'source',
// [source.tid]: source,
// });
if (!target) {
return log.dump({
start_error_l2: 'target not found',
});
}
// log.dump({
// t: 'target',
// [target.tid]: target,
// });
const index = Math.random() < 0.15 ? 1000 : target.tsort;
const operation = {
sourceId: source.tid,
// parentId : target.tparent_id || 1,
parentId: target.tid || 1,
nOneIndexed: index,
};
console.log(
`${(on + '').padStart(3, '0')}: source: ${operation.sourceId} parentId: ${operation.parentId} n: ${index}`
);
const snapshot = await mtree.treeCheckIntegrity(trx, 't.title');
try {
await man.treeMoveToNthChild(trx, operation);
} catch (e) {
// log.dump({
// e
// })
if ((e + '').indexOf(`already at the end because it's "last`) > -1) {
// log.dump({soft_error: on + ': already last'});
} else {
throw e;
}
}
const data = await mtree.treeCheckIntegrity(trx, 't.title');
const {tree, valid, invalidMsg} = data;
let invalid = false;
if (!valid) {
invalid = {
snapshot: toYml(snapshot, operation),
s: snapshot,
operation,
};
}
const enriched = enrich(JSON.parse(JSON.stringify(data.tree)));
const checked = JSON.parse(JSON.stringify(enriched));
check(checked, 1, '', false, 1, operation);
setTimeout(
() =>
emit('flood', {
old: data,
checked,
invalid,
on,
}),
0
); /* delay */
};
let i = 1;
while (i < 5) {
try {
await logic();
break;
} catch (e) {
if ((e + '').indexOf('move element as a child of the same paren') > -1) {
// console.log(`move element as a child of the same paren in ${i} attempt, let's repeat logic`);
} else {
throw e;
}
}
i += 1;
}
});
} catch (e) {
// log.dump({
// start_error: e,
// })
}
});
})();
});
server.listen(
// ... we have to listen on server
port,
host,
undefined, // io -- this extra parameter
() => {
console.log(`\n 🌎 Server is running ${host}:${port}` + '\n');
}
);