Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose a function for publishing an event with retries #35

Merged
merged 4 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions lib/api.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { platformForId, isKnownPlatformId } = require('./platform');
const { config } = require('./config');
const { delay } = require('./util');

const Particle = require('particle-api-js');

Expand Down Expand Up @@ -63,6 +64,23 @@ class ApiClient {
return p;
}

async publishEvent(name, data, { retries = 0, retryDelay = 1000 } = {}) {
for (;;) {
try {
await this._api.publishEvent({ name, data, auth: this._token });
break;
} catch (err) {
if (retries <= 0) {
throw err;
}
this._log.warn(`Failed to publish event: ${err.message}\nRetrying in ${retryDelay}ms`);
await delay(retryDelay);
retryDelay *= 2;
--retries;
}
}
}

setTestDevices(devices) {
this._deviceIds = new Set(devices.map(dev => dev.id));
this._events.clear();
Expand Down Expand Up @@ -110,8 +128,19 @@ class ApiClient {
deviceId: 'mine',
auth: this._token
});
this._stream.on('event', event => this._onEvent(event));
this._stream.on('error', error => this._onError(error));
this._stream.on('event', (event) => this._onEvent(event));
this._stream.on('error', (err) => {
this._log.error(`Event stream error: ${err.message}`);
});
this._stream.on('reconnect', () => {
this._log.warn('Event stream is reconnecting');
});
this._stream.on('reconnect-success', () => {
this._log.info('Event stream reconnected');
});
this._stream.on('reconnect-error', (err) => {
this._log.error(`Event stream failed to reconnect: ${err.message}`);
});
}

_onEvent(event) {
Expand Down
1 change: 1 addition & 0 deletions lib/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ class Runner {
log: this._log,
// Convenience functions
receiveEvent: (...args) => this._apiClient.receiveEvent(...args),
publishEvent: (...args) => this._apiClient.publishEvent(...args),
addDeviceTests: (suite, tests) => this._addDeviceTests(suite, tests)
};
this._log.verbose('Running tests');
Expand Down
2 changes: 1 addition & 1 deletion nyc.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = {
branches: 7,
branches: 6,
lines: 10,
functions: 15,
statements: 9
Expand Down