Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

UI: Improve WebSocket stability using access token retrieval (#2573)

Martin Peetersfa77dacc165d
diff --git a/ui/component/core/src/event.ts b/ui/component/core/src/event.ts
index 64644b5b9..e51184fb0 100644
--- a/ui/component/core/src/event.ts
+++ b/ui/component/core/src/event.ts
@@ -111,17 +111,20 @@ abstract class EventProviderImpl implements EventProvider {
}
public connect(): Promise<boolean> {
+ console.debug("Attempting to connect to events:", this.endpointUrl);
if (this._reconnectTimer) {
window.clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
}
if (this._status === EventProviderStatus.CONNECTED) {
+ console.debug("Already connected to events!");
return Promise.resolve(true);
}
this._disconnectRequested = false;
if (this._connectingDeferred) {
+ console.warn("Already connecting to events, continuing the previous one.");
return this._connectingDeferred.promise;
}
@@ -132,7 +135,6 @@ abstract class EventProviderImpl implements EventProvider {
this._doConnect().then((connected: boolean) => {
if (this._connectingDeferred) {
const deferred = this._connectingDeferred;
- this._connectingDeferred = null;
if (connected) {
console.debug("Connected to event service: " + this.endpointUrl);
@@ -144,11 +146,12 @@ abstract class EventProviderImpl implements EventProvider {
}, 0);
} else {
console.debug("Failed to connect to event service: " + this.endpointUrl);
- this._scheduleReconnect();
}
deferred.resolve(connected);
}
+ }).finally(() => {
+ this._connectingDeferred = null;
});
return this._connectingDeferred.promise;
@@ -207,6 +210,7 @@ abstract class EventProviderImpl implements EventProvider {
}
},
(reason) => {
+ console.error(reason);
if (this._pendingSubscription) {
const subscription = this._pendingSubscription;
this._pendingSubscription = null;
@@ -607,86 +611,97 @@ export class WebSocketEventProvider extends EventProviderImpl {
protected _doConnect(): Promise<boolean> {
let authorisedUrl = this._endpointUrl + "?Realm=" + manager.config.realm;
+ this._connectDeferred = new Deferred();
+ // Await access token retrieval from the Manager if necessary
+ let tokenPromise: Promise<void>;
if (manager.authenticated) {
- authorisedUrl += "&Authorization=" + manager.getAuthorizationHeader();
+ tokenPromise = manager.retrieveAuthorizationHeader().then(value => {
+ authorisedUrl += "&Authorization=" + value;
+ });
+ } else {
+ tokenPromise = Promise.resolve();
}
- this._webSocket = new WebSocket(authorisedUrl);
- this._connectDeferred = new Deferred();
+ // After retrieving the authorization header, open the connection.
+ tokenPromise.finally(() => {
- this._webSocket!.onopen = () => {
- if (this._connectDeferred) {
- const deferred = this._connectDeferred;
- this._connectDeferred = null;
- deferred.resolve(true);
- }
- };
-
- this._webSocket!.onerror = (err) => {
- if (this._connectDeferred) {
- const deferred = this._connectDeferred;
- this._connectDeferred = null;
- deferred.resolve(false);
- } else {
- console.debug("Event provider error");
- // Could have inconsistent state so disconnect and let consumers decide what to do and when to reconnect
- this._beforeDisconnect();
- }
- };
+ this._webSocket = new WebSocket(authorisedUrl);
- this._webSocket!.onclose = () => {
- this._webSocket = undefined;
+ this._webSocket!.onopen = (ev) => {
+ if (this._connectDeferred) {
+ const deferred = this._connectDeferred;
+ this._connectDeferred = null;
+ deferred.resolve(true);
+ }
+ };
- if (this._connectDeferred) {
- const deferred = this._connectDeferred;
- this._connectDeferred = null;
- deferred.resolve(false);
- } else {
- this._beforeDisconnect();
- }
- };
+ this._webSocket!.onerror = (err) => {
+ console.error("Event provider error:", err);
+ if (this._connectDeferred) {
+ const deferred = this._connectDeferred;
+ this._connectDeferred = null;
+ deferred.resolve(false);
+ } else {
+ // Could have inconsistent state so disconnect and let consumers decide what to do and when to reconnect
+ this._beforeDisconnect();
+ }
+ };
- this._webSocket!.onmessage = (e) => {
- const msg = e.data as string;
+ this._webSocket!.onclose = () => {
+ console.warn("The WebSocket connection of the event provider has been closed.");
+ this._webSocket = undefined;
- if (msg && msg.startsWith(SUBSCRIBED_MESSAGE_PREFIX)) {
- const jsonStr = msg.substring(SUBSCRIBED_MESSAGE_PREFIX.length);
- const subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;
- const deferred = this._subscribeDeferred;
- this._subscribeDeferred = null;
- if (deferred) {
- deferred.resolve(subscription.subscriptionId!);
- }
- } else if (msg.startsWith(UNAUTHORIZED_MESSAGE_PREFIX)) {
- const jsonStr = msg.substring(UNAUTHORIZED_MESSAGE_PREFIX.length);
- const subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;
- const deferred = this._subscribeDeferred;
- this._subscribeDeferred = null;
- if (deferred) {
- console.warn("Unauthorized event subscription: " + JSON.stringify(subscription, null, 2));
- deferred.reject("Unauthorized");
- }
- } else if (msg.startsWith(TRIGGERED_MESSAGE_PREFIX)) {
- const str = msg.substring(TRIGGERED_MESSAGE_PREFIX.length);
- const triggered = JSON.parse(str) as TriggeredEventSubscription<SharedEvent>;
- if (triggered.events) {
- triggered.events.forEach((event) => {
- this._onMessageReceived(triggered.subscriptionId!, event);
- });
+ if (this._connectDeferred) {
+ const deferred = this._connectDeferred;
+ this._connectDeferred = null;
+ deferred.resolve(false);
+ } else {
+ this._beforeDisconnect();
}
- } else if (msg.startsWith(EVENT_MESSAGE_PREFIX)) {
- const str = msg.substring(EVENT_MESSAGE_PREFIX.length);
- const event = JSON.parse(str) as SharedEvent;
- if (event.messageID) {
- const deferred = this._repliesDeferred.get(event.messageID!);
- this._repliesDeferred.delete(event.messageID!);
+ };
+
+ this._webSocket!.onmessage = (e) => {
+ const msg = e.data as string;
+
+ if (msg && msg.startsWith(SUBSCRIBED_MESSAGE_PREFIX)) {
+ const jsonStr = msg.substring(SUBSCRIBED_MESSAGE_PREFIX.length);
+ const subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;
+ const deferred = this._subscribeDeferred;
+ this._subscribeDeferred = null;
+ if (deferred) {
+ deferred.resolve(subscription.subscriptionId!);
+ }
+ } else if (msg.startsWith(UNAUTHORIZED_MESSAGE_PREFIX)) {
+ const jsonStr = msg.substring(UNAUTHORIZED_MESSAGE_PREFIX.length);
+ const subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;
+ const deferred = this._subscribeDeferred;
+ this._subscribeDeferred = null;
if (deferred) {
- deferred.resolve(event);
+ console.warn("Unauthorized event subscription: " + JSON.stringify(subscription, null, 2));
+ deferred.reject("Unauthorized");
+ }
+ } else if (msg.startsWith(TRIGGERED_MESSAGE_PREFIX)) {
+ const str = msg.substring(TRIGGERED_MESSAGE_PREFIX.length);
+ const triggered = JSON.parse(str) as TriggeredEventSubscription<SharedEvent>;
+ if (triggered.events) {
+ triggered.events.forEach((event) => {
+ this._onMessageReceived(triggered.subscriptionId!, event);
+ });
+ }
+ } else if (msg.startsWith(EVENT_MESSAGE_PREFIX)) {
+ const str = msg.substring(EVENT_MESSAGE_PREFIX.length);
+ const event = JSON.parse(str) as SharedEvent;
+ if (event.messageID) {
+ const deferred = this._repliesDeferred.get(event.messageID!);
+ this._repliesDeferred.delete(event.messageID!);
+ if (deferred) {
+ deferred.resolve(event);
+ }
}
}
- }
- };
+ };
+ });
return this._connectDeferred.promise;
}
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index 2fae52251..36d99afe4 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -12,7 +12,6 @@ import {
ConsoleAppConfig,
EventProviderType,
ManagerConfig,
- Role,
User,
UsernamePassword
} from "@openremote/model";
@@ -885,6 +884,19 @@ export class Manager implements EventProviderFactory {
}
}
+ /**
+ * This function revalidates the cache by checking if the token in the authorization header is still valid, and retrieves a new token if necessary.
+ * It is useful if you want to guarantee the token inside the header is valid before making a request to the Manager APIs.
+ */
+ public async retrieveAuthorizationHeader(): Promise<string | undefined> {
+ const keycloakToken = await this.retrieveKeycloakToken();
+ if(keycloakToken) {
+ return "Bearer " + keycloakToken;
+ } else {
+ return "Basic " + this.getBasicToken();
+ }
+ }
+
public getKeycloakToken(): string | undefined {
if (this.isKeycloak()) {
return this._keycloak!.token;
@@ -892,6 +904,18 @@ export class Manager implements EventProviderFactory {
return undefined;
}
+ /**
+ * This function revalidates the cached access token by checking if it is still valid, and retrieves a new token if necessary.
+ * It is useful if you want to guarantee the token is valid before making a request to the Manager APIs.
+ */
+ public async retrieveKeycloakToken(): Promise<string | undefined> {
+ if (this.isKeycloak()) {
+ await this._updateKeycloakAccessToken();
+ return this._keycloak!.token;
+ }
+ return undefined;
+ }
+
public getBasicToken(): string | undefined {
return this._basicIdentity ? this._basicIdentity.token : undefined;
}
@@ -1039,7 +1063,7 @@ export class Manager implements EventProviderFactory {
}
protected _onReconnected() {
- console.debug("Reconnected");
+ console.debug("Reconnected to the Manager.");
this._disconnected = false;
// Reinstate token update interval
@@ -1052,10 +1076,13 @@ export class Manager implements EventProviderFactory {
* online.
*/
public async reconnect(reattemptDelayMillis: number = 3000) {
+ console.debug("Checking connection to the Manager...");
if (!this._disconnected) {
+ console.debug("Manager is still connected. No action necessary.");
return;
}
+ console.debug("Manager is disconnected!");
if (this._reconnectTimer) {
window.clearTimeout(this._reconnectTimer);
@@ -1063,40 +1090,42 @@ export class Manager implements EventProviderFactory {
}
const tryReconnect = async () => {
- console.debug("Attempting reconnect");
- let keycloakOffline = !await this.isKeycloakReachable();
+ console.debug("Reconnecting to the Manager...");
+ const keycloakOffline = !await this.isKeycloakReachable();
if (keycloakOffline) {
- console.debug("Keycloak is unreachable");
+ console.error("Keycloak is not reachable. Reconnect attempt failed.");
return false;
}
- console.debug("Keycloak is reachable");
// Check if access token can be refreshed
- console.debug("Checking keycloak access token");
try {
await this._updateKeycloakAccessToken();
} catch (e) {
+ console.error("Could not update Keycloak access token, attempting again using offline token...", e);
// Try and use offline token if it is available
const offlineToken = await this._getNativeOfflineRefreshToken();
this._keycloak!.refreshToken = offlineToken;
+ if(!offlineToken) {
+ console.warn("No offline token was found on this device.");
+ }
try {
await this._updateKeycloakAccessToken();
} catch (e) {
- console.debug("Cannot update access token so sending to login");
this.login();
- return;
+ throw new Error("Cannot update access token so sending to login");
}
console.debug("Keycloak access token is valid");
- return true;
}
// Check events
- const eventsOffline = this.events && this.events.status === EventProviderStatus.CONNECTING;
- console.debug("If event provider offline then attempting reconnect: offline=" + eventsOffline);
- // Force reconnect attempt now if needed
- return !eventsOffline || await this.events?.connect();
+ const isEventsOnline = () => this.events?.status === EventProviderStatus.CONNECTED;
+ if(!isEventsOnline()) {
+ console.debug("Event provider offline, attempting to reconnect using latest auth token.");
+ await this.events?.connect();
+ }
+ return isEventsOnline();
};
const connected = await tryReconnect();
@@ -1106,10 +1135,10 @@ export class Manager implements EventProviderFactory {
return;
}
+ // If failed to connect, schedule another reconnect attempt
if (!connected) {
- // Schedule reconnect again
reattemptDelayMillis = Math.min(Manager.MAX_RECONNECT_DELAY, reattemptDelayMillis + 3000);
- console.debug("Scheduling another reconnect attempt in (ms): " + reattemptDelayMillis);
+ console.error(`Failed to reconnect to the Manager. Attempting again in ${reattemptDelayMillis}...`);
this._reconnectTimer = window.setTimeout(() => this.reconnect(reattemptDelayMillis), reattemptDelayMillis);
return;
}
@@ -1117,9 +1146,13 @@ export class Manager implements EventProviderFactory {
this._onReconnected();
}
- // Checks whether keycloak is reachable using a simple HTTP HEAD request since the keycloak JS adapter doesn't give
- // us details of the HTTP responses they get, we test it manually using this.
- protected async isKeycloakReachable(timeoutMillis: number = 2000) {
+ /**
+ * Checks whether keycloak is reachable using a simple HTTP HEAD request since the keycloak JS adapter doesn't give
+ * us details of the HTTP responses they get, we test it manually using this.
+ * @param timeoutMillis - Custom timeout of the HTTP HEAD request in milliseconds
+ * @protected
+ */
+ protected async isKeycloakReachable(timeoutMillis = 2000): Promise<boolean> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMillis);
try {
@@ -1129,7 +1162,7 @@ export class Manager implements EventProviderFactory {
// but this is handled by the catch block
// @ts-ignore
const tokenUrl = this._keycloak.endpoints.token();
- const result = await fetch(tokenUrl, {method: 'OPTIONS', signal: controller.signal});
+ const result = await fetch(tokenUrl, {method: "OPTIONS", signal: controller.signal});
return result.status === 200;
} catch (e) {
return false;
diff --git a/ui/component/or-app/src/index.ts b/ui/component/or-app/src/index.ts
index 3c3538411..3e0e66e46 100644
--- a/ui/component/or-app/src/index.ts
+++ b/ui/component/or-app/src/index.ts
@@ -160,18 +160,20 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
// TODO; Add an ConsoleProvider that listens to background/foreground changes, and dispatch the respective OREvent. This will improve responsiveness of logic attached to it.
// For example used for triggering reconnecting logic once the UI becomes visible again.
protected _handleVisibilityChange(ev: Event) {
+ console.debug("App visibility changed to", document.visibilityState);
if(document.visibilityState === "visible") {
this._store.dispatch((setVisibility(true)));
-
- // When the manager appears on Mobile devices, but the connection is OFFLINE,
- // we reset the timer to the {appConfig.offlineTimeout} seconds. This is because we saw issues with reopening the app,
- // and seeing a connection interval of 30+ seconds. We now give the user the benefit of the doubt, by resetting the timer.
- if(manager.console?.isMobile && this._offline) {
- this._startOfflineFallbackTimer(true);
- }
- // Always try reconnecting (just in case we are disconnected)
- manager.reconnect();
+ setTimeout(() => {
+ // When the manager appears on Mobile devices, but the connection is OFFLINE,
+ // we reset the timer to the {appConfig.offlineTimeout} seconds. This is because we saw issues with reopening the app,
+ // and seeing a connection interval of 30+ seconds. We now give the user the benefit of the doubt, by resetting the timer.
+ if(manager.console?.isMobile && this._offline) {
+ this._startOfflineFallbackTimer(true);
+ }
+ // Always try reconnecting the event provider (just in case we are disconnected)
+ manager.reconnect();
+ }, 500);
} else {
this._store.dispatch((setVisibility(false)));
}