mbase-sdk 0.0.2 → 0.0.5

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.
package/dist/index.d.cts CHANGED
@@ -29,6 +29,10 @@ type Request = RequestOptions & {
29
29
  };
30
30
  declare class Client {
31
31
  #private;
32
+ /** The engine's clock, as well as this client knows it. */
33
+ now(): number;
34
+ /** Off by up to one round trip, which a window in hours does not notice. */
35
+ observeServerTime(at: Date): void;
32
36
  constructor(options: MeterbaseOptions);
33
37
  request<T>(req: Request): Promise<T>;
34
38
  }
@@ -164,9 +168,47 @@ type CheckParams = {
164
168
  * asks whether there is any capacity at all. */
165
169
  quantity?: number;
166
170
  };
171
+ /**
172
+ * Which gate turned the request away. `entitlement` is named ahead of
173
+ * `rate_limit` when both refuse: running out of plan is the one the customer
174
+ * can act on, and being told about the window instead would send them to
175
+ * support over the wrong thing.
176
+ *
177
+ * Open on purpose. The engine's contract says this list will grow, and a
178
+ * closed union would turn every code the engine adds into a build the caller
179
+ * has to wait on the SDK for. Branch on the codes you know; anything else is
180
+ * still a refusal, and still means do not do the work.
181
+ */
182
+ type CheckReason = "entitlement" | "rate_limit" | (string & {});
183
+ /**
184
+ * One rate-limit window in force for this customer and meter.
185
+ *
186
+ * Windows are fixed and clock-aligned — a cell starts at a multiple of the
187
+ * window counted from the epoch — which is what lets `used` be a literal count
188
+ * of what the current cell holds and `resets_at` a clock time. A sliding
189
+ * window would owe the reader a tooltip for both.
190
+ */
191
+ type CheckRateLimit = {
192
+ /** A whole number of seconds from `60` to `2592000`: a minute to 30 days. */
193
+ window_seconds: number;
194
+ max: number;
195
+ used: number;
196
+ /** `max - used`, floored at 0. */
197
+ remaining: number;
198
+ /** `used + quantity > max`: this request does not fit in this window. */
199
+ exceeded: boolean;
200
+ /** End of the current cell, when `used` goes back to 0. Waiting for it is
201
+ * the fix for a window that refused — unless the quantity is larger than
202
+ * `max`, which never fits however long the caller waits. */
203
+ resets_at: string;
204
+ };
167
205
  type CheckResult = {
206
+ /** Both gates: the capacity covers the quantity **and** every rate-limit
207
+ * window admits it. */
168
208
  allowed: boolean;
169
- /** Unlimited for this meter. `available` is `null`. */
209
+ /** Unlimited for this meter. `available` is `null`. Rate limits still
210
+ * apply — a customer who is never refused on capacity is the one a runaway
211
+ * loop costs most. */
170
212
  no_cap: boolean;
171
213
  /**
172
214
  * The whole capacity: the plan's unused entitlement for the current period,
@@ -178,6 +220,20 @@ type CheckResult = {
178
220
  * per-grant detail, read `customers.allowances.list`.
179
221
  */
180
222
  available: number | null;
223
+ /** Which gate said no. Absent when allowed, so its presence is the denial
224
+ * and reading it is never a branch on a truthy string. */
225
+ reason?: CheckReason;
226
+ /**
227
+ * Every window in force, refused or not, which is why the engine reports
228
+ * them on every call: a caller that only heard about a limit when it was
229
+ * refused could not slow down before it, only after.
230
+ *
231
+ * A limit is protective, not commercial, so it sits beside `available` and
232
+ * is never folded into it — a customer well inside their plan can still be
233
+ * limited, and the two are fixed by different people for different reasons.
234
+ * `[]` when no rule applies, which is the ordinary case.
235
+ */
236
+ rate_limits: CheckRateLimit[];
181
237
  };
