-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1133 lines (929 loc) · 37.2 KB
/
main.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 DEBUG = true;
if (DEBUG) console.log('Requiring modules...');
const chokidar = require('chokidar');
if (DEBUG) console.log('chokidar loaded');
const os = require('os');
if (DEBUG) console.log('os loaded');
const {spawn, exec} = require('child_process');
if (DEBUG) console.log('child_process loaded');
const {createClient} = require('@supabase/supabase-js');
if (DEBUG) console.log('supabase-js loaded');
const {v4: uuidv4} = require('uuid');
if (DEBUG) console.log('uuid loaded');
const fs = require("fs");
if (DEBUG) console.log('fs loaded');
const path = require("path");
if (DEBUG) console.log('path loaded');
const fetch = require('node-fetch');
if (DEBUG) console.log('node-fetch loaded');
const cron = require('node-cron');
if (DEBUG) console.log('node-cron loaded');
const https = require('https');
if (DEBUG) console.log('https loaded');
const {randomUUID} = require("crypto");
if (DEBUG) console.log('crypto loaded');
if (DEBUG) console.log('All modules loaded successfully.');
const supabase = createClient('https://jfcurpgmlzlceotuthat.supabase.co', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpmY3VycGdtbHpsY2VvdHV0aGF0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDUwODQ4ODksImV4cCI6MjAyMDY2MDg4OX0.7rAa3V9obXlEhewdRah4unY0apsEPHWEYXk5OwKYkLI');
// Get the correct path for appdata in the current OS
const appDataPath = process.env.APPDATA || (os.platform() == 'darwin' ? path.join(process.env.HOME, 'Library', 'Application Support') : '/var/local');
const nodeFolderPath = path.join(appDataPath, 'Node Server');
const defaultUserID = "38a93bd6-ec88-4b66-a17c-c43f4fc8bcc5";
let userID = "38a93bd6-ec88-4b66-a17c-c43f4fc8bcc5";
async function handleUpdate(installerUrl, installerPath) {
const writer = fs.createWriteStream(installerPath);
const response = await fetch(installerUrl);
if (!response.ok) throw new Error(`Failed to fetch ${installerUrl}: ${response.statusText}`);
response.body.pipe(writer);
await new Promise((resolve, reject) => {
writer.on('finish', () => {
writer.close(); // Close the stream
});
writer.on('close', resolve); // Resolve the promise on stream close
writer.on('error', (error) => {
console.error(`Error writing file: ${error}`);
reject(error);
});
});
console.log('Installer downloaded, starting the update process...');
// Execute the installer
exec(`"${installerPath}" /VERYSILENT`, (err) => {
if (err) {
console.error(`Error executing installer: ${err}`);
return;
}
// Terminate the service
process.exit(0);
});
}
async function checkIfUpdate() {
try {
console.log("cur user: " + userID);
const filePath = path.join(nodeFolderPath, 'version.txt');
const curVersion = fs.readFileSync(filePath, 'utf8');
let {data: server, error} = await supabase
.from('servers')
.select('owner_id, version')
.eq('owner_id', userID)
if (server.length > 0) {
const expectedVersion = server[0].version;
if (expectedVersion != null && expectedVersion != curVersion) {
console.log("update required!");
await getUpdate(expectedVersion)
}
}
}
catch {
console.error("error checking for update");
}
}
async function getUpdate(versionNumber) {
try {
const response = await fetch('https://api.github.com/repos/proshkin/SkedAIServer/releases/tags/' + versionNumber);
if (!response.ok) throw new Error(`Failed to fetch release info: ${response.statusText}`);
const releaseData = await response.json();
const installerUrl = releaseData.assets[0].browser_download_url; // Assuming the installer is the first asset
const versionFilePath = path.join(nodeFolderPath, 'version.txt');
const filename = path.basename(new URL(installerUrl).pathname);
const downloadPath = path.join(nodeFolderPath, filename);
console.log("Update found!");
await handleUpdate(installerUrl, downloadPath);
} catch (error) {
console.error('Error updating:', error);
}
}
async function checkForUpdates() {
try {
const response = await fetch('https://api.github.com/repos/proshkin/SkedAIServer/releases/latest');
if (!response.ok) throw new Error(`Failed to fetch latest release info: ${response.statusText}`);
const releaseData = await response.json();
const latestVersion = releaseData.tag_name;
const installerUrl = releaseData.assets[0].browser_download_url; // Assuming the installer is the first asset
const versionFilePath = path.join(nodeFolderPath, 'version.txt');
const currentVersion = fs.readFileSync(versionFilePath, 'utf8');
// Compare with current version
if (latestVersion !== currentVersion) {
console.log('New version available:', latestVersion);
console.log('URL', installerUrl);
const filename = path.basename(new URL(installerUrl).pathname);
const downloadPath = path.join(nodeFolderPath, filename);
await handleUpdate(installerUrl, downloadPath);
} else {
console.log('No updates found');
}
} catch (error) {
console.error('Error checking for updates:', error);
}
}
// Define the path of the file to watch
const tokenFilePath = path.join(appDataPath, 'Node Server', 'token.txt');
// Initialize watcher
const watcher = chokidar.watch(tokenFilePath, {
persistent: true,
ignoreInitial: false
});
// Add event listeners
watcher
.on('add', path => handleFileChange(path))
.on('change', path => handleFileChange(path));
supabase.auth.onAuthStateChange((event, session) => {
if (event == "TOKEN_REFRESHED") {
writeRefreshedTokens(session.access_token, session.refresh_token);
}
// console.log(event, session);
})
// checkForUpdates();
cron.schedule('0 21 * * *', () => {
console.log('Running scheduled update check...');
checkIfUpdate();
});
async function handleFileChange(path) {
// stopPythonScript;
console.log(`File ${path} has been added or changed`);
try {
const data = fs.readFileSync(path, 'utf8');
if (data.length === 0) {
console.log(`File ${path} is empty. Stopping the service.`);
process.exit(0);
}
let lastPeriodIndex = data.lastIndexOf('.');
let accessToken = data.substring(0, lastPeriodIndex);
let refreshToken = data.substring(lastPeriodIndex + 1);
// console.log("Access Token: " + accessToken + "\nRefresh Token: " + refreshToken);
try {
let curUser = await authenticateUser(accessToken, refreshToken, supabase);
checkIfUpdate();
addServerIfNewUser();
return curUser;
} catch (error) {
console.error('Authentication error:', error);
}
} catch (err) {
console.error(`Error reading file ${path}:`, err);
}
}
async function authenticateUser(accessToken, refreshToken) {
try {
const {session, error} = await supabase.auth.setSession({
access_token: accessToken,
refresh_token: refreshToken,
});
const user = session.user;
userID = user.id;
return user;
} catch (error) {
console.error(error);
}
}
const addServerIfNewUser = async (localServerState) => {
macAddress = localServerState.macAddress;
ipAddress = localServerState.ipAddress;
cpuCores = localServerState.cpuCores;
const serverFilePath = path.join(nodeFolderPath, 'servers.txt');
const prevServer = fs.readFileSync(serverFilePath, 'utf8');
let {data: server, error} = await supabase
.from('servers')
.select('server_id')
.eq('server_id', prevServer)
if (error) {
console.error('Error fetching servers:', error);
return;
}
if (!server || server.length === 0) {
let {error} = await supabase
.from('servers')
.insert([{
server_id: randomUUID(),
mac_address: macAddress,
cpu_cores: cpuCores,
ip_address: ipAddress,
is_user_server: true,
owner_id: userID,
version: 0.1
}]);
if (error) {
console.error('Error inserting server:', error);
}
}
}
async function writeRefreshedTokens(accessToken, refreshToken) {
try {
// ensure the directory exists
// await fs.promises.mkdir(appDataPath, { recursive: true });
const filePath = path.join(nodeFolderPath, 'token.txt');
await fs.promises.writeFile(filePath, accessToken + '.' + refreshToken, {
flag: 'w',
});
const filePath2 = path.join(appDataPath, 'cookie.txt');
const content = fs.readFileSync(filePath2, { encoding: 'utf8' });
let data = JSON.parse(content);
data.access_token = accessToken;
data.refresh_token = refreshToken;
await fs.promises.writeFile(filePath2, JSON.stringify(data, null), {
flag: 'w',
});
} catch (error) {
console.error(error);
}
}
const localServerState = {
macAddress: null,
ipAddress: null,
cpuCores: null
}
function debugLog(msg) {
if (DEBUG) {
// log message with time stamp
console.log(new Date().toLocaleString() + " " + msg);
}
}
function retry(fn, timeout, maxRetries) {
return new Promise((resolve, reject) => {
let attempts = 0;
const tryCall = () => {
fn()
.then(resolve)
.catch((error) => {
attempts += 1;
if (maxRetries === undefined || attempts < maxRetries) {
debugLog(`Retrying in ${timeout / 1000} seconds...`);
setTimeout(tryCall, timeout);
} else {
reject(new Error(`Failed after ${maxRetries} retries: ${error.message}`));
}
});
};
tryCall();
});
}
const getMACAddress = async () => {
const interfaces = os.networkInterfaces();
// check OS type
if (os.type() === 'Darwin') {
if (interfaces.en0?.[0]?.mac) {
return interfaces.en0?.[0]?.mac;
}
throw new Error('MAC address not found for Darwin');
} else if (os.type() === 'Windows_NT') {
if (interfaces['Wi-Fi']?.[1]?.mac) {
return interfaces['Wi-Fi']?.[1]?.mac;
}
throw new Error('MAC address not found for Windows_NT');
} else {
// Linux and other UNIX-like systems
for (const [name, infos] of Object.entries(interfaces)) {
if (name !== 'lo') {
for (const info of infos) {
if (info.mac && info.mac !== '00:00:00:00:00:00') {
return info.mac;
}
}
}
}
}
throw new Error('MAC address not found');
};
const getIPAddress = async () => {
try {
const interfaces = os.networkInterfaces();
const osType = os.type();
if (osType === 'Darwin') {
for (const info of interfaces.en0 || []) {
if (info.family === 'IPv4' && !info.internal) {
return info.address;
}
}
} else if (osType === 'Windows_NT') {
for (const [name, infos] of Object.entries(interfaces)) {
if (name.includes('Wi-Fi') || name.includes('Ethernet')) {
for (const info of infos) {
if (info.family === 'IPv4' && !info.internal) {
return info.address;
}
}
}
}
} else {
// Linux and other UNIX-like systems
for (const [name, infos] of Object.entries(interfaces)) {
if (name !== 'lo') {
for (const info of infos) {
if (info.family === 'IPv4' && !info.internal) {
return info.address;
}
}
}
}
}
throw new Error('No IP address found');
} catch (error) {
console.error("An error occurred while getting the IP address:", error);
throw error;
}
};
// create a new uuid server_id
// const serverId = randomUUID();
// Check if MAC address exists in the list of servers and add if it does not then add it
const addServerIfAbsent = async (localServerState) => {
macAddress = localServerState.macAddress;
ipAddress = localServerState.ipAddress;
cpuCores = localServerState.cpuCores;
debugLog("Checking if server with MAC address " + macAddress + " exists");
let {data: server, error} = await supabase
.from('servers')
.select('mac_address')
.eq('mac_address', macAddress)
if (error) {
console.error('Error fetching servers:', error);
return;
}
if (!server || server.length === 0) {
let {error} = await supabase
.from('servers')
.insert([{
mac_address: macAddress,
cpu_cores: cpuCores,
ip_address: ipAddress,
is_user_server: true,
owner_id: userID
}]);
if (error) {
console.error('Error inserting server:', error);
}
}
}
//create a new solver queue class with some max size
class SolverQueue {
constructor(solverId, maxSize) {
this.solverId = solverId;
this.maxSize = maxSize;
this.runningQueue = [];
this.pendingQueue = [];
console.log("Solver queue created with solver_id: " + solverId + " and max size: " + maxSize);
}
enqueue(modelId) {
// print current status of queue
if (this.runningQueue.length < this.maxSize) {
console.log("adding model to queue");
// print current status of queue
this.runningQueue.push(modelId);
//check if queue is empty
//if empty, run the solver
//else, add to queue
if (this.runningQueue.length === 1) {
console.log("running model");
// set status to running
updateSolverQueueStatus(this.solverId, modelId, "running");
updateModelStatus(modelId, "running");
runCppScript(this.solverId, modelId, 30, 2);
} else {
// set status to queued
updateSolverQueueStatus(this.solverId, modelId, "queued").then(() => {
console.log("Solver status updated");
});
}
} else {
this.dequeue();
this._addPending(modelId);
}
}
_addPending(modelId) {
this.pendingQueue.push(modelId);
updateSolverQueueStatus(this.solverId, modelId, "pending").then(() => {
console.log("Solver status updated");
});
}
dequeue() {
if (this.runningQueue.length > 0) {
// get the solver_id of the first solver in the queue
const modelId = this.runningQueue[0];
// remove the first solver from the queue
this.runningQueue.shift();
// run the solver with the solver_id
terminateSolver(modelId).then(r => {
console.log("Solver terminated");
})
stopCppScript(modelId);
// run the next solver in the queue
if (this.runningQueue.length > 0) {
const nextModelId = this.runningQueue[0];
runCppScript(this.solverId, nextModelId, 30, 2);
}
} else {
console.log("Solver queue empty");
}
}
// remove a specific element matching a given solver_id from the queue and terminate the solver
remove(modelId) {
if (this.runningQueue.length > 0) {
// get the index of the solver_id in the queue
const index = this.runningQueue.indexOf(modelId);
// remove the solver from the queue
this.runningQueue.splice(index, 1);
// terminate the solver
terminateSolver(modelId).then(r => {
console.log("Solver terminated");
})
stopCppScript(modelId);
} else {
console.log("Solver queue empty");
}
}
// when the python script is finished, remove the solver from the queue
async removeOnFinish(modelId) {
console.log("process completed, removing solver from queue");
if (this.runningQueue.length > 0) {
// get the index of the solver_id in the queue
const index = this.runningQueue.indexOf(modelId);
// delete the model / solver from the solver_queue table
console.log(`Attempting to delete model ${modelId} with solver_id ${this.solverId}`);
let {error} = await supabase
.from('solver_queue')
.delete()
.eq('solver_id', this.solverId)
.eq('model_id', modelId);
if (error) {
console.error('Error deleting solver_queue:', error);
}
// remove the solver from the queue
this.runningQueue.splice(index, 1);
// remove the model from the bin directory
if (fs.existsSync(path.join(__dirname, 'bin', modelId + ".gz"))) {
fs.unlinkSync(path.join(__dirname, 'bin', modelId + ".gz"));
}
if (fs.existsSync(path.join(__dirname, 'bin', modelId + ".txt"))) {
fs.unlinkSync(path.join(__dirname, 'bin', modelId + ".txt"));
}
if (fs.existsSync(path.join(__dirname, 'bin', modelId + "_vars.json"))) {
fs.unlinkSync(path.join(__dirname, 'bin', modelId + "_vars.json"));
}
if (fs.existsSync(path.join(__dirname, 'bin', modelId + "_vars_list.json"))) {
fs.unlinkSync(path.join(__dirname, 'bin', modelId + "_vars_list.json"));
}
// set the status of the model to completed
updateModelStatus(modelId, "completed");
} else {
console.log("Solver queue empty");
}
if (this.pendingQueue.length > 0) {
console.log("running next model");
const nextModelId = this.pendingQueue[0];
this.pendingQueue.shift();
this.enqueue(nextModelId);
}
}
// get the current status of the solver
isRunning(modelId) {
if (this.runningQueue.length > 0) {
return this.runningQueue.includes(modelId);
} else {
return false;
}
}
}
// terminate a solver with a given solver_id
const terminateSolver = async (solverId) => {
let {error} = await supabase
.from('solver_queue')
.update({status: "terminated"})
.eq('solver_id', solverId)
if (error) {
console.error('Error terminating solver:', error);
return;
}
}
// define a map of solverQueues based on solver_id
let solverQueues = new Map();
const getServerId = async () => {
let {data: servers, error: fetchError} = await supabase
.from('servers')
.select('server_id')
.eq('mac_address', localServerState.macAddress);
if (fetchError) {
console.error('Error fetching server_id:', fetchError);
throw new Error('Error fetching server_id');
}
if (!servers.length) {
console.error('No server found with the given MAC address:', localServerState.macAddress);
await resetServerAndSolver();
throw new Error('Server reset due to deletion. Re-initializing.');
}
return servers[0].server_id;
}
// set the SolverQueue objects based on the solvers in the DB
const setSolverQueueStructures = async () => {
try {
const serverId = await retry(getServerId, 2000);
let {data: solvers, error} = await supabase
.from('solvers')
.select('solver_id')
.eq('server_id', serverId);
if (error) {
console.error('Error fetching solvers:', error);
return;
}
// for each solver in the solvers array, add it to the solverQueue, it should have a max length of num_instances
for (const solver of solvers) {
const solverId = solver.solver_id;
const numInstances = await getNumInstances(solverId);
solverQueues.set(solverId, new SolverQueue(solverId, numInstances));
}
return solvers.length;
} catch (error) {
console.error("ServerID not found ", error);
}
}
// get the number of instances associated with a solver_id by querying the solvers table
const getNumInstances = async (solverId) => {
let {data: solvers, error} = await supabase
.from('solvers')
.select('num_instances')
.eq('solver_id', solverId);
if (error) {
console.error('Error fetching solvers:', error);
return;
}
return solvers[0].num_instances;
}
// retrieve the auto generated server_id and insert a new row in the solvers table with the server_id
const addSolver = async () => {
const serverId = await retry(getServerId, 2000);
let {error} = await supabase
.from('solvers')
.insert([{server_id: serverId, owner_id: userID}])
if (error) {
console.error('Error inserting solver:', error);
}
}
// get all solvers associated with the current server
const getSolvers = async () => {
const serverId = await retry(getServerId, 2000);
let {data: solvers, error} = await supabase
.from('solvers')
.select('*')
.eq('server_id', serverId);
if (error) {
console.error('Error fetching solvers:', error);
return;
}
console.log("found " + solvers.length + " preexisting solvers");
return solvers;
}
// If there is no solver associated with the current server, if fail attempt to add one every 10 seconds
const addSolverIfAbsent = async () => {
try {
let solvers = await getSolvers();
// check if solvers is defined
if (!solvers) {
console.log("solvers is undefined");
return;
}
if (!solvers.length) {
try {
await addSolver();
console.log("No solver found, added solver");
} catch (error) {
debugLog("Error adding solver, retrying in 10 seconds", error);
setTimeout(addSolverIfAbsent, 10000);
}
}
} catch (error) {
console.error("An error occurred:", error);
}
}
// get the models with status "ready" from the solver_queue table
const getReadyModels = async () => {
const serverId = await retry(getServerId, 2000);
let {data: models, error} = await supabase
.from('solver_queue')
.select('model_id, solver_id')
.eq('status', 'ready')
.eq('server_id', serverId);
if (error) {
console.error('Error fetching models:', error);
return;
}
return models;
}
// check for ready models in the solver_queue table every 1 second
const startCheckForReadyModels = async () => {
setInterval(async () => {
// Fetch models with status "ready"
const readyModels = await getReadyModels();
// console.log(`Found ${readyModels.length} ready models:` + readyModels.map(m => m.model_id).join(', ') + ".");
// Check if there are any ready models, if not, return
if (!readyModels) {
return;
}
// For each ready model, add it to the solver queue
for (const model of readyModels) {
const {model_id, solver_id} = model;
console.log("Solver id: " + solver_id + " Model id: " + model_id);
solverQueues.get(solver_id).enqueue(model_id);
console.log(`Solver ${solver_id} enqueued model ${model_id}`);
}
}, 1000); // Check every 1 second
};
// update the status column of a specific row in the models table with the specified model_id with the given status
const updateModelStatus = async (modelId, status) => {
let {error} = await supabase
.from('models')
.update({status: status})
.eq('model_id', modelId);
if (error) {
console.error('Error updating model status:', error);
}
}
// update the status column of a specific row in the solver_queue table with the specified solver_id and model_id with the output of the python script
const updateSolverQueueStatus = async (solver_id, model_id, output) => {
// update the status of the row in solver_queue with the given solver_id and model_id with the output value given
let {error} = await supabase
.from('solver_queue')
.update({status: output})
.eq('solver_id', solver_id)
.eq('model_id', model_id)
if (error) {
console.error('Error updating solver_queue:', error);
}
// update the updated_at column of a specific row in the solver_queue table with the current server time
// (already done in the trigger function)
}
function deepFlatten(obj) {
let flatArray = [];
for (const key in obj) {
const value = obj[key];
if (Array.isArray(value)) {
flatArray = flatArray.concat(value);
} else if (typeof value === 'object') {
flatArray = flatArray.concat(deepFlatten(value));
} else {
flatArray.push(value);
}
}
// remove all strings from the array
return flatArray.filter(val => typeof val !== 'string');
}
function deepMap(obj, array) {
let counter = 0;
function helper(input) {
if (Array.isArray(input)) {
let arrayVals = input.map(val => typeof val === 'string' ? parseInt(val) : array[counter++])
.filter(val => val !== undefined);
if (arrayVals.length === 3 && arrayVals.every(val => typeof val === 'number')) {
if (arrayVals[2] === 0) {
return undefined;
}
if (arrayVals[2] === 1) {
arrayVals.pop();
} else {
throw new Error(`Invalid is_present value: ${arrayVals[2]}`);
}
}
return arrayVals.length > 0 ? arrayVals : undefined;
} else if (typeof input === 'object' && input !== null) {
const newObj = {};
for (const key in input) {
const value = helper(input[key]);
if (value !== undefined) {
newObj[key] = value;
}
}
return Object.keys(newObj).length > 0 ? newObj : undefined;
} else if (typeof input === 'string') {
return isNaN(parseInt(input)) ? input : parseInt(input);
} else {
return array[counter++];
}
}
const result = helper(obj);
const filteredResult = {};
for (const key in result) {
if (result[key] !== undefined) {
filteredResult[key] = result[key];
}
}
return filteredResult;
}
let cppProcesses = new Map();
const runCppScript = async (solver_id, model_id, duration, interval) => {
// Spawn the C++ process
// let test_model_id = "22931d4b-052f-43d2-8466-617af8de0803";
let test_model_id = "2e7ab3e6-7c06-4c34-9227-a476db3fbda7";
test_model_id = model_id;
const fs = require('fs');
const path = require('path');
let structuredIndexJson = null;
const blobToBuffer = (blob) => {
return new Promise((resolve, reject) => {
const reader = blob.stream().getReader();
const chunks = [];
const pump = () => {
reader.read().then(({value, done}) => {
if (done) {
resolve(Buffer.concat(chunks));
return;
}
chunks.push(Buffer.from(value));
pump();
}).catch(reject);
};
pump();
});
};
const downloadModel = async () => {
let model_extension = ".gz";
let data;
debugLog("Downloading model with gz extension");
let {data: gz_data, error: gz_error} = await supabase.storage
.from('models')
.download(test_model_id + model_extension);
if (gz_error) {
debugLog(`Error downloading model with gz extension: ${gz_error}`);
debugLog("Attempting to download model with txt extension");
let {data: txt_data, error: txt_error} = await supabase.storage
.from('models')
.download(test_model_id + ".txt");
if (txt_error) {
console.error(`Error downloading model with txt extension: ${txt_error}`);
return;
}
debugLog("TXT data download successful, setting data to txt_data");
data = txt_data;
debugLog(!data ? "Data is undefined" : "Success! Data is defined");
} else {
debugLog("GZ data download successful, setting data to gz_data");
data = gz_data;
debugLog(!data ? "Data is undefined" : "Success! Data is defined");
}
if (!data) {
console.error("Data is undefined, exiting");
return;
}
const resolvedData = await blobToBuffer(data);
try {
fs.writeFileSync(path.join(__dirname, 'bin', test_model_id + model_extension), resolvedData);
} catch (err) {
console.error(err);
}
return model_extension;
};
const downloadModelVars = async () => {
const {data, error} = await supabase.storage
.from('models')
.download(`${test_model_id}_vars.json`);
if (error) {
console.error(error);
return;
}
// Convert Blob to Buffer
const resolvedData = await blobToBuffer(data);
// Parse the buffer to JSON
const jsonData = JSON.parse(resolvedData.toString());
structuredIndexJson = jsonData;
console.log("structuredIndexJson", structuredIndexJson);
fs.writeFileSync(path.join(__dirname, 'bin', `${test_model_id}_vars.json`), resolvedData);
const taskList = deepFlatten(jsonData);
// Convert the JSON object back to string
const editedData = taskList.join(',');
// Write the edited JSON back to ./bin folder
fs.writeFileSync(path.join(__dirname, 'bin', `${test_model_id}_vars_list.json`), editedData);
};
// Call the download functions
let model_extension = await downloadModel();
await downloadModelVars();
console.log("Model vars downloaded");
const cppProcess = spawn('./bin/mod_sat_runner', [
'--input=./bin/' + test_model_id + model_extension,
'--callback=./bin/' + test_model_id + '_vars_list.json',
'--print_wait=200',
'--objective_print_wait=3000',
'--params=log_search_progress:false,num_search_workers:8'
]);
const id = solver_id + " " + model_id;
const removeFiles = () => {
if (fs.existsSync(path.join(__dirname, 'bin', test_model_id + model_extension))) {
fs.unlinkSync(path.join(__dirname, 'bin', test_model_id + model_extension));
} else {
console.log(`File ${test_model_id}.txt does not exist`);
}
if (fs.existsSync(path.join(__dirname, 'bin', `${test_model_id}_vars.json`))) {
fs.unlinkSync(path.join(__dirname, 'bin', `${test_model_id}_vars.json`));
} else {
console.log(`File ${test_model_id}_vars.json does not exist`);
}
}
// Listen for data events to capture the output
cppProcess.stdout.on('data', async (data) => {
const outputData = data.toString().trim().split(",");
const time_from_start = outputData[0];
const status = outputData[1]; // 2 == feasible, 4 == optimal
const score = outputData[2];
// get the user_id with the associated model_id