forked from hakatashi/esolang-battle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.ts
80 lines (68 loc) · 2.02 KB
/
worker.ts
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
// Launch esolang-battle with worker mode.
// This will be combined with polyglot-battle.
import {Mutex} from 'async-mutex';
import dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';
import firebase from 'firebase-admin';
import docker from './engines/docker.js';
dotenvExpand.expand(dotenv.config({path: '.env'}));
const mutex = new Mutex();
firebase.initializeApp({
credential: firebase.credential.applicationDefault(),
databaseURL: 'https://hakatashi.firebaseio.com',
});
const db = firebase.firestore();
const submissionsRef = db.collection('polyglot-battle-submissions');
const dequeue = async () => {
const submissionDoc = await db.runTransaction(async (transaction) => {
const query = submissionsRef
.where('status', '==', 'pending')
.orderBy('createdAt')
.limit(1);
const snapshot = await transaction.get(query);
if (snapshot.size <= 0) {
return null;
}
// eslint-disable-next-line prefer-destructuring
const doc = snapshot.docs[0];
await transaction.update(doc.ref, {
status: 'running',
});
return doc;
});
if (submissionDoc === null) {
return;
}
const submission = submissionDoc.data();
console.log(`Processing ${submissionDoc.id}...`);
console.log(
`date: ${new Date(submission.createdAt._seconds * 1000).toString()}`,
);
console.log(`lang: ${submission.lang}`);
console.log(`code: ${submission.code.slice(0, 50).replace(/\n/g, ' ')}...`);
const result = await docker({
id: submission.lang,
code: Buffer.from(submission.code),
stdin: submission.stdin,
trace: false,
disasm: false,
});
await submissionDoc.ref.update({
stdout: result.stdout.toString(),
stderr: result.stderr.toString(),
duration: result.duration,
error: result.error ? result.error.toString() : null,
status: 'completed',
});
};
(async () => {
const docs = await submissionsRef.listDocuments();
const batch = db.batch();
for (const doc of docs) {
batch.update(doc, {status: 'pending'});
}
await batch.commit();
submissionsRef.onSnapshot(() => {
mutex.runExclusive(dequeue);
});
})();