182
238
  /**
183
239
  * `track` records work that already happened, so it never refuses on capacity
@@ -426,13 +482,58 @@ type WhoAmI = {
426
482
  caller: string;
427
483
  kind: "api_key" | "service";
428
484
  };
485
+ /**
486
+ * A reserve is a check that means it: the same decision, and then a **hold**
487
+ * on the capacity until a track commits it, a release gives it back, or it
488
+ * expires. It is the gate for work that cannot be done twice.
489
+ */
490
+ type ReserveParams = {
491
+ customer_id: string;
492
+ meter_id: string;
493
+ /** What the hold sets aside, `1 … 100000000000`. Defaults to `1`. */
494
+ quantity?: number;
495
+ /**
496
+ * The hold's id, and the event's id once a track commits it. A UUIDv7, and
497
+ * the SDK mints one when it is omitted.
498
+ *
499
+ * An id is for one reserve and its retries. Once its hold is committed or
500
+ * released the row is gone, so sending the same id again reserves afresh
501
+ * rather than finding anything.
502
+ */
503
+ reservation_id?: string;
504
+ /**
505
+ * How long the hold counts against the pair before it comes back on its
506
+ * own: `1 … 900`, defaulting to `60`.
507
+ *
508
+ * It is a timeout on your own work, and the field callers get wrong. Too
509
+ * short and the hold evaporates mid-operation, which is worse than no hold
510
+ * at all because you believe you are protected; too long and a crash wedges
511
+ * the customer's capacity until it expires.
512
+ */
513
+ expires_in_seconds?: number;
514
+ };
515
+ /** What the engine answers a reserve with, before the SDK adds its helpers. */
516
+ type ReserveResponse = CheckResult & {
517
+ /** Present only when allowed: a refusal holds nothing. */
518
+ reservation_id?: string;
519
+ quantity?: number;
520
+ expires_at?: string;
521
+ };
522
+ type ReleaseParams = {
523
+ reservation_id: string;
524
+ };
525
+ /** The hold that was given back, and what it had set aside. */
526
+ type ReleaseResult = {
527
+ reservation_id: string;
528
+ quantity: number;
529
+ };
429
530
 
430
531
  /**
431
532
  * Capacity handed to one customer on top of their plan. A grant with
432
533
  * `source: "plan"` is the engine's own, minted when a plan is assigned, and
433
534
  * cannot be created here.
434
535
  */
