push: Await and retry supervisor API requests to a local device

Change-type: patch
This commit is contained in:
Paulo Castro 2021-09-09 22:21:14 +01:00
parent a4fc95e99b
commit b30075a18b
2 changed files with 37 additions and 22 deletions

View File

@ -20,6 +20,7 @@ import * as os from 'os';
import * as request from 'request'; import * as request from 'request';
import type * as Stream from 'stream'; import type * as Stream from 'stream';
import { retry } from '../helpers';
import Logger = require('../logger'); import Logger = require('../logger');
import * as ApiErrors from './errors'; import * as ApiErrors from './errors';
@ -260,24 +261,35 @@ export class DeviceAPI {
} }
} }
return new Promise((resolve, reject) => { const doRequest = async () => {
return request(opts, (err, response, body) => { return await new Promise((resolve, reject) => {
if (err) { return request(opts, (err, response, body) => {
return reject(err); if (err) {
} return reject(err);
switch (response.statusCode) { }
case 200: switch (response.statusCode) {
return resolve(body); case 200:
case 400: return resolve(body);
return reject(new ApiErrors.BadRequestDeviceAPIError(body.message)); case 400:
case 503: return reject(
return reject( new ApiErrors.BadRequestDeviceAPIError(body.message),
new ApiErrors.ServiceUnavailableAPIError(body.message), );
); case 503:
default: return reject(
return reject(new ApiErrors.DeviceAPIError(body.message)); new ApiErrors.ServiceUnavailableAPIError(body.message),
} );
default:
return reject(new ApiErrors.DeviceAPIError(body.message));
}
});
}); });
};
return await retry({
func: doRequest,
initialDelayMs: 2000,
maxAttempts: 6,
label: `Supervisor API (${opts.method} ${(opts as any).url})`,
}); });
} }
} }

View File

@ -80,16 +80,19 @@ async function displayDeviceLogs(
jsonStream.on('error', (e) => { jsonStream.on('error', (e) => {
logger.logWarn(`Error parsing NDJSON log chunk: ${e}`); logger.logWarn(`Error parsing NDJSON log chunk: ${e}`);
}); });
logs.once('error', reject); logs.once('error', handleError);
logs.once('end', () => { logs.once('end', handleError);
logs.pipe(jsonStream);
function handleError(error?: Error | string) {
logger.logWarn(DeviceConnectionLostError.defaultMsg); logger.logWarn(DeviceConnectionLostError.defaultMsg);
if (gotSignal) { if (gotSignal) {
reject(new SIGINTError('Log streaming aborted on SIGINT signal')); reject(new SIGINTError('Log streaming aborted on SIGINT signal'));
} else { } else {
reject(new DeviceConnectionLostError()); const msg = typeof error === 'string' ? error : error?.message;
reject(new DeviceConnectionLostError(msg));
} }
}); }
logs.pipe(jsonStream);
}); });
} finally { } finally {
process.removeListener('SIGINT', handleSignal); process.removeListener('SIGINT', handleSignal);