handleRequest method
Handles an incoming ServerRequest through the full SSR pipeline.
Implementation
Future<ServerResponse> handleRequest(ServerRequest request) async {
// 1. Method verification: Only GET and HEAD are supported for SSR
if (request.method != 'GET' && request.method != 'HEAD') {
return ServerResponse(
statusCode: 405,
headers: {'Allow': 'GET, HEAD'},
body: 'Method Not Allowed',
);
}
// 2. Host Validation & Tenant Resolution (Multi-Tenant Security Guard)
TenantContext? validatedTenant;
if (tenantHostValidator != null) {
final host = request.header('host') ?? request.uri.host;
if (host.isEmpty) {
return ServerResponse(
statusCode: 400,
body: 'Bad Request: Missing Host header.',
);
}
try {
validatedTenant = tenantHostValidator!.validate(host);
} on HostValidationException catch (e) {
return ServerResponse(
statusCode: 400,
body: 'Bad Request: ${e.message}',
);
}
}
// 3. Redirect Resolution
final redirect = redirects.resolve(request.path);
if (redirect != null) {
return ServerResponse.redirect(
redirect.targetPath,
statusCode: redirect.statusCode,
);
}
// 4. Route Matching
final match = _findRoute(request.path);
if (match == null) {
return ServerResponse.notFound(
message: 'No route matched path "${request.path}".',
);
}
final route = match.route;
final params = match.parameters;
final context = RouteDataContext(
path: request.path,
parameters: params,
queryParameters: request.queryParameters,
headers: request.headers,
locale:
validatedTenant?.defaultLocale ??
request.header('accept-language')?.split(',').first.trim() ??
config.language,
);
final selectedArtifactStore = validatedTenant == null
? artifactStore
: artifactStoreForTenant?.call(validatedTenant);
final canUseArtifacts =
selectedArtifactStore != null &&
artifactMaxAge != null &&
artifactMaxAge! >= Duration.zero &&
request.queryParameters.isEmpty &&
request.header('authorization') == null &&
request.header('cookie') == null &&
request.header('accept-language') == null;
var artifactMiss = false;
// Fresh, published HTML can satisfy a request without loading route data.
if (canUseArtifacts) {
final published = await selectedArtifactStore.readPublished(request.path);
final dependency = published?.dependency;
final generatedAt = dependency?.generatedAt;
if (dependency != null && generatedAt != null && published != null) {
final html = published.html;
final etag = _generateEtag(html);
final lastModified = dependency.lastModified ?? generatedAt;
final age = DateTime.now().toUtc().difference(generatedAt);
final stale = age > artifactMaxAge!;
if (stale && onStaleArtifact != null) {
unawaited(_notifyStaleArtifact(request.path, dependency));
final responseHtml = request.method == 'HEAD' ? '' : html;
return ServerResponse.okHtml(
responseHtml,
etag: etag,
lastModified: lastModified,
cacheControl:
'public, max-age=0, stale-while-revalidate=${artifactStaleWhileRevalidate.inSeconds}',
headers: {'X-MetaMantle-Cache': 'STALE-ARTIFACT'},
);
}
if (stale) {
// Without a revalidation hook, stale artifacts fall through to SSR.
} else {
if (_isNotModified(request, etag, lastModified)) {
return ServerResponse.notModified(
etag: etag,
lastModified: lastModified,
cacheControl: 'public, max-age=${artifactMaxAge!.inSeconds}',
);
}
return _buildResponse(
request,
html: html,
etag: etag,
lastModified: lastModified,
policy: CachePolicy(ttl: artifactMaxAge!),
cacheStatus: 'ARTIFACT',
);
}
} else {
artifactMiss = true;
}
}
if (canUseArtifacts &&
artifactMiss &&
route.artifactMissPolicy == ArtifactMissPolicy.notFound) {
return ServerResponse.notFound(
message: 'No generated artifact exists for "${request.path}".',
);
}
// 5. Cache Key Calculation (Tenant-partitioned)
final cacheKey = _computeCacheKey(
request,
route,
tenantContext: validatedTenant,
);
// 6. Cache Lookup
if (route.cachePolicy.isCacheable) {
final cached = await cache.get(cacheKey);
if (cached != null) {
// Check conditional GET (RFC 7232 precedence & weak ETag)
if (_isNotModified(request, cached.etag, cached.lastModified)) {
return ServerResponse.notModified(
etag: cached.etag,
lastModified: cached.lastModified,
cacheControl: _buildCacheControl(route.cachePolicy),
);
}
// Stale-While-Revalidate background regeneration
if (cached.isStaleWhileRevalidate()) {
unawaited(_regenerate(route, context, cacheKey));
}
return _buildResponse(
request,
html: cached.html,
etag: cached.etag,
lastModified: cached.lastModified,
policy: route.cachePolicy,
cacheStatus: cached.isStaleWhileRevalidate() ? 'STALE' : 'HIT',
);
}
}
// 7. Cache Miss: Execute single-flight regeneration
try {
final rendered = await singleFlight.run(
cacheKey,
() => _renderRoute(route, context, cacheKey),
);
if (rendered.response != null) {
return rendered.response!;
}
var cacheStatus = 'MISS';
if (canUseArtifacts &&
artifactMiss &&
route.artifactMissPolicy == ArtifactMissPolicy.renderAndPublish) {
final published = await _publishOnDemandArtifact(
path: request.path,
route: route,
rendered: rendered,
store: selectedArtifactStore,
);
if (published) cacheStatus = 'MISS-PUBLISHED';
}
// Check conditional GET on fresh render
if (_isNotModified(request, rendered.etag, rendered.lastModified)) {
return ServerResponse.notModified(
etag: rendered.etag,
lastModified: rendered.lastModified,
cacheControl: _buildCacheControl(route.cachePolicy),
);
}
return _buildResponse(
request,
html: rendered.html!,
etag: rendered.etag,
lastModified: rendered.lastModified,
policy: route.cachePolicy,
cacheStatus: cacheStatus,
);
} catch (e) {
if (route.cachePolicy.staleIfError != null) {
final stale = await cache.get(cacheKey, allowStale: true);
if (stale != null && stale.isStaleIfError()) {
return _buildResponse(
request,
html: stale.html,
etag: stale.etag,
lastModified: stale.lastModified,
policy: route.cachePolicy,
cacheStatus: 'STALE-IF-ERROR',
);
}
}
return ServerResponse.serverError();
}
}