RevenueFlow.Metering
0.1.0-alpha.7.2
dotnet add package RevenueFlow.Metering --version 0.1.0-alpha.7.2
NuGet\Install-Package RevenueFlow.Metering -Version 0.1.0-alpha.7.2
<PackageReference Include="RevenueFlow.Metering" Version="0.1.0-alpha.7.2" />
<PackageVersion Include="RevenueFlow.Metering" Version="0.1.0-alpha.7.2" />
<PackageReference Include="RevenueFlow.Metering" />
paket add RevenueFlow.Metering --version 0.1.0-alpha.7.2
#r "nuget: RevenueFlow.Metering, 0.1.0-alpha.7.2"
#:package RevenueFlow.Metering@0.1.0-alpha.7.2
#addin nuget:?package=RevenueFlow.Metering&version=0.1.0-alpha.7.2&prerelease
#tool nuget:?package=RevenueFlow.Metering&version=0.1.0-alpha.7.2&prerelease
RevenueFlow.Metering
RevenueUsageMetering records operational usage with any conforming IRevenueDocumentStore and scoped IRevenueUserStore. Each event, CAS window aggregate, receipt, business history and outbox shares one transaction. All ingestion paths use bounded point reads and bounded writes; statements never depend on analytics queries or ledger scans. A hot account/window remains a transactional contention boundary. This initial implementation does not promise arbitrary per-window write throughput.
Create an immutable plan version, open a named user/meter window, record positive usage with stable (scope, source, eventKey) identities, then close after the acceptance cutoff. Separate command IDs cannot count the same economic event twice. Reusing an economic identity for different facts conflicts. Window creation uses an account CAS to enforce nonoverlap and monotonic provisioning; older existing open windows may still accept late events until their cutoff.
Included units are deducted once per window. Graduated pricing sums the units in each tier; volume pricing applies the selected tier's rate to all overage units. Unit prices are exact nonnegative decimal minor units, including fractional prices. Rating sums exact decimal amounts across all tiers, then rounds once to the nearest minor unit with midpoint rounding away from zero. Aggregate units and final money use checked Int64 bounds; decimal arithmetic overflow also rejects ingestion atomically.
Plans select Sum, Last or Maximum aggregation. SUM accepts positive additive units. LAST/MAX accept zero samples. LAST compares occurrence UTC first, then the stable economic entry UUID for equal timestamps; ingestion order cannot change the answer. MAX retains the highest sample. Both keep bounded aggregate state without rescanning history. Partial unit reversal is SUM-only: LAST is corrected by a later sample; MAX intentionally cannot erase an observed maximum. Closed statements remain immutable.
RecordBatchAsync atomically admits 1–128 distinct economic events for one personal window, with the window aggregate, one batch business event, configured outboxes and one command receipt. Economic duplicates shared with single-event ingestion are retained once. Any invalid item rolls back the entire batch. At the maximum 32 consumers, the batch uses at most 162 document writes. This API does not batch several account actors under one authorization decision.
RecordCalendarAsync automatically opens/reuses a deterministic personal hour/day/month UTC window with a pinned plan and lateness cutoff. Gregorian month and leap-day boundaries are explicit. Opening and recording are separate durable commands: interruption can leave an empty window, and retry recovers it. An exact retained usage command can replay after a backward clock adjustment, while the original calendar-open plan, period and lateness remain validated. Fresh future usage still rejects before provisioning a window. CloseElapsedWindowsAsync closes one discovery page of up to 100 elapsed windows; hosts schedule it and retain the cursor. Each close commits independently, and retry uses the stable close receipt. Discovery scans are bounded per call rather than an unbounded scheduled transaction.
Corrections append reversal entries and update a separate CAS reversal total, preserving the original event. Reversals cannot exceed original usage and cannot modify a closed window. Late additional usage can be recorded only as an explicitly authorized new economic event in another window, with that window's occurrence time and pricing terms. Credits against closed statements and provider invoice amendments remain application-owned; this slice cannot create a negative statement or silently rewrite previous billing evidence.
RevenueUsageSubmission exports a closed statement's total units to one application-selected provider binding. The provider's configured meter, included allowance and pricing must agree with the application's intended invoice policy; local rated money is not sent as a charge. Mapping is re-supplied and fingerprinted; customer references are not retained in intent documents. Each statement/provider binding has one durable operation. Only a new committed claim owns submission. Lost commit responses, cancellation, timeouts and uncertain remote results require read-only reconciliation and never trigger automatic resubmission.
Billing-account usage
OpenAccountWindowAsync and RecordAccountAsync use an explicit RevenueOwnerRef.BillingAccount and retain the acting user separately on each economic entry. Several members contribute to one account/meter window and one rated statement. They do not create a statement or multiply a subscription's revenue per seat. Prepaid resource debits and postpaid metering remain separate operations; applications choose which economic activity is billable.
Configure IUsageOwnerGuardPreparer on RevenueUsageMetering; account mutations fail with NotSupportedException when it is absent. TeamsUsageOwnerGuardPreparer in RevenueFlow.Teams returns a real billing-account CAS write from the same operational store, checks the account is active and validates the scoped actor. The metering command commits that write with usage, its receipt, history and outbox. A concurrent account freeze conflicts and forces preparation to recheck authority. Applications authenticate callers and authorize ingestion. Trusted late usage may arrive after the acting user's seat was reclaimed; account billing does not infer event-time organization membership from the user's current seat.
Create the frozen target with UsageBillingTarget.Capture(binding, opaqueTargetKey, customerId, meterId). Windows and statements retain the exact binding, an application-owned opaque key and a SHA-256 mapping fingerprint. Customer and meter references are re-supplied transiently for export. Export verifies that mapping against the frozen statement; it never selects the last actor's customer. A transactional target claim allows one user or billing account to own each (binding, customer, meter) aggregation target. Independently rated accounts, or a personal user and an account, cannot share that target. An application requiring a shared payer must configure separate customer/meter aggregation targets; implicit pooled billing is unsupported.
Account documents use schema 2 with explicit Owner; the UserId ownership property is absent, including when an account UUID happens to equal a user UUID. Entries carry ActorUserId. Legacy user windows, statements, entries, request fingerprints and serialized nonempty UserId shapes remain schema 1 without new null properties. Mixed user/account ownership fails closed. Reversals retain their original account and actor; closing freezes the same target and rates the account once. Migration must transfer owned-account heads, target claims/registry, windows, entries, statements, reversal counters and pending exports together.
Existing usage-export migration
Old provider-submission documents retain only a request fingerprint, so their original customer/meter cannot be guessed. Before opening an account target on a binding with legacy exports, call RegisterLegacyUsageTargetAsync(gateway, exactOriginalRequest) for each old operation. Registration recomputes the exact retained request fingerprint, verifies the original statement owner, claims the mapping and updates the operation atomically. It performs no provider submission or reconciliation. A wrong or guessed request conflicts.
Account-window creation verifies registered-target coverage in a bounded scan of at most 1,000 operations. Unregistered legacy operations block creation. For larger inventories, call VerifyRegisteredUsageTargetsAsync(binding, maximumRecords) repeatedly; each call examines at most 1–1,000 rows and commits a durable cursor until complete. Account opening then uses the retained coverage marker. New personal exports, explicit registrations and account target creation all CAS the binding registry, preventing a concurrent new export from bypassing target discovery. Deploy this change through the normal quiesced migration protocol and stop old binaries before establishing coverage; old writers do not honor the new registry fence. A custom account-metering store must support bounded document queries and atomic CAS in addition to the owner-guard contract.
The optional MeteringUsageSubmissionHealthContributor reports bounded live coverage, pending/uncertain exports, invalid records and the oldest known pending-intent creation time. Partial scans cannot report healthy coverage; store failures explicitly report unavailable. Older imported intents without a creation timestamp retain unknown age. Register it through the Core operational-health contributor abstraction; it performs no remote calls and exposes no customer mapping.
StripeUsageGateway in RevenueFlow.Providers.Stripe posts to the current v1 billing meter-event endpoint using a stable operation identifier and idempotency key. MeterId is the configured event name, not the Stripe mtr_ identifier. It uses default stripe_customer_id/value payload keys and supports SUM/LAST meters; MAX exports reject explicitly. Submission aggregation must equal the frozen statement plan. Accepted means asynchronous ingestion acceptance, not successful invoice inclusion or payment. Stripe accepts timestamps in a limited historical window and identifier deduplication is time-limited. Its aggregate summaries cannot prove an individual uncertain submission; the supplied Stripe reconciler conservatively returns Unknown without any remote mutation. Apps must surface unresolved operations and handle provider error reports, invoice deadlines and manual resolution.
RevenueUsageMeterProvisioning consumes Core IProviderUsageMeterProvisioner. It persists immutable scoped intent, separately claims creation, then records the observation with business history/outboxes. Only the invocation that receives a new committed claim may POST. Lost claims/responses, cancellation and unknown creation permit only exact read-only recovery using a supplied remote meter ID. The Stripe adapter creates SUM/LAST raw meters and verifies exact event name, formula, account mode, active status and default payload mapping on creation/read. No inferred retry after Stripe's idempotency retention expires; attaching that meter to provider prices remains the catalog/billing integration's responsibility.
References: Stripe meter-event API, recording usage and invoice cutoffs.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- RevenueFlow.Events.Abstractions (>= 0.1.0-alpha.7.2)
- RevenueFlow.Metering.Abstractions (>= 0.1.0-alpha.7.2)
- RevenueFlow.Stores.Abstractions (>= 0.1.0-alpha.7.2)
- RevenueFlow.Users.Abstractions (>= 0.1.0-alpha.7.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.0-alpha.7.2 | 51 | 11/10/2026 |