Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
fix(console): treat runloop timer id 0 as a real pending install retry
Ronald A. Richardson35a6a9a09fdd
diff --git a/console/app/services/installation.js b/console/app/services/installation.jsindex 6b678539..5588d4cd 100644--- a/console/app/services/installation.js+++ b/console/app/services/installation.js@@ -93,7 +93,10 @@ export default class InstallationService extends Service {}async listenForInstallComplete() {- if (this.installChannel || this.listenRetry) {+ // listenRetry holds a runloop timer id, and those are plain integers that can+ // legitimately be 0 — compare against the null sentinel rather than truthiness, or a+ // retry scheduled as timer 0 looks like "nothing pending" and we subscribe twice.+ if (this.installChannel || this.listenRetry !== null) {return;}@@ -121,7 +124,9 @@ export default class InstallationService extends Service {}stopListeningForInstallComplete() {- if (this.listenRetry) {+ // Same reason as above: timer id 0 is falsy but perfectly valid, and skipping the+ // cancel would leave the retry to fire after we have stopped listening.+ if (this.listenRetry !== null) {cancel(this.listenRetry);}@@ -157,6 +162,11 @@ export default class InstallationService extends Service {this.reloadConsole();}+ /* istanbul ignore next -- window.location.reload() cannot be stubbed: the HTML spec+ marks every Location member as an own, non-configurable property, so defineProperty+ throws and calling it for real would reload the test runner. This wrapper exists+ precisely so callers can be tested by replacing reloadConsole() on the instance,+ which the handleInstallCompleteEvent tests do. */reloadConsole() {window.location.reload();}diff --git a/console/app/services/user-verification.js b/console/app/services/user-verification.jsindex c0ff3191..3ad48b1b 100644--- a/console/app/services/user-verification.js+++ b/console/app/services/user-verification.js@@ -18,7 +18,9 @@ export default class UserVerificationService extends Service {@tracked waiting = false;@action start(options = {}) {- this.#wait(options?.timeout ?? 75000);+ // Hand the timer back so callers can cancel it. Without this the 75s wait is+ // unreachable once scheduled and will still fire after its caller has gone away.+ return this.#wait(options?.timeout ?? 75000);}@action didntReceiveCode() {@@ -106,7 +108,9 @@ export default class UserVerificationService extends Service {this.code = code;}- #wait(timeout = 75000) {+ // start() is the only caller and always resolves the timeout itself, so this takes no+ // default of its own.+ #wait(timeout) {return later(this,() => {diff --git a/console/tests/unit/services/installation-test.js b/console/tests/unit/services/installation-test.jsindex 9088218b..3352a00e 100644--- a/console/tests/unit/services/installation-test.js+++ b/console/tests/unit/services/installation-test.js@@ -1,6 +1,53 @@import { module, test } from 'qunit';import Service from '@ember/service';import { setupTest } from '@fleetbase/console/tests/helpers';+import { settled } from '@ember/test-helpers';+import { later } from '@ember/runloop';++/**+ * Builds a socket service whose channel yields the given payloads to the service's+ * `for await` loop, then completes.+ */+function socketStubYielding(payloads = [], onSubscribe = () => {}) {+ return class SocketStub extends Service {+ instance() {+ return {+ subscribe(channelId) {+ onSubscribe(channelId);++ return {+ listener() {+ return { once: () => Promise.resolve() };+ },+ async *[Symbol.asyncIterator]() {+ for (const payload of payloads) {+ yield payload;+ }+ },+ };+ },+ };+ }+ };+}++/**+ * Captures console.warn for the duration of a callback so the service's warning path can be+ * asserted instead of just printed into the test output.+ */+async function captureWarnings(callback) {+ const warnings = [];+ const original = console.warn;+ console.warn = (...args) => warnings.push(args);++ try {+ await callback();+ } finally {+ console.warn = original;+ }++ return warnings;+}module('Unit | Service | installation', function (hooks) {setupTest(hooks);@@ -243,4 +290,271 @@ module('Unit | Service | installation', function (hooks) {assert.true(service.shouldRetrySocketListen(new ReferenceError('socketClusterClient is not defined')));assert.false(service.shouldRetrySocketListen(new Error('socket unavailable')));});++ test('it starts out in an unknown, non-onboarding, non-refreshing state', function (assert) {+ const service = this.owner.lookup('service:installation');++ // Reads the tracked defaults before any request writes over them.+ assert.strictEqual(service.status, 'unknown');+ assert.false(service.shouldOnboard);+ assert.false(service.isRefreshing);+ assert.strictEqual(service.installChannel, null);+ assert.strictEqual(service.listenRetry, null);+ });++ test('a response with no should_onboard flag is treated as not needing onboarding', async function (assert) {+ class FetchStub extends Service {+ get() {+ return Promise.resolve({});+ }+ }++ this.owner.register('service:fetch', FetchStub);++ const service = this.owner.lookup('service:installation');+ const result = await service.checkOnboarding();++ assert.false(result.shouldOnboard, 'an absent flag defaults to false');+ assert.false(result.notConfigured);+ assert.strictEqual(service.status, 'configured');+ });++ test('the install route sends a configured tenant to login when should_onboard is absent', async function (assert) {+ let transitionedTo;++ class FetchStub extends Service {+ get() {+ return Promise.resolve({});+ }+ }++ this.owner.register('service:fetch', FetchStub);++ const service = this.owner.lookup('service:installation');+ Object.defineProperty(service.router, 'transitionTo', {+ configurable: true,+ value: (routeName) => {+ transitionedTo = routeName;+ return 'login-transition';+ },+ });++ await service.redirectIfConfiguredFromInstall();++ assert.strictEqual(transitionedTo, 'auth.login');+ assert.false(service.shouldOnboard);+ });++ test('it rethrows non configuration failures raised from the install route', async function (assert) {+ const expectedError = new Error('server_error');++ class FetchStub extends Service {+ get() {+ return Promise.reject(expectedError);+ }+ }++ this.owner.register('service:fetch', FetchStub);++ const service = this.owner.lookup('service:installation');++ try {+ await service.redirectIfConfiguredFromInstall();+ assert.true(false, 'Expected redirectIfConfiguredFromInstall to reject');+ } catch (error) {+ assert.strictEqual(error, expectedError);+ }++ assert.strictEqual(service.status, 'unknown', 'an unrelated failure says nothing about configuration');+ });++ test('handleError redirects to install for a configuration error and ignores anything else', function (assert) {+ const service = this.owner.lookup('service:installation');++ Object.defineProperty(service.router, 'currentRouteName', { configurable: true, value: 'auth.login' });+ Object.defineProperty(service.router, 'transitionTo', { configurable: true, value: () => 'install-transition' });++ assert.strictEqual(service.handleError({ error: 'fleetbase_not_configured' }), 'install-transition');+ assert.strictEqual(service.status, 'not-configured');++ assert.false(service.handleError(new Error('server_error')), 'other errors are left to bubble');+ });++ test('it does not transition when already sitting on the install route', function (assert) {+ const service = this.owner.lookup('service:installation');+ let transitioned = false;++ Object.defineProperty(service.router, 'currentRouteName', { configurable: true, value: 'install' });+ Object.defineProperty(service.router, 'transitionTo', { configurable: true, value: () => (transitioned = true) });++ assert.true(service.transitionToInstall(), 'reports handled without moving');+ assert.false(transitioned);+ });++ test('it hands socket payloads to the install complete handler', async function (assert) {+ this.owner.register(+ 'service:socket',+ socketStubYielding([+ { event: 'other.event', installed: true },+ { event: 'fleetbase.installed', installed: true },+ ])+ );++ const service = this.owner.lookup('service:installation');+ let reloads = 0;+ service.reloadConsole = () => reloads++;++ await service.listenForInstallComplete();++ assert.strictEqual(reloads, 1, 'only the installed event triggers a reload');+ assert.true(service.isRefreshing);+ });++ test('it does not resubscribe while a channel or retry is already in flight', async function (assert) {+ let subscribes = 0;+ this.owner.register(+ 'service:socket',+ socketStubYielding([], () => subscribes++)+ );++ const service = this.owner.lookup('service:installation');++ service.installChannel = { close() {} };+ await service.listenForInstallComplete();+ assert.strictEqual(subscribes, 0, 'an open channel short-circuits');++ service.installChannel = null;+ service.listenRetry = 'pending-timer';+ await service.listenForInstallComplete();+ assert.strictEqual(subscribes, 0, 'a scheduled retry short-circuits too');++ // Regression guard: runloop timer ids are integers, so a pending retry can be timer+ // 0. Under a truthiness check that read as "nothing scheduled" and resubscribed.+ service.listenRetry = 0;+ await service.listenForInstallComplete();+ assert.strictEqual(subscribes, 0, 'timer id 0 still counts as a pending retry');++ service.listenRetry = null;+ });++ test('it retries listening once the socket client global appears', async function (assert) {+ let attempts = 0;++ class SocketStub extends Service {+ instance() {+ attempts++;++ if (attempts === 1) {+ throw new ReferenceError('socketClusterClient is not defined');+ }++ return {+ subscribe() {+ return {+ listener() {+ return { once: () => Promise.resolve() };+ },+ async *[Symbol.asyncIterator]() {},+ };+ },+ };+ }+ }++ this.owner.register('service:socket', SocketStub);++ const service = this.owner.lookup('service:installation');++ await service.listenForInstallComplete();++ assert.strictEqual(attempts, 1, 'the first attempt failed');+ // Not assert.ok: a runloop timer id is an integer and can be 0.+ assert.notStrictEqual(service.listenRetry, null, 'and a retry was scheduled');+ assert.strictEqual(service.installChannel, null);++ await settled();++ assert.strictEqual(attempts, 2, 'the retry ran');+ assert.strictEqual(service.listenRetry, null, 'and cleared itself');+ assert.ok(service.installChannel, 'the channel is subscribed on the second go');+ });++ test('it warns and gives up on a socket failure it cannot retry', async function (assert) {+ class SocketStub extends Service {+ instance() {+ throw new Error('socket unavailable');+ }+ }++ this.owner.register('service:socket', SocketStub);+ const service = this.owner.lookup('service:installation');++ const warnings = await captureWarnings(() => service.listenForInstallComplete());++ assert.strictEqual(warnings.length, 1);+ assert.strictEqual(warnings[0][0], '[Install] Unable to listen for install completion:');+ assert.strictEqual(service.listenRetry, null, 'no retry is scheduled for an unrelated failure');+ });++ test('it stays silent when the failure arrives after the service is torn down', async function (assert) {+ let rejectSubscribe;++ class SocketStub extends Service {+ instance() {+ return {+ subscribe() {+ return {+ listener() {+ return {+ once() {+ return new Promise((resolve, reject) => {+ rejectSubscribe = reject;+ });+ },+ };+ },+ async *[Symbol.asyncIterator]() {},+ };+ },+ };+ }+ }++ this.owner.register('service:socket', SocketStub);+ const service = this.owner.lookup('service:installation');++ const warnings = await captureWarnings(async () => {+ const pending = service.listenForInstallComplete();+ service.destroy();+ rejectSubscribe(new Error('socket closed during teardown'));+ await pending;+ });++ assert.deepEqual(warnings, [], 'a destroyed service does not log about its own teardown');+ });++ test('stopping cancels a scheduled retry before it can fire', async function (assert) {+ const service = this.owner.lookup('service:installation');+ let fired = false;++ service.listenRetry = later(() => (fired = true), 10);++ service.stopListeningForInstallComplete();++ assert.strictEqual(service.listenRetry, null);++ await new Promise((resolve) => setTimeout(resolve, 40));++ assert.false(fired, 'the cancelled retry never ran');+ });++ test('stopping tolerates a channel that cannot be closed', function (assert) {+ const service = this.owner.lookup('service:installation');++ service.installChannel = {};++ service.stopListeningForInstallComplete();++ assert.strictEqual(service.installChannel, null, 'a channel with no close() is simply dropped');+ });});diff --git a/console/tests/unit/services/user-verification-test.js b/console/tests/unit/services/user-verification-test.jsindex caef18f3..5f16385a 100644--- a/console/tests/unit/services/user-verification-test.js+++ b/console/tests/unit/services/user-verification-test.js@@ -1,7 +1,61 @@import { module, test } from 'qunit';import { setupTest } from '@fleetbase/console/tests/helpers';+import { settled } from '@ember/test-helpers';+import { cancel } from '@ember/runloop';import Service from '@ember/service';+class NotificationsStub extends Service {+ successes = [];+ infos = [];+ errors = [];+ serverErrors = [];++ success(message) {+ this.successes.push(message);+ }+ info(message) {+ this.infos.push(message);+ }+ error(message) {+ this.errors.push(message);+ }+ serverError(error) {+ this.serverErrors.push(error);+ }+}++class ModalsManagerStub extends Service {+ shown = [];++ show(name, options) {+ this.shown.push({ name, options });+ }+}++/**+ * Stands in for the modal instance the confirm() callback is handed, recording the+ * lifecycle calls it makes so the tests can assert the loading/done sequence.+ */+function fakeModal(options = {}) {+ const calls = [];++ return {+ calls,+ startLoading() {+ calls.push('startLoading');+ },+ stopLoading() {+ calls.push('stopLoading');+ },+ done() {+ calls.push('done');+ },+ getOption(key) {+ return options[key];+ },+ };+}+module('Unit | Service | user-verification', function (hooks) {setupTest(hooks);@@ -15,6 +69,19 @@ module('Unit | Service | user-verification', function (hooks) {assert.false(service.ready, 'missing value is treated as empty');});+ test('validateInput reads the value straight off a DOM element', function (assert) {+ const service = this.owner.lookup('service:user-verification');+ const input = document.createElement('input');++ input.value = '123456';+ service.validateInput(input);+ assert.true(service.ready, 'an element is read via its own value property, not event.target');++ input.value = '123';+ service.validateInput(input);+ assert.false(service.ready);+ });+test('didntReceiveCode marks the service waiting', function (assert) {const service = this.owner.lookup('service:user-verification');assert.false(service.waiting);@@ -22,6 +89,32 @@ module('Unit | Service | user-verification', function (hooks) {assert.true(service.waiting);});+ test('start flips the service into waiting once the timeout elapses', async function (assert) {+ const service = this.owner.lookup('service:user-verification');+ assert.false(service.waiting, 'precondition: not waiting yet');++ service.start({ timeout: 1 });+ await settled();++ assert.true(service.waiting, 'the resend options are offered once the wait is up');+ });++ test('start schedules the default wait when no timeout is given', async function (assert) {+ const service = this.owner.lookup('service:user-verification');++ // The default is 75 seconds, so this timer has to be cancelled rather than waited+ // out — left running it fires long after the test container is gone.+ const timer = service.start();++ assert.ok(timer, 'a timer is returned so the caller can cancel it');+ assert.false(service.waiting, 'the default wait has not elapsed');++ cancel(timer);+ await settled();++ assert.false(service.waiting, 'a cancelled wait never fires');+ });+test('setToken and setCode store their values', function (assert) {const service = this.owner.lookup('service:user-verification');service.setToken('tok');@@ -42,11 +135,6 @@ module('Unit | Service | user-verification', function (hooks) {authenticated = t;}}- class NotificationsStub extends Service {- success() {}- info() {}- serverError() {}- }class IntlStub extends Service {t() {return 'Fleetbase';@@ -69,6 +157,10 @@ module('Unit | Service | user-verification', function (hooks) {assert.strictEqual(authenticated, 'auth-token');assert.strictEqual(transitioned, 'console');++ const notifications = this.owner.lookup('service:notifications');+ assert.deepEqual(notifications.successes, ['Email successfully verified!']);+ assert.deepEqual(notifications.infos, ['Welcome to Fleetbase']);});test('verifyCode transitions to login when no token is returned', async function (assert) {@@ -78,11 +170,6 @@ module('Unit | Service | user-verification', function (hooks) {return Promise.resolve({ status: 'ok' });}}- class NotificationsStub extends Service {- success() {}- info() {}- serverError() {}- }this.owner.register('service:fetch', FetchStub);this.owner.register('service:notifications', NotificationsStub);@@ -96,4 +183,211 @@ module('Unit | Service | user-verification', function (hooks) {assert.strictEqual(transitioned, 'auth.login');});++ test('verifyCode sends the stored token and code and stays put on a non-ok status', async function (assert) {+ let payload;+ class FetchStub extends Service {+ post(path, body) {+ payload = { path, body };+ return Promise.resolve({ status: 'invalid' });+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);++ const service = this.owner.lookup('service:user-verification');+ let transitioned = false;+ service.router.transitionTo = () => (transitioned = true);++ service.setToken('tok');+ service.setCode('123456');+ const result = await service.verifyCode.perform();++ assert.strictEqual(payload.path, 'auth/verify-email');+ assert.strictEqual(payload.body.token, 'tok');+ assert.strictEqual(payload.body.code, '123456');+ assert.true(payload.body.authenticate);+ assert.strictEqual(result, undefined, 'nothing is returned for an unverified code');+ assert.false(transitioned, 'and the user is left on the verification screen');+ assert.deepEqual(this.owner.lookup('service:notifications').successes, [], 'no success is reported');+ });++ test('verifyCode reports a failed request as a server error', async function (assert) {+ const failure = new Error('gateway timeout');+ class FetchStub extends Service {+ post() {+ return Promise.reject(failure);+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);++ const service = this.owner.lookup('service:user-verification');++ await service.verifyCode.perform();++ assert.deepEqual(this.owner.lookup('service:notifications').serverErrors, [failure]);+ });++ test('resendBySms opens the phone modal seeded with the current user phone', function (assert) {+ this.owner.register('service:modals-manager', ModalsManagerStub);+ const service = this.owner.lookup('service:user-verification');++ service.resendBySms();++ const { name, options } = this.owner.lookup('service:modals-manager').shown[0];+ assert.strictEqual(name, 'modals/verify-by-sms');+ assert.strictEqual(options.title, 'Verify Account by Phone');+ assert.strictEqual(options.acceptButtonText, 'Send');+ assert.strictEqual(options.phone, service.currentUser.phone, 'the modal is seeded from the signed-in user');+ });++ test('confirming the sms modal sends the code and closes the modal', async function (assert) {+ let request;+ class FetchStub extends Service {+ post(path, body) {+ request = { path, body };+ return Promise.resolve({});+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:modals-manager', ModalsManagerStub);++ const service = this.owner.lookup('service:user-verification');+ service.resendBySms();++ const modal = fakeModal({ phone: '+15550001111' });+ await this.owner.lookup('service:modals-manager').shown[0].options.confirm(modal);++ assert.strictEqual(request.path, 'onboard/send-verification-sms');+ assert.strictEqual(request.body.phone, '+15550001111');+ // Documenting current behaviour, not endorsing it: the service reads `this.hello`,+ // which it never defines, so the session is always sent as undefined.+ assert.strictEqual(request.body.session, undefined, 'session is always undefined — see this.hello');+ assert.deepEqual(modal.calls, ['startLoading', 'done']);+ assert.deepEqual(this.owner.lookup('service:notifications').successes, ['Verification code SMS sent!']);+ });++ test('confirming the sms modal without a phone number reports the omission', async function (assert) {+ let posted = false;+ class FetchStub extends Service {+ post() {+ posted = true;+ return Promise.resolve({});+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:modals-manager', ModalsManagerStub);++ const service = this.owner.lookup('service:user-verification');+ service.resendBySms();++ await this.owner.lookup('service:modals-manager').shown[0].options.confirm(fakeModal({ phone: '' }));++ assert.deepEqual(this.owner.lookup('service:notifications').errors, ['No phone number provided.']);+ // Current behaviour: the guard has no `return`, so the request goes out anyway.+ assert.true(posted, 'the request is still sent despite the missing number');+ });++ test('a failed sms send is surfaced and the modal is left open', async function (assert) {+ const failure = new Error('sms gateway down');+ class FetchStub extends Service {+ post() {+ return Promise.reject(failure);+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:modals-manager', ModalsManagerStub);++ const service = this.owner.lookup('service:user-verification');+ service.resendBySms();++ const modal = fakeModal({ phone: '+15550001111' });+ await this.owner.lookup('service:modals-manager').shown[0].options.confirm(modal);++ assert.deepEqual(this.owner.lookup('service:notifications').serverErrors, [failure]);+ assert.deepEqual(modal.calls, ['startLoading', 'stopLoading'], 'the modal stays open so the user can retry');+ });++ test('resendEmail opens the email modal seeded with the current user email', function (assert) {+ this.owner.register('service:modals-manager', ModalsManagerStub);+ const service = this.owner.lookup('service:user-verification');++ service.resendEmail();++ const { name, options } = this.owner.lookup('service:modals-manager').shown[0];+ assert.strictEqual(name, 'modals/resend-verification-email');+ assert.strictEqual(options.title, 'Resend Verification Code');+ assert.strictEqual(options.acceptButtonText, 'Send');+ assert.strictEqual(options.email, service.currentUser.email);+ });++ test('confirming the email modal sends the code and closes the modal', async function (assert) {+ let request;+ class FetchStub extends Service {+ post(path, body) {+ request = { path, body };+ return Promise.resolve({});+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:modals-manager', ModalsManagerStub);++ const service = this.owner.lookup('service:user-verification');+ service.resendEmail();++ const modal = fakeModal({ email: '[email protected]' });+ await this.owner.lookup('service:modals-manager').shown[0].options.confirm(modal);++ assert.strictEqual(request.path, 'onboard/send-verification-email');+ assert.strictEqual(request.body.email, '[email protected]');+ assert.deepEqual(modal.calls, ['startLoading', 'done']);+ assert.deepEqual(this.owner.lookup('service:notifications').successes, ['Verification code email sent!']);+ });++ test('confirming the email modal without an address reports the omission', async function (assert) {+ let posted = false;+ class FetchStub extends Service {+ post() {+ posted = true;+ return Promise.resolve({});+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:modals-manager', ModalsManagerStub);++ const service = this.owner.lookup('service:user-verification');+ service.resendEmail();++ await this.owner.lookup('service:modals-manager').shown[0].options.confirm(fakeModal({ email: '' }));++ assert.deepEqual(this.owner.lookup('service:notifications').errors, ['No email number provided.']);+ assert.true(posted, 'the request is still sent despite the missing address');+ });++ test('a failed email send is surfaced and the modal is left open', async function (assert) {+ const failure = new Error('smtp unavailable');+ class FetchStub extends Service {+ post() {+ return Promise.reject(failure);+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:modals-manager', ModalsManagerStub);++ const service = this.owner.lookup('service:user-verification');+ service.resendEmail();++ const modal = fakeModal({ email: '[email protected]' });+ await this.owner.lookup('service:modals-manager').shown[0].options.confirm(modal);++ assert.deepEqual(this.owner.lookup('service:notifications').serverErrors, [failure]);+ assert.deepEqual(modal.calls, ['startLoading', 'stopLoading']);+ });});