-
Notifications
You must be signed in to change notification settings - Fork 0
/
log-downloader.js
96 lines (71 loc) · 2.39 KB
/
log-downloader.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
const jwt = require('jsonwebtoken');
const fs = require('fs');
class LogDownloader {
constructor(environmentId, keyId, keySecret) {
this.environmentId = environmentId;
this.keyId = keyId;
this.keySecret = typeof keySecret === 'string'
? Buffer.from(keySecret, 'base64') // decode from base64 string
: this.keySecret = keySecret;
}
async download(path, options) {
let continuationToken;
let errorCount = 0;
do {
var params = new URLSearchParams();
if (options.start) {
params.append('start', options.start);
}
if (options.end) {
params.append('end', options.end);
}
if (continuationToken) {
params.append('continuationToken', continuationToken);
}
let url = `https://api.accelerator.net/environments/${this.environmentId}/log?${params}`;
let payload = { url, method: 'GET' };
let header = { type: 'JWT', alg: 'HS256', kid: this.keyId }
let token = jwt.sign(payload, this.keySecret, { header: header, expiresIn: 60 * 5 });
let response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Accept-Encoding': 'gzip'
}
});
if (response.headers.get('x-start')) {
console.log('cursor @', response.headers.get('x-start'));
}
if (!response.ok) {
if (response.headers.get('Content-Type') === 'application/problem+json') {
let problem = await response.json(); // { type, detail, status }
console.log('error', problem);
}
else {
console.log('error', response.status);
errorCount++;
if (errorCount < 10) {
console.log('retrying');
await new Promise((resolve, reject) => {
setTimeout(resolve, 3000);
});
continue;
}
}
return;
}
const fileStream = fs.createWriteStream(path, { flags: 'a' }); // append to the log
var reader = response.body.getReader();
while (true) {
let { done, value } = await reader.read();
if (done) {
break;
}
fileStream.write(value);
}
continuationToken = response.headers.get('continuation-token');
}
while (!!continuationToken);
}
}
module.exports = { LogDownloader };