2025-07-04 17:11:26 -04:00
|
|
|
import { create } from "zustand";
|
|
|
|
|
import { AxiosInstance } from "axios";
|
2025-07-07 22:30:33 -04:00
|
|
|
import { lsKeys } from "@/util/env";
|
2025-07-04 17:11:26 -04:00
|
|
|
|
|
|
|
|
export interface BrowserSessionData {
|
|
|
|
|
browser_session_id: string | null;
|
|
|
|
|
expires_at: number | null; // seconds since epoch
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface OptimisticBrowserSessionIdState extends BrowserSessionData {
|
|
|
|
|
run: (client: AxiosInstance) => Promise<BrowserSessionData>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const SESSION_TIMEOUT_MINUTES = 60;
|
|
|
|
|
|
|
|
|
|
export const useOptimisticallyRequestBrowserSessionId =
|
|
|
|
|
create<OptimisticBrowserSessionIdState>((set) => ({
|
|
|
|
|
browser_session_id: null,
|
|
|
|
|
expires_at: null,
|
|
|
|
|
run: async (client) => {
|
2025-07-07 22:30:33 -04:00
|
|
|
const stored = localStorage.getItem(lsKeys.optimisticBrowserSession);
|
2025-07-04 17:11:26 -04:00
|
|
|
if (stored) {
|
|
|
|
|
try {
|
|
|
|
|
const parsed = JSON.parse(stored);
|
|
|
|
|
const { browser_session_id, expires_at } = parsed;
|
|
|
|
|
const now = Math.floor(Date.now() / 1000); // seconds since epoch
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
browser_session_id &&
|
|
|
|
|
typeof browser_session_id === "string" &&
|
|
|
|
|
expires_at &&
|
|
|
|
|
typeof expires_at === "number" &&
|
|
|
|
|
now < expires_at
|
|
|
|
|
) {
|
|
|
|
|
set({ browser_session_id, expires_at });
|
|
|
|
|
return { browser_session_id, expires_at };
|
|
|
|
|
}
|
|
|
|
|
} catch (e) {
|
|
|
|
|
// pass
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const resp = await client.post("/browser_sessions", {
|
2025-07-08 14:14:56 -04:00
|
|
|
timeout: SESSION_TIMEOUT_MINUTES,
|
2025-07-04 17:11:26 -04:00
|
|
|
});
|
|
|
|
|
const { browser_session_id: newBrowserSessionId, timeout } = resp.data;
|
2025-07-08 14:14:56 -04:00
|
|
|
const newExpiresAt = Math.floor(Date.now() / 1000) + timeout * 60 * 0.9;
|
2025-07-04 17:11:26 -04:00
|
|
|
set({
|
|
|
|
|
browser_session_id: newBrowserSessionId,
|
|
|
|
|
expires_at: newExpiresAt,
|
|
|
|
|
});
|
|
|
|
|
localStorage.setItem(
|
2025-07-07 22:30:33 -04:00
|
|
|
lsKeys.optimisticBrowserSession,
|
2025-07-04 17:11:26 -04:00
|
|
|
JSON.stringify({
|
|
|
|
|
browser_session_id: newBrowserSessionId,
|
|
|
|
|
expires_at: newExpiresAt,
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
browser_session_id: newBrowserSessionId,
|
|
|
|
|
expires_at: newExpiresAt,
|
|
|
|
|
};
|
|
|
|
|
},
|
|
|
|
|
}));
|