meterflow 0.1.0__tar.gz → 0.1.2__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.
- {meterflow-0.1.0 → meterflow-0.1.2}/PKG-INFO +53 -2
- {meterflow-0.1.0 → meterflow-0.1.2}/README.md +52 -1
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/_version.py +1 -1
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/resources/usage.py +24 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/types.py +17 -2
- {meterflow-0.1.0 → meterflow-0.1.2}/LICENSE +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/pyproject.toml +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/__init__.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/_http.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/_retry.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/client.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/errors.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/py.typed +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/resources/__init__.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/resources/credits.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/resources/entitlements.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/resources/plans.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/resources/subscriptions.py +0 -0
- {meterflow-0.1.0 → meterflow-0.1.2}/src/meterflow/webhook.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: meterflow
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
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
|
|
@@ -279,6 +279,42 @@ for start in range(0, len(events), MAX_BATCH_EVENTS):
|
|
|
279
279
|
client.usage.record_batch(chunk, idempotency_key=f"job-42:chunk-{start // MAX_BATCH_EVENTS}")
|
|
280
280
|
```
|
|
281
281
|
|
|
282
|
+
### Record quantities, not calls
|
|
283
|
+
|
|
284
|
+
**A batch of 100 events is still 100 events.** Batching saves HTTP requests, not quota: each item in a `record_batch` is its own record, and your plan's monthly allowance counts records. The thing that actually moves the number is sending **one event that carries the quantity**.
|
|
285
|
+
|
|
286
|
+
If your meter's aggregation is `sum`, MeterFlow adds up the `value` of its events — so one event with `value=100` is **one** event against your monthly allowance and **100 units** against the meter. Record per unit of work instead of per API call:
|
|
287
|
+
|
|
288
|
+
```python
|
|
289
|
+
# ❌ One event per call — 100 calls is 100 events against your plan.
|
|
290
|
+
for chunk in completion.chunks:
|
|
291
|
+
client.usage.record(
|
|
292
|
+
{
|
|
293
|
+
"event_name": "tokens.used",
|
|
294
|
+
"customer_external_id": "customer_123",
|
|
295
|
+
"value": 1,
|
|
296
|
+
"properties": {},
|
|
297
|
+
}
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
# ✅ One event carrying the quantity — 1 event against your plan, 1,300 units on the meter.
|
|
301
|
+
client.usage.record(
|
|
302
|
+
{
|
|
303
|
+
"event_name": "tokens.used",
|
|
304
|
+
"customer_external_id": "customer_123",
|
|
305
|
+
"value": 1300, # a `sum` meter adds these up
|
|
306
|
+
"properties": {"model": "gpt-4o-mini"},
|
|
307
|
+
}
|
|
308
|
+
)
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
This is usually the difference between fitting a plan and outgrowing it: 1,000 users × 100 calls a day is ~3M events a month recorded per call, and ~30k recorded per session. Aggregate in your app over whatever window you can afford to lose on a crash — a request, a job, a minute — then send one event.
|
|
312
|
+
|
|
313
|
+
Two things to keep in mind:
|
|
314
|
+
|
|
315
|
+
- **It only helps a `sum` meter.** A `count` meter ignores `value` and counts occurrences, so there each occurrence has to be its own event. `max`, `min` and `unique_count` read `value` as a measurement, not a quantity to add.
|
|
316
|
+
- **Billing is unchanged.** A metered plan limit charges per unit — the event's `value` — so 100 units cost the same whether they arrived as 100 events or one. You are not rounding anyone's bill by batching.
|
|
317
|
+
|
|
282
318
|
**Summary** — a customer's usage, broken down by meter:
|
|
283
319
|
|
|
284
320
|
```python
|
|
@@ -402,6 +438,17 @@ client.credits.deduct(
|
|
|
402
438
|
|
|
403
439
|
Every write method accepts the keyword: `credits.grant/deduct`, `usage.record/record_batch`, `subscriptions.create/update`. Use a key that identifies the *business operation* (order ID, job ID) — not a random value per attempt, which would defeat the purpose.
|
|
404
440
|
|
|
441
|
+
**A key is bound to the body you first used it with.** MeterFlow stores a fingerprint of the request alongside the key, so a retry only replays when it is genuinely the same request. Reuse the key with a *different* body and the call is refused with `ConflictError` (409) instead of quietly handing back the original record:
|
|
442
|
+
|
|
443
|
+
```python
|
|
444
|
+
client.credits.grant({"customer_external_id": "customer_123", "amount": 100, "metadata": {}}, idempotency_key="welcome-123")
|
|
445
|
+
|
|
446
|
+
# Same key, different amount -> ConflictError. Nothing is written, and the first grant stands.
|
|
447
|
+
client.credits.grant({"customer_external_id": "customer_123", "amount": 250, "metadata": {}}, idempotency_key="welcome-123")
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
That is deliberate: silently returning the first record would turn two different operations into one and report success. One key per operation, reused only to retry that same operation. Keys stay namespaced per environment, so a `mf_test_` and a `mf_live_` key never collide.
|
|
451
|
+
|
|
405
452
|
## Automatic retries
|
|
406
453
|
|
|
407
454
|
The SDK retries transient failures for you — exponential backoff with jitter, 3 attempts by default:
|
|
@@ -434,7 +481,7 @@ Every error carries:
|
|
|
434
481
|
|
|
435
482
|
- **`request_id`** — the API's `X-Request-ID` for that call. Include it when contacting support; it pinpoints the exact request in our logs.
|
|
436
483
|
- **`status_code`**, **`error_type`**, and **`retryable`** — for programmatic handling and structured logging.
|
|
437
|
-
- **`message`** (also `str(err)`) — the API's own sentence (e.g. `Plan limit reached: the Drip plan includes
|
|
484
|
+
- **`message`** (also `str(err)`) — the API's own sentence (e.g. `Plan limit reached: the Drip plan includes 50,000 usage events per month…`). A `ValidationError` appends its field detail (`Validation failed: amount: must be greater than 0`) and also exposes it structured as **`.fields`** (`[{"field": ..., "message": ...}]`).
|
|
438
485
|
|
|
439
486
|
```python
|
|
440
487
|
from meterflow import MeterFlowError, InsufficientCreditsError, RateLimitError
|
|
@@ -491,6 +538,10 @@ Every delivery is a flat JSON object (`Content-Type: application/json`) with two
|
|
|
491
538
|
| `subscription.created` | a subscription is created | `customer_id`, `plan_id`, `subscription_id`, `status` |
|
|
492
539
|
| `subscription.updated` | a subscription is updated | `customer_id`, `subscription_id`, `status` |
|
|
493
540
|
| `limit.reached` | a customer first reaches a **hard** or **soft** limit's included units this billing period (once per meter per period; metered limits report through `credit.deducted` instead) | `customer_id`, `subscription_id`, `feature` (the meter's `event_name`), `meter_id`, `limit_type`, `included`, `used`, `period_start`, `period_end` |
|
|
541
|
+
| `balance.low` | a deduction takes a customer's balance **down through** this endpoint's `low_balance_threshold` — a crossing, so it fires once and not again while they stay below. Needs the threshold set on the webhook; without one it never fires | `customer_id`, `balance`, `threshold`, `transaction_id` |
|
|
542
|
+
| `balance.exhausted` | a balance reaches zero, **or** a request is refused for want of credits (a deduction returning 402, or `entitlements.check` answering `insufficient_credits`). Unlike `balance.low` this repeats: every refused request is its own blocked request | `customer_id`, `balance`, `reason` (`balance_zero` / `insufficient_credits`), `requested_amount` and `feature` where they apply, `transaction_id` on the zero case |
|
|
543
|
+
| `subscription.renewed` | a billing period rolls forward (the renewer; no `subscription.updated` is emitted for a renewal) | `customer_id`, `subscription_id`, `plan_id`, `current_period_start`, `current_period_end`, `credits_granted` |
|
|
544
|
+
| `subscription.canceled` | a subscription's status becomes canceled — fired **alongside** `subscription.updated`, once, on the call that actually cancels | `customer_id`, `subscription_id`, `plan_id`, `canceled_at` |
|
|
494
545
|
|
|
495
546
|
For example, a `credit.granted` delivery:
|
|
496
547
|
|
|
@@ -227,6 +227,42 @@ for start in range(0, len(events), MAX_BATCH_EVENTS):
|
|
|
227
227
|
client.usage.record_batch(chunk, idempotency_key=f"job-42:chunk-{start // MAX_BATCH_EVENTS}")
|
|
228
228
|
```
|
|
229
229
|
|
|
230
|
+
### Record quantities, not calls
|
|
231
|
+
|
|
232
|
+
**A batch of 100 events is still 100 events.** Batching saves HTTP requests, not quota: each item in a `record_batch` is its own record, and your plan's monthly allowance counts records. The thing that actually moves the number is sending **one event that carries the quantity**.
|
|
233
|
+
|
|
234
|
+
If your meter's aggregation is `sum`, MeterFlow adds up the `value` of its events — so one event with `value=100` is **one** event against your monthly allowance and **100 units** against the meter. Record per unit of work instead of per API call:
|
|
235
|
+
|
|
236
|
+
```python
|
|
237
|
+
# ❌ One event per call — 100 calls is 100 events against your plan.
|
|
238
|
+
for chunk in completion.chunks:
|
|
239
|
+
client.usage.record(
|
|
240
|
+
{
|
|
241
|
+
"event_name": "tokens.used",
|
|
242
|
+
"customer_external_id": "customer_123",
|
|
243
|
+
"value": 1,
|
|
244
|
+
"properties": {},
|
|
245
|
+
}
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
# ✅ One event carrying the quantity — 1 event against your plan, 1,300 units on the meter.
|
|
249
|
+
client.usage.record(
|
|
250
|
+
{
|
|
251
|
+
"event_name": "tokens.used",
|
|
252
|
+
"customer_external_id": "customer_123",
|
|
253
|
+
"value": 1300, # a `sum` meter adds these up
|
|
254
|
+
"properties": {"model": "gpt-4o-mini"},
|
|
255
|
+
}
|
|
256
|
+
)
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
This is usually the difference between fitting a plan and outgrowing it: 1,000 users × 100 calls a day is ~3M events a month recorded per call, and ~30k recorded per session. Aggregate in your app over whatever window you can afford to lose on a crash — a request, a job, a minute — then send one event.
|
|
260
|
+
|
|
261
|
+
Two things to keep in mind:
|
|
262
|
+
|
|
263
|
+
- **It only helps a `sum` meter.** A `count` meter ignores `value` and counts occurrences, so there each occurrence has to be its own event. `max`, `min` and `unique_count` read `value` as a measurement, not a quantity to add.
|
|
264
|
+
- **Billing is unchanged.** A metered plan limit charges per unit — the event's `value` — so 100 units cost the same whether they arrived as 100 events or one. You are not rounding anyone's bill by batching.
|
|
265
|
+
|
|
230
266
|
**Summary** — a customer's usage, broken down by meter:
|
|
231
267
|
|
|
232
268
|
```python
|
|
@@ -350,6 +386,17 @@ client.credits.deduct(
|
|
|
350
386
|
|
|
351
387
|
Every write method accepts the keyword: `credits.grant/deduct`, `usage.record/record_batch`, `subscriptions.create/update`. Use a key that identifies the *business operation* (order ID, job ID) — not a random value per attempt, which would defeat the purpose.
|
|
352
388
|
|
|
389
|
+
**A key is bound to the body you first used it with.** MeterFlow stores a fingerprint of the request alongside the key, so a retry only replays when it is genuinely the same request. Reuse the key with a *different* body and the call is refused with `ConflictError` (409) instead of quietly handing back the original record:
|
|
390
|
+
|
|
391
|
+
```python
|
|
392
|
+
client.credits.grant({"customer_external_id": "customer_123", "amount": 100, "metadata": {}}, idempotency_key="welcome-123")
|
|
393
|
+
|
|
394
|
+
# Same key, different amount -> ConflictError. Nothing is written, and the first grant stands.
|
|
395
|
+
client.credits.grant({"customer_external_id": "customer_123", "amount": 250, "metadata": {}}, idempotency_key="welcome-123")
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
That is deliberate: silently returning the first record would turn two different operations into one and report success. One key per operation, reused only to retry that same operation. Keys stay namespaced per environment, so a `mf_test_` and a `mf_live_` key never collide.
|
|
399
|
+
|
|
353
400
|
## Automatic retries
|
|
354
401
|
|
|
355
402
|
The SDK retries transient failures for you — exponential backoff with jitter, 3 attempts by default:
|
|
@@ -382,7 +429,7 @@ Every error carries:
|
|
|
382
429
|
|
|
383
430
|
- **`request_id`** — the API's `X-Request-ID` for that call. Include it when contacting support; it pinpoints the exact request in our logs.
|
|
384
431
|
- **`status_code`**, **`error_type`**, and **`retryable`** — for programmatic handling and structured logging.
|
|
385
|
-
- **`message`** (also `str(err)`) — the API's own sentence (e.g. `Plan limit reached: the Drip plan includes
|
|
432
|
+
- **`message`** (also `str(err)`) — the API's own sentence (e.g. `Plan limit reached: the Drip plan includes 50,000 usage events per month…`). A `ValidationError` appends its field detail (`Validation failed: amount: must be greater than 0`) and also exposes it structured as **`.fields`** (`[{"field": ..., "message": ...}]`).
|
|
386
433
|
|
|
387
434
|
```python
|
|
388
435
|
from meterflow import MeterFlowError, InsufficientCreditsError, RateLimitError
|
|
@@ -439,6 +486,10 @@ Every delivery is a flat JSON object (`Content-Type: application/json`) with two
|
|
|
439
486
|
| `subscription.created` | a subscription is created | `customer_id`, `plan_id`, `subscription_id`, `status` |
|
|
440
487
|
| `subscription.updated` | a subscription is updated | `customer_id`, `subscription_id`, `status` |
|
|
441
488
|
| `limit.reached` | a customer first reaches a **hard** or **soft** limit's included units this billing period (once per meter per period; metered limits report through `credit.deducted` instead) | `customer_id`, `subscription_id`, `feature` (the meter's `event_name`), `meter_id`, `limit_type`, `included`, `used`, `period_start`, `period_end` |
|
|
489
|
+
| `balance.low` | a deduction takes a customer's balance **down through** this endpoint's `low_balance_threshold` — a crossing, so it fires once and not again while they stay below. Needs the threshold set on the webhook; without one it never fires | `customer_id`, `balance`, `threshold`, `transaction_id` |
|
|
490
|
+
| `balance.exhausted` | a balance reaches zero, **or** a request is refused for want of credits (a deduction returning 402, or `entitlements.check` answering `insufficient_credits`). Unlike `balance.low` this repeats: every refused request is its own blocked request | `customer_id`, `balance`, `reason` (`balance_zero` / `insufficient_credits`), `requested_amount` and `feature` where they apply, `transaction_id` on the zero case |
|
|
491
|
+
| `subscription.renewed` | a billing period rolls forward (the renewer; no `subscription.updated` is emitted for a renewal) | `customer_id`, `subscription_id`, `plan_id`, `current_period_start`, `current_period_end`, `credits_granted` |
|
|
492
|
+
| `subscription.canceled` | a subscription's status becomes canceled — fired **alongside** `subscription.updated`, once, on the call that actually cancels | `customer_id`, `subscription_id`, `plan_id`, `canceled_at` |
|
|
442
493
|
|
|
443
494
|
For example, a `credit.granted` delivery:
|
|
444
495
|
|
|
@@ -29,6 +29,10 @@ def record_batch_spec(events: list[UsageEventRequest], idempotency_key: str | No
|
|
|
29
29
|
return RequestSpec("POST", "usage/events/batch", body={"events": events}, idempotency_key=idempotency_key)
|
|
30
30
|
|
|
31
31
|
|
|
32
|
+
def event_spec(event_id: str) -> RequestSpec:
|
|
33
|
+
return RequestSpec("GET", f"usage/events/{encode_path_segment(event_id)}")
|
|
34
|
+
|
|
35
|
+
|
|
32
36
|
def summary_spec(customer_id: str, meter_id: str | None, from_: str | None, to: str | None) -> RequestSpec:
|
|
33
37
|
return RequestSpec("GET", f"usage/{encode_path_segment(customer_id)}", query={"meter_id": meter_id, "from_": from_, "to": to})
|
|
34
38
|
|
|
@@ -47,6 +51,16 @@ class UsageResource:
|
|
|
47
51
|
result: list[UsageEventResponse] = self._client.request(record_batch_spec(events, idempotency_key))
|
|
48
52
|
return result
|
|
49
53
|
|
|
54
|
+
def event(self, event_id: str) -> UsageEventResponse:
|
|
55
|
+
"""Read one recorded event back, with ``billing_outcome`` — what the worker decided.
|
|
56
|
+
|
|
57
|
+
One of ``charged``, ``no_subscription``, ``no_meter_limit``, ``not_metered``,
|
|
58
|
+
``within_allowance`` or ``not_deducted``, and ``None`` while ``processed`` is False: the
|
|
59
|
+
worker runs after ``record`` answers, so poll this to learn what happened to a charge.
|
|
60
|
+
"""
|
|
61
|
+
result: UsageEventResponse = self._client.request(event_spec(event_id))
|
|
62
|
+
return result
|
|
63
|
+
|
|
50
64
|
def summary(
|
|
51
65
|
self, customer_id: str, *, meter_id: str | None = None, from_: str | None = None, to: str | None = None
|
|
52
66
|
) -> UsageSummaryResponse:
|
|
@@ -69,6 +83,16 @@ class AsyncUsageResource:
|
|
|
69
83
|
result: list[UsageEventResponse] = await self._client.request(record_batch_spec(events, idempotency_key))
|
|
70
84
|
return result
|
|
71
85
|
|
|
86
|
+
async def event(self, event_id: str) -> UsageEventResponse:
|
|
87
|
+
"""Read one recorded event back, with ``billing_outcome`` — what the worker decided.
|
|
88
|
+
|
|
89
|
+
One of ``charged``, ``no_subscription``, ``no_meter_limit``, ``not_metered``,
|
|
90
|
+
``within_allowance`` or ``not_deducted``, and ``None`` while ``processed`` is False: the
|
|
91
|
+
worker runs after ``record`` answers, so poll this to learn what happened to a charge.
|
|
92
|
+
"""
|
|
93
|
+
result: UsageEventResponse = await self._client.request(event_spec(event_id))
|
|
94
|
+
return result
|
|
95
|
+
|
|
72
96
|
async def summary(
|
|
73
97
|
self, customer_id: str, *, meter_id: str | None = None, from_: str | None = None, to: str | None = None
|
|
74
98
|
) -> UsageSummaryResponse:
|
|
@@ -16,6 +16,7 @@ SubscriptionStatus = Literal["active", "trialing", "past_due", "paused", "cancel
|
|
|
16
16
|
class CreditBalanceResponse(TypedDict):
|
|
17
17
|
id: str
|
|
18
18
|
project_id: str
|
|
19
|
+
environment: str
|
|
19
20
|
customer_external_id: str
|
|
20
21
|
balance: str
|
|
21
22
|
total_granted: str
|
|
@@ -50,6 +51,7 @@ class CreditGrantRequest(_CreditGrantRequestRequired, total=False):
|
|
|
50
51
|
class CreditTransactionResponse(TypedDict):
|
|
51
52
|
id: str
|
|
52
53
|
project_id: str
|
|
54
|
+
environment: str
|
|
53
55
|
customer_external_id: str
|
|
54
56
|
transaction_type: str
|
|
55
57
|
amount: str
|
|
@@ -107,6 +109,7 @@ class PlanResponse(TypedDict):
|
|
|
107
109
|
trial_days: int
|
|
108
110
|
is_active: bool
|
|
109
111
|
is_public: bool
|
|
112
|
+
is_published: bool
|
|
110
113
|
metadata_: dict[str, Any]
|
|
111
114
|
meter_limits: list[PlanMeterLimitResponse]
|
|
112
115
|
features: list[str]
|
|
@@ -127,6 +130,7 @@ class SubscriptionCreateRequest(_SubscriptionCreateRequestRequired, total=False)
|
|
|
127
130
|
class SubscriptionResponse(TypedDict):
|
|
128
131
|
id: str
|
|
129
132
|
project_id: str
|
|
133
|
+
environment: str
|
|
130
134
|
plan_id: str
|
|
131
135
|
customer_external_id: str
|
|
132
136
|
status: str
|
|
@@ -160,9 +164,10 @@ class UsageEventRequest(_UsageEventRequestRequired, total=False):
|
|
|
160
164
|
timestamp: str | None
|
|
161
165
|
|
|
162
166
|
|
|
163
|
-
class
|
|
167
|
+
class _UsageEventResponseRequired(TypedDict):
|
|
164
168
|
id: str
|
|
165
169
|
project_id: str
|
|
170
|
+
environment: str
|
|
166
171
|
meter_id: str
|
|
167
172
|
customer_external_id: str
|
|
168
173
|
event_name: str
|
|
@@ -174,7 +179,12 @@ class UsageEventResponse(TypedDict):
|
|
|
174
179
|
created_at: str
|
|
175
180
|
|
|
176
181
|
|
|
177
|
-
class
|
|
182
|
+
class UsageEventResponse(_UsageEventResponseRequired, total=False):
|
|
183
|
+
billing_outcome: str | None
|
|
184
|
+
processed_at: str | None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class _UsageSummaryItemRequired(TypedDict):
|
|
178
188
|
meter_id: str
|
|
179
189
|
meter_name: str
|
|
180
190
|
event_name: str
|
|
@@ -183,6 +193,11 @@ class UsageSummaryItem(TypedDict):
|
|
|
183
193
|
event_count: int
|
|
184
194
|
|
|
185
195
|
|
|
196
|
+
class UsageSummaryItem(_UsageSummaryItemRequired, total=False):
|
|
197
|
+
first_event_at: str | None
|
|
198
|
+
last_event_at: str | None
|
|
199
|
+
|
|
200
|
+
|
|
186
201
|
class UsageSummaryResponse(TypedDict):
|
|
187
202
|
project_id: str
|
|
188
203
|
customer_external_id: str
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|