meterflow 0.5.0__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {meterflow-0.5.0 → meterflow-0.6.0}/PKG-INFO +31 -3
  2. {meterflow-0.5.0 → meterflow-0.6.0}/README.md +30 -2
  3. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/_version.py +1 -1
  4. meterflow-0.6.0/src/meterflow/resources/credits.py +215 -0
  5. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/types.py +47 -0
  6. meterflow-0.5.0/src/meterflow/resources/credits.py +0 -98
  7. {meterflow-0.5.0 → meterflow-0.6.0}/LICENSE +0 -0
  8. {meterflow-0.5.0 → meterflow-0.6.0}/pyproject.toml +0 -0
  9. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/__init__.py +0 -0
  10. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/_entitlement_cache.py +0 -0
  11. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/_http.py +0 -0
  12. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/_retry.py +0 -0
  13. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/client.py +0 -0
  14. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/errors.py +0 -0
  15. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/py.typed +0 -0
  16. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/resources/__init__.py +0 -0
  17. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/resources/entitlements.py +0 -0
  18. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/resources/plans.py +0 -0
  19. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/resources/portal.py +0 -0
  20. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/resources/subscriptions.py +0 -0
  21. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/resources/usage.py +0 -0
  22. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/resources/webhooks.py +0 -0
  23. {meterflow-0.5.0 → meterflow-0.6.0}/src/meterflow/webhook.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: meterflow
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Official Python SDK for MeterFlow — usage-based billing, credit management, and metering.
5
5
  Project-URL: Homepage, https://meter-flow.com
6
6
  Project-URL: Documentation, https://meter-flow.com/guide
