72 lines
1.9 KiB
JavaScript
72 lines
1.9 KiB
JavaScript
import { createSessionAccess } from '../session-broker.mjs';
|
|
import { isSessionBrokerEnabled } from '../session-broker.mjs';
|
|
|
|
export function createPortalSessionCoordinator({
|
|
getSessionAccess = () => null,
|
|
getUserAuth = () => null,
|
|
createSessionAccessFn = createSessionAccess,
|
|
isSessionBrokerEnabledFn = isSessionBrokerEnabled,
|
|
} = {}) {
|
|
const pageDeliveryLocks = new Map();
|
|
|
|
async function resolveActiveSessionAccess() {
|
|
const active = getSessionAccess();
|
|
if (active) return active;
|
|
const userAuth = getUserAuth();
|
|
if (!userAuth) return null;
|
|
return createSessionAccessFn({
|
|
userAuth,
|
|
enabled: isSessionBrokerEnabledFn(),
|
|
});
|
|
}
|
|
|
|
async function ownsAgentSession(userId, sessionId) {
|
|
if (!userId || !sessionId) return false;
|
|
const access = await resolveActiveSessionAccess();
|
|
if (!access) return false;
|
|
return access.validateOwnership(userId, sessionId);
|
|
}
|
|
|
|
async function unregisterAgentSessionForUser(
|
|
userId,
|
|
sessionId,
|
|
) {
|
|
if (!userId || !sessionId) return;
|
|
const access = await resolveActiveSessionAccess();
|
|
if (!access) return;
|
|
await access.unregisterSession({ userId, sessionId });
|
|
}
|
|
|
|
function beginSessionPageDelivery(sessionId) {
|
|
if (!sessionId) return;
|
|
pageDeliveryLocks.set(
|
|
sessionId,
|
|
Number(pageDeliveryLocks.get(sessionId) ?? 0) + 1,
|
|
);
|
|
}
|
|
|
|
function endSessionPageDelivery(sessionId) {
|
|
if (!sessionId) return;
|
|
const remaining =
|
|
Number(pageDeliveryLocks.get(sessionId) ?? 0) - 1;
|
|
if (remaining > 0) {
|
|
pageDeliveryLocks.set(sessionId, remaining);
|
|
} else {
|
|
pageDeliveryLocks.delete(sessionId);
|
|
}
|
|
}
|
|
|
|
function isSessionPageDeliveryActive(sessionId) {
|
|
return Number(pageDeliveryLocks.get(sessionId) ?? 0) > 0;
|
|
}
|
|
|
|
return {
|
|
resolveActiveSessionAccess,
|
|
ownsAgentSession,
|
|
unregisterAgentSessionForUser,
|
|
beginSessionPageDelivery,
|
|
endSessionPageDelivery,
|
|
isSessionPageDeliveryActive,
|
|
};
|
|
}
|