435
- declare class CustomerAllowances {
536
+ declare class CustomerAllowances$1 {
436
537
  #private;
437
538
  constructor(client: Client);
438
539
  grant(customerId: string, params: AllowanceGrantParams, options?: RequestOptions): Promise<Allowance>;
@@ -453,7 +554,7 @@ declare class CustomerAllowances {
453
554
  * that picking one does not mean knowing what `effective` and `reconciliation`
454
555
  * do to a half-used period.
455
556
  */
456
- declare class CustomerPlan {
557
+ declare class CustomerPlan$1 {
457
558
  #private;
458
559
  constructor(client: Client);
459
560
  /**
@@ -542,12 +643,12 @@ declare class CustomerPlan {
542
643
  history(customerId: string, options?: RequestOptions): Promise<List<Assignment>>;
543
644
  }
544
645
 
545
- declare class Customers {
646
+ declare class Customers$1 {
546
647
  #private;
547
648
  /** The plan they hold, and the trail of instructions that got them there. */
548
- readonly plan: CustomerPlan;
649
+ readonly plan: CustomerPlan$1;
549
650
  /** Grants, which sit on top of whatever the plan gives. */
550
- readonly allowances: CustomerAllowances;
651
+ readonly allowances: CustomerAllowances$1;
551
652
  constructor(client: Client);
552
653
  create(params: CustomerCreateParams, options?: RequestOptions): Promise<Customer>;
553
654
  /** Lean: a listing does not embed the plan. Read one customer for that. */
@@ -569,7 +670,7 @@ declare class Customers {
569
670
  delete(id: string, options?: RequestOptions): Promise<Customer>;
570
671
  }
571
672
 
572
- declare class Meters {
673
+ declare class Meters$1 {
573
674
  #private;
574
675
  constructor(client: Client);
575
676
  create(params: MeterCreateParams, options?: RequestOptions): Promise<Meter>;
@@ -584,16 +685,16 @@ declare class Meters {
584
685
  * A plan's entitlement, versioned. There is no update and no delete: an edit
585
686
  * appends the next version, so which amount applied when stays derivable.
586
687
  */
587
- declare class PlanAllowances {
688
+ declare class PlanAllowances$1 {
588
689
  #private;
589
690
  constructor(client: Client);
590
691
  set(planId: string, params: PlanAllowanceSetParams, options?: RequestOptions): Promise<PlanAllowance>;
591
692
  /** Every version of every meter, newest first — history, not just current. */
592
693
  list(planId: string, params?: PlanAllowanceListParams, options?: RequestOptions): Promise<List<PlanAllowance>>;
593
694
  }
594
- declare class Plans {
695
+ declare class Plans$1 {
595
696
  #private;
596
- readonly allowances: PlanAllowances;
697
+ readonly allowances: PlanAllowances$1;
597
698
  constructor(client: Client);
598
699
  /** A new plan grants nothing; attach entitlement with `allowances.set`. */
599
700
  create(params: PlanCreateParams, options?: RequestOptions): Promise<Plan>;
@@ -634,21 +735,37 @@ declare class NotFoundError extends APIError {
634
735
  }
635
736
  declare class ConflictError extends APIError {
636
737
  }
738
+ declare class InvalidRequestError extends APIError {
739
+ }
740
+ /**
741
+ * `422 invalid_idempotency_key`: the key was not a UUID version 7.
742
+ * `crypto.randomUUID()` mints a v4, so omit `idempotency_key` and let this
743
+ * SDK mint the right thing.
744
+ */
745
+ declare class InvalidIdempotencyKeyError extends InvalidRequestError {
746
+ }
637
747
  /**
638
- * `409 idempotency_conflict`: the key is in use for a different meter or
639
- * quantity. A caller told their key is taken asks what it recorded next, so
640
- * the engine names the original and this carries it.
748
+ * `422 too_late`: the key's timestamp is more than an hour from the engine's
749
+ * clock, so a retry can no longer be told from a new event. **Nothing was
750
+ * recorded** — the check runs before any write.
641
751
  *
642
- * A `ConflictError` still, so `catch (e) { if (e instanceof ConflictError) }`
643
- * keeps working.
752
+ * The usual cause is this machine's clock. When this SDK minted the key it
753
+ * corrects the offset from `serverTime` and retries once, so you only see
754
+ * this for a key you supplied. If that key is a retry of a call made over an
755
+ * hour ago, do not resend it under a new one: it may already be recorded.
644
756
  */
645
- declare class IdempotencyConflictError extends ConflictError {
646
- /** The event that key already recorded. Undefined only if the engine sent a
647
- * body this could not be read out of. */
648
- readonly existingEventId: string | undefined;
757
+ declare class TooLateError extends InvalidRequestError {
758
+ /** The engine's clock when it refused. */
759
+ readonly serverTime: Date | undefined;
649
760
  constructor(args: ConstructorParameters<typeof APIError>[0]);
650
761
  }
651
- declare class InvalidRequestError extends APIError {
762
+ /**
763
+ * `422 reservation_mismatch`: the reservation id names a hold made for a
764
+ * different customer or meter than the call sends. A caller bug, refused
765
+ * before anything is written — nothing was recorded and the hold still
766
+ * stands.
767
+ */
768
+ declare class ReservationMismatchError extends InvalidRequestError {
652
769
  }
653
770
  /**
654
771
  * `422 cycle_change_requires_reset`: the two plans measure different cycles,
@@ -684,6 +801,43 @@ declare function errorFromResponse(args: {
684
801
  body?: unknown;
685
802
  }): APIError;
686
803
 
804
+ /**
805
+ * A granted hold, with the two calls that close it. `commit` is `track` under
806
+ * the hold's own id; `release` gives the capacity back.
807
+ */
808
+ type Hold = ReserveResponse & {
809
+ allowed: true;
810
+ reservation_id: string;
811
+ quantity: number;
812
+ expires_at: string;
813
+ /**
814
+ * Records what the work actually cost and releases the rest. Omit the
815
+ * quantity to record what was held.
816
+ *
817
+ * Warns when it runs after `expires_at`: the hold stopped holding anything
818
+ * at that instant, so the work was no longer protected. That warning is the
819
+ * only feedback there is on an `expires_in_seconds` guessed too short.
820
+ */
821
+ commit(quantity?: number, options?: RequestOptions): Promise<TrackResult>;
822
+ /**
823
+ * Gives the hold back. Nothing is recorded.
824
+ *
825
+ * Resolves with `null` rather than throwing when there is nothing left to
826
+ * release — already committed, already released. This is the one call meant
827
+ * to run on the failure path, where throwing would mask the error the
828
+ * caller is already handling, and "nothing left to release" is the outcome
829
+ * a release wanted anyway. `meterbase.release` throws the 404, as every
830
+ * other call does.
831
+ */
832
+ release(options?: RequestOptions): Promise<ReleaseResult | null>;
833
+ };
834
+ /** A refused reserve holds nothing, so it carries no id and no expiry. */
835
+ type ReserveRefused = ReserveResponse & {
836
+ allowed: false;
837
+ reservation_id?: undefined;
838
+ expires_at?: undefined;
839
+ };
840
+ type ReserveResult = Hold | ReserveRefused;
687
841
  declare class Meterbase {
688
842
  #private;
689
843
  readonly customers: Customers;
@@ -697,6 +851,12 @@ declare class Meterbase {
697
851
  *
698
852
  * This is the gate, and the only call that ever refuses. Run it before the
699
853
  * work; record the work with `track` afterwards.
854
+ *
855
+ * Two gates answer it, and `allowed` needs both: the customer's capacity has
856
+ * to cover the quantity, and every rate-limit window in force has to admit
857
+ * it. `reason` names the one that said no. `rate_limits` reports each window
858
+ * whether or not it refused, so a caller can ease off as its headroom closes
859
+ * instead of discovering the ceiling by hitting it.
700
860
  */
701
861
  check(params: CheckParams, options?: RequestOptions): Promise<CheckResult>;
702
862
  /**
@@ -705,13 +865,48 @@ declare class Meterbase {
705
865
  * customer's capacity is recorded, drives `available` to 0, and the next
706
866
  * `check` says no. The answer is a receipt, not a verdict.
707
867
  *
708
- * `idempotency_key` is generated when omitted, so retrying this call — the
709
- * SDK's own retries included — replays the original rather than counting
710
- * the same work twice.
868
+ * `idempotency_key` is a UUIDv7, generated when omitted, so retrying this
869
+ * call — the SDK's own retries included — replays the original rather than
870
+ * counting the same work twice. The engine keeps that claim for an hour,
871
+ * which is how long a retry stays recognisable.
711
872
  */
712
873
  track(params: TrackParams, options?: RequestOptions): Promise<TrackResult>;
874
+ /**
875
+ * Holds capacity for work that cannot be done twice, or refuses. The same
876
+ * decision `check` makes, and then a hold on the capacity until the work
877
+ * is committed, released, or expires.
878
+ *
879
+ * The rule for choosing: can you afford to do the work twice? `check`. No?
880
+ * `reserve`. A reserve costs a transaction where a check costs a cached
881
+ * read, refusals included, so it is not a per-request gate on cheap work.
882
+ *
883
+ * Two concurrent reserves for the same customer and meter cannot both be
884
+ * granted the same capacity; that is the whole point, and it is what
885
+ * `check` → work → `track` could never promise.
886
+ */
887
+ reserve(params: ReserveParams, options?: RequestOptions): Promise<ReserveResult>;
888
+ /**
889
+ * Gives a hold back: the work did not happen, so nothing is recorded.
890
+ *
891
+ * Throws `NotFoundError` when the id names nothing — committed, released
892
+ * already, or never made, which are one absence with one meaning. Prefer
893
+ * `hold.release()`, which treats that as the success it is.
894
+ */
895
+ release(params: ReleaseParams, options?: RequestOptions): Promise<ReleaseResult>;
713
896
  /** Reports which workspace this key acts for. */
714
897
  whoami(options?: RequestOptions): Promise<WhoAmI>;
715
898
  }
899
+ /**
900
+ * The resource namespaces, type-only: none is constructible without the
901
+ * unexported Client. Instance types rather than `export type { Customers }`,
902
+ * which the declaration bundler re-emits as a value export — promising a
903
+ * runtime binding the bundle never has.
904
+ */
905
+ type CustomerAllowances = InstanceType<typeof CustomerAllowances$1>;
906
+ type CustomerPlan = InstanceType<typeof CustomerPlan$1>;
907
+ type Customers = InstanceType<typeof Customers$1>;
908
+ type Meters = InstanceType<typeof Meters$1>;
909
+ type PlanAllowances = InstanceType<typeof PlanAllowances$1>;
910
+ type Plans = InstanceType<typeof Plans$1>;
716
911
 
717
- export { APIError, type Allowance, type AllowanceGrantParams, type AllowanceListParams, type AllowanceSource, type ApplyMode, type AssignPlanParams, type Assignment, AuthenticationError, type CheckParams, type CheckResult, ConflictError, ConnectionError, type Customer, CustomerAllowances, type CustomerCreateParams, type CustomerListParams, CustomerPlan, type CustomerUpdateParams, type CustomerWithPlan, Customers, CycleChangeRequiresResetError, type EmbeddedPlan, IdempotencyConflictError, InvalidRequestError, type List, type Meter, type MeterCreateParams, type MeterListParams, type MeterUpdateParams, Meterbase, MeterbaseError, type MeterbaseOptions, Meters, NotFoundError, PermissionDeniedError, type Plan, type PlanAllowance, type PlanAllowanceKind, type PlanAllowanceListParams, type PlanAllowanceSetParams, PlanAllowances, type PlanChangeNowParams, type PlanChangeParams, type PlanCreateParams, type PlanCycle, type PlanListParams, type PlanMoveParams, type PlanUpdateParams, Plans, RateLimitError, type Reconciliation, type RecordedReconciliation, type RequestOptions, ServerError, TimeoutError, type TrackParams, type TrackResult, type UsageEvent, type Validity, type WhoAmI, errorFromResponse };
912
+ export { APIError, type Allowance, type AllowanceGrantParams, type AllowanceListParams, type AllowanceSource, type ApplyMode, type AssignPlanParams, type Assignment, AuthenticationError, type CheckParams, type CheckRateLimit, type CheckReason, type CheckResult, ConflictError, ConnectionError, type Customer, type CustomerAllowances, type CustomerCreateParams, type CustomerListParams, type CustomerPlan, type CustomerUpdateParams, type CustomerWithPlan, type Customers, CycleChangeRequiresResetError, type EmbeddedPlan, type Hold, InvalidIdempotencyKeyError, InvalidRequestError, type List, type Meter, type MeterCreateParams, type MeterListParams, type MeterUpdateParams, Meterbase, MeterbaseError, type MeterbaseOptions, type Meters, NotFoundError, PermissionDeniedError, type Plan, type PlanAllowance, type PlanAllowanceKind, type PlanAllowanceListParams, type PlanAllowanceSetParams, type PlanAllowances, type PlanChangeNowParams, type PlanChangeParams, type PlanCreateParams, type PlanCycle, type PlanListParams, type PlanMoveParams, type PlanUpdateParams, type Plans, RateLimitError, type Reconciliation, type RecordedReconciliation, type ReleaseParams, type ReleaseResult, type RequestOptions, ReservationMismatchError, type ReserveParams, type ReserveRefused, type ReserveResponse, type ReserveResult, ServerError, TimeoutError, TooLateError, type TrackParams, type TrackResult, type UsageEvent, type Validity, type WhoAmI, errorFromResponse };