Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/lib/metrics/storage-traffic.ts
T

75 lines
2.6 KiB
TypeScript

/**
* Low-cardinality storage-delivery telemetry for BILL-25.
*
* The counters deliberately describe an authorization/delivery decision, not
* provider egress: a presigned URL can remain unused, be reused before expiry,
* or serve byte ranges without another application request. Never add tenant,
* file, object-key, filename, or URL labels here.
*/
import type { DefaultMetrics } from "@hivegrid/metrics";
import { getWebMetrics } from "./registry.js";
const STORAGE_DOWNLOAD_SURFACES = ["files", "portal_document"] as const;
const STORAGE_DOWNLOAD_DELIVERIES = ["signed_redirect"] as const;
export type StorageDownloadSurface = (typeof STORAGE_DOWNLOAD_SURFACES)[number];
export type StorageDownloadDelivery = (typeof STORAGE_DOWNLOAD_DELIVERIES)[number];
type StorageTrafficMetrics = Pick<
DefaultMetrics,
"storageAuthorizedDownloadsTotal" | "storageAuthorizedDownloadObjectBytesTotal"
>;
export type AuthorizedStorageDownloadInput = {
readonly surface: StorageDownloadSurface;
readonly delivery: StorageDownloadDelivery;
/** Whole-object size when the authorization boundary has a trustworthy value. */
readonly objectSizeBytes?: number | null;
};
type RecordAuthorizedStorageDownloadOptions = {
/** Test seam; production always uses the web service-scoped registry. */
readonly metrics?: StorageTrafficMetrics;
};
export function recordAuthorizedStorageDownload(
input: AuthorizedStorageDownloadInput,
options: RecordAuthorizedStorageDownloadOptions = {}
): void {
let metrics: StorageTrafficMetrics;
try {
metrics = options.metrics ?? getWebMetrics().metrics;
} catch {
return;
}
const surface = boundedLabel(input.surface, STORAGE_DOWNLOAD_SURFACES);
const delivery = boundedLabel(input.delivery, STORAGE_DOWNLOAD_DELIVERIES);
const objectSizeBytes = knownObjectSize(input.objectSizeBytes);
try {
metrics.storageAuthorizedDownloadsTotal
.labels({ surface, delivery, size_known: objectSizeBytes === null ? "unknown" : "known" })
.inc();
} catch {
// Observability must never block a valid download.
}
if (objectSizeBytes !== null) {
try {
metrics.storageAuthorizedDownloadObjectBytesTotal.labels({ surface, delivery }).inc(objectSizeBytes);
} catch {
// Keep the authorization path fail-open even when one metric is broken.
}
}
}
function boundedLabel<TValue extends string>(value: TValue, allowed: readonly TValue[]): TValue | "other" {
return allowed.includes(value) ? value : "other";
}
function knownObjectSize(value: number | null | undefined): number | null {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
}