Skip to content

Commit

Permalink
Expose a function for publishing an event with retries; add logging
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeuz committed Jan 29, 2025
1 parent 1be1b31 commit eeae06d
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 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,22 @@ class ApiClient {
return p;
}

async publishEvent(name, data, { retries = 0, retryDelay = 1000 } = {}) {
for (;;) {
try {
await this.particle.apiClient.instance.publishEvent({ name, data, auth: this._token });
} catch (err) {
if (retries <= 0) {
throw err;
}
this._log.warn(`Failed to publish event: ${err.message}\n\tRetrying 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 +127,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', (err) => {

Check failure on line 134 in lib/api.js

View workflow job for this annotation

GitHub Actions / Test (Node.js v12)

Expected error to be handled

Check failure on line 134 in lib/api.js

View workflow job for this annotation

GitHub Actions / Test (Node.js v12)

'err' is defined but never used

Check failure on line 134 in lib/api.js

View workflow job for this annotation

GitHub Actions / Test (Node.js v14)

Expected error to be handled

Check failure on line 134 in lib/api.js

View workflow job for this annotation

GitHub Actions / Test (Node.js v14)

'err' is defined but never used

Check failure on line 134 in lib/api.js

View workflow job for this annotation

GitHub Actions / Test (Node.js v16)

Expected error to be handled

Check failure on line 134 in lib/api.js

View workflow job for this annotation

GitHub Actions / Test (Node.js v16)

'err' is defined but never used
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

0 comments on commit eeae06d

Please sign in to comment.