Enterprise Edition
Database usage
Database usage is an Enterprise module, database_usage. It turns on with OM_ENABLE_ENTERPRISE_MODULES=true; there is no separate flag and it adds no database tables or migrations. It answers one operator question: which enabled modules occupy the most PostgreSQL storage or hold the most live records, and what (if anything) keeps that data from growing forever.
Overview
- Where: Settings → System → Database Usage (
/backend/config/database-usage). - Who: installation superadmins only. The user must be an active human user of an active tenant whose superadmin grant is not restricted to specific organizations. API keys, customer-portal principals, impersonated sessions and organization-scoped admins are denied before any catalog query runs. The page also requires the
database_usage.viewfeature; refreshing requiresdatabase_usage.refresh. - What: a treemap and a ranking table of enabled modules and their entities, sorted by allocated bytes (table + indexes + TOAST) or by estimated live records. Selecting an entity opens a detail drawer with its tables, indexes, partitions and the owning module's retention policy.
- Read-only: the dashboard never deletes, rotates, vacuums or otherwise modifies data. It only reads PostgreSQL catalog statistics and displays policy descriptors that owning modules publish.
Row counts are estimates (pg_stat_user_tables.n_live_tup, falling back to pg_class.reltuples), not COUNT(*). Bytes are allocated file sizes: deleting or rotating rows frees space inside PostgreSQL for reuse, but the file size shrinks only after maintenance such as VACUUM FULL or pg_repack.
How the snapshot is collected
The collector runs one bounded, read-only transaction (transaction_read_only, a short statement_timeout and lock_timeout) against the PostgreSQL catalog. Partitions are folded into their parent table, and the scan stops at 2,000 physical relations; when the cap is hit, the page shows a partial-coverage banner.
Relations are attributed to modules through the generated ORM entity-ownership registry, so a custom module's tables appear automatically once the module is enabled and its migrations are applied. A table claimed by more than one module, or by none, is shown as Shared / unattributed.
Snapshots are cached installation-wide (fresh for 5 minutes, served as stale for up to 30 minutes while a refresh runs). Concurrent refreshes are coalesced, and manual refresh has a 60-second cooldown.
| Endpoint | Purpose |
|---|---|
GET /api/database_usage/overview | Ranked module/entity snapshot. |
GET /api/database_usage/entities/{id} | Entity detail including the resolved retention policy. |
POST /api/database_usage/refresh | Forces a new snapshot (subject to the cooldown). |
All responses carry Cache-Control: private, no-store.
Retention policy states
The detail drawer shows one of four states for each entity:
| Status | Meaning |
|---|---|
active | The owning module rotates or expires rows. The drawer lists the trigger (write-triggered, scheduled worker, manual only) and the effective rules, such as the retention window. |
disabled | The owning module supports rotation, but it is turned off by configuration. |
unsupported | No provider is registered, the provider does not cover this entity, the owning module is disabled, or the entity is shared/unattributed. |
unavailable | The provider threw, returned an invalid descriptor, or claimed to own an entity it does not own. The footprint view stays available. |
Shipped providers: audit_logs (AccessLog write-triggered rotation; ActionLog unsupported), customer_accounts (CustomerUserSession expiry) and auth (Session unsupported).
Contributing retention guidance from your module
Any module — core, Enterprise, or an app module in src/modules/ — can tell the dashboard how its own data is rotated or expired. The contract is a read-only DI provider. It lives in @open-mercato/shared so your module does not depend on the Enterprise package; when database_usage is not enabled, your registration is simply never resolved.
DI key
Register exactly one provider per module under the key returned by databaseUsageRetentionProviderKey(moduleId), which is databaseUsageRetentionProvider:<moduleId>:
import { databaseUsageRetentionProviderKey } from '@open-mercato/shared/lib/db/retentionProvider'
The dashboard looks up the provider for the module that owns the selected entity. It never asks one module's provider about another module's entities.
Provider and descriptor shape
interface ModuleRetentionPolicyProvider {
readonly moduleId: string
resolvePolicy(input: { canonicalEntityId: string }):
| ModuleRetentionPolicyDescriptor
| null
| Promise<ModuleRetentionPolicyDescriptor | null>
}
interface ModuleRetentionPolicyDescriptor {
status: 'active' | 'disabled' | 'unsupported' | 'unavailable'
moduleId: string
canonicalEntityId: string // '<moduleId>.<EntityExportName>', e.g. 'audit_logs.AccessLog'
triggerKind: 'write_triggered' | 'scheduled_worker' | 'manual_only' | 'none' | 'unknown'
policySourceKey: string
summaryKey: string
summaryParams?: Record<string, string | number | boolean | undefined>
guidanceKeys: string[]
operatorRoute?: string | null
documentationSlug?: string | null
effectiveRules?: Array<{
labelKey: string
valueKey: string
valueParams?: Record<string, string | number | boolean | undefined>
}>
}
Return null for entities your module does not cover; the dashboard shows them as unsupported.
Rules the dashboard enforces
- Module ownership. The provider's
moduleId, and the descriptor'smoduleIdandcanonicalEntityId, must match the entity the dashboard asked about. A mismatch is rejected and shown asunavailable, so one module cannot publish guidance for another module's tables. - Text is i18n keys only.
policySourceKey,summaryKey,guidanceKeysand thelabelKey/valueKeyof each rule are translation keys, not prose. Ship them in your module'si18n/<locale>.jsonfiles (prefix them with your module id); untranslated keys are rendered verbatim. Dynamic values go intosummaryParams/valueParamsand are interpolated by the translator. - Sanitized parameters. Only strings (truncated to 120 characters), finite numbers and booleans survive. Do not put secrets, tenant data or full connection strings in parameters.
- Bounded lists. At most 8 guidance keys and 8 effective rules are kept. A generic "deleted rows free space for reuse" guidance line is always appended.
- Internal links only.
operatorRouteis shown only when it is an internal backend path matching/backend/...(letters, digits,/,_,-). Absolute URLs,javascript:and query strings are dropped. Point it at an existing page where an operator manages the policy; never at an endpoint that performs rotation. - Failure isolation. If your provider throws, or its registration fails to construct, the error is logged and reported to telemetry and the entity shows
unavailable. A missing registration isunsupportedand is not an error.
Example
import { asValue } from 'awilix'
import type { AppContainer } from '@open-mercato/shared/lib/di/container'
import {
databaseUsageRetentionProviderKey,
type ModuleRetentionPolicyProvider,
} from '@open-mercato/shared/lib/db/retentionProvider'
export function createMyModuleRetentionProvider(
env: Record<string, string | undefined> = process.env,
): ModuleRetentionPolicyProvider {
return {
moduleId: 'my_module',
resolvePolicy({ canonicalEntityId }) {
if (canonicalEntityId !== 'my_module.ImportLog') return null
const days = Number(env.MY_MODULE_IMPORT_LOG_RETENTION_DAYS ?? 30)
return {
status: days > 0 ? 'active' : 'disabled',
moduleId: 'my_module',
canonicalEntityId,
triggerKind: 'scheduled_worker',
policySourceKey: 'my_module.retention.importLog.source',
summaryKey: 'my_module.retention.importLog.summary',
summaryParams: { days },
guidanceKeys: ['my_module.retention.importLog.guidance'],
operatorRoute: '/backend/config/my-module',
effectiveRules: [
{
labelKey: 'my_module.retention.importLog.windowLabel',
valueKey: 'my_module.retention.importLog.windowValue',
valueParams: { days },
},
],
}
},
}
}
export function register(container: AppContainer) {
container.register({
[databaseUsageRetentionProviderKey('my_module')]: asValue(createMyModuleRetentionProvider()),
})
}
Keep resolvePolicy cheap and side-effect free: read configuration, do not query large tables, and never start a cleanup from it. Describe what your module actually does — if the rotation is triggered by writes, by a worker, or only by an operator, say so through triggerKind and the rules.
Rotation stays in the owning module
The provider is descriptive. Rotation, expiry jobs, their schedules and their configuration remain inside your module (for example a worker, a write-path cleanup like audit_logs' access-log rotation, or a CLI command). The Database Usage dashboard has no action that triggers them.
Compatibility
The DI key format databaseUsageRetentionProvider:<moduleId>, the @open-mercato/shared/lib/db/retentionProvider import path, and the descriptor fields above are a stable contract. New optional fields may be added; existing fields and status/trigger values will not be renamed or removed without the deprecation protocol.
Testing a provider
Unit-test the factory directly (call resolvePolicy with your canonical entity ids and with an unrelated id that must return null). To check the end-to-end result, enable Enterprise modules, open Settings → System → Database Usage, refresh, and open your entity's detail drawer.