Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(platfor-415): usage metering pipeline for License Server v2

Tre Dubrava5669d10660e7
diff --git a/backend/src/ee/services/pam-resource/pam-resource-service.ts b/backend/src/ee/services/pam-resource/pam-resource-service.ts
index a101cd9f8d..cfbc98ae37 100644
--- a/backend/src/ee/services/pam-resource/pam-resource-service.ts
+++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts
@@ -19,6 +19,8 @@ import { TAppConnectionDALFactory } from "@app/services/app-connection/app-conne
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
+import { MaxResources } from "@app/services/license-client";
+import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";
@@ -68,6 +70,7 @@ type TPamResourceServiceFactoryDep = {
pamProjectRecordingConfigDAL: {
findByProjectId: (projectId: string) => Promise<unknown>;
};
+ usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
};
export type TPamResourceServiceFactory = ReturnType<typeof pamResourceServiceFactory>;
@@ -83,7 +86,8 @@ export const pamResourceServiceFactory = ({
gatewayPoolService,
resourceMetadataDAL,
appConnectionDAL,
- pamProjectRecordingConfigDAL
+ pamProjectRecordingConfigDAL,
+ usageMeteringService
}: TPamResourceServiceFactoryDep) => {
const assertDomainInProject = async (domainId: string, projectId: string) => {
const domain = await pamDomainDAL.findById(domainId);
@@ -287,6 +291,8 @@ export const pamResourceServiceFactory = ({
return { resource: newResource, insertedMetadata: metadataRows };
});
+ usageMeteringService.emitForProject(projectId, MaxResources.key);
+
return {
...(await decryptResource(resource, projectId, kmsService)),
metadata: insertedMetadata?.map(({ id, key, value }) => ({ id, key, value: value ?? "" })) ?? []
@@ -616,6 +622,7 @@ export const pamResourceServiceFactory = ({
try {
const deletedResource = await pamResourceDAL.deleteById(id);
+ usageMeteringService.emitForProject(resource.projectId, MaxResources.key);
return await decryptResource(deletedResource, resource.projectId, kmsService);
} catch (err) {
if (
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index aaac1a7eed..20dafbf278 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -132,6 +132,7 @@ export const KeyStorePrefixes = {
AuditLogMigrationAlert: "audit-log-migration-alert-last-row-count",
LicenseCloudPlan: (orgId: string) => `infisical-cloud-plan-${orgId}` as const,
LicenseEntitlements: (orgId: string) => `license-entitlements-${orgId}` as const,
+ UsageLastReported: (orgId: string, featureKey: string) => `usage-last-reported-${orgId}-${featureKey}` as const,
IdentityLockoutState: (identityId: string, authMethod: string, slug: string) =>
`lockout:identity:${identityId}:${authMethod}:${slug}` as const,
IdentityLockoutStateByMethodPattern: (identityId: string, authMethod: string) =>
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 9661687fc1..7f96f213e7 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -37,7 +37,8 @@ export const CronJobName = {
SignerDailyAutoRenewal: "signer-daily-auto-renewal",
SignerIssuancePolling: "signer-issuance-polling",
AuditLogStreamOutboxStaleClaimSweeper: "audit-log-stream-outbox-stale-claim-sweeper",
- AuditLogStreamOutboxCleanup: "audit-log-stream-outbox-cleanup"
+ AuditLogStreamOutboxCleanup: "audit-log-stream-outbox-cleanup",
+ UsageFlush: "usage-flush"
} as const;
// ── tuning constants ──────────────────────────────────────────────────────────
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 71a902207f..a6da7ffdab 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -114,7 +114,8 @@ export enum QueueName {
CaAutoRenewal = "ca-auto-renewal",
ProjectHardDelete = "project-hard-delete",
SignerAutoRenewal = "signer-auto-renewal",
- SecretBlindIndexMigration = "secret-blind-index-migration"
+ SecretBlindIndexMigration = "secret-blind-index-migration",
+ UsageEvent = "usage-event"
}
export enum QueueJobs {
@@ -191,7 +192,8 @@ export enum QueueJobs {
GoDaddyOrderPolling = "godaddy-order-polling-job",
ProjectHardDelete = "project-hard-delete-job",
SignerDailyAutoRenewal = "signer-daily-auto-renewal",
- SecretBlindIndexMigration = "secret-blind-index-migration"
+ SecretBlindIndexMigration = "secret-blind-index-migration",
+ UsageEvent = "usage-event-job"
}
export enum JobState {
@@ -528,6 +530,10 @@ export type TQueueJobTypes = {
name: QueueJobs.SecretBlindIndexMigration;
payload: { projectId: string };
};
+ [QueueName.UsageEvent]: {
+ name: QueueJobs.UsageEvent;
+ payload: { orgId: string; featureKey: string };
+ };
};
const SECRET_SCANNING_QUEUES = [
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index e5470935f0..f932ba0f20 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -379,6 +379,13 @@ import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal"
import { kmsServiceFactory } from "@app/services/kms/kms-service";
import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";
import { licenseClientFactory } from "@app/services/license-client";
+import {
+ buildMeteredFeatures,
+ buildUsageReporter,
+ usageCounterDALFactory,
+ usageEventQueueFactory,
+ usageMeteringServiceFactory
+} from "@app/services/license-client/usage";
import { applicationMembershipCleanupServiceFactory } from "@app/services/membership/application-membership-cleanup-service";
import { membershipDALFactory } from "@app/services/membership/membership-dal";
import { membershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
@@ -791,6 +798,28 @@ export const registerRoutes = async (
// is the single read primitive; falls back to feature defaults until the server is configured.
const licenseClient = licenseClientFactory({ envConfig, keyStore });
+ // Usage metering: counts the 5 metered features and reports them to the License Server. Inert
+ // until LICENSE_SERVER_V2_ENABLED is on (the emitter no-ops, the worker no-ops without a reporter).
+ const usageCounterDAL = usageCounterDALFactory(db);
+ const meteredFeatures = buildMeteredFeatures({ licenseDAL, usageCounterDAL });
+ meteredFeatures.forEach(({ feature, count }) => licenseClient.registerCounter(feature, count));
+ const usageReporter = buildUsageReporter(envConfig);
+ const usageMeteringService = usageMeteringServiceFactory({ queueService, projectDAL, envConfig });
+ let usageSource = "self-hosted";
+ if (envConfig.isCloud) {
+ usageSource = "cloud";
+ }
+ const usageEventQueue = usageEventQueueFactory({
+ queueService,
+ cronJob,
+ keyStore,
+ orgDAL,
+ usageMeteringService,
+ meteredFeatures,
+ usageReporter,
+ source: usageSource
+ });
+
// Project events SSE service (for clients to subscribe to secret mutation events)
const projectEventsSSEService = projectEventsSSEServiceFactory({
projectEventsService,
@@ -2142,7 +2171,8 @@ export const registerRoutes = async (
keyStore,
orgDAL,
membershipIdentityDAL,
- membershipRoleDAL
+ membershipRoleDAL,
+ usageMeteringService
});
const identityAccessTokenService = identityAccessTokenServiceFactory({
@@ -2791,7 +2821,8 @@ export const registerRoutes = async (
kmsService,
permissionService,
licenseService,
- caSigningConfigDAL
+ caSigningConfigDAL,
+ usageMeteringService
});
const caAutoRenewalQueue = caAutoRenewalQueueFactory({
@@ -2831,7 +2862,8 @@ export const registerRoutes = async (
certificateRequestDAL,
resourceMetadataDAL,
gatewayV2Service,
- gatewayPoolService
+ gatewayPoolService,
+ usageMeteringService
});
const certificateEstService = certificateEstServiceFactory({
@@ -2892,7 +2924,8 @@ export const registerRoutes = async (
resourceMetadataDAL,
pkiAlertV2Queue,
pkiApplicationDAL,
- licenseService
+ licenseService,
+ usageMeteringService
});
const digicertCaFns = DigiCertCertificateAuthorityFns({
@@ -3381,7 +3414,8 @@ export const registerRoutes = async (
gatewayPoolService,
resourceMetadataDAL,
appConnectionDAL,
- pamProjectRecordingConfigDAL
+ pamProjectRecordingConfigDAL,
+ usageMeteringService
});
const pamDomainService = pamDomainServiceFactory({
@@ -3623,6 +3657,7 @@ export const registerRoutes = async (
dailyResourceCleanUp.init();
projectEnvQueue.init();
projectCleanupQueue.init();
+ usageEventQueue.init();
healthAlert.init();
auditLogStreamOutboxQueue.init();
pkiSyncCleanup.init();
diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.ts
index afc45b538b..fb02898e32 100644
--- a/backend/src/services/certificate-authority/certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts
@@ -27,6 +27,8 @@ import {
TUpdateCertificateRequestStatusDTO
} from "../certificate-request/certificate-request-types";
import { TKmsServiceFactory } from "../kms/kms-service";
+import { MaxInternalCas } from "../license-client";
+import { TUsageMeteringServiceFactory } from "../license-client/usage";
import { TPkiSubscriberDALFactory } from "../pki-subscriber/pki-subscriber-dal";
import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
@@ -139,6 +141,7 @@ type TCertificateAuthorityServiceFactoryDep = {
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
};
export type TCertificateAuthorityServiceFactory = ReturnType<typeof certificateAuthorityServiceFactory>;
@@ -162,7 +165,8 @@ export const certificateAuthorityServiceFactory = ({
certificateRequestDAL,
resourceMetadataDAL,
gatewayV2Service,
- gatewayPoolService
+ gatewayPoolService,
+ usageMeteringService
}: TCertificateAuthorityServiceFactoryDep) => {
const acmeFns = AcmeCertificateAuthorityFns({
appConnectionDAL,
@@ -291,6 +295,8 @@ export const certificateAuthorityServiceFactory = ({
});
}
+ usageMeteringService.emitForProject(projectId, MaxInternalCas.key);
+
return {
id: ca.id,
type,
@@ -783,6 +789,7 @@ export const certificateAuthorityServiceFactory = ({
await certificateAuthorityDAL.deleteById(certificateAuthority.id);
if (type === CaType.INTERNAL) {
+ usageMeteringService.emitForProject(certificateAuthority.projectId, MaxInternalCas.key);
return {
id: certificateAuthority.id,
type,
@@ -1000,6 +1007,7 @@ export const certificateAuthorityServiceFactory = ({
await certificateAuthorityDAL.deleteById(certificateAuthority.id);
if (type === CaType.INTERNAL) {
+ usageMeteringService.emitForProject(certificateAuthority.projectId, MaxInternalCas.key);
return {
id: certificateAuthority.id,
type,
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index ff4789d34d..7179b9dd34 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -34,6 +34,8 @@ import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { MaxActiveCerts } from "@app/services/license-client";
+import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal";
import { TPkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-collection-item-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -129,6 +131,7 @@ type TInternalCertificateAuthorityServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
caSigningConfigDAL: Pick<TCaSigningConfigDALFactory, "findByCaId" | "create" | "deleteById" | "transaction">;
+ usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
};
export type TInternalCertificateAuthorityServiceFactory = ReturnType<typeof internalCertificateAuthorityServiceFactory>;
@@ -149,7 +152,8 @@ export const internalCertificateAuthorityServiceFactory = ({
kmsService,
permissionService,
licenseService,
- caSigningConfigDAL
+ caSigningConfigDAL,
+ usageMeteringService
}: TInternalCertificateAuthorityServiceFactoryDep) => {
const $validatePqcLicense = (keyAlgorithm: string, projectId: string) =>
validatePqcLicense({ keyAlgorithm, projectId, projectDAL, licenseService });
@@ -2091,6 +2095,8 @@ export const internalCertificateAuthorityServiceFactory = ({
cert = await certificateDAL.transaction(executeIssueCertOperations);
}
+ usageMeteringService.emitForProject(ca.projectId, MaxActiveCerts.key);
+
return {
certificate: leafCert.toString("pem"),
certificateChain: certificateChainPem,
@@ -2550,6 +2556,8 @@ export const internalCertificateAuthorityServiceFactory = ({
cert = await certificateDAL.transaction(createSignedCert);
}
+ usageMeteringService.emitForProject(ca.projectId, MaxActiveCerts.key);
+
return {
certificate: leafCert,
certificateChain: certificateChainPem,
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index cf4f4ba6d6..03709c15fc 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -27,6 +27,8 @@ import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { MaxActiveCerts } from "@app/services/license-client";
+import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
@@ -101,6 +103,7 @@ type TCertificateServiceFactoryDep = {
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
};
export type TCertificateServiceFactory = ReturnType<typeof certificateServiceFactory>;
@@ -125,7 +128,8 @@ export const certificateServiceFactory = ({
resourceMetadataDAL,
pkiAlertV2Queue,
pkiApplicationDAL,
- licenseService
+ licenseService,
+ usageMeteringService
}: TCertificateServiceFactoryDep) => {
const $canActOnCertViaApplication = async (
cert: { applicationId?: string | null; projectId: string },
@@ -402,6 +406,8 @@ export const certificateServiceFactory = ({
pkiSyncQueue
});
+ usageMeteringService.emitForProject(cert.projectId, MaxActiveCerts.key);
+
return {
deletedCert
};
@@ -517,6 +523,8 @@ export const certificateServiceFactory = ({
}
);
+ usageMeteringService.emitForProject(ca.projectId, MaxActiveCerts.key);
+
// Trigger auto sync for PKI syncs connected to this certificate
await triggerAutoSyncForCertificate(cert.id, {
certificateSyncDAL,
@@ -908,6 +916,8 @@ export const certificateServiceFactory = ({
}
});
+ usageMeteringService.emitForProject(projectId, MaxActiveCerts.key);
+
return {
certificate: certificatePem,
certificateChain: chainPem,
diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.ts
index c03ccad70d..01150110f5 100644
--- a/backend/src/services/identity/identity-service.ts
+++ b/backend/src/services/identity/identity-service.ts
@@ -14,6 +14,8 @@ import { BadRequestError, NotFoundError, PermissionBoundaryError } from "@app/li
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { TIdentityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";
+import { MaxIdentities } from "@app/services/license-client";
+import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
import { ActorType } from "../auth/auth-type";
@@ -48,6 +50,7 @@ type TIdentityServiceFactoryDep = {
keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;
orgDAL: Pick<TOrgDALFactory, "findById" | "findEffectiveOrgMembership">;
additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;
+ usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
};
export type TIdentityServiceFactory = ReturnType<typeof identityServiceFactory>;
@@ -64,7 +67,8 @@ export const identityServiceFactory = ({
orgDAL,
membershipIdentityDAL,
membershipRoleDAL,
- additionalPrivilegeDAL
+ additionalPrivilegeDAL,
+ usageMeteringService
}: TIdentityServiceFactoryDep) => {
const createIdentity = async ({
name,
@@ -182,6 +186,7 @@ export const identityServiceFactory = ({
};
});
await licenseService.updateSubscriptionOrgMemberCount(orgId);
+ usageMeteringService.emit(orgId, MaxIdentities.key);
return identity;
};
@@ -373,6 +378,7 @@ export const identityServiceFactory = ({
const deletedIdentity = await identityDAL.deleteById(id);
await licenseService.updateSubscriptionOrgMemberCount(identityOrgMembership.scopeOrgId);
+ usageMeteringService.emit(identityOrgMembership.scopeOrgId, MaxIdentities.key);
return { ...deletedIdentity, orgId: identityOrgMembership.scopeOrgId };
}
@@ -406,6 +412,7 @@ export const identityServiceFactory = ({
});
const deletedIdentity = await requestMemoize(requestMemoKeys.identityFindById(id), () => identityDAL.findById(id));
+ usageMeteringService.emit(identityOrgMembership.scopeOrgId, MaxIdentities.key);
return { ...deletedIdentity, orgId: identityOrgMembership.scopeOrgId };
};
diff --git a/backend/src/services/license-client/features.ts b/backend/src/services/license-client/features.ts
index b1eef16303..38a31a09cf 100644
--- a/backend/src/services/license-client/features.ts
+++ b/backend/src/services/license-client/features.ts
@@ -3,5 +3,10 @@ import { defineFeature, defineLimitFeature } from "./feature";
// Add a constant here when a call site needs to gate on a feature. The key matches a license
// server feature by name; the fallback is served when the server is disabled or unreachable.
export const SsoEnforcement = defineFeature("sso_enforcement", false);
-export const MaxIdentities = defineLimitFeature("max_identities", 0);
export const AuditRetentionDays = defineFeature("audit_retention_days", 30);
+
+// Metered limit features. Their key is both the resolved cap and the usage meter (see usage/).
+export const MaxIdentities = defineLimitFeature("max_identities", 0);
+export const MaxInternalCas = defineLimitFeature("max_internal_cas", 0);
+export const MaxActiveCerts = defineLimitFeature("max_active_certs", 0);
+export const MaxResources = defineLimitFeature("max_resources", 0);
diff --git a/backend/src/services/license-client/usage/index.ts b/backend/src/services/license-client/usage/index.ts
new file mode 100644
index 0000000000..8d7706397b
--- /dev/null
+++ b/backend/src/services/license-client/usage/index.ts
@@ -0,0 +1,9 @@
+export type { TUsageCounterDALFactory } from "./usage-counter-dal";
+export { usageCounterDALFactory } from "./usage-counter-dal";
+export type { TMeteredFeature } from "./usage-counters";
+export { buildMeteredFeatures } from "./usage-counters";
+export { usageEventQueueFactory } from "./usage-event-queue";
+export type { TUsageMeteringServiceFactory } from "./usage-metering-service";
+export { usageMeteringServiceFactory } from "./usage-metering-service";
+export type { TUsageReporter, TUsageSnapshot } from "./usage-reporter";
+export { buildUsageReporter, usageReporterFactory } from "./usage-reporter";
diff --git a/backend/src/services/license-client/usage/usage-counter-dal.ts b/backend/src/services/license-client/usage/usage-counter-dal.ts
new file mode 100644
index 0000000000..cc86d4433a
--- /dev/null
+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts
@@ -0,0 +1,69 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { CertStatus } from "@app/services/certificate/certificate-types";
+
+export type TUsageCounterDALFactory = ReturnType<typeof usageCounterDALFactory>;
+
+const toCount = (row: unknown): number => Number((row as { count?: string | number } | undefined)?.count ?? 0);
+
+// Live counts for the project-scoped metered features. Each sums across the org's projects,
+// excluding soft-deleted projects so they don't inflate a quota. Org-scoped identities are
+// counted via licenseDAL.countOrgUsersAndIdentities and wired in usage-counters.ts.
+export const usageCounterDALFactory = (db: TDbClient) => {
+ const countInternalCas = async (orgId: string): Promise<number> => {
+ try {
+ const row = await db
+ .replicaNode()(TableName.CertificateAuthority)
+ .join(
+ TableName.InternalCertificateAuthority,
+ `${TableName.CertificateAuthority}.id`,
+ `${TableName.InternalCertificateAuthority}.caId`
+ )
+ .join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .count(`${TableName.CertificateAuthority}.id as count`)
+ .first();
+ return toCount(row);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count internal CAs for usage" });
+ }
+ };
+
+ const countActiveCerts = async (orgId: string): Promise<number> => {
+ try {
+ const row = await db
+ .replicaNode()(TableName.Certificate)
+ .join(TableName.Project, `${TableName.Certificate}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .where(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
+ .where(`${TableName.Certificate}.notAfter`, ">", new Date())
+ .whereNull(`${TableName.Certificate}.revokedAt`)
+ .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
+ .count(`${TableName.Certificate}.id as count`)
+ .first();
+ return toCount(row);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count active certificates for usage" });
+ }
+ };
+
+ const countPamResources = async (orgId: string): Promise<number> => {
+ try {
+ const row = await db
+ .replicaNode()(TableName.PamResource)
+ .join(TableName.Project, `${TableName.PamResource}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .count(`${TableName.PamResource}.id as count`)
+ .first();
+ return toCount(row);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count PAM resources for usage" });
+ }
+ };
+
+ return { countInternalCas, countActiveCerts, countPamResources };
+};
diff --git a/backend/src/services/license-client/usage/usage-counters.ts b/backend/src/services/license-client/usage/usage-counters.ts
new file mode 100644
index 0000000000..7f15ddab64
--- /dev/null
+++ b/backend/src/services/license-client/usage/usage-counters.ts
@@ -0,0 +1,24 @@
+import { TLicenseDALFactory } from "@app/ee/services/license/license-dal";
+
+import { TFeatureCounterFn, TLimitFeatureDescriptor } from "../feature";
+import { MaxActiveCerts, MaxIdentities, MaxInternalCas, MaxResources } from "../features";
+import { TUsageCounterDALFactory } from "./usage-counter-dal";
+
+export type TMeteredFeature = {
+ feature: TLimitFeatureDescriptor;
+ count: TFeatureCounterFn;
+};
+
+type TBuildMeteredFeaturesDep = {
+ licenseDAL: Pick<TLicenseDALFactory, "countOrgUsersAndIdentities">;
+ usageCounterDAL: TUsageCounterDALFactory;
+};
+
+// The single source of truth pairing each metered feature with its live-count fn. Reused by the
+// worker (count + report) and by registerCounter (so canUse() resolves current usage).
+export const buildMeteredFeatures = ({ licenseDAL, usageCounterDAL }: TBuildMeteredFeaturesDep): TMeteredFeature[] => [
+ { feature: MaxIdentities, count: (orgId) => licenseDAL.countOrgUsersAndIdentities(orgId) },
+ { feature: MaxInternalCas, count: (orgId) => usageCounterDAL.countInternalCas(orgId) },
+ { feature: MaxActiveCerts, count: (orgId) => usageCounterDAL.countActiveCerts(orgId) },
+ { feature: MaxResources, count: (orgId) => usageCounterDAL.countPamResources(orgId) }
+];
diff --git a/backend/src/services/license-client/usage/usage-event-queue.ts b/backend/src/services/license-client/usage/usage-event-queue.ts
new file mode 100644
index 0000000000..74bb31f610
--- /dev/null
+++ b/backend/src/services/license-client/usage/usage-event-queue.ts
@@ -0,0 +1,109 @@
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { getConfig } from "@app/lib/config/env";
+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
+import { logger } from "@app/lib/logger";
+import { QueueName, TQueueServiceFactory } from "@app/queue";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+
+import { TMeteredFeature } from "./usage-counters";
+import { TUsageMeteringServiceFactory } from "./usage-metering-service";
+import { TUsageReporter } from "./usage-reporter";
+
+type TUsageEventQueueFactoryDep = {
+ queueService: Pick<TQueueServiceFactory, "start">;
+ cronJob: TCronJobFactory;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItem">;
+ orgDAL: Pick<TOrgDALFactory, "find">;
+ usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
+ meteredFeatures: TMeteredFeature[];
+ usageReporter: TUsageReporter | null;
+ source: string;
+};
+
+export const usageEventQueueFactory = ({
+ queueService,
+ cronJob,
+ keyStore,
+ orgDAL,
+ usageMeteringService,
+ meteredFeatures,
+ usageReporter,
+ source
+}: TUsageEventQueueFactoryDep) => {
+ const featureByKey = new Map(meteredFeatures.map((m) => [m.feature.key, m]));
+
+ // Counts the meter and reports it to the License Server only when the value changed since the last
+ // report. No-ops when the reporter is null (v2 disabled), so queued events drain harmlessly.
+ const handleUsageEvent = async (orgId: string, featureKey: string) => {
+ if (!usageReporter) {
+ return;
+ }
+
+ const metered = featureByKey.get(featureKey);
+ if (!metered) {
+ logger.warn(`usage-metering: unknown metered feature, dropping event [featureKey=${featureKey}]`);
+ return;
+ }
+
+ const value = await metered.count(orgId);
+
+ const lastReportedKey = KeyStorePrefixes.UsageLastReported(orgId, featureKey);
+ const lastReported = await keyStore.getItem(lastReportedKey);
+ if (lastReported !== null && Number(lastReported) === value) {
+ return;
+ }
+
+ const observedAt = new Date();
+ const minuteBucketSeconds = Math.floor(observedAt.getTime() / 60_000) * 60;
+ await usageReporter.reportSnapshots([
+ {
+ org_id: orgId,
+ feature_key: featureKey,
+ value,
+ observed_at: observedAt.toISOString(),
+ idempotency_key: `${source}:${orgId}:${featureKey}:${minuteBucketSeconds}`,
+ source
+ }
+ ]);
+
+ await keyStore.setItem(lastReportedKey, String(value));
+ };
+
+ // Self-hosted true-up: online instances also report event-driven, so this is a periodic backstop
+ // for cap visibility and renewal. Cloud is event-driven only.
+ const flushAllOrgs = async () => {
+ if (!usageReporter) {
+ return;
+ }
+
+ const orgs = await orgDAL.find({});
+ for (const org of orgs) {
+ for (const metered of meteredFeatures) {
+ usageMeteringService.emit(org.id, metered.feature.key);
+ }
+ }
+ };
+
+ const startWorker = () => {
+ // Counts are DB-heavy, so concurrency + limiter rate-shape a backlog instead of bursting the read replica.
+ queueService.start(QueueName.UsageEvent, (job) => handleUsageEvent(job.data.orgId, job.data.featureKey), {
+ concurrency: 5,
+ limiter: { max: 50, duration: 1000 }
+ });
+ };
+
+ const init = () => {
+ startWorker();
+
+ const appCfg = getConfig();
+ cronJob.register({
+ name: CronJobName.UsageFlush,
+ pattern: "*/30 * * * *",
+ runHashTtlS: 60 * 60,
+ enabled: !appCfg.isCloud,
+ handler: flushAllOrgs
+ });
+ };
+
+ return { init, handleUsageEvent, flushAllOrgs };
+};
diff --git a/backend/src/services/license-client/usage/usage-metering-service.ts b/backend/src/services/license-client/usage/usage-metering-service.ts
new file mode 100644
index 0000000000..9a50a0c614
--- /dev/null
+++ b/backend/src/services/license-client/usage/usage-metering-service.ts
@@ -0,0 +1,66 @@
+import { TEnvConfig } from "@app/lib/config/env";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+export type TUsageMeteringServiceFactory = ReturnType<typeof usageMeteringServiceFactory>;
+
+type TUsageMeteringServiceFactoryDep = {
+ queueService: Pick<TQueueServiceFactory, "queue">;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
+ envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_ENABLED">;
+};
+
+// Debounce window: bursts for the same {org, feature} collapse to one count because the delayed job
+// shares a deterministic jobId.
+const DEBOUNCE_MS = 60_000;
+
+export const usageMeteringServiceFactory = ({
+ queueService,
+ projectDAL,
+ envConfig
+}: TUsageMeteringServiceFactoryDep) => {
+ const enqueue = async (orgId: string, featureKey: string) => {
+ await queueService.queue(
+ QueueName.UsageEvent,
+ QueueJobs.UsageEvent,
+ { orgId, featureKey },
+ { jobId: `usage-event:${orgId}:${featureKey}`, delay: DEBOUNCE_MS, removeOnComplete: true, removeOnFail: true }
+ );
+ };
+
+ // Fire-and-forget signal from a metered create/delete on an org-scoped meter. Never awaited and
+ // never throws into the request path; inert until the v2 license server is enabled.
+ const emit = (orgId: string, featureKey: string) => {
+ if (!envConfig.LICENSE_SERVER_V2_ENABLED) {
+ return;
+ }
+
+ void enqueue(orgId, featureKey).catch((error) => {
+ logger.error(error, `usage-metering: failed to enqueue usage event [orgId=${orgId}] [featureKey=${featureKey}]`);
+ });
+ };
+
+ // Project-scoped meters sum across an org's projects, so the event is keyed by org. The org is
+ // resolved in the background to keep the request path free of an extra read.
+ const emitForProject = (projectId: string, featureKey: string) => {
+ if (!envConfig.LICENSE_SERVER_V2_ENABLED) {
+ return;
+ }
+
+ void (async () => {
+ const project = await projectDAL.findById(projectId);
+ if (!project) {
+ return;
+ }
+ await enqueue(project.orgId, featureKey);
+ })().catch((error) => {
+ logger.error(
+ error,
+ `usage-metering: failed to enqueue usage event [projectId=${projectId}] [featureKey=${featureKey}]`
+ );
+ });
+ };
+
+ return { emit, emitForProject };
+};
diff --git a/backend/src/services/license-client/usage/usage-metering.test.ts b/backend/src/services/license-client/usage/usage-metering.test.ts
new file mode 100644
index 0000000000..1f3336f5bd
--- /dev/null
+++ b/backend/src/services/license-client/usage/usage-metering.test.ts
@@ -0,0 +1,290 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { QueueJobs, QueueName } from "@app/queue";
+
+import { featureReaderFactory } from "../feature-reader";
+import { MaxActiveCerts, MaxIdentities, MaxInternalCas, MaxResources } from "../features";
+import { buildMeteredFeatures } from "./usage-counters";
+import { usageEventQueueFactory } from "./usage-event-queue";
+import { usageMeteringServiceFactory } from "./usage-metering-service";
+import { buildUsageReporter, TUsageSnapshot } from "./usage-reporter";
+
+type TQueueCall = [QueueName, QueueJobs, { orgId: string; featureKey: string }, { jobId: string; delay?: number }];
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
+}));
+
+const ORG_ID = "11111111-1111-1111-1111-111111111111";
+const PROJECT_ID = "33333333-3333-3333-3333-333333333333";
+
+const flushAsync = () =>
+ new Promise((resolve) => {
+ setImmediate(resolve);
+ });
+
+const makeQueueMock = () => vi.fn(async () => {});
+
+const createFakeKeyStore = () => {
+ const store = new Map<string, string>();
+ return {
+ getItem: vi.fn(async (key: string) => store.get(key) ?? null),
+ setItem: vi.fn(async (key: string, value: string | number | Buffer) => {
+ store.set(key, String(value));
+ return "OK" as const;
+ }),
+ store
+ };
+};
+
+describe("usageMeteringService.emit (org-scoped)", () => {
+ test("does nothing when the v2 license server is disabled", async () => {
+ const queue = makeQueueMock();
+ const svc = usageMeteringServiceFactory({
+ queueService: { queue },
+ projectDAL: { findById: vi.fn() },
+ envConfig: { LICENSE_SERVER_V2_ENABLED: false }
+ });
+
+ svc.emit(ORG_ID, MaxIdentities.key);
+ await flushAsync();
+
+ expect(queue).not.toHaveBeenCalled();
+ });
+
+ test("enqueues a debounced, deduplicated job when enabled", async () => {
+ const queue = makeQueueMock();
+ const svc = usageMeteringServiceFactory({
+ queueService: { queue },
+ projectDAL: { findById: vi.fn() },
+ envConfig: { LICENSE_SERVER_V2_ENABLED: true }
+ });
+
+ svc.emit(ORG_ID, MaxIdentities.key);
+ await flushAsync();
+
+ expect(queue).toHaveBeenCalledTimes(1);
+ const [name, job, data, opts] = queue.mock.calls[0] as unknown as TQueueCall;
+ expect(name).toBe(QueueName.UsageEvent);
+ expect(job).toBe(QueueJobs.UsageEvent);
+ expect(data).toEqual({ orgId: ORG_ID, featureKey: MaxIdentities.key });
+ expect(opts.jobId).toBe(`usage-event:${ORG_ID}:${MaxIdentities.key}`);
+ expect(opts.delay).toBe(60_000);
+ });
+
+ test("never throws into the caller when enqueue fails", async () => {
+ const queue = vi.fn(async () => {
+ throw new Error("redis down");
+ });
+ const svc = usageMeteringServiceFactory({
+ queueService: { queue },
+ projectDAL: { findById: vi.fn() },
+ envConfig: { LICENSE_SERVER_V2_ENABLED: true }
+ });
+
+ expect(() => svc.emit(ORG_ID, MaxIdentities.key)).not.toThrow();
+ await flushAsync();
+ });
+});
+
+describe("usageMeteringService.emitForProject (project-scoped)", () => {
+ test("resolves the org from the project and enqueues an org-keyed job", async () => {
+ const queue = makeQueueMock();
+ const findById = vi.fn(async () => ({ id: PROJECT_ID, orgId: ORG_ID }));
+ const svc = usageMeteringServiceFactory({
+ queueService: { queue },
+ projectDAL: { findById } as never,
+ envConfig: { LICENSE_SERVER_V2_ENABLED: true }
+ });
+
+ svc.emitForProject(PROJECT_ID, MaxResources.key);
+ await flushAsync();
+
+ expect(findById).toHaveBeenCalledWith(PROJECT_ID);
+ expect(queue).toHaveBeenCalledTimes(1);
+ const [, , data, opts] = queue.mock.calls[0] as unknown as TQueueCall;
+ expect(data).toEqual({ orgId: ORG_ID, featureKey: MaxResources.key });
+ expect(opts.jobId).toBe(`usage-event:${ORG_ID}:${MaxResources.key}`);
+ });
+
+ test("does not enqueue when the project is missing (e.g. soft-deleted)", async () => {
+ const queue = makeQueueMock();
+ const svc = usageMeteringServiceFactory({
+ queueService: { queue },
+ projectDAL: { findById: vi.fn(async () => undefined) } as never,
+ envConfig: { LICENSE_SERVER_V2_ENABLED: true }
+ });
+
+ svc.emitForProject(PROJECT_ID, MaxResources.key);
+ await flushAsync();
+
+ expect(queue).not.toHaveBeenCalled();
+ });
+
+ test("does nothing when disabled", async () => {
+ const queue = makeQueueMock();
+ const findById = vi.fn();
+ const svc = usageMeteringServiceFactory({
+ queueService: { queue },
+ projectDAL: { findById },
+ envConfig: { LICENSE_SERVER_V2_ENABLED: false }
+ });
+
+ svc.emitForProject(PROJECT_ID, MaxResources.key);
+ await flushAsync();
+
+ expect(findById).not.toHaveBeenCalled();
+ expect(queue).not.toHaveBeenCalled();
+ });
+});
+
+describe("buildUsageReporter", () => {
+ test("is null when disabled", () => {
+ expect(buildUsageReporter({ LICENSE_SERVER_V2_ENABLED: false })).toBeNull();
+ });
+
+ test("is null when enabled but unconfigured", () => {
+ expect(buildUsageReporter({ LICENSE_SERVER_V2_ENABLED: true })).toBeNull();
+ });
+
+ test("is a reporter when enabled and configured", () => {
+ const reporter = buildUsageReporter({
+ LICENSE_SERVER_V2_ENABLED: true,
+ LICENSE_SERVER_V2_URL: "https://license.example.com",
+ LICENSE_SERVER_V2_SERVICE_KEY: "svc-key"
+ });
+ expect(reporter).not.toBeNull();
+ expect(typeof reporter?.reportSnapshots).toBe("function");
+ });
+});
+
+describe("buildMeteredFeatures", () => {
+ test("wires all four meters to their count fns", async () => {
+ const licenseDAL = { countOrgUsersAndIdentities: vi.fn(async () => 7) };
+ const usageCounterDAL = {
+ countInternalCas: vi.fn(async () => 1),
+ countActiveCerts: vi.fn(async () => 2),
+ countPamResources: vi.fn(async () => 3)
+ };
+ const metered = buildMeteredFeatures({ licenseDAL, usageCounterDAL });
+
+ const byKey = Object.fromEntries(metered.map((m) => [m.feature.key, m.count]));
+ expect(Object.keys(byKey).sort()).toEqual(
+ [MaxIdentities.key, MaxInternalCas.key, MaxActiveCerts.key, MaxResources.key].sort()
+ );
+
+ expect(await byKey[MaxIdentities.key](ORG_ID)).toBe(7);
+ expect(await byKey[MaxInternalCas.key](ORG_ID)).toBe(1);
+ expect(await byKey[MaxActiveCerts.key](ORG_ID)).toBe(2);
+ expect(await byKey[MaxResources.key](ORG_ID)).toBe(3);
+ expect(licenseDAL.countOrgUsersAndIdentities).toHaveBeenCalledWith(ORG_ID);
+ });
+});
+
+describe("usageEventQueue.handleUsageEvent (worker)", () => {
+ const meteredFeatures = [{ feature: MaxIdentities, count: vi.fn(async () => 42) }];
+
+ const buildQueue = (
+ overrides: { usageReporter?: unknown; keyStore?: ReturnType<typeof createFakeKeyStore> } = {}
+ ) => {
+ const reportSnapshots = vi.fn(async () => {});
+ const keyStore = overrides.keyStore ?? createFakeKeyStore();
+ const usageReporter = overrides.usageReporter === undefined ? { reportSnapshots } : overrides.usageReporter;
+ const queue = usageEventQueueFactory({
+ queueService: { start: vi.fn() },
+ cronJob: { register: vi.fn(), start: vi.fn(), stop: vi.fn() } as never,
+ keyStore,
+ orgDAL: { find: vi.fn(async () => []) },
+ usageMeteringService: { emit: vi.fn() },
+ meteredFeatures,
+ usageReporter: usageReporter as never,
+ source: "test-region"
+ });
+ return { queue, reportSnapshots, keyStore };
+ };
+
+ beforeEach(() => {
+ meteredFeatures[0].count.mockClear();
+ });
+
+ test("no-ops when the reporter is null (v2 disabled)", async () => {
+ const { queue } = buildQueue({ usageReporter: null });
+ await queue.handleUsageEvent(ORG_ID, MaxIdentities.key);
+ expect(meteredFeatures[0].count).not.toHaveBeenCalled();
+ });
+
+ test("reports a snapshot and records the value on first observation", async () => {
+ const { queue, reportSnapshots, keyStore } = buildQueue();
+ await queue.handleUsageEvent(ORG_ID, MaxIdentities.key);
+
+ expect(reportSnapshots).toHaveBeenCalledTimes(1);
+ const [snapshots] = reportSnapshots.mock.calls[0] as unknown as [TUsageSnapshot[]];
+ expect(snapshots[0]).toMatchObject({
+ org_id: ORG_ID,
+ feature_key: MaxIdentities.key,
+ value: 42,
+ source: "test-region"
+ });
+ expect(keyStore.store.get(`usage-last-reported-${ORG_ID}-${MaxIdentities.key}`)).toBe("42");
+ });
+
+ test("skips the report when the count is unchanged", async () => {
+ const keyStore = createFakeKeyStore();
+ keyStore.store.set(`usage-last-reported-${ORG_ID}-${MaxIdentities.key}`, "42");
+ const { queue, reportSnapshots } = buildQueue({ keyStore });
+
+ await queue.handleUsageEvent(ORG_ID, MaxIdentities.key);
+ expect(reportSnapshots).not.toHaveBeenCalled();
+ });
+
+ test("drops events for unknown features", async () => {
+ const { queue, reportSnapshots } = buildQueue();
+ await queue.handleUsageEvent(ORG_ID, "not_a_meter");
+ expect(reportSnapshots).not.toHaveBeenCalled();
+ });
+});
+
+// Demonstrates how a metered create path would gate on the new framework once enforcement is wired
+// (PLATFOR-449/418): register the live-count fns with the SDK (as routes/index.ts does at boot),
+// then read the feature and call canUse() before allowing the action. No production call site does
+// this yet — these tests document the intended pattern.
+describe("canUse enforcement (using the framework from a call site)", () => {
+ const buildReader = (
+ caps: Record<string, { value: number }>,
+ counts: { identities?: number; internalCas?: number }
+ ) => {
+ const reader = featureReaderFactory({ getEntitlements: async () => ({ features: caps }) });
+ const licenseDAL = { countOrgUsersAndIdentities: async () => counts.identities ?? 0 };
+ const usageCounterDAL = {
+ countInternalCas: async () => counts.internalCas ?? 0,
+ countActiveCerts: async () => 0,
+ countPamResources: async () => 0
+ };
+ buildMeteredFeatures({ licenseDAL, usageCounterDAL }).forEach(({ feature, count }) =>
+ reader.registerCounter(feature, count)
+ );
+ return reader;
+ };
+
+ test("canUse() compares the live count against the cap resolved from entitlements", async () => {
+ const reader = buildReader({ max_identities: { value: 100 } }, { identities: 99 });
+
+ const identities = await reader.getFeature(ORG_ID, MaxIdentities);
+ expect(identities.value).toBe(100); // cap comes from the License Server entitlement
+ expect(await identities.canUse(1)).toBe(true); // 99 + 1 <= 100
+ expect(await identities.canUse(2)).toBe(false); // 99 + 2 > 100
+ });
+
+ test("a metered create path blocks once the cap is reached", async () => {
+ const reader = buildReader({ max_internal_cas: { value: 1 } }, { internalCas: 1 });
+
+ const assertCanCreateInternalCa = async () => {
+ const cas = await reader.getFeature(ORG_ID, MaxInternalCas);
+ if (!(await cas.canUse(1))) {
+ throw new Error(`max_internal_cas limit reached (cap ${cas.value})`);
+ }
+ };
+
+ await expect(assertCanCreateInternalCa()).rejects.toThrow("max_internal_cas limit reached (cap 1)");
+ });
+});
diff --git a/backend/src/services/license-client/usage/usage-reporter.ts b/backend/src/services/license-client/usage/usage-reporter.ts
new file mode 100644
index 0000000000..d4febc641d
--- /dev/null
+++ b/backend/src/services/license-client/usage/usage-reporter.ts
@@ -0,0 +1,57 @@
+import { TEnvConfig } from "@app/lib/config/env";
+import { logger } from "@app/lib/logger";
+
+const SNAPSHOTS_PATH = "/v1/usage/snapshots";
+
+export type TUsageSnapshot = {
+ org_id: string;
+ feature_key: string;
+ value: number;
+ observed_at: string;
+ idempotency_key: string;
+ source: string;
+};
+
+export type TUsageReporter = {
+ reportSnapshots: (snapshots: TUsageSnapshot[]) => Promise<void>;
+};
+
+export const usageReporterFactory = (serverUrl: string, serviceKey: string): TUsageReporter => ({
+ reportSnapshots: async (snapshots: TUsageSnapshot[]) => {
+ if (!snapshots.length) {
+ return;
+ }
+
+ const url = new URL(SNAPSHOTS_PATH, serverUrl);
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${serviceKey}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ snapshots }),
+ redirect: "manual"
+ });
+
+ if (!res.ok) {
+ throw new Error(`usage snapshot report failed with ${res.status}`);
+ }
+ }
+});
+
+// Returns null when the v2 license server is disabled or unconfigured, which keeps usage reporting
+// inert until Phase 2 flips LICENSE_SERVER_V2_ENABLED on.
+export const buildUsageReporter = (
+ envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_ENABLED" | "LICENSE_SERVER_V2_URL" | "LICENSE_SERVER_V2_SERVICE_KEY">
+): TUsageReporter | null => {
+ if (!envConfig.LICENSE_SERVER_V2_ENABLED) {
+ return null;
+ }
+
+ const serverUrl = envConfig.LICENSE_SERVER_V2_URL;
+ if (!serverUrl || !envConfig.LICENSE_SERVER_V2_SERVICE_KEY) {
+ logger.warn(
+ "usage-reporter: enabled but LICENSE_SERVER_V2_URL / LICENSE_SERVER_V2_SERVICE_KEY is missing; usage reporting disabled"
+ );
+ return null;
+ }
+
+ return usageReporterFactory(serverUrl, envConfig.LICENSE_SERVER_V2_SERVICE_KEY);
+};