@noony-serverless/core
Version:
A Middy base framework compatible with Firebase and GCP Cloud Functions with TypeScript
227 lines • 7.86 kB
TypeScript
/**
* Fast User Context Service
*
* High-performance user context management with configurable permission resolution.
* This service orchestrates the permission resolution strategies, manages caching,
* and provides sub-millisecond user permission checks for serverless environments.
*
* Key Features:
* - Configurable permission resolution (pre-expansion vs on-demand)
* - Multi-layer caching (L1 memory + L2 distributed)
* - Conservative cache invalidation for security
* - Permission expansion and validation
* - Performance monitoring and metrics
* - TypeDI integration for dependency injection
*
* Architecture:
* - Uses strategy pattern for different resolution approaches
* - Implements repository pattern for user context storage
* - Follows single responsibility principle with focused methods
* - Provides comprehensive error handling and logging
*
* @author Noony Framework Team
* @version 1.0.0
*/
import { CacheAdapter } from '../cache/CacheAdapter';
import { GuardConfiguration, PermissionResolutionStrategy } from '../config/GuardConfiguration';
import { PermissionRegistry } from '../registry/PermissionRegistry';
import { PermissionResolverType, PermissionCheckResult, PermissionExpression } from '../resolvers/PermissionResolver';
/**
* Type alias for permission requirements that can be strings, string arrays, or complex expressions
* Note: Currently defined but reserved for future use
*/
export type PermissionRequirement = string | string[] | PermissionExpression | Record<string, unknown>;
/**
* User context with cached permissions and metadata
*/
export interface UserContext {
userId: string;
permissions: Set<string>;
roles: string[];
metadata: Record<string, any>;
expandedPermissions?: Set<string>;
lastUpdated: string;
expiresAt?: string;
}
/**
* User permission source for loading raw user data
*/
export interface UserPermissionSource {
/**
* Load user's basic information and permissions
*/
getUserPermissions(userId: string): Promise<{
permissions: string[];
roles: string[];
metadata?: Record<string, any>;
} | null>;
/**
* Get role-based permissions for expansion
*/
getRolePermissions(roles: string[]): Promise<string[]>;
/**
* Check if user context needs refresh
*/
isUserContextStale(userId: string, lastUpdated: string): Promise<boolean>;
}
/**
* Permission check options
*/
export interface PermissionCheckOptions {
resolverType?: PermissionResolverType;
useCache?: boolean;
trackMetrics?: boolean;
auditTrail?: boolean;
}
/**
* Fast User Context Service Implementation
*/
export declare class FastUserContextService {
private readonly cache;
private readonly config;
private readonly permissionSource;
private readonly _permissionRegistry;
private readonly plainResolver;
private readonly wildcardResolver;
private readonly expressionResolver;
private contextLoads;
private cacheHits;
private cacheMisses;
private permissionChecks;
private totalResolutionTimeUs;
constructor(cache: CacheAdapter, config: GuardConfiguration, permissionSource: UserPermissionSource, permissionRegistry: PermissionRegistry);
/**
* Check if caching is effectively disabled
*
* @returns true if caching is disabled (either by environment variable or NoopCacheAdapter)
*/
private isCachingDisabled;
/**
* Get or load user context with permissions
*
* This is the primary method for retrieving user contexts with caching.
* It handles both pre-expansion and on-demand permission strategies.
*
* @param userId - Unique user identifier
* @param forceRefresh - Skip cache and force reload
* @returns User context with permissions or null if user not found
*/
getUserContext(userId: string, forceRefresh?: boolean): Promise<UserContext | null>;
/**
* Check user permission using appropriate resolver
*
* Routes permission checks to the optimal resolver based on requirement type.
* Provides detailed results including performance metrics and cache status.
*
* @param userId - User identifier
* @param requirement - Permission requirement (string[], wildcard pattern, or expression)
* @param options - Check options
* @returns Detailed permission check result
*/
checkPermission(userId: string, requirement: any, options?: PermissionCheckOptions): Promise<PermissionCheckResult>;
/**
* Batch check multiple permissions for a user
*
* Optimized for checking multiple permissions at once.
* Uses the same user context for all checks to minimize overhead.
*
* @param userId - User identifier
* @param requirements - Array of permission requirements
* @param options - Check options
* @returns Array of permission check results
*/
checkPermissions(userId: string, requirements: Array<{
requirement: any;
resolverType?: PermissionResolverType;
}>, options?: PermissionCheckOptions): Promise<PermissionCheckResult[]>;
/**
* Invalidate user context cache
*
* Removes user context from cache when permissions change.
* Uses conservative approach by also clearing related cached data.
*
* @param userId - User identifier
* @param clearRelated - Also clear permission-related caches
*/
invalidateUserContext(userId: string, clearRelated?: boolean): Promise<void>;
/**
* Pre-expand wildcard permissions for user context
*
* Used when pre-expansion strategy is enabled to convert
* wildcard permissions to concrete permission sets.
*
* @param permissions - Raw permissions from user/roles
* @returns Expanded permission set
*/
expandPermissions(permissions: string[]): Promise<Set<string>>;
/**
* Get service performance statistics
*/
getStats(): {
contextLoads: number;
permissionChecks: number;
cacheHitRate: number;
cacheHits: number;
cacheMisses: number;
averageResolutionTimeUs: number;
totalResolutionTimeUs: number;
resolverStats: {
plain: {
checkCount: number;
averageResolutionTimeUs: number;
totalResolutionTimeUs: number;
};
wildcard: {
strategy: PermissionResolutionStrategy;
checkCount: number;
averageResolutionTimeUs: number;
totalResolutionTimeUs: number;
cacheHitRate: number;
cacheHits: number;
cacheMisses: number;
};
expression: {
checkCount: number;
averageResolutionTimeUs: number;
totalResolutionTimeUs: number;
cacheHitRate: number;
cacheHits: number;
cacheMisses: number;
complexityDistribution: {
simple: number;
moderate: number;
complex: number;
};
};
};
};
/**
* Reset performance statistics
*/
resetStats(): void;
/**
* Load user context from cache
*/
private loadFromCache;
/**
* Save user context to cache
*/
private saveToCache;
/**
* Build user context from raw user data
*/
private buildUserContext;
/**
* Select appropriate permission resolver
*/
private selectResolver;
/**
* Get resolver by type
*/
private getResolverByType;
/**
* Record audit trail for permission checks
*/
private recordAuditTrail;
}
//# sourceMappingURL=FastUserContextService.d.ts.map