This repository has been archived by the owner on Jan 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
relay
executable file
·74 lines (64 loc) · 2.62 KB
/
relay
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
#!/usr/bin/env node
'use strict';
// This is a proof of concept. The code below is ugly, inefficient and has no tests.
const CoSocketClient = require('../CoSocket/client');
const fs = require('fs');
const path = require('path');
const uuid4 = require('uuid4');
const yargs = require('yargs');
async function main(argv) {
fs.mkdirSync(argv.incoming, {recursive: true});
fs.mkdirSync(argv.outgoing, {recursive: true});
const client = new CoSocketClient(argv.cosocket);
const outgoingCargoes = generateOutgoingCargoes(argv.incoming);
const deliveredCargoPaths = await client.deliverCargoes(outgoingCargoes);
for (const deliveredCargoPath of deliveredCargoPaths) {
console.log(`Cargo ${deliveredCargoPath} was delivered, so it will now be removed.`);
fs.unlinkSync(deliveredCargoPath);
}
// Allow sufficient time for any responses to arrive
console.log('Cargo delivery complete. Will now wait a few seconds before collecting new cargo.');
await sleep(5);
const collectedCargoes = await client.collectCargoes();
for (const cargoReadable of collectedCargoes) {
const cargoFilePath = path.join(argv.outgoing, `${uuid4()}.cargo`);
console.log(`Saving collected cargo in ${cargoFilePath}`);
const cargoFile = fs.createWriteStream(cargoFilePath);
cargoReadable.pipe(cargoFile);
}
}
function* generateOutgoingCargoes(outgoingCargoDirPath) {
const outgoingCargoPaths = fs.readdirSync(outgoingCargoDirPath).map(f => path.join(argv.incoming, f));
for (const cargoPath of outgoingCargoPaths) {
// We should use fs.createReadStream() in production to avoid loading the entire cargo in memory.
// That'd require yielding the cargo size as well.
const cargoSerialized = fs.readFileSync(cargoPath);
yield [cargoPath, cargoSerialized];
}
}
function sleep(timeoutSeconds) {
return new Promise(resolve => setTimeout(resolve, timeoutSeconds * 1000));
}
const argv = yargs
.option('cosocket', {
demandOption: true,
requiresArg: true,
description: "Path to the gateway's CoSocket socket",
normalize: true,
})
.option('incoming', {
demandOption: true,
requiresArg: true,
description: "Path to the directory containing the cargo(es) to deliver to the gateway",
normalize: true,
})
.option('outgoing', {
demandOption: true,
requiresArg: true,
description: "Path to the directory where the cargo(es) collected from the gateway should be stored",
normalize: true,
})
.help()
.strict()
.argv;
(async () => await main(argv))();