@@ -76,6 +76,7 @@ Track what your customers use, enforce credit balances, gate features, and manag
76
76
  - [Configuration](#configuration)
77
77
  - [Usage guide](#usage-guide)
78
78
  - [Credits](#credits)
79
+ - [Holding credits for a long job](#holding-credits-for-a-long-job)
79
80
  - [Usage events](#usage-events)
80
81
  - [Subscriptions](#subscriptions)
81
82
  - [Plans](#plans)
@@ -218,7 +219,7 @@ txn = client.credits.grant({
218
219
  print(txn["balance_after"]) # "5000.000000"
219
220
  ```
220
221
 
221
- **Deduct** — remove credits. Raises `InsufficientCreditsError` (HTTP 402) if the balance can't cover it — the customer is never taken below zero:
222
+ **Deduct** — remove credits. Raises `InsufficientCreditsError` (HTTP 402) if the available credits can't cover it (the balance less what [holds](#holding-credits-for-a-long-job) keep) — the customer is never taken below zero:
222
223
 
223
224
  ```python
224
225
  from meterflow import InsufficientCreditsError
@@ -241,6 +242,8 @@ bal = client.credits.balance("customer_123")
241
242
  bal["balance"] # "3545.000000" ← decimal string, see note below
242
243
  bal["total_granted"] # "5250.000000"
243
244
  bal["total_consumed"] # "1705.000000"
245
+ bal["reserved"] # "200.000000" ← held by reservations, still in balance
246
+ bal["available"] # "3345.000000" ← balance − reserved: what can be spent now
244
247
  bal["usage_draws_credits"] # True | False | None
245
248
  ```
246
249
 
@@ -268,6 +271,31 @@ while True:
268
271
 
269
272
  > **Amounts are decimal strings.** Balances and amounts come back as strings (`"3545.000000"`) to avoid floating-point drift on money-like values. Parse deliberately (`decimal.Decimal(...)`) when you need arithmetic. When *sending* an amount, a number or a numeric string are both accepted.
270
273
 
274
+ ### Holding credits for a long job
275
+
276
+ A job that runs for minutes — a render, an agent run — should not find, at the end, that other spending took the credits it was counting on. **Reserve** them first: the balance stays where it is, but `available` drops, and every other spend (`credits.deduct()`, usage charged by a metered plan, a `check()` that would charge, another hold) is measured against `available`.
277
+
278
+ ```python
279
+ hold = client.credits.reserve(
280
+ {"customer_external_id": "customer_123", "amount": 200, "ttl_seconds": 600, "description": "render #42"},
281
+ idempotency_key="render-42",
282
+ )
283
+
284
+ try:
285
+ used = render() # the long job
286
+ client.credits.confirm_reservation(hold["id"], {"amount": used.credits}) # take what it used; the rest is freed
287
+ except Exception:
288
+ client.credits.release_reservation(hold["id"]) # nothing taken
289
+ raise
290
+ ```
291
+
292
+ `AsyncMeterFlow` has the same four methods, awaited.
293
+
294
+ - **Reserve** raises `InsufficientCreditsError` (402) when `available` cannot cover the amount, and `ConflictError` (409) when held credits would pass the subscription's spend cap: a hold counts against the cap as it will when confirmed. `ttl_seconds` defaults to 300 and is at most 86,400 (a day).
295
+ - **Confirm** writes one ordinary `deduct` to the ledger, with your hold's description and `metadata["reservation_id"]`, and fires the same webhooks a deduct does. Leave out `amount` to take the whole hold; more than the hold is a `ValidationError` (422). Whatever it does not take is freed.
296
+ - **Release** frees the hold with nothing taken. A hold left alone expires at `expires_at` and frees itself: `reservation(id)` then answers `"status": "expired"`, a confirm raises `ConflictError` (409), and a release answers it as expired.
297
+ - Confirming or releasing a hold that is already confirmed or released raises `ConflictError` (409). If a retry of a confirm meets a 409, `client.credits.reservation(hold["id"])` tells you whether the first attempt landed.
298
+
271
299
  ### Usage events
272
300
 
273
301
  Record an event every time a customer does the thing you charge for. Events are matched to a meter by `event_name` and processed asynchronously into totals (and, if the meter is metered on a plan, into credit deductions).
@@ -485,7 +513,7 @@ Prefer to be told rather than to ask? Subscribe a webhook to `limit.reached` (se
485
513
 
486
514
  A MeterFlow blip should never take your product down with it. Three things keep `check()` answering, on `MeterFlow` and `AsyncMeterFlow` alike:
487
515
 
488
- - **The cache.** Answers from `check()` and `get()` are reused for the `max-age` the API sends (15 s), per client, up to 1,000 of them. A response without `Cache-Control` is never cached. A successful `usage.record()`, `usage.record_batch()`, `credits.grant()` or `credits.deduct()` makes that customer's answers stale, so the next `check()` asks again. `entitlements_cache=False` turns the cache off.
516
+ - **The cache.** Answers from `check()` and `get()` are reused for the `max-age` the API sends (15 s), per client, up to 1,000 of them. A response without `Cache-Control` is never cached. A successful `usage.record()`, `usage.record_batch()`, `credits.grant()`, `credits.deduct()`, `credits.reserve()`, `confirm_reservation()` or `release_reservation()` makes that customer's answers stale, so the next `check()` asks again. `entitlements_cache=False` turns the cache off.
489
517
  - **The last answer.** When the API cannot be reached — a network error, a timeout, a 5xx or a 429, once the retries are spent — a call returns its last answer for that customer and feature, past its age, with `"stale": True`.
490
518
  - **Your defaults.** With no earlier answer, `check()` returns your `entitlement_defaults` entry for the feature, else its `"*"` entry: `{"feature", "feature_type": None, "allowed", "reason": "offline_default"}`. With neither, it raises as before. `get()` has no default: a whole plan cannot be guessed.
491
519
 
@@ -24,6 +24,7 @@ Track what your customers use, enforce credit balances, gate features, and manag
24
24
  - [Configuration](#configuration)
25
25
  - [Usage guide](#usage-guide)
26
26
  - [Credits](#credits)
27
+ - [Holding credits for a long job](#holding-credits-for-a-long-job)
27
28
  - [Usage events](#usage-events)
28
29
  - [Subscriptions](#subscriptions)
29
30
  - [Plans](#plans)
@@ -166,7 +167,7 @@ txn = client.credits.grant({
166
167
  print(txn["balance_after"]) # "5000.000000"
167
168
  ```
168
169
 
169
- **Deduct** — remove credits. Raises `InsufficientCreditsError` (HTTP 402) if the balance can't cover it — the customer is never taken below zero:
170
+ **Deduct** — remove credits. Raises `InsufficientCreditsError` (HTTP 402) if the available credits can't cover it (the balance less what [holds](#holding-credits-for-a-long-job) keep) — the customer is never taken below zero:
170
171
 
171
172
  ```python
172
173
  from meterflow import InsufficientCreditsError
@@ -189,6 +190,8 @@ bal = client.credits.balance("customer_123")
189
190
  bal["balance"] # "3545.000000" ← decimal string, see note below
190
191
  bal["total_granted"] # "5250.000000"
191
192
  bal["total_consumed"] # "1705.000000"
193
+ bal["reserved"] # "200.000000" ← held by reservations, still in balance
194
+ bal["available"] # "3345.000000" ← balance − reserved: what can be spent now
192
195
  bal["usage_draws_credits"] # True | False | None
193
196
  ```
194
197
 
@@ -216,6 +219,31 @@ while True:
216
219
 
217
220
  > **Amounts are decimal strings.** Balances and amounts come back as strings (`"3545.000000"`) to avoid floating-point drift on money-like values. Parse deliberately (`decimal.Decimal(...)`) when you need arithmetic. When *sending* an amount, a number or a numeric string are both accepted.
218
221
 
222
+ ### Holding credits for a long job
223
+
224
+ A job that runs for minutes — a render, an agent run — should not find, at the end, that other spending took the credits it was counting on. **Reserve** them first: the balance stays where it is, but `available` drops, and every other spend (`credits.deduct()`, usage charged by a metered plan, a `check()` that would charge, another hold) is measured against `available`.
225
+
226
+ ```python
227
+ hold = client.credits.reserve(
228
+ {"customer_external_id": "customer_123", "amount": 200, "ttl_seconds": 600, "description": "render #42"},
229
+ idempotency_key="render-42",
230
+ )
231
+
232
+ try:
233
+ used = render() # the long job
234
+ client.credits.confirm_reservation(hold["id"], {"amount": used.credits}) # take what it used; the rest is freed
235
+ except Exception:
236
+ client.credits.release_reservation(hold["id"]) # nothing taken
237
+ raise
238
+ ```
239
+
240
+ `AsyncMeterFlow` has the same four methods, awaited.
241
+
242
+ - **Reserve** raises `InsufficientCreditsError` (402) when `available` cannot cover the amount, and `ConflictError` (409) when held credits would pass the subscription's spend cap: a hold counts against the cap as it will when confirmed. `ttl_seconds` defaults to 300 and is at most 86,400 (a day).
243
+ - **Confirm** writes one ordinary `deduct` to the ledger, with your hold's description and `metadata["reservation_id"]`, and fires the same webhooks a deduct does. Leave out `amount` to take the whole hold; more than the hold is a `ValidationError` (422). Whatever it does not take is freed.
244
+ - **Release** frees the hold with nothing taken. A hold left alone expires at `expires_at` and frees itself: `reservation(id)` then answers `"status": "expired"`, a confirm raises `ConflictError` (409), and a release answers it as expired.
245
+ - Confirming or releasing a hold that is already confirmed or released raises `ConflictError` (409). If a retry of a confirm meets a 409, `client.credits.reservation(hold["id"])` tells you whether the first attempt landed.
246
+
219
247
  ### Usage events
220
248
 
221
249
  Record an event every time a customer does the thing you charge for. Events are matched to a meter by `event_name` and processed asynchronously into totals (and, if the meter is metered on a plan, into credit deductions).
@@ -433,7 +461,7 @@ Prefer to be told rather than to ask? Subscribe a webhook to `limit.reached` (se
433
461
 
434
462
  A MeterFlow blip should never take your product down with it. Three things keep `check()` answering, on `MeterFlow` and `AsyncMeterFlow` alike:
435
463
 
436
- - **The cache.** Answers from `check()` and `get()` are reused for the `max-age` the API sends (15 s), per client, up to 1,000 of them. A response without `Cache-Control` is never cached. A successful `usage.record()`, `usage.record_batch()`, `credits.grant()` or `credits.deduct()` makes that customer's answers stale, so the next `check()` asks again. `entitlements_cache=False` turns the cache off.
464
+ - **The cache.** Answers from `check()` and `get()` are reused for the `max-age` the API sends (15 s), per client, up to 1,000 of them. A response without `Cache-Control` is never cached. A successful `usage.record()`, `usage.record_batch()`, `credits.grant()`, `credits.deduct()`, `credits.reserve()`, `confirm_reservation()` or `release_reservation()` makes that customer's answers stale, so the next `check()` asks again. `entitlements_cache=False` turns the cache off.
437
465
  - **The last answer.** When the API cannot be reached — a network error, a timeout, a 5xx or a 429, once the retries are spent — a call returns its last answer for that customer and feature, past its age, with `"stale": True`.
438
466
  - **Your defaults.** With no earlier answer, `check()` returns your `entitlement_defaults` entry for the feature, else its `"*"` entry: `{"feature", "feature_type": None, "allowed", "reason": "offline_default"}`. With neither, it raises as before. `get()` has no default: a whole plan cannot be guessed.
439
467
 
@@ -1,3 +1,3 @@
1
1
  # The one place the version lives. pyproject.toml reads it (hatch dynamic version) and the
2
2
  # User-Agent header reports it, so a release bump edits this file and nothing else.
3
- __version__ = "0.5.0"
3
+ __version__ = "0.6.0"
@@ -0,0 +1,215 @@
1
+ """Credits — an append-only ledger per customer: grant up, deduct down, never edited in place; holds set credits aside."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from .._entitlement_cache import expire_entitlements
8
+ from .._http import RequestSpec, encode_path_segment
9
+ from ..types import (
10
+ CreditBalanceResponse,
11
+ CreditDeductRequest,
12
+ CreditGrantRequest,
13
+ CreditReservationConfirmRequest,
14
+ CreditReservationRequest,
15
+ CreditReservationResponse,
16
+ CreditTransactionPage,
17
+ CreditTransactionResponse,
18
+ )
19
+
20
+ if TYPE_CHECKING:
21
+ from ..client import AsyncMeterFlow, MeterFlow
22
+
23
+
24
+ def grant_spec(body: CreditGrantRequest, idempotency_key: str | None) -> RequestSpec:
25
+ return RequestSpec("POST", "credits/grant", body=body, idempotency_key=idempotency_key)
26
+
27
+
28
+ def deduct_spec(body: CreditDeductRequest, idempotency_key: str | None) -> RequestSpec:
29
+ return RequestSpec("POST", "credits/deduct", body=body, idempotency_key=idempotency_key)
30
+
31
+
32
+ def reserve_spec(body: CreditReservationRequest, idempotency_key: str | None) -> RequestSpec:
33
+ return RequestSpec("POST", "credits/reservations", body=body, idempotency_key=idempotency_key)
34
+
35
+
36
+ def confirm_reservation_spec(reservation_id: str, body: CreditReservationConfirmRequest | None) -> RequestSpec:
37
+ return RequestSpec("POST", f"credits/reservations/{encode_path_segment(reservation_id)}/confirm", body=body or {})
38
+
39
+
40
+ def release_reservation_spec(reservation_id: str) -> RequestSpec:
41
+ return RequestSpec("POST", f"credits/reservations/{encode_path_segment(reservation_id)}/release")
42
+
43
+
44
+ def reservation_spec(reservation_id: str) -> RequestSpec:
45
+ return RequestSpec("GET", f"credits/reservations/{encode_path_segment(reservation_id)}")
46
+
47
+
48
+ def balance_spec(customer_id: str) -> RequestSpec:
49
+ return RequestSpec("GET", f"credits/{encode_path_segment(customer_id)}/balance")
50
+
51
+
52
+ def transactions_spec(customer_id: str, limit: int | None, cursor: str | None) -> RequestSpec:
53
+ return RequestSpec("GET", f"credits/{encode_path_segment(customer_id)}/transactions", query={"limit": limit, "cursor": cursor})
54
+
55
+
56
+ class CreditsResource:
57
+ def __init__(self, client: MeterFlow) -> None:
58
+ self._client = client
59
+
60
+ def grant(self, body: CreditGrantRequest, *, idempotency_key: str | None = None) -> CreditTransactionResponse:
61
+ """Add credits (plan renewals, top-ups, goodwill). Returns the ledger line. The customer's cached entitlement answers go stale."""
62
+ result: CreditTransactionResponse = self._client.request(grant_spec(body, idempotency_key))
63
+ expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
64
+ return result
65
+
66
+ def deduct(self, body: CreditDeductRequest, *, idempotency_key: str | None = None) -> CreditTransactionResponse:
67
+ """Remove credits. Raises ``InsufficientCreditsError`` (402) rather than take the customer below zero.
68
+
69
+ The customer's cached entitlement answers go stale.
70
+ """
71
+ result: CreditTransactionResponse = self._client.request(deduct_spec(body, idempotency_key))
72
+ expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
73
+ return result
74
+
75
+ def reserve(self, body: CreditReservationRequest, *, idempotency_key: str | None = None) -> CreditReservationResponse:
76
+ """Hold credits until confirmed, released or ``ttl_seconds`` (default 300) runs out; the balance stays, ``available`` drops.
77
+
78
+ Raises ``InsufficientCreditsError`` (402) when the available credits cannot cover it. The customer's cached entitlement
79
+ answers go stale.
80
+
81
+ body: the customer, the amount, how long to hold it, a description and metadata.
82
+ idempotency_key: makes a retried hold the same hold.
83
+ """
84
+ result: CreditReservationResponse = self._client.request(reserve_spec(body, idempotency_key))
85
+ expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
86
+ return result
87
+
88
+ def confirm_reservation(self, reservation_id: str, body: CreditReservationConfirmRequest | None = None) -> CreditReservationResponse:
89
+ """Take some or all of a hold from the balance, as one ``deduct`` ledger row, and free the rest.
90
+
91
+ Raises ``ConflictError`` (409) unless it is still held, ``ValidationError`` (422) above the amount held. The customer's
92
+ cached entitlement answers go stale.
93
+
94
+ reservation_id: the hold's ``id``.
95
+ body: ``amount`` to take; the whole hold when left out.
96
+ """
97
+ result: CreditReservationResponse = self._client.request(confirm_reservation_spec(reservation_id, body))
98
+ expire_entitlements(self._client.entitlement_cache, [result["customer_external_id"]])
99
+ return result
100
+
101
+ def release_reservation(self, reservation_id: str) -> CreditReservationResponse:
102
+ """Free a hold with nothing taken; an expired hold answers ``status: "expired"``, a settled one raises ``ConflictError`` (409).
103
+
104
+ The customer's cached entitlement answers go stale.
105
+
106
+ reservation_id: the hold's ``id``.
107
+ """
108
+ result: CreditReservationResponse = self._client.request(release_reservation_spec(reservation_id))
109
+ expire_entitlements(self._client.entitlement_cache, [result["customer_external_id"]])
110
+ return result
111
+
112
+ def reservation(self, reservation_id: str) -> CreditReservationResponse:
113
+ """One hold and how it ended: ``held``, ``confirmed``, ``released``, or ``expired`` once held past ``expires_at``.
114
+
115
+ reservation_id: the hold's ``id``.
116
+ """
117
+ result: CreditReservationResponse = self._client.request(reservation_spec(reservation_id))
118
+ return result
119
+
120
+ def balance(self, customer_id: str) -> CreditBalanceResponse:
121
+ """The customer's current position — amounts are decimal strings."""
122
+ result: CreditBalanceResponse = self._client.request(balance_spec(customer_id))
123
+ return result
124
+
125
+ def transactions(self, customer_id: str, *, limit: int | None = None, cursor: str | None = None) -> CreditTransactionPage:
126
+ """One page of the ledger, newest first.
127
+
128
+ The ledger grows with every charge, so it is read a page at a time: ``data`` holds the rows
129
+ and ``next_cursor`` the mark for the page after this one (``None`` on the last). Pass it
130
+ back as ``cursor`` unchanged — it is opaque, and nothing but this API reads it.
131
+ """
132
+ result: CreditTransactionPage = self._client.request(transactions_spec(customer_id, limit, cursor))
133
+ return result
134
+
135
+
136
+ class AsyncCreditsResource:
137
+ def __init__(self, client: AsyncMeterFlow) -> None:
138
+ self._client = client
139
+
140
+ async def grant(self, body: CreditGrantRequest, *, idempotency_key: str | None = None) -> CreditTransactionResponse:
141
+ """Add credits (plan renewals, top-ups, goodwill). Returns the ledger line. The customer's cached entitlement answers go stale."""
142
+ result: CreditTransactionResponse = await self._client.request(grant_spec(body, idempotency_key))
143
+ expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
144
+ return result
145
+
146
+ async def deduct(self, body: CreditDeductRequest, *, idempotency_key: str | None = None) -> CreditTransactionResponse:
147
+ """Remove credits. Raises ``InsufficientCreditsError`` (402) rather than take the customer below zero.
148
+
149
+ The customer's cached entitlement answers go stale.
150
+ """
151
+ result: CreditTransactionResponse = await self._client.request(deduct_spec(body, idempotency_key))
152
+ expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
153
+ return result
154
+
155
+ async def reserve(self, body: CreditReservationRequest, *, idempotency_key: str | None = None) -> CreditReservationResponse:
156
+ """Hold credits until confirmed, released or ``ttl_seconds`` (default 300) runs out; the balance stays, ``available`` drops.
157
+
158
+ Raises ``InsufficientCreditsError`` (402) when the available credits cannot cover it. The customer's cached entitlement
159
+ answers go stale.
160
+
161
+ body: the customer, the amount, how long to hold it, a description and metadata.
162
+ idempotency_key: makes a retried hold the same hold.
163
+ """
164
+ result: CreditReservationResponse = await self._client.request(reserve_spec(body, idempotency_key))
165
+ expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
166
+ return result
167
+
168
+ async def confirm_reservation(
169
+ self, reservation_id: str, body: CreditReservationConfirmRequest | None = None
170
+ ) -> CreditReservationResponse:
171
+ """Take some or all of a hold from the balance, as one ``deduct`` ledger row, and free the rest.
172
+
173
+ Raises ``ConflictError`` (409) unless it is still held, ``ValidationError`` (422) above the amount held. The customer's
174
+ cached entitlement answers go stale.
175
+
176
+ reservation_id: the hold's ``id``.
177
+ body: ``amount`` to take; the whole hold when left out.
178
+ """
179
+ result: CreditReservationResponse = await self._client.request(confirm_reservation_spec(reservation_id, body))
180
+ expire_entitlements(self._client.entitlement_cache, [result["customer_external_id"]])
181
+ return result
182
+
183
+ async def release_reservation(self, reservation_id: str) -> CreditReservationResponse:
184
+ """Free a hold with nothing taken; an expired hold answers ``status: "expired"``, a settled one raises ``ConflictError`` (409).
185
+
186
+ The customer's cached entitlement answers go stale.
187
+
188
+ reservation_id: the hold's ``id``.
189
+ """
190
+ result: CreditReservationResponse = await self._client.request(release_reservation_spec(reservation_id))
191
+ expire_entitlements(self._client.entitlement_cache, [result["customer_external_id"]])
192
+ return result
193
+
194
+ async def reservation(self, reservation_id: str) -> CreditReservationResponse:
195
+ """One hold and how it ended: ``held``, ``confirmed``, ``released``, or ``expired`` once held past ``expires_at``.
196
+
197
+ reservation_id: the hold's ``id``.
198
+ """
199
+ result: CreditReservationResponse = await self._client.request(reservation_spec(reservation_id))
200
+ return result
201
+
202
+ async def balance(self, customer_id: str) -> CreditBalanceResponse:
203
+ """The customer's current position — amounts are decimal strings."""
204
+ result: CreditBalanceResponse = await self._client.request(balance_spec(customer_id))
205
+ return result
206
+
207
+ async def transactions(self, customer_id: str, *, limit: int | None = None, cursor: str | None = None) -> CreditTransactionPage:
208
+ """One page of the ledger, newest first.
209
+
210
+ The ledger grows with every charge, so it is read a page at a time: ``data`` holds the rows
211
+ and ``next_cursor`` the mark for the page after this one (``None`` on the last). Pass it
212
+ back as ``cursor`` unchanged — it is opaque, and nothing but this API reads it.
213
+ """
214
+ result: CreditTransactionPage = await self._client.request(transactions_spec(customer_id, limit, cursor))
215
+ return result
@@ -17,6 +17,8 @@ EntitlementReason = Literal[
17
17
 
18
18
  FeatureType = Literal["boolean", "metered"]
19
19
 
20
+ ReservationStatus = Literal["held", "confirmed", "released", "expired"]
21
+
20
22
  SubscriptionStatus = Literal["active", "trialing", "past_due", "paused", "canceled", "expired"]
21
23
 
22
24
 
@@ -31,6 +33,8 @@ class CreditBalanceResponse(TypedDict):
31
33
  version: int
32
34
  created_at: str
33
35
  updated_at: str
36
+ reserved: str
37
+ available: str
34
38
  usage_draws_credits: bool | None
35
39
 
36
40
 
@@ -56,6 +60,45 @@ class CreditGrantRequest(_CreditGrantRequestRequired, total=False):
56
60
  metadata: dict[str, Any]
57
61
 
58
62
 
63
+ class CreditReservationConfirmRequest(TypedDict, total=False):
64
+ """Settle a hold: take some or all of it from the balance, and free the rest."""
65
+
66
+ amount: float | str | None
67
+
68
+
69
+ class _CreditReservationRequestRequired(TypedDict):
70
+ customer_external_id: str
71
+ amount: float | str
72
+
73
+
74
+ class CreditReservationRequest(_CreditReservationRequestRequired, total=False):
75
+ """Hold part of a customer's balance for a while, so other spending cannot take it first."""
76
+
77
+ ttl_seconds: int
78
+ description: str | None
79
+ idempotency_key: str | None
80
+ metadata: dict[str, Any]
81
+
82
+
83
+ class CreditReservationResponse(TypedDict):
84
+ """A hold on part of a customer's balance, and how it ended."""
85
+
86
+ id: str
87
+ project_id: str
88
+ environment: str
89
+ customer_external_id: str
90
+ amount: str
91
+ status: ReservationStatus
92
+ expires_at: str
93
+ description: str | None
94
+ metadata_: dict[str, Any]
95
+ idempotency_key: str | None
96
+ confirmed_amount: str | None
97
+ transaction_id: str | None
98
+ created_at: str
99
+ settled_at: str | None
100
+
101
+
59
102
  class _CreditTransactionPageRequired(TypedDict):
60
103
  data: list[CreditTransactionResponse]
61
104
 
@@ -327,6 +370,9 @@ __all__ = [
327
370
  "CreditBalanceResponse",
328
371
  "CreditDeductRequest",
329
372
  "CreditGrantRequest",
373
+ "CreditReservationConfirmRequest",
374
+ "CreditReservationRequest",
375
+ "CreditReservationResponse",
330
376
  "CreditTransactionPage",
331
377
  "CreditTransactionResponse",
332
378
  "EntitlementReason",
@@ -337,6 +383,7 @@ __all__ = [
337
383
  "PlanResponse",
338
384
  "PortalLinkRequest",
339
385
  "PortalLinkResponse",
386
+ "ReservationStatus",
340
387
  "SubscriptionCreateRequest",
341
388
  "SubscriptionPage",
342
389
  "SubscriptionResponse",
@@ -1,98 +0,0 @@
1
- """Credits — an append-only ledger per customer: grant up, deduct down, never edited in place."""
2
-
3
- from __future__ import annotations
4
-
5
- from typing import TYPE_CHECKING
6
-
7
- from .._entitlement_cache import expire_entitlements
8
- from .._http import RequestSpec, encode_path_segment
9
- from ..types import CreditBalanceResponse, CreditDeductRequest, CreditGrantRequest, CreditTransactionPage, CreditTransactionResponse
10
-
11
- if TYPE_CHECKING:
12
- from ..client import AsyncMeterFlow, MeterFlow
13
-
14
-
15
- def grant_spec(body: CreditGrantRequest, idempotency_key: str | None) -> RequestSpec:
16
- return RequestSpec("POST", "credits/grant", body=body, idempotency_key=idempotency_key)
17
-
18
-
19
- def deduct_spec(body: CreditDeductRequest, idempotency_key: str | None) -> RequestSpec:
20
- return RequestSpec("POST", "credits/deduct", body=body, idempotency_key=idempotency_key)
21
-
22
-
23
- def balance_spec(customer_id: str) -> RequestSpec:
24
- return RequestSpec("GET", f"credits/{encode_path_segment(customer_id)}/balance")
25
-
26
-
27
- def transactions_spec(customer_id: str, limit: int | None, cursor: str | None) -> RequestSpec:
28
- return RequestSpec("GET", f"credits/{encode_path_segment(customer_id)}/transactions", query={"limit": limit, "cursor": cursor})
29
-
30
-
31
- class CreditsResource:
32
- def __init__(self, client: MeterFlow) -> None:
33
- self._client = client
34
-
35
- def grant(self, body: CreditGrantRequest, *, idempotency_key: str | None = None) -> CreditTransactionResponse:
36
- """Add credits (plan renewals, top-ups, goodwill). Returns the ledger line. The customer's cached entitlement answers go stale."""
37
- result: CreditTransactionResponse = self._client.request(grant_spec(body, idempotency_key))
38
- expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
39
- return result
40
-
41
- def deduct(self, body: CreditDeductRequest, *, idempotency_key: str | None = None) -> CreditTransactionResponse:
42
- """Remove credits. Raises ``InsufficientCreditsError`` (402) rather than take the customer below zero.
43
-
44
- The customer's cached entitlement answers go stale.
45
- """
46
- result: CreditTransactionResponse = self._client.request(deduct_spec(body, idempotency_key))
47
- expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
48
- return result
49
-
50
- def balance(self, customer_id: str) -> CreditBalanceResponse:
51
- """The customer's current position — amounts are decimal strings."""
52
- result: CreditBalanceResponse = self._client.request(balance_spec(customer_id))
53
- return result
54
-
55
- def transactions(self, customer_id: str, *, limit: int | None = None, cursor: str | None = None) -> CreditTransactionPage:
56
- """One page of the ledger, newest first.
57
-
58
- The ledger grows with every charge, so it is read a page at a time: ``data`` holds the rows
59
- and ``next_cursor`` the mark for the page after this one (``None`` on the last). Pass it
60
- back as ``cursor`` unchanged — it is opaque, and nothing but this API reads it.
61
- """
62
- result: CreditTransactionPage = self._client.request(transactions_spec(customer_id, limit, cursor))
63
- return result
64
-
65
-
66
- class AsyncCreditsResource:
67
- def __init__(self, client: AsyncMeterFlow) -> None:
68
- self._client = client
69
-
70
- async def grant(self, body: CreditGrantRequest, *, idempotency_key: str | None = None) -> CreditTransactionResponse:
71
- """Add credits (plan renewals, top-ups, goodwill). Returns the ledger line. The customer's cached entitlement answers go stale."""
72
- result: CreditTransactionResponse = await self._client.request(grant_spec(body, idempotency_key))
73
- expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
74
- return result
75
-
76
- async def deduct(self, body: CreditDeductRequest, *, idempotency_key: str | None = None) -> CreditTransactionResponse:
77
- """Remove credits. Raises ``InsufficientCreditsError`` (402) rather than take the customer below zero.
78
-
79
- The customer's cached entitlement answers go stale.
80
- """
81
- result: CreditTransactionResponse = await self._client.request(deduct_spec(body, idempotency_key))
82
- expire_entitlements(self._client.entitlement_cache, [body["customer_external_id"]])
83
- return result
84
-
85
- async def balance(self, customer_id: str) -> CreditBalanceResponse:
86
- """The customer's current position — amounts are decimal strings."""
87
- result: CreditBalanceResponse = await self._client.request(balance_spec(customer_id))
88
- return result
89
-
90
- async def transactions(self, customer_id: str, *, limit: int | None = None, cursor: str | None = None) -> CreditTransactionPage:
91
- """One page of the ledger, newest first.
92
-
93
- The ledger grows with every charge, so it is read a page at a time: ``data`` holds the rows
94
- and ``next_cursor`` the mark for the page after this one (``None`` on the last). Pass it
95
- back as ``cursor`` unchanged — it is opaque, and nothing but this API reads it.
96
- """
97
- result: CreditTransactionPage = await self._client.request(transactions_spec(customer_id, limit, cursor))
98
- return result
File without changes
File without changes