Entitlement Dispatch Archetype — Implementation Guide¶
This guide covers the event-reaction write path of the self-hosted entitlement chain for apps generated by mozaiks. It explains how the entitlement_dispatch module writes subscription assignment records that ConfiguredEntitlementAdapter reads to grant or deny capability access.
Scope: Self-hosted OSS apps only. Apps on the mozaiks-app hosted platform do not instantiate this module — the hosted entitlement service manages grants and is the authoritative source for hosted apps.
Managed-capability path: when a trusted adapter already has a verified billing fact, prefer the OSS
BillingFulfillmentServiceorPOST /api/billing/fulfillment/applywith aBillingFulfillmentCommand. That path updates the configuredassignment_storeand token wallet effects directly. Useentitlement_dispatchonly when the self-hosted app intentionally routes normalized domain events throughcontracts/reactions.yaml.
When to Use This Archetype¶
Select entitlement_dispatch when all of the following are true:
- The app declares
config/subscriptions.yamlwith plans that grant capabilities. - The app is self-hosted (not deployed on mozaiks-app hosted platform).
- The app needs to activate or deactivate capability grants when subscription events arrive.
- The app integrates with a billing adapter that emits normalized subscription domain events instead of applying a
BillingFulfillmentCommanddirectly.
Architecture Overview¶
Payment Provider Webhook
│
▼
services/adapters/payments/{provider}.py
(normalizes webhook to domain event)
│
▼ domain.subscription.activated / domain.subscription.cancelled
contracts/reactions.yaml
(routes event to a handler method)
│
▼
entitlement_dispatch module
activate_subscription / deactivate_subscription
│
▼
MongoDB collection (assignment_store.data_alias → data/contract.json)
← ConfiguredEntitlementAdapter reads here at action dispatch time
│
▼
module_executor.py enforces entitlement gate
(grants or denies capability at runtime; skipped only for requests with
development access, such as this machine with AUTH_ENABLED=false)
The gate is enforced for every caller without development access; see Subscriptions.
The entitlement_dispatch module owns only the write path. The read path (ConfiguredEntitlementAdapter) and enforcement (module_executor.py) are OSS runtime primitives — no app code needed for those.
For MozaiksPay or another managed adapter that can submit a verified normalized command directly, the shorter path is:
verified billing fact
|
v
BillingFulfillmentCommand
|
v
POST /api/billing/fulfillment/apply
|
v
assignment_store + token wallet effects
|
v
ConfiguredEntitlementAdapter + module_executor
Do not stack both write paths for the same subscription lifecycle event. Either the app reacts to normalized events through entitlement_dispatch, or a trusted adapter applies a BillingFulfillmentCommand through the OSS fulfillment service.
Assignment Record Schema¶
Write records with these fields to the collection that config/subscriptions.yaml → assignment_store.data_alias resolves to. data_alias is a data-contract alias, not a collection name: declare it in data/contract.json, for example "aliases": [{"alias": "billing.subscriptions", "collection": "billing_subscriptions"}]. If the alias is not declared, the adapter fails closed and denies every gated action for every user.
The field names are configured in assignment_store via user_id_field, tenant_id_field, workspace_id_field. user_id_field has no default; set user_id_field: user_id in assignment_store for a user-scoped app. Without it, the adapter does not look records up by user, so one record entitles every user of the app.
Gated dispatch looks records up by the caller's verified identity only. A tenant-scoped record entitles callers whose token is bound to that tenant (AUTH_TENANT_ID_CLAIM, default tid). A workspace-scoped record entitles callers whose token is bound to that workspace (AUTH_WORKSPACE_ID_CLAIM, default workspace_id), or whose workspace a host-verified membership assertion supplies. A tenant or workspace named in the request never selects a record.
{
# Required: identifies who holds the grant
"app_id": str, # the app this grant belongs to (app_id_field, default "app_id")
"user_id": str, # user-scoped grant (user_id_field: user_id in subscriptions.yaml)
"tenant_id": str | None, # org-scoped grant (tenant_id_field, default "tenant_id")
"workspace_id": str | None, # workspace-scoped grant (workspace_id_field)
# Required: what was granted and its state
"plan_id": str, # e.g. "pro", "enterprise"
"status": str, # active when it matches assignment_store.active_statuses
# (default: active, pending, trialing)
# Optional
"expires_at": str | None, # ISO-8601; a past value denies like an inactive status
"granted_capabilities": list[str], # snapshot that overrides the plan catalog
"granted_at": str, # ISO-8601; stored for audit, not read by the adapter
"external_subscription_id": str | None, # provider's subscription ID for idempotency
}
granted_capabilities is optional. When a record has a non-empty list, the adapter grants exactly those capabilities and ignores the plan catalog for that record, so a stale snapshot wins over a changed plan. When it is absent, the adapter grants the capabilities of plan_id from subscriptions.yaml. The shipped pack does not write a snapshot.
Key Actions¶
activate_subscription¶
- Input:
{ user_id, plan_id, granted_at?, expires_at?, external_subscription_id? } - Optionally copies
granted_capabilitiesfrom the matching plan as a snapshot (see above) - Writes (or upserts) the assignment record with
status=active - Must be idempotent — duplicate events for the same user/plan must not create duplicate records. Use
external_subscription_idfor deduplication. - API surface:
internal— triggered viacontracts/reactions.yaml, not exposed to UI
deactivate_subscription¶
- Input:
{ user_id, reason } - Updates the assignment record
statustocancelledorexpired - Does not delete the record — keep audit trail
- API surface:
internal
A cancelled or expired record does not fall back to the default plan: the adapter denies every gated capability for that user, including capabilities the default plan grants to users who never subscribed. Do not gate capabilities the default plan grants, or have deactivation write the default plan as an active assignment.
get_entitlement_status¶
- Returns:
{ plan_id, status, granted_capabilities }for the requesting user - No entitlement gate — this action is itself free to call
- Omit
api_surfaceso authenticated UI callers can invoke it
Minimal module.yaml Example¶
schema_version: mozaiks.module.v1
module:
id: entitlement_dispatch
display_name: Entitlement Dispatch
version: 1.0.0
type: entitlement_dispatch
description: >
Self-hosted write path for subscription entitlement grants.
Writes assignment records that ConfiguredEntitlementAdapter reads.
handler: backend.handler:EntitlementDispatchHandler
permissions: []
actions:
- id: activate_subscription
description: >
Activates a subscription grant. Called via reactions.yaml when
a domain.subscription.activated event is received.
handler_method: activate_subscription
api_surface: internal
permissions: []
input_schema:
type: object
additionalProperties: false
required: [user_id, plan_id]
properties:
user_id: { type: string }
plan_id: { type: string }
granted_at: { type: string }
external_subscription_id: { type: string }
expires_at: { type: string }
- id: deactivate_subscription
description: >
Cancels an active subscription grant. Called via reactions.yaml when
a domain.subscription.cancelled or domain.subscription.expired event
is received.
handler_method: deactivate_subscription
api_surface: internal
permissions: []
input_schema:
type: object
additionalProperties: false
required: [user_id]
properties:
user_id: { type: string }
reason: { type: string }
- id: get_entitlement_status
description: Read-only status check for the requesting user. No entitlement gate.
handler_method: get_entitlement_status
Every action needs id, description, and handler_method; inputs are a JSON Schema under input_schema. api_surface accepts public, public_readonly, internal, or admin_internal; omit it for actions that authenticated UI and API callers invoke. The shipped pack template at factory_app/build_context/entitlement_dispatch/templates/modules/entitlement_dispatch/module.yaml is the generator's source of truth for this module. It declares only activate_subscription and deactivate_subscription, with different inputs from this example.
contracts/reactions.yaml Example¶
schema_version: mozaiks.reactions.v1
reactions:
- id: activate_on_subscription_activated
event_type: domain.subscription.activated
target:
kind: handler
handler_method: activate_subscription
- id: deactivate_on_subscription_cancelled
event_type: domain.subscription.cancelled
target:
kind: handler
handler_method: deactivate_subscription
- id: deactivate_on_subscription_expired
event_type: domain.subscription.expired
target:
kind: handler
handler_method: deactivate_subscription
Every reaction needs an id, an event_type with a canonical prefix (domain., platform., hosted., or mozaikspay.), and a target. A handler target calls the module's handler method directly, with the event's payload as keyword arguments. There is no field mapping, so the billing adapter must publish payloads whose keys match the method's parameters, such as {"user_id": "...", "plan_id": "pro"} for domain.subscription.activated and {"user_id": "...", "reason": "cancelled"} for domain.subscription.cancelled. A reaction does not go through the action's input_schema. If reactions.yaml fails validation, the module does not load and every action on it returns HTTP 503.
Connecting to a Billing Adapter¶
Self-hosted apps can connect to a managed billing service such as MozaiksPay using an API key:
The app-facing facade or adapter can either:
- apply a verified provider-neutral
BillingFulfillmentCommanddirectly through the OSS fulfillment ingress - normalize the verified billing fact into
domain.subscription.activated/domain.subscription.cancelleddomain events that this module reacts to
No provider-specific code lives in entitlement_dispatch. If the integration can call the OSS fulfillment ingress directly, prefer BillingFulfillmentCommand(event_type="subscription_activated") instead of adding this module just to rewrite the same assignment.
The billing adapter and this module are independent: either can be swapped without touching the other. You can use MozaiksPay with a different entitlement write path, or use a different billing provider with this module.
Hard Constraints¶
- Self-hosted only. Do not instantiate on apps deployed on the mozaiks-app hosted platform.
- No payment provider calls. This module receives only normalized domain events. Provider webhooks are handled in
services/adapters/payments/. - Idempotent writes. Duplicate activation events must upsert, not insert.
- Snapshots override the catalog. If you store
granted_capabilities, refresh it when the plan changes; otherwise omit it and let the adapter read the plan catalog. - Read path is OSS. Do not reimplement
ConfiguredEntitlementAdapter— it ships with the mozaiks runtime.
Testing¶
See tests/test_self_hosted_entitlement_chain.py in the mozaiks OSS repo for an integration test that validates the full write → read chain using FakeCollection (no real MongoDB required).