forked from leela-zero/leela-zero-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1696 lines (1430 loc) · 69.2 KB
/
server.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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const moment = require('moment');
const express = require('express');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const fs = require('fs-extra');
const MongoClient = require('mongodb').MongoClient;
const Long = require('mongodb').Long;
const ObjectId = require('mongodb').ObjectID;
const safeObjectId = s => ObjectId.isValid(s) ? new ObjectId(s) : null;
const zlib = require('zlib');
const converter = require('hex2dec');
const Cacheman = require('cacheman');
const app = express();
const Busboy = require('busboy');
const weight_parser = require('./classes/weight_parser.js');
const rss_generator = require('./classes/rss_generator.js');
const os = require("os");
const util = require("util");
const path = require("path");
var auth_key = String(fs.readFileSync(__dirname + "/auth_key")).trim();
var cacheIP24hr = new Cacheman('IP24hr');
var cacheIP1hr = new Cacheman('IP1hr');
var cachematches = new Cacheman('matches');
var fastClientsMap = new Map;
app.set('view engine', 'pug')
// This shouldn't be needed but now and then when I restart test server, I see an uncaught ECONNRESET and I'm not sure
// where it is coming from. In case a server restart did the same thing, this should prevent a crash that would stop nodemon.
//
// It was a bug in nodemon which has now been fixed. It is bad practice to leave this here, eventually remove it.
//
process.on('uncaughtException', (err) => {
console.error('Caught exception: ' + err);
});
// https://blog.tompawlak.org/measure-execution-time-nodejs-javascript
var counter;
var best_network_mtimeMs = 0;
var best_network_hash_promise = null;
var db;
// TODO Make a map to store pending match info, use mapReduce to find who to serve out, only
// delete when SPRT fail or needed games have all arrived? Then we can update stats easily on
// all matches except just the current one (end of queue).
//
var pending_matches = [];
var MATCH_EXPIRE_TIME = 30 * 60 * 1000; // matches expire after 30 minutes. After that the match will be lost and an extra request will be made.
const SI_PREFIXES = ["", "k", "M", "G", "T", "P", "E"];
function network_exists(hash) {
var network_file = __dirname + "/network/" + hash + ".gz";
return !fs.existsSync(network_file);
}
// From https://stackoverflow.com/questions/9461621/how-to-format-a-number-as-2-5k-if-a-thousand-or-more-otherwise-900-in-javascrip
//
function abbreviateNumber(number, length) {
// what tier? (determines SI prefix)
var tier = Math.log10(number) / 3 | 0;
// if zero, we don't need a prefix
if(tier == 0) return number;
// get prefix and determine scale
var prefix = SI_PREFIXES[tier];
var scale = Math.pow(10, tier * 3);
// scale the number
var scaled = number / scale;
// format number and add prefix as suffix
return scaled.toPrecision(length) + prefix;
}
Number.prototype.abbr = function(length) {
return abbreviateNumber(this, length);
};
function CalculateEloFromPercent(percentage) {
return -400 * Math.log(1 / percentage - 1) / Math.LN10;
}
function checksum (str, algorithm, encoding) {
return crypto
.createHash(algorithm || 'md5')
.update(str, 'utf8')
.digest(encoding || 'hex')
}
function seed_from_mongolong (seed) {
return converter.hexToDec(
"0x"
+ (new Uint32Array([seed.getHighBits()]))[0].toString(16)
+ (new Uint32Array([seed.getLowBits()]))[0].toString(16).padStart(8, "0")
).toString();
}
//console.log("Small int test 777: " + seed_from_mongolong(Long.fromString("777", 10)));
//console.log("Broken int test 883863265504794200: " + seed_from_mongolong(Long.fromString("883863265504794200", 10)));
function objectIdFromDate (date) {
//return Math.floor(date.getTime() / 1000).toString(16) + "0000000000000000";
return safeObjectId( Math.floor(date / 1000).toString(16) + "0000000000000000" );
}
// This comes from https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
//
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
function get_options_hash (options) {
if (options.visits) {
return checksum("" + options.visits + options.resignation_percent + options.noise + options.randomcnt).slice(0,6);
} else {
return checksum("" + options.playouts + options.resignation_percent + options.noise + options.randomcnt).slice(0,6);
}
};
async function get_fast_clients () {
return new Promise( (resolve, reject) => {
db.collection("games").aggregate( [
{ $match: { _id: { $gt: objectIdFromDate(Date.now() - 1000 * 60 * 60)}}},
{ $group: { _id: "$ip", total: { $sum: 1 }}},
{ $match: { total: { $gt: 4 }}}
] ).forEach( (match) => {
fastClientsMap.set(match._id, true);
}, (err) => {
if (err) {
console.error("Error fetching matches: " + err);
return reject(err);
}
});
resolve();
});
};
// db.matches.aggregate( [ { "$redact": { "$cond": [ { "$gt": [ "$number_to_play", "$game_count" ] }, "$$KEEP", "$$PRUNE" ] } } ] )
//
async function get_pending_matches () {
pending_matches = [];
return new Promise( (resolve, reject) => {
db.collection("matches").aggregate( [
{ "$redact": { "$cond":
[
{ "$gt": [ "$number_to_play", "$game_count" ] },
"$$KEEP", "$$PRUNE"
] } }
] ).sort({_id:-1}).forEach( (match) => {
match.requests = []; // init request list.
// Client only accepts strings for now
//
Object.keys(match.options).map( (key, index) => {
match.options[key] = String(match.options[key]);
});
// If SPRT=pass use unshift() instead of push() so "elo only" matches go last in priority
//
switch(SPRT(match.network1_wins, match.network1_losses)) {
case false:
break;
case true:
pending_matches.unshift( match );
console.log("SPRT: Unshifting: " + JSON.stringify(match));
break;
default:
pending_matches.push( match );
console.log("SPRT: Pushing: " + JSON.stringify(match));
}
}, (err) => {
if (err) {
console.error("Error fetching matches: " + err);
return reject(err);
}
});
resolve();
});
};
function log_memory_stats (string) {
console.log(string);
const used = process.memoryUsage();
for (let key in used) {
var size = (used[key] / 1024 / 1024).toFixed(2);
size = " ".repeat(6 - size.length) + size;
key += " ".repeat(9 - key.length);
console.log(`\t${key} ${size} MB`);
}
};
async function get_best_network_hash () {
// Check if file has changed. If not, send cached version instead.
//
return fs.stat(__dirname + '/network/best-network.gz')
.then((stats) => {
if (!best_network_hash_promise || best_network_mtimeMs != stats.mtimeMs) {
best_network_mtimeMs = stats.mtimeMs;
best_network_hash_promise = new Promise( (resolve, reject) => {
log_memory_stats("best_network_hash_promise begins");
var rstream = fs.createReadStream(__dirname + '/network/best-network.gz');
var gunzip = zlib.createGunzip();
var hash = crypto.createHash('sha256')
hash.setEncoding('hex');
log_memory_stats("Streams prepared");
rstream
.pipe(gunzip)
.pipe(hash)
.on('error', () => {
console.error("Error opening/gunzip/hash best-network.gz: " + err);
err => reject(err);
})
.on('finish', () => {
var best_network_hash = hash.read();
log_memory_stats("Streams completed: " + best_network_hash);
resolve(best_network_hash);
});
});
}
return best_network_hash_promise;
})
.catch(err => console.error(err));
};
//SPRT
//
function LL (x) {
return 1/(1+10**(-x/400));
}
function LLR(W, L, elo0, elo1) {
//if (W==0 || L==0) return 0;
if (!W) W=1;
if (!L) L=1;
var N = W + L;
var w = W/N, l = L/N;
var s = w;
var m2 = w;
var variance = m2-s**2;
var variance_s = variance / N;
var s0 = LL(elo0);
var s1 = LL(elo1);
return (s1-s0)*(2*s-s0-s1)/variance_s/2.0;
}
//function SPRTold(W,L,elo0,elo1)
function SPRTold(W,L)
{
var elo0 = 0, elo1 = 35;
var alpha = .05, beta = .05;
var LLR_ = LLR(W,L,elo0,elo1);
var LA = Math.log(beta/(1-alpha));
var LB = Math.log((1-beta)/alpha);
if (LLR_ > LB && W + L > 100) {
return true;
} else if (LLR_ < LA) {
return false;
} else {
return null;
}
}
function stDev(n) {
return Math.sqrt(n/4);
}
function canReachLimit(w, l, max, aim) {
var aimPerc = aim/max;
var remaining = max-w-l;
var expected = remaining*aimPerc;
var maxExpected = expected+3*stDev(remaining)
var needed = aim-w;
return maxExpected>needed;
}
function SPRT(w, l) {
var max = 400;
var aim = max / 2 + 2 * stDev(max);
if(w+l>=max&&w/(w+l)>=(aim/max)) return true;
if (!canReachLimit(w, l, max, aim)) return false;
return SPRTold(w,l);
}
var QUEUE_BUFFER = 25;
var PESSIMISTIC_RATE = 0.2;
function how_many_games_to_queue(max_games, w_obs, l_obs, pessimistic_rate) {
var games_left = max_games - w_obs - l_obs;
if (SPRT(w_obs, l_obs) === true) {
return games_left + QUEUE_BUFFER;
}
if (SPRT(w_obs, l_obs) === false) {
return 0;
}
for (var queued_games=0; queued_games < games_left; queued_games++) {
if (SPRT(w_obs+queued_games*pessimistic_rate, l_obs+queued_games*(1-pessimistic_rate)) === false) {
return queued_games + QUEUE_BUFFER;
}
}
return games_left + QUEUE_BUFFER;
}
app.enable('trust proxy');
app.use(bodyParser.urlencoded({extended: true}));
app.use(/\/((?!submit-network).)*/, fileUpload());
app.use('/view/player', express.static('static/eidogo-player-1.2/player'));
app.use('/viewmatch/player', express.static('static/eidogo-player-1.2/player'));
app.use('/view/wgo', express.static('static/wgo'));
app.use('/viewmatch/wgo', express.static('static/wgo'));
app.use('/static', express.static('static', { maxage: '365d', etag: true }));
// This is async but we don't need it to start the server. I'm calling it during startup so it'll get the value cached right away
// instead of when the first /best-network request comes in, in case a lot of those requests come in at once when server
// starts up.
get_best_network_hash().then( (hash) => console.log("Current best hash " + hash) );
setInterval( () => {
get_fast_clients()
.then()
.catch();
}, 1000 * 60 * 10);
var last_match_db_check = Date.now();
setInterval( () => {
var now = Date.now();
// In case we have no matches scheduled, we check the db.
//
if (pending_matches.length === 0 && now > last_match_db_check + 30 * 60 * 1000) {
console.log("No matches scheduled. Updating pending list.");
last_match_db_check = now;
get_pending_matches()
.then()
.catch();
}
}, 1000 * 60 * 1);
MongoClient.connect('mongodb://localhost/test', (err, database) => {
if (err) return console.log(err);
db = database;
db.collection("networks").count()
.then((count) => {
console.log ( count + " networks.");
});
db.collection("networks").aggregate( [
{
$group: {
_id: null,
total: { $sum: "$game_count" }
}
}
], (err, res) => {
if (err) console.log( err );
get_fast_clients()
.then()
.catch();
get_pending_matches()
.then()
.catch();
counter = res[0] && res[0].total;
console.log ( counter + " games.");
app.listen(8080, () => {
console.log('listening on 8080')
});
// Listening to both ports while /next people are moving over to real server adddress
//
// app.listen(8081, () => {
// console.log('listening on 8081')
// });
});
});
// Obsolete
//
app.use('/best-network-hash', asyncMiddleware( async (req, res, next) => {
var hash = await get_best_network_hash();
res.write(hash);
res.write("\n");
// Can remove if autogtp no longer reads this. Required client and leelza versions are in get-task now.
res.write("11");
res.end();
}));
// Server will copy a new best-network to the proper location if validation testing of an uploaded network shows
// it is stronger than the prior network. So we don't need to worry about locking the file/etc when uploading to
// avoid an accidential download of a partial upload.
//
// This is no longer used, as /network/ is served by nginx and best-network.gz downloaded directly from it
//
app.use('/best-network', asyncMiddleware( async (req, res, next) => {
var hash = await get_best_network_hash();
var readStream = fs.createReadStream(__dirname + '/network/best-network.gz');
readStream.on('error', (err) => {
res.send("Error: " + err);
console.error("ERROR /best-network : " + err);
});
readStream.on('open', () => {
res.setHeader('Content-Disposition', 'attachment; filename=' + hash + ".gz");
res.setHeader('Content-Transfer-Encoding', 'binary');
res.setHeader('Content-Type', 'application/octet-stream');
});
readStream.pipe(res);
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " downloaded /best-network");
}));
app.post('/request-match', (req, res) => {
// "number_to_play" : 400, "options" : { "playouts" : 1600, "resignation_percent" : 1, "randomcnt" : 0, "noise" : "false" }
if (!req.body.key || req.body.key != auth_key) {
console.log("AUTH FAIL: '" + String(req.body.key) + "' VS '" + String(auth_key) + "'");
return res.status(400).send('Incorrect key provided.');
}
if (!req.body.network1)
return res.status(400).send('No network1 hash specified.');
else if (network_exists(req.body.network1))
return res.status(400).send('network1 hash not found.');
if (!req.body.network2)
req.body.network2 = null;
else if (network_exists(req.body.network2))
return res.status(400).send('network2 hash not found.');
// TODO Need to support new --visits flag as an alternative to --playouts. Use visits if both are missing? Don't allow both to be set.
//
if (req.body.playouts && req.body.visits)
return res.status(400).send('Please set only playouts or visits, not both');
if (!req.body.playouts && !req.body.visits)
//req.body.playouts = 1600;
req.body.visits = 3200;
//return res.status(400).send('No playouts specified.');
if (!req.body.resignation_percent)
req.body.resignation_percent = 5;
//return res.status(400).send('No resignation_percent specified.');
if (!req.body.noise)
req.body.noise = false;
//return res.status(400).send('No noise specified.');
if (!req.body.randomcnt)
req.body.randomcnt = 0;
//return res.status(400).send('No randomcnt specified.');
if (!req.body.number_to_play)
req.body.number_to_play = 400;
//return res.status(400).send('No number_to_play specified.');
var options = { "resignation_percent": Number(req.body.resignation_percent),
"randomcnt": Number(req.body.randomcnt),
"noise": String(req.body.noise) };
if (req.body.playouts) {
options.playouts = Number(req.body.playouts);
}
if (req.body.visits) {
options.visits = Number(req.body.visits);
}
// Usage:
// - schedule a Test match, set is_test=true
// curl -F is_test=true <other params>
//
// - schedule a Normal match, leave out the flag
// curl <other params>
//
if (req.body.is_test === 'true')
req.body.is_test = true;
else
req.body.is_test = false;
var match = { "network1": req.body.network1,
"network2": req.body.network2, "network1_losses": 0,
"network1_wins": 0,
"game_count": 0, "number_to_play": Number(req.body.number_to_play),
"is_test" : req.body.is_test,
"options": options, "options_hash": get_options_hash(options) };
db.collection("matches").insertOne( match )
.then( () => {
// Client only accepts strings for now
Object.keys(match.options).map( (key, index) => {
match.options[key] = String(match.options[key]);
});
match.requests = []; // init request list.
pending_matches.unshift( match );
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " Match added!");
res.send((match.is_test ? "Test" : "Regular") + " Match added!\n");
console.log("Pending is now: " + JSON.stringify(pending_matches));
} )
.catch( (err) => {
console.error(req.ip + " (" + req.headers['x-real-ip'] + ") " + " ERROR: Match addition failed: " + err);
res.send("ERROR: Match addition failed\n");
} );
});
// curl -F '[email protected]' -F 'training_count=175000' http://localhost:8080/submit-network
//
// Detect if network already exists and if so, inform the uploader and don't overwrite?
// So we don't think the network is newer than it really is. Actually, upsert shouldn't change
// the ObjectID so date will remain original insertion date.
//
app.post('/submit-network', asyncMiddleware((req, res, next) => {
log_memory_stats("submit network start");
var busboy = new Busboy({ headers: req.headers });
req.body = {};
var file_promise = null;
req.pipe(busboy).on('field', (name, value) => {
req.body[name] = value;
}).on('file', (name, file_stream, file_name) => {
if (!req.files)
req.files = {};
if (name != "weights") {
// Not the file we expected, flush the stream and do nothing
//
file_stream.on('readable', file_stream.read);
return;
}
var temp_file = path.join(os.tmpdir(), file_name);
// Pipes
// - file_stream.pipe(fs_stream)
// - file_stream.pipe(gunzip_stream)
// - gunzip_stream.pipe(hasher)
// - gunzip_stream.pipe(parser)
file_promise = new Promise((resolve, reject) => {
var fs_stream = file_stream.pipe(fs.createWriteStream(temp_file)).on('error', reject);
var gunzip_stream = file_stream.pipe(zlib.createGunzip()).on('error', reject);
Promise.all([
new Promise(resolve => {
fs_stream.on('finish', () => { resolve({ path: fs_stream.path }) });
}),
new Promise(resolve => {
var hasher = gunzip_stream.pipe(crypto.createHash('sha256')).on('finish', () => resolve({ hash: hasher.read().toString('hex') }));
}),
new Promise(resolve => {
var parser = gunzip_stream.pipe(new weight_parser).on('finish', () => resolve(parser.read()));
})
]).then(results => {
// consolidate results
results = req.files[name] = Object.assign.apply(null, results);
// Move temp file to network folder with hash name
results.path = path.join(__dirname, "network", results.hash + ".gz");
if (fs.existsSync(temp_file))
fs.moveSync(temp_file, results.path, { overwrite: true });
// We are all done (hash, parse and save file)
resolve();
});
}).catch(err => {
console.error(err);
req.files[name] = { error: err };
// Clean up, flush stream and delete temp file
file_stream.on('readable', file_stream.read);
if (fs.existsSync(temp_file))
fs.removeSync(temp_file);
});
}).on('finish', async () => {
await file_promise;
if (!req.body.key || req.body.key != auth_key) {
console.log("AUTH FAIL: '" + String(req.body.key) + "' VS '" + String(auth_key) + "'");
return res.status(400).send('Incorrect key provided.');
}
if (!req.files || !req.files.weights)
return res.status(400).send('No weights file was uploaded.');
if (req.files.weights.error)
return res.status(400).send(req.files.weights.error.message);
var set = {
hash: req.files.weights.hash,
ip: req.ip,
training_count: +req.body.training_count || null,
training_steps: +req.body.training_steps || null,
filters: req.files.weights.filters,
blocks: req.files.weights.blocks,
description: req.body.description,
};
// No training count given, we'll calculate it from database.
//
if (!set.training_count) {
var cursor = db.collection("networks").aggregate([{ $group: { _id: 1, count: { $sum: "$game_count" } } }]);
var totalgames = await cursor.next();
set.training_count = totalgames.count;
}
// Prepare variables for printing messages
//
var hash = set.hash,
filters = set.filters,
blocks = set.blocks,
training_count = set.training_count
;
db.collection("networks").updateOne(
{ hash: set.hash },
{ $set: set },
{ upsert: true },
(err, dbres) => {
if (err) {
res.end(err.message);
console.error(err);
}
else {
var msg = 'Network weights (' + filters + ' x ' + blocks + ') ' + hash + " (" + training_count + ") " + (dbres.upsertedCount == 0 ? "exists" : "uploaded") + "!";
res.end(msg);
console.log(msg);
log_memory_stats('submit network ends');
}
}
);
});
}));
app.post('/submit-match', asyncMiddleware( async (req, res, next) => {
if (!req.files) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No files were uploaded.');
return res.status(400).send('No files were uploaded.');
}
if (!req.files.sgf) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No sgf file provided.');
return res.status(400).send('No sgf file provided.');
}
if (!req.body.clientversion) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No clientversion specified.');
return res.status(400).send('No clientversion specified.');
}
if (!req.body.winnerhash) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No winnerhash (network hash for winner) specified.');
return res.status(400).send('No winnerhash (network hash for winner) specified.');
}
if (!req.body.loserhash) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No loserhash (network hash for loser) specified.');
return res.status(400).send('No loserhash (network hash for loser) specified.');
}
if (!req.body.winnercolor) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No winnercolor provided.');
return res.status(400).send('No winnercolor provided.');
}
if (!req.body.movescount) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No movescount provided.');
}
if (!req.body.score) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No score provided.');
return res.status(400).send('No score provided.');
}
if (!req.body.options_hash) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + '/submit-match: No options_hash provided.');
return res.status(400).send('No options_hash provided.');
}
if (!req.body.random_seed) {
req.body.random_seed = null;
} else {
req.body.random_seed = Long.fromString(req.body.random_seed, 10);
}
var best_network_hash = await get_best_network_hash();
var new_best_network_flag = false;
var sgfbuffer = Buffer.from(req.files.sgf.data);
zlib.unzip(sgfbuffer, (err, sgfbuffer) => {
if (err) {
console.error("Error decompressing sgffile in /submit-match: " + err);
} else {
var sgffile = sgfbuffer.toString();
var sgfhash = checksum(sgffile, 'sha256');
db.collection("match_games").updateOne(
{ sgfhash: sgfhash },
{ $set: { ip: req.ip, winnerhash: req.body.winnerhash, loserhash: req.body.loserhash, sgf: sgffile,
options_hash: req.body.options_hash,
clientversion: Number(req.body.clientversion), winnercolor: req.body.winnercolor,
movescount: (req.body.movescount ? Number(req.body.movescount) : null),
score: req.body.score,
random_seed: req.body.random_seed
}},
{ upsert: true },
(err, dbres) => {
// Need to catch this better perhaps? Although an error here really is totally unexpected/critical.
//
if (err) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " uploaded match " + sgfhash + " ERROR: " + err);
res.send("Match data " + sgfhash + " stored in database\n");
} else {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " uploaded match " + sgfhash);
res.send("Match data " + sgfhash + " stored in database\n");
}
}
);
// TODO: Check dbres above to see if it was a duplicate, if possible? Then don't update stats below if so.
//
db.collection("matches").updateOne(
{ network1: req.body.winnerhash, network2: req.body.loserhash, options_hash: req.body.options_hash },
{ $inc: { network1_wins: 1, game_count: 1 } },
{ },
(err, dbres) => {
if (err) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " uploaded match " + sgfhash + " INCREMENT ERROR: " + err);
} else {
pending_matches
.filter(e => ((e.network1 === req.body.winnerhash && e.network2 === req.body.loserhash) ||
(e.network2 === req.body.winnerhash && e.network1 === req.body.loserhash)) &&
e.options_hash === req.body.options_hash)
.forEach(match => {
var index = match.requests.findIndex(e => e.seed === seed_from_mongolong(req.body.random_seed));
if (index !== -1) {
match.requests.splice(index, 1); // remove the match from the requests array.
}
match.game_count++;
})
if (dbres.modifiedCount == 0) {
db.collection("matches").updateOne(
{ network1: req.body.loserhash, network2: req.body.winnerhash, options_hash: req.body.options_hash },
{ $inc: { network1_losses: 1, game_count: 1 } },
{ },
(err, dbres) => {
if (err) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " uploaded match " + sgfhash + " INCREMENT ERROR: " + err);
} else {
if (dbres.modifiedCount == 0) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " ERROR: No match found to update from " + JSON.stringify(req.body));
} else {
// network1 was the loser
if (pending_matches.length &&
pending_matches[pending_matches.length - 1].network1 == req.body.loserhash &&
pending_matches[pending_matches.length - 1].network2 == req.body.winnerhash &&
pending_matches[pending_matches.length - 1].options_hash == req.body.options_hash)
{
pending_matches[pending_matches.length - 1].network1_losses++;
// Adding a loss might make us fail SPRT
//
if (SPRT(pending_matches[pending_matches.length - 1].network1_wins,
pending_matches[pending_matches.length - 1].network1_losses) === false)
{
console.log("SPRT: Early fail pop: " + JSON.stringify(pending_matches[pending_matches.length - 1]));
pending_matches.pop();
console.log("SPRT: Early fail post-pop: " + JSON.stringify(pending_matches));
}
}
}
}
}
);
} else {
// network1 was the winner
if (pending_matches.length &&
pending_matches[pending_matches.length - 1].network1 == req.body.winnerhash &&
pending_matches[pending_matches.length - 1].network2 == req.body.loserhash &&
pending_matches[pending_matches.length - 1].options_hash == req.body.options_hash)
{
pending_matches[pending_matches.length - 1].network1_wins++;
// Adding a win might make us pass SPRT.
//
//if (pending_matches.length > 1 &&
if (SPRT(pending_matches[pending_matches.length - 1].network1_wins,
pending_matches[pending_matches.length - 1].network1_losses) === true)
{
// Check > 1 since we'll run to 400 even on a SPRT pass, but will do it at end.
//
if (pending_matches.length > 1)
{
console.log("SPRT: Early pass unshift: "
+ JSON.stringify(pending_matches[pending_matches.length - 1]));
pending_matches.unshift( pending_matches.pop() );
}
// Now, if we are playing vs best_network_hash and we have SPRT pass, promote new network.
//
// Actually if we do async functions in here, we might pop wrong stuff off the queue. Better to just check
// at the end and not try to reduce database lookups?
//
// Ok new problem, during the async stuff later more requests come in and so network2=null matches
// don't face right opponent. Lets do a sync copy if this was in fact a new best network
// situation for the current active match in queue.
//
// added !is_test flag
//
if (req.body.loserhash == best_network_hash && !pending_matches[pending_matches.length - 1].is_test) {
new_best_network_flag = true;
fs.copyFileSync(__dirname + '/network/' + req.body.winnerhash + '.gz', __dirname + '/network/best-network.gz');
console.log("New best network copied from (fast check): " + __dirname + '/network/' + req.body.winnerhash + '.gz');
}
}
} else {
// network1 was the winner but it was no longer at the end of the pending_match queue.
//
}
}
}
}
);
}
});
// Check if network2 == best_network_hash and if so, check SPRT. If SPRT pass, promote network1 as new best-network.
// This is for the case where a match comes in to promote us, after it is no longer the active match in queue.
//
if (!new_best_network_flag && req.body.loserhash == best_network_hash) {
db.collection("matches").findOne({ network1: req.body.winnerhash, network2: best_network_hash, options_hash: req.body.options_hash})
.then((match) => {
// added !is_test flag
//
if (match && !match.is_test && ( (SPRT(match.network1_wins, match.network1_losses) === true) || (match.game_count >= 400 && match.network1_wins / match.game_count >= 0.55) ) ) {
fs.copyFileSync(__dirname + '/network/' + req.body.winnerhash + '.gz', __dirname + '/network/best-network.gz');
console.log("New best network copied from (normal check): " + __dirname + '/network/' + req.body.winnerhash + '.gz');
}
}).catch( err => {
console.log("ERROR: " + req.body.winnerhash + " " + best_network_hash + " " + req.body.options_hash);
console.log("ERROR: Couldn't check for new best network: " + err);
});
}
cachematches.clear( () => { console.log("Cleared match cache."); } );
}));
// curl -F 'networkhash=abc123' -F '[email protected]' http://localhost:8080/submit
// curl -F 'networkhash=abc123' -F '[email protected]' -F '[email protected]' http://localhost:8080/submit
app.post('/submit', (req, res) => {
if (!req.files)
return res.status(400).send('No files were uploaded.');
if (!req.body.networkhash)
return res.status(400).send('No network hash specified.');
if (!req.files.sgf)
return res.status(400).send('No sgf file provided.');
if (!req.files.trainingdata)
return res.status(400).send('No trainingdata file provided.');
if (!req.body.random_seed) {
req.body.random_seed = null;
} else {
req.body.random_seed = Long.fromString(req.body.random_seed, 10);
}
let clientversion;
if (!req.body.clientversion) {
clientversion = 0;
} else {
clientversion = req.body.clientversion;
}
var networkhash = req.body.networkhash;
var trainingdatafile;
var sgffile;
var sgfhash;
var sgfbuffer = Buffer.from(req.files.sgf.data);
var trainbuffer = Buffer.from(req.files.trainingdata.data);
if (req.ip == "xxx") {
res.send("Game data " + sgfhash + " stored in database\n");
console.log("FAKE/SPAM reply sent to " + "xxx" + " (" + req.headers['x-real-ip'] + ")");
} else {
zlib.unzip(sgfbuffer, (err, sgfbuffer) => {
if (err) {
console.error("Error decompressing sgffile: " + err);
} else {
sgffile = sgfbuffer.toString();
sgfhash = checksum(sgffile, 'sha256');
zlib.unzip(trainbuffer, (err, trainbuffer) => {
if (err) {
console.error("Error decompressing trainingdata: " + err);
} else {
trainingdatafile = trainbuffer.toString();
db.collection("games").updateOne(
{ sgfhash: sgfhash },
{ $set: { ip: req.ip, networkhash: networkhash, sgf: sgffile, options_hash: req.body.options_hash,
movescount: (req.body.movescount ? Number(req.body.movescount) : null),
data: trainingdatafile, clientversion: Number(clientversion),
winnercolor: req.body.winnercolor, random_seed: req.body.random_seed }},
{ upsert: true },
(err, dbres) => {
// Need to catch this better perhaps? Although an error here really is totally unexpected/critical.
//
if (err) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " uploaded game #" + counter + ": " + sgfhash + " ERROR: " + err);
res.send("Game data " + sgfhash + " stored in database\n");
} else {
counter++;
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " uploaded game #" + counter + ": " + sgfhash);
res.send("Game data " + sgfhash + " stored in database\n");
}
}
);
db.collection("networks").updateOne(
{ hash: networkhash },
{ $inc: { game_count: 1 } },
{ },
(err, dbres) => {
if (err) {
console.log(req.ip + " (" + req.headers['x-real-ip'] + ") " + " uploaded game #" + counter + ": " + sgfhash + " INCREMENT ERROR: " + err);
} else {
//console.log("Incremented " + networkhash);
}
}
);
}
});
}
});
}
});
app.get('/network-profiles/:hash(\\w+)/:tab(matches|self-play)?', asyncMiddleware(async (req, res, next) => {
var network = await db.collection("networks")
.findOne({ hash: req.params.hash });
if (!network) {
return res.status(404).render("404");
}