Skip to content

Commit

Permalink
Merge pull request #35 from particle-iot/fix/event-retries
Browse files Browse the repository at this point in the history
Expose a function for publishing an event with retries
  • Loading branch information
avtolstoy authored Jan 29, 2025
2 parents 1be1b31 + e400471 commit 04cd0f2
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
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

0 comments on commit 04cd0f2

Please sign in to comment.