This is an automated email from the ASF dual-hosted git repository.

tiagobento pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-kie-tools.git


The following commit(s) were added to refs/heads/main by this push:
     new baeb8394930 kie-issues#743: AuthSessions migration scripts can't 
handle expired auth sessions on KIE Sandbox (#2085)
baeb8394930 is described below

commit baeb83949309b2493ea90a5add5192059215661b
Author: Thiago Lugli <[email protected]>
AuthorDate: Fri Dec 8 13:15:06 2023 -0300

    kie-issues#743: AuthSessions migration scripts can't handle expired auth 
sessions on KIE Sandbox (#2085)
---
 packages/kie-sandbox-fs/src/PromisifiedFS.js       |   3 +
 packages/kie-sandbox-fs/src/index.js               |   4 +
 .../online-editor/src/accounts/AccountsContext.tsx |   1 -
 .../src/accounts/git/ConnectToGitSection.tsx       |   4 +-
 .../kubernetes/ConnectToKubernetesSection.tsx      |   1 -
 .../kubernetes/ConnectToKubernetesSimple.tsx       |   8 +-
 .../ConnectToLocalKubernetesClusterWizard.tsx      |   8 +-
 .../accounts/openshift/ConnecToOpenShiftSimple.tsx |   8 +-
 ...tToDeveloperSandboxForRedHatOpenShiftWizard.tsx |   8 +-
 .../openshift/ConnectToOpenShiftSection.tsx        |   2 +-
 .../src/authSessions/AuthSessionApi.ts             |  32 ++++++-
 .../src/authSessions/AuthSessionMigrations.ts      |  66 ++++++++++++-
 .../src/authSessions/AuthSessionsContext.tsx       | 105 +++++++++------------
 13 files changed, 173 insertions(+), 77 deletions(-)

diff --git a/packages/kie-sandbox-fs/src/PromisifiedFS.js 
b/packages/kie-sandbox-fs/src/PromisifiedFS.js
index ef1eeb8b847..bcd412eef2e 100644
--- a/packages/kie-sandbox-fs/src/PromisifiedFS.js
+++ b/packages/kie-sandbox-fs/src/PromisifiedFS.js
@@ -180,6 +180,9 @@ module.exports = class PromisifiedKieSandboxFs {
     }
     await this._activationPromise;
   }
+  async deactivate() {
+    await this._deactivate();
+  }
   async _deactivate() {
     if (this._activationPromise) await this._activationPromise;
 
diff --git a/packages/kie-sandbox-fs/src/index.js 
b/packages/kie-sandbox-fs/src/index.js
index 10f2a46c8c5..d3b9b858ce2 100755
--- a/packages/kie-sandbox-fs/src/index.js
+++ b/packages/kie-sandbox-fs/src/index.js
@@ -16,6 +16,7 @@ module.exports = class KieSandboxFs {
     this.promises = new PromisifiedKieSandboxFs(...args);
     // Needed so things don't break if you destructure fs and pass individual 
functions around
     this.init = this.init.bind(this);
+    this.deactivate = this.deactivate.bind(this);
     this.readFile = this.readFile.bind(this);
     this.readFileBulk = this.readFileBulk.bind(this);
     this.writeFile = this.writeFile.bind(this);
@@ -36,6 +37,9 @@ module.exports = class KieSandboxFs {
   init(name, options) {
     return this.promises.init(name, options);
   }
+  deactivate() {
+    return this.promises.deactivate();
+  }
   readFile(filepath, opts, cb) {
     const [resolve, reject] = wrapCallback(opts, cb);
     this.promises.readFile(filepath, opts).then(resolve).catch(reject);
diff --git a/packages/online-editor/src/accounts/AccountsContext.tsx 
b/packages/online-editor/src/accounts/AccountsContext.tsx
index 524b025c986..e025095c261 100644
--- a/packages/online-editor/src/accounts/AccountsContext.tsx
+++ b/packages/online-editor/src/accounts/AccountsContext.tsx
@@ -20,7 +20,6 @@
 import * as React from "react";
 import { useCallback, useContext, useReducer } from "react";
 import {
-  AuthProvider,
   AuthProviderGroup,
   GitAuthProvider,
   KubernetesAuthProvider,
diff --git a/packages/online-editor/src/accounts/git/ConnectToGitSection.tsx 
b/packages/online-editor/src/accounts/git/ConnectToGitSection.tsx
index a0f8d27c918..2beca9522a6 100644
--- a/packages/online-editor/src/accounts/git/ConnectToGitSection.tsx
+++ b/packages/online-editor/src/accounts/git/ConnectToGitSection.tsx
@@ -35,7 +35,7 @@ import { useCancelableEffect } from 
"@kie-tools-core/react-hooks/dist/useCancela
 import { AccountsDispatchActionKind, AccountsSection, useAccounts, 
useAccountsDispatch } from "../AccountsContext";
 import { useAuthSessions, useAuthSessionsDispatch } from 
"../../authSessions/AuthSessionsContext";
 import { AuthSessionDescriptionList } from 
"../../authSessions/AuthSessionsList";
-import { AUTH_SESSION_VERSION, GitAuthSession } from 
"../../authSessions/AuthSessionApi";
+import { AUTH_SESSION_VERSION_NUMBER, GitAuthSession } from 
"../../authSessions/AuthSessionApi";
 import { PromiseStateStatus, usePromiseState } from 
"@kie-tools-core/react-hooks/dist/PromiseState";
 import {
   GitAuthProvider,
@@ -145,7 +145,7 @@ export function ConnectToGitSection(props: { authProvider: 
GitAuthProvider }) {
 
             const newAuthSession: GitAuthSession = {
               id: uuid(),
-              version: AUTH_SESSION_VERSION,
+              version: AUTH_SESSION_VERSION_NUMBER,
               token: tokenInput,
               type: "git",
               login: response.data.login,
diff --git 
a/packages/online-editor/src/accounts/kubernetes/ConnectToKubernetesSection.tsx 
b/packages/online-editor/src/accounts/kubernetes/ConnectToKubernetesSection.tsx
index 76b6d1dcab3..5bba8a46d77 100644
--- 
a/packages/online-editor/src/accounts/kubernetes/ConnectToKubernetesSection.tsx
+++ 
b/packages/online-editor/src/accounts/kubernetes/ConnectToKubernetesSection.tsx
@@ -19,7 +19,6 @@
 
 import React, { useCallback, useEffect, useMemo, useState } from "react";
 import { KubernetesInstanceStatus } from "./KubernetesInstanceStatus";
-import { useExtendedServices } from 
"../../extendedServices/ExtendedServicesContext";
 import { ConnectToKubernetesSimple } from "./ConnectToKubernetesSimple";
 import { AccountsDispatchActionKind, AccountsSection, useAccounts, 
useAccountsDispatch } from "../AccountsContext";
 import { Button, ButtonVariant } from 
"@patternfly/react-core/dist/js/components/Button";
diff --git 
a/packages/online-editor/src/accounts/kubernetes/ConnectToKubernetesSimple.tsx 
b/packages/online-editor/src/accounts/kubernetes/ConnectToKubernetesSimple.tsx
index 0dec7652d23..218d1e14f7c 100644
--- 
a/packages/online-editor/src/accounts/kubernetes/ConnectToKubernetesSimple.tsx
+++ 
b/packages/online-editor/src/accounts/kubernetes/ConnectToKubernetesSimple.tsx
@@ -29,7 +29,11 @@ import { TimesIcon } from 
"@patternfly/react-icons/dist/js/icons/times-icon";
 import { useOnlineI18n } from "../../i18n";
 import { useAuthSessionsDispatch } from 
"../../authSessions/AuthSessionsContext";
 import { v4 as uuid } from "uuid";
-import { AUTH_SESSION_VERSION, CloudAuthSessionType, KubernetesAuthSession } 
from "../../authSessions/AuthSessionApi";
+import {
+  AUTH_SESSION_VERSION_NUMBER,
+  CloudAuthSessionType,
+  KubernetesAuthSession,
+} from "../../authSessions/AuthSessionApi";
 import { KieSandboxKubernetesService } from 
"../../devDeployments/services/KieSandboxKubernetesService";
 import { KubernetesInstanceStatus } from "./KubernetesInstanceStatus";
 import {
@@ -81,7 +85,7 @@ export function ConnectToKubernetesSimple(props: {
     if (isConnectionEstablished === KubernetesConnectionStatus.CONNECTED && 
props.kieSandboxKubernetesService) {
       const newAuthSession: KubernetesAuthSession = {
         type: CloudAuthSessionType.Kubernetes,
-        version: AUTH_SESSION_VERSION,
+        version: AUTH_SESSION_VERSION_NUMBER,
         id: uuid(),
         ...props.connection,
         authProviderId: "kubernetes",
diff --git 
a/packages/online-editor/src/accounts/kubernetes/ConnectToLocalKubernetesClusterWizard.tsx
 
b/packages/online-editor/src/accounts/kubernetes/ConnectToLocalKubernetesClusterWizard.tsx
index 375755f48aa..905f2eab0c1 100644
--- 
a/packages/online-editor/src/accounts/kubernetes/ConnectToLocalKubernetesClusterWizard.tsx
+++ 
b/packages/online-editor/src/accounts/kubernetes/ConnectToLocalKubernetesClusterWizard.tsx
@@ -33,7 +33,11 @@ import { KubernetesSettingsTabMode } from 
"./ConnectToKubernetesSection";
 import { KubernetesInstanceStatus } from "./KubernetesInstanceStatus";
 import { v4 as uuid } from "uuid";
 import { useAuthSessionsDispatch } from 
"../../authSessions/AuthSessionsContext";
-import { AUTH_SESSION_VERSION, CloudAuthSessionType, KubernetesAuthSession } 
from "../../authSessions/AuthSessionApi";
+import {
+  AUTH_SESSION_VERSION_NUMBER,
+  CloudAuthSessionType,
+  KubernetesAuthSession,
+} from "../../authSessions/AuthSessionApi";
 import {
   KubernetesConnection,
   KubernetesConnectionStatus,
@@ -252,7 +256,7 @@ export function 
ConnectToLocalKubernetesClusterWizard(props: {
     if (isConnectionEstablished === KubernetesConnectionStatus.CONNECTED && 
props.kieSandboxKubernetesService) {
       const newAuthSession: KubernetesAuthSession = {
         type: CloudAuthSessionType.Kubernetes,
-        version: AUTH_SESSION_VERSION,
+        version: AUTH_SESSION_VERSION_NUMBER,
         id: uuid(),
         ...props.connection,
         authProviderId: "kubernetes",
diff --git 
a/packages/online-editor/src/accounts/openshift/ConnecToOpenShiftSimple.tsx 
b/packages/online-editor/src/accounts/openshift/ConnecToOpenShiftSimple.tsx
index f81f195df84..b48d76978b9 100644
--- a/packages/online-editor/src/accounts/openshift/ConnecToOpenShiftSimple.tsx
+++ b/packages/online-editor/src/accounts/openshift/ConnecToOpenShiftSimple.tsx
@@ -34,7 +34,11 @@ import { OpenShiftSettingsTabMode } from 
"./ConnectToOpenShiftSection";
 import { KieSandboxOpenShiftService } from 
"../../devDeployments/services/KieSandboxOpenShiftService";
 import { useAuthSessionsDispatch } from 
"../../authSessions/AuthSessionsContext";
 import { v4 as uuid } from "uuid";
-import { AUTH_SESSION_VERSION, CloudAuthSessionType, OpenShiftAuthSession } 
from "../../authSessions/AuthSessionApi";
+import {
+  AUTH_SESSION_VERSION_NUMBER,
+  CloudAuthSessionType,
+  OpenShiftAuthSession,
+} from "../../authSessions/AuthSessionApi";
 import {
   KubernetesConnection,
   KubernetesConnectionStatus,
@@ -81,7 +85,7 @@ export function ConnecToOpenShiftSimple(props: {
     if (isConnectionEstablished === KubernetesConnectionStatus.CONNECTED && 
props.kieSandboxOpenShiftService) {
       const newAuthSession: OpenShiftAuthSession = {
         type: CloudAuthSessionType.OpenShift,
-        version: AUTH_SESSION_VERSION,
+        version: AUTH_SESSION_VERSION_NUMBER,
         id: uuid(),
         ...props.connection,
         authProviderId: "openshift",
diff --git 
a/packages/online-editor/src/accounts/openshift/ConnectToDeveloperSandboxForRedHatOpenShiftWizard.tsx
 
b/packages/online-editor/src/accounts/openshift/ConnectToDeveloperSandboxForRedHatOpenShiftWizard.tsx
index 13f28007ccc..819c95fec69 100644
--- 
a/packages/online-editor/src/accounts/openshift/ConnectToDeveloperSandboxForRedHatOpenShiftWizard.tsx
+++ 
b/packages/online-editor/src/accounts/openshift/ConnectToDeveloperSandboxForRedHatOpenShiftWizard.tsx
@@ -36,7 +36,11 @@ import { OpenShiftInstanceStatus } from 
"./OpenShiftInstanceStatus";
 import { KieSandboxOpenShiftService } from 
"../../devDeployments/services/KieSandboxOpenShiftService";
 import { v4 as uuid } from "uuid";
 import { useAuthSessionsDispatch } from 
"../../authSessions/AuthSessionsContext";
-import { AUTH_SESSION_VERSION, CloudAuthSessionType, OpenShiftAuthSession } 
from "../../authSessions/AuthSessionApi";
+import {
+  AUTH_SESSION_VERSION_NUMBER,
+  CloudAuthSessionType,
+  OpenShiftAuthSession,
+} from "../../authSessions/AuthSessionApi";
 import {
   KubernetesConnection,
   isHostValid,
@@ -159,7 +163,7 @@ export function 
ConnectToDeveloperSandboxForRedHatOpenShiftWizard(props: {
     if (isConnectionEstablished === KubernetesConnectionStatus.CONNECTED && 
props.kieSandboxOpenShiftService) {
       const newAuthSession: OpenShiftAuthSession = {
         type: CloudAuthSessionType.OpenShift,
-        version: AUTH_SESSION_VERSION,
+        version: AUTH_SESSION_VERSION_NUMBER,
         id: uuid(),
         ...props.connection,
         authProviderId: "openshift",
diff --git 
a/packages/online-editor/src/accounts/openshift/ConnectToOpenShiftSection.tsx 
b/packages/online-editor/src/accounts/openshift/ConnectToOpenShiftSection.tsx
index 7dda0479a89..67eb8f5698a 100644
--- 
a/packages/online-editor/src/accounts/openshift/ConnectToOpenShiftSection.tsx
+++ 
b/packages/online-editor/src/accounts/openshift/ConnectToOpenShiftSection.tsx
@@ -17,7 +17,7 @@
  * under the License.
  */
 
-import React, { useMemo, useState, useEffect, useCallback } from "react";
+import React, { useMemo, useState, useCallback } from "react";
 import { OpenShiftInstanceStatus } from "./OpenShiftInstanceStatus";
 import { KieSandboxOpenShiftService } from 
"../../devDeployments/services/KieSandboxOpenShiftService";
 import { ConnecToOpenShiftSimple } from "./ConnecToOpenShiftSimple";
diff --git a/packages/online-editor/src/authSessions/AuthSessionApi.ts 
b/packages/online-editor/src/authSessions/AuthSessionApi.ts
index cecec00402c..4346be92cda 100644
--- a/packages/online-editor/src/authSessions/AuthSessionApi.ts
+++ b/packages/online-editor/src/authSessions/AuthSessionApi.ts
@@ -18,15 +18,43 @@
  */
 
 import { K8sApiServerEndpointByResourceKind } from 
"@kie-tools-core/k8s-yaml-to-apiserver-requests/dist";
+import { LfsFsCache } from 
"@kie-tools-core/workspaces-git-fs/dist/lfs/LfsFsCache";
+import { LfsStorageService } from 
"@kie-tools-core/workspaces-git-fs/dist/lfs/LfsStorageService";
 
-export const AUTH_SESSION_VERSION = 1;
+export const authSessionFsCache = new LfsFsCache();
+export const authSessionFsService = new LfsStorageService();
+export const authSessionBroadcastChannel = new 
BroadcastChannel("auth_sessions");
+
+export const AUTH_SESSIONS_FILE_PATH = "/authSessions.json";
+export const AUTH_SESSIONS_FS_NAME = "auth_sessions";
+export const AUTH_SESSION_VERSION_NUMBER = 1;
+export const AUTH_SESSIONS_FS_NAME_WITH_VERSION = 
`${AUTH_SESSIONS_FS_NAME}_v${AUTH_SESSION_VERSION_NUMBER.toString()}`;
+
+export function mapSerializer(_: string, value: any) {
+  if (value instanceof Map) {
+    return {
+      __$$jsClassName: "Map",
+      value: Array.from(value.entries()),
+    };
+  }
+  return value;
+}
+
+export function mapDeSerializer(_: string, value: any) {
+  if (typeof value === "object" && value) {
+    if (value.__$$jsClassName === "Map") {
+      return new Map(value.value);
+    }
+  }
+  return value;
+}
 
 export const AUTH_SESSION_NONE = {
   id: "none",
   name: "Unauthenticated",
   type: "none",
   login: "Unauthenticated",
-  version: AUTH_SESSION_VERSION,
+  version: AUTH_SESSION_VERSION_NUMBER,
 } as const;
 
 export type NoneAuthSession = typeof AUTH_SESSION_NONE;
diff --git a/packages/online-editor/src/authSessions/AuthSessionMigrations.ts 
b/packages/online-editor/src/authSessions/AuthSessionMigrations.ts
index 6e07bf9f6ae..35f3b94efe5 100644
--- a/packages/online-editor/src/authSessions/AuthSessionMigrations.ts
+++ b/packages/online-editor/src/authSessions/AuthSessionMigrations.ts
@@ -17,11 +17,72 @@
  * under the License.
  */
 
+import { decoder } from 
"@kie-tools-core/workspaces-git-fs/dist/encoderdecoder/EncoderDecoder";
 import { KubernetesService } from 
"../devDeployments/services/KubernetesService";
-import { AUTH_SESSION_VERSION, AuthSession, CloudAuthSessionType } from 
"./AuthSessionApi";
+import {
+  AUTH_SESSIONS_FILE_PATH,
+  AUTH_SESSIONS_FS_NAME,
+  AUTH_SESSION_VERSION_NUMBER,
+  AuthSession,
+  CloudAuthSessionType,
+  authSessionFsCache,
+  authSessionFsService,
+  mapDeSerializer,
+} from "./AuthSessionApi";
+
+export async function getAuthSessionsFromVersion(version?: number) {
+  const authSessionFsName = version && version >= 0 ? 
`${AUTH_SESSIONS_FS_NAME}_v${version}` : AUTH_SESSIONS_FS_NAME;
+  const fs = authSessionFsCache.getOrCreateFs(authSessionFsName);
+  const authSessionsFile = await authSessionFsService.getFile(fs, 
AUTH_SESSIONS_FILE_PATH);
+  if (!authSessionsFile) {
+    return [];
+  }
+  const content = await authSessionsFile.getFileContents();
+  const parsedAuthSessions = Array.from(JSON.parse(decoder.decode(content), 
mapDeSerializer));
+  return parsedAuthSessions;
+}
+
+export async function getAllAuthSessions() {
+  let allAuthSessions: any[] = [];
+  for (let i = AUTH_SESSION_VERSION_NUMBER; i >= 0; i--) {
+    const authSessions = await getAuthSessionsFromVersion(i);
+    allAuthSessions = allAuthSessions.concat(authSessions);
+  }
+  return allAuthSessions;
+}
+
+export async function deleteOlderAuthSessionsStorage() {
+  for (let i = AUTH_SESSION_VERSION_NUMBER - 1; i >= 0; i--) {
+    const authSessionFsName = i && i >= 0 ? `${AUTH_SESSIONS_FS_NAME}_v${i}` : 
AUTH_SESSIONS_FS_NAME;
+    const fs = authSessionFsCache.getOrCreateFs(authSessionFsName);
+    if (await authSessionFsService.exists(fs, AUTH_SESSIONS_FILE_PATH)) {
+      await authSessionFsService.deleteFile(fs, AUTH_SESSIONS_FILE_PATH);
+    }
+    await fs.deactivate();
+    indexedDB.deleteDatabase(authSessionFsName);
+  }
+}
+
+export async function migrateAuthSessions() {
+  const olderAuthSessions = await getAllAuthSessions();
+  const migratedAuthSessions = new Map<string, AuthSession>();
+  for (const [key, authSession] of olderAuthSessions) {
+    try {
+      const migratedAuthSession = await 
applyAuthSessionMigrations(authSession);
+      migratedAuthSessions.set(key, migratedAuthSession);
+    } catch (e) {
+      console.error("Failed to apply migrations to auth session", {
+        id: authSession.id,
+        authProvider: authSession.authProviderId,
+        host: authSession.host,
+      });
+    }
+  }
+  return migratedAuthSessions;
+}
 
 export async function applyAuthSessionMigrations(authSession: any): 
Promise<AuthSession> {
-  if (authSession.version && authSession.version > AUTH_SESSION_VERSION) {
+  if (authSession.version && authSession.version > 
AUTH_SESSION_VERSION_NUMBER) {
     throw new Error(
       `Failed to apply migration script to AuthSession: ${authSession.id}. 
Version is greater than current version.`
     );
@@ -42,6 +103,7 @@ export async function 
applyAuthSessionMigrations(authSession: any): Promise<Auth
         });
       }
     case 1:
+    // Already at current version. Nothing to do.
     default:
       break;
   }
diff --git a/packages/online-editor/src/authSessions/AuthSessionsContext.tsx 
b/packages/online-editor/src/authSessions/AuthSessionsContext.tsx
index 78670694608..78426e39494 100644
--- a/packages/online-editor/src/authSessions/AuthSessionsContext.tsx
+++ b/packages/online-editor/src/authSessions/AuthSessionsContext.tsx
@@ -21,18 +21,28 @@ import React, { createContext, PropsWithChildren, 
useCallback, useContext, useEf
 import { Holder } from "@kie-tools-core/react-hooks/dist/Holder";
 import { useCancelableEffect } from 
"@kie-tools-core/react-hooks/dist/useCancelableEffect";
 import { decoder, encoder } from 
"@kie-tools-core/workspaces-git-fs/dist/encoderdecoder/EncoderDecoder";
-import { LfsFsCache } from 
"@kie-tools-core/workspaces-git-fs/dist/lfs/LfsFsCache";
-import { LfsStorageFile, LfsStorageService } from 
"@kie-tools-core/workspaces-git-fs/dist/lfs/LfsStorageService";
+import { LfsStorageFile } from 
"@kie-tools-core/workspaces-git-fs/dist/lfs/LfsStorageService";
 import { useAuthProviders } from "../authProviders/AuthProvidersContext";
 import { fetchAuthenticatedBitbucketUser, fetchAuthenticatedGitHubUser } from 
"../accounts/git/ConnectToGitSection";
-import { AuthSession, AuthSessionStatus, AUTH_SESSION_NONE } from 
"./AuthSessionApi";
+import {
+  AuthSession,
+  AuthSessionStatus,
+  AUTH_SESSION_NONE,
+  authSessionFsCache,
+  authSessionFsService,
+  mapDeSerializer,
+  AUTH_SESSIONS_FILE_PATH,
+  AUTH_SESSIONS_FS_NAME_WITH_VERSION,
+  mapSerializer,
+  authSessionBroadcastChannel,
+} from "./AuthSessionApi";
 import { KieSandboxOpenShiftService } from 
"../devDeployments/services/KieSandboxOpenShiftService";
 import { isGitAuthProvider, isSupportedGitAuthProviderType } from 
"../authProviders/AuthProvidersApi";
 import { switchExpression } from "../switchExpression/switchExpression";
 import { KubernetesConnectionStatus } from 
"@kie-tools-core/kubernetes-bridge/dist/service";
 import { useEnv } from "../env/hooks/EnvContext";
 import { KieSandboxKubernetesService } from 
"../devDeployments/services/KieSandboxKubernetesService";
-import { applyAuthSessionMigrations } from "./AuthSessionMigrations";
+import { deleteOlderAuthSessionsStorage, migrateAuthSessions } from 
"./AuthSessionMigrations";
 
 export type AuthSessionsContextType = {
   authSessions: Map<string, AuthSession>;
@@ -56,43 +66,22 @@ export function useAuthSessionsDispatch() {
   return useContext(AuthSessionsDispatchContext);
 }
 
-const fsCache = new LfsFsCache();
-const fsService = new LfsStorageService();
-const broadcastChannel = new BroadcastChannel("auth_sessions");
-
-const AUTH_SESSIONS_FILE_PATH = "/authSessions.json";
-const AUTH_SESSIONS_FS_NAME = "auth_sessions";
-
-function mapSerializer(_: string, value: any) {
-  if (value instanceof Map) {
-    return {
-      __$$jsClassName: "Map",
-      value: Array.from(value.entries()),
-    };
-  }
-  return value;
-}
-
-function mapDeSerializer(_: string, value: any) {
-  if (typeof value === "object" && value) {
-    if (value.__$$jsClassName === "Map") {
-      return new Map(value.value);
-    }
-  }
-  return value;
-}
-
 export function AuthSessionsContextProvider(props: PropsWithChildren<{}>) {
   const authProviders = useAuthProviders();
   const { env } = useEnv();
-  const [authSessions, setAuthSessions] = useState<Map<string, AuthSession>>();
-  const [authSessionStatus, setAuthSessionStatus] = useState<Map<string, 
AuthSessionStatus>>();
+  const [authSessions, setAuthSessions] = useState<Map<string, 
AuthSession>>(new Map<string, AuthSession>());
+  const [authSessionStatus, setAuthSessionStatus] = useState<Map<string, 
AuthSessionStatus>>(
+    new Map<string, AuthSessionStatus>()
+  );
 
   const getAuthSessionsFromFile = useCallback(async () => {
-    const fs = fsCache.getOrCreateFs(AUTH_SESSIONS_FS_NAME);
-    const content = await (await fsService.getFile(fs, 
AUTH_SESSIONS_FILE_PATH))?.getFileContents();
-    const parsedAuthSessions = JSON.parse(decoder.decode(content), 
mapDeSerializer);
-    return parsedAuthSessions;
+    const fs = 
authSessionFsCache.getOrCreateFs(AUTH_SESSIONS_FS_NAME_WITH_VERSION);
+    if (await authSessionFsService.exists(fs, AUTH_SESSIONS_FILE_PATH)) {
+      const content = await (await authSessionFsService.getFile(fs, 
AUTH_SESSIONS_FILE_PATH))?.getFileContents();
+      const parsedAuthSessions = JSON.parse(decoder.decode(content), 
mapDeSerializer);
+      return parsedAuthSessions;
+    }
+    return [];
   }, []);
 
   const refresh = useCallback(async () => {
@@ -101,8 +90,8 @@ export function AuthSessionsContextProvider(props: 
PropsWithChildren<{}>) {
 
   const persistAuthSessions = useCallback(
     async (map: Map<string, AuthSession>) => {
-      const fs = fsCache.getOrCreateFs(AUTH_SESSIONS_FS_NAME);
-      await fsService.createOrOverwriteFile(
+      const fs = 
authSessionFsCache.getOrCreateFs(AUTH_SESSIONS_FS_NAME_WITH_VERSION);
+      await authSessionFsService.createOrOverwriteFile(
         fs,
         new LfsStorageFile({
           path: AUTH_SESSIONS_FILE_PATH,
@@ -111,7 +100,7 @@ export function AuthSessionsContextProvider(props: 
PropsWithChildren<{}>) {
       );
 
       // This goes to other broadcast channel instances, on other tabs
-      broadcastChannel.postMessage("UPDATE_AUTH_SESSIONS");
+      authSessionBroadcastChannel.postMessage("UPDATE_AUTH_SESSIONS");
 
       // This updates this tab
       refresh();
@@ -139,30 +128,26 @@ export function AuthSessionsContextProvider(props: 
PropsWithChildren<{}>) {
 
   // Update after persisted
   useEffect(() => {
-    broadcastChannel.onmessage = refresh;
+    authSessionBroadcastChannel.onmessage = refresh;
   }, [refresh]);
 
   // Init
-  useEffect(() => {
-    async function run() {
-      const fs = fsCache.getOrCreateFs(AUTH_SESSIONS_FS_NAME);
-      if (!(await fsService.exists(fs, AUTH_SESSIONS_FILE_PATH))) {
-        await persistAuthSessions(new Map());
-      } else {
-        const parsedAuthSessions = await getAuthSessionsFromFile();
-        const migratedAuthSessions = new Map<string, AuthSession>();
-        if (parsedAuthSessions instanceof Map || parsedAuthSessions instanceof 
Array) {
-          for (const [key, authSession] of parsedAuthSessions) {
-            const migratedAuthSession = await 
applyAuthSessionMigrations(authSession);
-            migratedAuthSessions.set(key, migratedAuthSession);
+  useCancelableEffect(
+    useCallback(
+      ({ canceled }) => {
+        const run = async () => {
+          const migratedAuthSessions = await migrateAuthSessions();
+          if (canceled.get()) {
+            return;
           }
-        }
-        await persistAuthSessions(migratedAuthSessions);
-      }
-    }
-
-    run();
-  }, [persistAuthSessions, refresh, getAuthSessionsFromFile]);
+          await persistAuthSessions(migratedAuthSessions);
+          await deleteOlderAuthSessionsStorage();
+        };
+        run();
+      },
+      [persistAuthSessions]
+    )
+  );
 
   const recalculateAuthSessionStatus = useCallback(
     (args?: { canceled: Holder<boolean> }) => {
@@ -254,7 +239,7 @@ export function AuthSessionsContextProvider(props: 
PropsWithChildren<{}>) {
   }, [add, remove, recalculateAuthSessionStatus]);
 
   const value = useMemo(() => {
-    return authSessions && authSessionStatus ? { authSessions, 
authSessionStatus } : undefined;
+    return { authSessions, authSessionStatus };
   }, [authSessionStatus, authSessions]);
 
   return (


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to