Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/db/permissions/permission-cache.server.ts
T

143 lines
5.3 KiB
TypeScript

import { createTwoTierCache, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { clearCacheKey } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
const log = createScopedLogger("permission-cache");
// Pub/sub is the primary revocation path. The short TTL is the safety net for
// a replica that was disconnected while an invalidation was published.
const AUTHORIZATION_CACHE_TTL_SECONDS = 30;
const ADMIN_SCOPE_KEY = "__admin__";
export type PermissionCache = TwoTierCache<string[]>;
let cacheSingleton: PermissionCache | null = null;
let subscribeDisposer: (() => Promise<void>) | null = null;
function permissionCacheKey(userId: string, tenantId: string | null): string {
return `${userId}:${tenantId ?? ADMIN_SCOPE_KEY}`;
}
function legacyPermissionCacheKey(userId: string, tenantId: string | null): string {
return `userRoles:${userId}:${tenantId}`;
}
function pubsubEnabledFromEnv(): boolean {
const raw = process.env.CACHE_INVALIDATION_ENABLED;
if (raw === undefined || raw === null || raw === "") return true;
return raw.toLowerCase() !== "false" && raw !== "0";
}
export function createPermissionCache(store: SharedStore): PermissionCache {
return createTwoTierCache<string[]>({
store,
namespace: "user-permissions",
ttlSeconds: AUTHORIZATION_CACHE_TTL_SECONDS,
pubsubEnabled: pubsubEnabledFromEnv(),
logger: {
warn: (obj, msg) => log.warn(obj, msg),
info: (obj, msg) => log.info(obj, msg),
error: (obj, msg) => log.error(obj, msg),
},
});
}
export function getPermissionCache(): PermissionCache {
if (!cacheSingleton) {
cacheSingleton = createPermissionCache(getSharedStore());
}
return cacheSingleton;
}
export async function getCachedPermissionNames(userId: string, tenantId: string | null): Promise<string[] | null> {
try {
const cached = await getPermissionCache().get(permissionCacheKey(userId, tenantId));
return cached === null ? null : [...cached];
} catch (error) {
// Cache availability must not become an authorization availability
// dependency. The caller falls back to the authoritative database.
log.warn(
{ op: "permission-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
"Permission cache read failed; falling back to the database."
);
return null;
}
}
export async function cachePermissionNames(userId: string, tenantId: string | null, permissionNames: readonly string[]): Promise<boolean> {
try {
await getPermissionCache().set(permissionCacheKey(userId, tenantId), [...permissionNames]);
return true;
} catch (error) {
log.warn(
{ op: "permission-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
"Permission cache write failed; continuing with the database result."
);
return false;
}
}
/**
* Invalidates one authorization scope locally, in shared L2, and on every
* subscribed web replica. Publish errors propagate: callers changing roles
* must not report success while peer replicas could still hold a stale grant.
*/
export async function invalidateUserPermissionCache(userId: string, tenantId: string | null): Promise<void> {
const key = permissionCacheKey(userId, tenantId);
clearCacheKey(legacyPermissionCacheKey(userId, tenantId));
const cache = getPermissionCache();
cache.deleteLocal(key);
try {
await cache.l2.invalidate(key);
} catch (error) {
log.error(
{ op: "permission-cache.invalidate", err: { name: error instanceof Error ? error.name : "Error" } },
"Permission cache invalidation could not be published."
);
throw error;
}
}
export async function invalidateUserPermissionCacheScopes(scopes: readonly { userId: string; tenantId: string | null }[]): Promise<void> {
const unique = [...new Map(scopes.map((scope) => [permissionCacheKey(scope.userId, scope.tenantId), scope])).values()];
if (unique.length === 0) return;
if (unique.length === 1) {
const scope = unique[0]!;
await invalidateUserPermissionCache(scope.userId, scope.tenantId);
return;
}
const cache = getPermissionCache();
const keys = unique.map((scope) => permissionCacheKey(scope.userId, scope.tenantId));
unique.forEach((scope) => {
clearCacheKey(legacyPermissionCacheKey(scope.userId, scope.tenantId));
cache.deleteLocal(permissionCacheKey(scope.userId, scope.tenantId));
});
try {
// Delete every affected shared snapshot, then use one wildcard broadcast
// to flush peer L1s. This avoids one PUBLISH per user on large roles.
await Promise.all(keys.map((key) => cache.l2.delete(key)));
await cache.l2.invalidate("*");
} catch (error) {
log.error(
{ op: "permission-cache.invalidate-many", err: { name: error instanceof Error ? error.name : "Error" } },
"Permission cache invalidation batch could not be published."
);
throw error;
}
}
export async function subscribePermissionCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
subscribeDisposer = await getPermissionCache().subscribe();
log.info({ namespace: "user-permissions" }, "Permission cache subscriber started.");
return subscribeDisposer;
}
/** Test seam. */
export function __resetPermissionCacheForTests(): void {
cacheSingleton = null;
subscribeDisposer = null;
}