@fantastic.dev/better-stripe 0.53.0 → 0.54.0

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 (121) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +116 -2
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +58 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +116 -2
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +58 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +3 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/client.d.ts +2 -2
  16. package/dist/client/usage/client.d.ts.map +1 -1
  17. package/dist/client/usage/client.js +3 -3
  18. package/dist/client/usage/client.js.map +1 -1
  19. package/dist/client/usage/deliveryClient.d.ts +64 -0
  20. package/dist/client/usage/deliveryClient.d.ts.map +1 -0
  21. package/dist/client/usage/deliveryClient.js +60 -0
  22. package/dist/client/usage/deliveryClient.js.map +1 -0
  23. package/dist/client/usage/deliveryProtocol.d.ts +130 -0
  24. package/dist/client/usage/deliveryProtocol.d.ts.map +1 -0
  25. package/dist/client/usage/deliveryProtocol.js +21 -0
  26. package/dist/client/usage/deliveryProtocol.js.map +1 -0
  27. package/dist/client/usage/deliveryProvider.d.ts +32 -0
  28. package/dist/client/usage/deliveryProvider.d.ts.map +1 -0
  29. package/dist/client/usage/deliveryProvider.js +127 -0
  30. package/dist/client/usage/deliveryProvider.js.map +1 -0
  31. package/dist/client/usage/index.d.ts +3 -0
  32. package/dist/client/usage/index.d.ts.map +1 -1
  33. package/dist/client/usage/index.js +1 -0
  34. package/dist/client/usage/index.js.map +1 -1
  35. package/dist/client/webhooks/handler.d.ts.map +1 -1
  36. package/dist/client/webhooks/handler.js +2 -1
  37. package/dist/client/webhooks/handler.js.map +1 -1
  38. package/dist/client/webhooks/meterErrors.d.ts +5 -0
  39. package/dist/client/webhooks/meterErrors.d.ts.map +1 -0
  40. package/dist/client/webhooks/meterErrors.js +98 -0
  41. package/dist/client/webhooks/meterErrors.js.map +1 -0
  42. package/dist/client/webhooks/v2.d.ts.map +1 -1
  43. package/dist/client/webhooks/v2.js +5 -0
  44. package/dist/client/webhooks/v2.js.map +1 -1
  45. package/dist/component/_generated/api.d.ts +14 -0
  46. package/dist/component/_generated/api.d.ts.map +1 -1
  47. package/dist/component/_generated/api.js.map +1 -1
  48. package/dist/component/_generated/component.d.ts +170 -0
  49. package/dist/component/_generated/component.d.ts.map +1 -1
  50. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  51. package/dist/component/earnings/triggers.d.ts +104 -2
  52. package/dist/component/earnings/triggers.d.ts.map +1 -1
  53. package/dist/component/refundHistory/queries.d.ts +1 -1
  54. package/dist/component/schema.d.ts +58 -1
  55. package/dist/component/schema.js +3 -0
  56. package/dist/component/schema.js.map +1 -1
  57. package/dist/component/usage/schema.d.ts +96 -1
  58. package/dist/component/usage/schema.d.ts.map +1 -1
  59. package/dist/component/usage/schema.js +11 -2
  60. package/dist/component/usage/schema.js.map +1 -1
  61. package/dist/component/usageDelivery/bridge.d.ts +25 -0
  62. package/dist/component/usageDelivery/bridge.d.ts.map +1 -0
  63. package/dist/component/usageDelivery/bridge.js +45 -0
  64. package/dist/component/usageDelivery/bridge.js.map +1 -0
  65. package/dist/component/usageDelivery/fields.d.ts +78 -0
  66. package/dist/component/usageDelivery/fields.d.ts.map +1 -0
  67. package/dist/component/usageDelivery/fields.js +38 -0
  68. package/dist/component/usageDelivery/fields.js.map +1 -0
  69. package/dist/component/usageDelivery/helpers.d.ts +83 -0
  70. package/dist/component/usageDelivery/helpers.d.ts.map +1 -0
  71. package/dist/component/usageDelivery/helpers.js +63 -0
  72. package/dist/component/usageDelivery/helpers.js.map +1 -0
  73. package/dist/component/usageDelivery/mutations.d.ts +97 -0
  74. package/dist/component/usageDelivery/mutations.d.ts.map +1 -0
  75. package/dist/component/usageDelivery/mutations.js +153 -0
  76. package/dist/component/usageDelivery/mutations.js.map +1 -0
  77. package/dist/component/usageDelivery/queries.d.ts +113 -0
  78. package/dist/component/usageDelivery/queries.d.ts.map +1 -0
  79. package/dist/component/usageDelivery/queries.js +22 -0
  80. package/dist/component/usageDelivery/queries.js.map +1 -0
  81. package/dist/component/usageDelivery/schema.d.ts +79 -0
  82. package/dist/component/usageDelivery/schema.d.ts.map +1 -0
  83. package/dist/component/usageDelivery/schema.js +30 -0
  84. package/dist/component/usageDelivery/schema.js.map +1 -0
  85. package/dist/component/usageDelivery/steps.d.ts +85 -0
  86. package/dist/component/usageDelivery/steps.d.ts.map +1 -0
  87. package/dist/component/usageDelivery/steps.js +154 -0
  88. package/dist/component/usageDelivery/steps.js.map +1 -0
  89. package/dist/component/usageDelivery/workflow.d.ts +15 -0
  90. package/dist/component/usageDelivery/workflow.d.ts.map +1 -0
  91. package/dist/component/usageDelivery/workflow.js +28 -0
  92. package/dist/component/usageDelivery/workflow.js.map +1 -0
  93. package/docs/README.md +3 -1
  94. package/docs/metering-setup.md +1 -1
  95. package/docs/usage-delivery.md +143 -0
  96. package/package.json +3 -2
  97. package/src/client/index.ts +16 -0
  98. package/src/client/usage/client.ts +5 -2
  99. package/src/client/usage/deliveryClient.ts +130 -0
  100. package/src/client/usage/deliveryProtocol.ts +26 -0
  101. package/src/client/usage/deliveryProvider.test.ts +207 -0
  102. package/src/client/usage/deliveryProvider.ts +155 -0
  103. package/src/client/usage/index.ts +13 -0
  104. package/src/client/webhooks/handler.ts +2 -1
  105. package/src/client/webhooks/meterErrors.test.ts +164 -0
  106. package/src/client/webhooks/meterErrors.ts +118 -0
  107. package/src/client/webhooks/v2.ts +5 -0
  108. package/src/component/_generated/api.ts +14 -0
  109. package/src/component/_generated/component.ts +302 -0
  110. package/src/component/schema.ts +6 -0
  111. package/src/component/usage/schema.ts +11 -2
  112. package/src/component/usageDelivery/bridge.ts +56 -0
  113. package/src/component/usageDelivery/concurrency.test.ts +62 -0
  114. package/src/component/usageDelivery/fields.ts +59 -0
  115. package/src/component/usageDelivery/helpers.ts +77 -0
  116. package/src/component/usageDelivery/mutations.ts +185 -0
  117. package/src/component/usageDelivery/queries.ts +25 -0
  118. package/src/component/usageDelivery/schema.ts +33 -0
  119. package/src/component/usageDelivery/steps.ts +171 -0
  120. package/src/component/usageDelivery/workflow.test.ts +402 -0
  121. package/src/component/usageDelivery/workflow.ts +36 -0
@@ -167,6 +167,13 @@ import type * as usage_mutations from "../usage/mutations.js";
167
167
  import type * as usage_queries from "../usage/queries.js";
168
168
  import type * as usageCatalog_mutations from "../usageCatalog/mutations.js";
169
169
  import type * as usageCatalog_queries from "../usageCatalog/queries.js";
170
+ import type * as usageDelivery_bridge from "../usageDelivery/bridge.js";
171
+ import type * as usageDelivery_fields from "../usageDelivery/fields.js";
172
+ import type * as usageDelivery_helpers from "../usageDelivery/helpers.js";
173
+ import type * as usageDelivery_mutations from "../usageDelivery/mutations.js";
174
+ import type * as usageDelivery_queries from "../usageDelivery/queries.js";
175
+ import type * as usageDelivery_steps from "../usageDelivery/steps.js";
176
+ import type * as usageDelivery_workflow from "../usageDelivery/workflow.js";
170
177
  import type * as webhooks_mutations from "../webhooks/mutations.js";
171
178
  import type * as webhooks_queries from "../webhooks/queries.js";
172
179
  import type * as webhooks_validators from "../webhooks/validators.js";
@@ -338,6 +345,13 @@ const fullApi: ApiFromModules<{
338
345
  "usage/queries": typeof usage_queries;
339
346
  "usageCatalog/mutations": typeof usageCatalog_mutations;
340
347
  "usageCatalog/queries": typeof usageCatalog_queries;
348
+ "usageDelivery/bridge": typeof usageDelivery_bridge;
349
+ "usageDelivery/fields": typeof usageDelivery_fields;
350
+ "usageDelivery/helpers": typeof usageDelivery_helpers;
351
+ "usageDelivery/mutations": typeof usageDelivery_mutations;
352
+ "usageDelivery/queries": typeof usageDelivery_queries;
353
+ "usageDelivery/steps": typeof usageDelivery_steps;
354
+ "usageDelivery/workflow": typeof usageDelivery_workflow;
341
355
  "webhooks/mutations": typeof webhooks_mutations;
342
356
  "webhooks/queries": typeof webhooks_queries;
343
357
  "webhooks/validators": typeof webhooks_validators;
@@ -8454,6 +8454,308 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8454
8454
  >;
8455
8455
  };
8456
8456
  };
8457
+ usageDelivery: {
8458
+ mutations: {
8459
+ hold: FunctionReference<
8460
+ "mutation",
8461
+ "internal",
8462
+ {
8463
+ eventId: string;
8464
+ scope: {
8465
+ customerAccount: string;
8466
+ livemode: boolean;
8467
+ meterId: string;
8468
+ stripeAccountId: string;
8469
+ };
8470
+ },
8471
+ {
8472
+ attempts: number;
8473
+ eventId: string;
8474
+ held: boolean;
8475
+ providerIdentifier: string;
8476
+ reason?:
8477
+ | "rate_limited"
8478
+ | "provider_unavailable"
8479
+ | "provider_outcome_unknown"
8480
+ | "provider_rejected"
8481
+ | "retry_exhausted"
8482
+ | "delivery_window_expired"
8483
+ | "scope_busy"
8484
+ | "administrative_hold";
8485
+ receipt?: { created: number; identifier: string };
8486
+ state:
8487
+ | "queued"
8488
+ | "sending"
8489
+ | "provider_accepted"
8490
+ | "rejected"
8491
+ | "unknown"
8492
+ | "held";
8493
+ validationErrors: Array<{
8494
+ code:
8495
+ | "meter_event_customer_not_found"
8496
+ | "meter_event_no_customer_defined"
8497
+ | "meter_event_dimension_count_too_high"
8498
+ | "archived_meter"
8499
+ | "timestamp_too_far_in_past"
8500
+ | "timestamp_in_future"
8501
+ | "meter_event_value_not_found"
8502
+ | "meter_event_invalid_value"
8503
+ | "no_meter";
8504
+ observedAt: number;
8505
+ providerEventId: string;
8506
+ }>;
8507
+ validationHistoryComplete: boolean;
8508
+ },
8509
+ Name
8510
+ >;
8511
+ recordErrorReport: FunctionReference<
8512
+ "mutation",
8513
+ "internal",
8514
+ {
8515
+ livemode: boolean;
8516
+ meterId?: string;
8517
+ providerEventId: string;
8518
+ samples: Array<{
8519
+ code:
8520
+ | "meter_event_customer_not_found"
8521
+ | "meter_event_no_customer_defined"
8522
+ | "meter_event_dimension_count_too_high"
8523
+ | "archived_meter"
8524
+ | "timestamp_too_far_in_past"
8525
+ | "timestamp_in_future"
8526
+ | "meter_event_value_not_found"
8527
+ | "meter_event_invalid_value"
8528
+ | "no_meter";
8529
+ identifier: string;
8530
+ }>;
8531
+ stripeAccountId: string;
8532
+ truncated: boolean;
8533
+ },
8534
+ { matched: number; truncated: boolean; unattributed: number },
8535
+ Name
8536
+ >;
8537
+ resume: FunctionReference<
8538
+ "mutation",
8539
+ "internal",
8540
+ {
8541
+ eventId: string;
8542
+ scope: {
8543
+ customerAccount: string;
8544
+ livemode: boolean;
8545
+ meterId: string;
8546
+ stripeAccountId: string;
8547
+ };
8548
+ },
8549
+ {
8550
+ attempts: number;
8551
+ eventId: string;
8552
+ held: boolean;
8553
+ providerIdentifier: string;
8554
+ reason?:
8555
+ | "rate_limited"
8556
+ | "provider_unavailable"
8557
+ | "provider_outcome_unknown"
8558
+ | "provider_rejected"
8559
+ | "retry_exhausted"
8560
+ | "delivery_window_expired"
8561
+ | "scope_busy"
8562
+ | "administrative_hold";
8563
+ receipt?: { created: number; identifier: string };
8564
+ state:
8565
+ | "queued"
8566
+ | "sending"
8567
+ | "provider_accepted"
8568
+ | "rejected"
8569
+ | "unknown"
8570
+ | "held";
8571
+ validationErrors: Array<{
8572
+ code:
8573
+ | "meter_event_customer_not_found"
8574
+ | "meter_event_no_customer_defined"
8575
+ | "meter_event_dimension_count_too_high"
8576
+ | "archived_meter"
8577
+ | "timestamp_too_far_in_past"
8578
+ | "timestamp_in_future"
8579
+ | "meter_event_value_not_found"
8580
+ | "meter_event_invalid_value"
8581
+ | "no_meter";
8582
+ observedAt: number;
8583
+ providerEventId: string;
8584
+ }>;
8585
+ validationHistoryComplete: boolean;
8586
+ },
8587
+ Name
8588
+ >;
8589
+ start: FunctionReference<
8590
+ "mutation",
8591
+ "internal",
8592
+ {
8593
+ definitionVersion: 1;
8594
+ eventId: string;
8595
+ provider: string;
8596
+ scope: {
8597
+ customerAccount: string;
8598
+ livemode: boolean;
8599
+ meterId: string;
8600
+ stripeAccountId: string;
8601
+ };
8602
+ },
8603
+ {
8604
+ attempts: number;
8605
+ eventId: string;
8606
+ held: boolean;
8607
+ providerIdentifier: string;
8608
+ reason?:
8609
+ | "rate_limited"
8610
+ | "provider_unavailable"
8611
+ | "provider_outcome_unknown"
8612
+ | "provider_rejected"
8613
+ | "retry_exhausted"
8614
+ | "delivery_window_expired"
8615
+ | "scope_busy"
8616
+ | "administrative_hold";
8617
+ receipt?: { created: number; identifier: string };
8618
+ state:
8619
+ | "queued"
8620
+ | "sending"
8621
+ | "provider_accepted"
8622
+ | "rejected"
8623
+ | "unknown"
8624
+ | "held";
8625
+ validationErrors: Array<{
8626
+ code:
8627
+ | "meter_event_customer_not_found"
8628
+ | "meter_event_no_customer_defined"
8629
+ | "meter_event_dimension_count_too_high"
8630
+ | "archived_meter"
8631
+ | "timestamp_too_far_in_past"
8632
+ | "timestamp_in_future"
8633
+ | "meter_event_value_not_found"
8634
+ | "meter_event_invalid_value"
8635
+ | "no_meter";
8636
+ observedAt: number;
8637
+ providerEventId: string;
8638
+ }>;
8639
+ validationHistoryComplete: boolean;
8640
+ },
8641
+ Name
8642
+ >;
8643
+ };
8644
+ queries: {
8645
+ get: FunctionReference<
8646
+ "query",
8647
+ "internal",
8648
+ {
8649
+ eventId: string;
8650
+ scope: {
8651
+ customerAccount: string;
8652
+ livemode: boolean;
8653
+ meterId: string;
8654
+ stripeAccountId: string;
8655
+ };
8656
+ },
8657
+ {
8658
+ attempts: number;
8659
+ eventId: string;
8660
+ held: boolean;
8661
+ providerIdentifier: string;
8662
+ reason?:
8663
+ | "rate_limited"
8664
+ | "provider_unavailable"
8665
+ | "provider_outcome_unknown"
8666
+ | "provider_rejected"
8667
+ | "retry_exhausted"
8668
+ | "delivery_window_expired"
8669
+ | "scope_busy"
8670
+ | "administrative_hold";
8671
+ receipt?: { created: number; identifier: string };
8672
+ state:
8673
+ | "queued"
8674
+ | "sending"
8675
+ | "provider_accepted"
8676
+ | "rejected"
8677
+ | "unknown"
8678
+ | "held";
8679
+ validationErrors: Array<{
8680
+ code:
8681
+ | "meter_event_customer_not_found"
8682
+ | "meter_event_no_customer_defined"
8683
+ | "meter_event_dimension_count_too_high"
8684
+ | "archived_meter"
8685
+ | "timestamp_too_far_in_past"
8686
+ | "timestamp_in_future"
8687
+ | "meter_event_value_not_found"
8688
+ | "meter_event_invalid_value"
8689
+ | "no_meter";
8690
+ observedAt: number;
8691
+ providerEventId: string;
8692
+ }>;
8693
+ validationHistoryComplete: boolean;
8694
+ },
8695
+ Name
8696
+ >;
8697
+ snapshot: FunctionReference<
8698
+ "query",
8699
+ "internal",
8700
+ {
8701
+ eventId: string;
8702
+ scope: {
8703
+ customerAccount: string;
8704
+ livemode: boolean;
8705
+ meterId: string;
8706
+ stripeAccountId: string;
8707
+ };
8708
+ },
8709
+ {
8710
+ event: {
8711
+ _creationTime: number;
8712
+ _id: string;
8713
+ acceptedAt: number;
8714
+ identity: string;
8715
+ occurredAt: number;
8716
+ recordJson: string;
8717
+ reservationId?: string;
8718
+ scopeKey: string;
8719
+ subscriptionJson: string;
8720
+ };
8721
+ outbox: {
8722
+ _creationTime: number;
8723
+ _id: string;
8724
+ attempts: number;
8725
+ definitionVersion?: 1;
8726
+ dispatch?: string;
8727
+ eventId: string;
8728
+ firstSendAt?: number;
8729
+ held?: boolean;
8730
+ leaseUntil?: number;
8731
+ nextAttemptAt: number;
8732
+ provider?: string;
8733
+ providerIdentifier: string;
8734
+ reason?:
8735
+ | "rate_limited"
8736
+ | "provider_unavailable"
8737
+ | "provider_outcome_unknown"
8738
+ | "provider_rejected"
8739
+ | "retry_exhausted"
8740
+ | "delivery_window_expired"
8741
+ | "scope_busy"
8742
+ | "administrative_hold";
8743
+ receipt?: { created: number; identifier: string };
8744
+ scopeKey: string;
8745
+ state:
8746
+ | "queued"
8747
+ | "sending"
8748
+ | "provider_accepted"
8749
+ | "rejected"
8750
+ | "unknown"
8751
+ | "held";
8752
+ workflowId?: string;
8753
+ };
8754
+ },
8755
+ Name
8756
+ >;
8757
+ };
8758
+ };
8457
8759
  webhooks: {
8458
8760
  mutations: {
8459
8761
  insertWebhookEvent: FunctionReference<
@@ -1,3 +1,7 @@
1
+ import {
2
+ errorsTable as usageDeliveryErrors,
3
+ locksTable as usageDeliveryLocks,
4
+ } from "./usageDelivery/fields.js";
1
5
  import { claimsTable as refundSyncClaimsTable } from "./refundSync/schema.js";
2
6
  import { operationsTable as processingCostReconciliationOperations } from "./processingCostReconciliation/schema.js";
3
7
  import {
@@ -96,6 +100,8 @@ import { pricesTable, productsTable } from "./products/schema";
96
100
  import { webhookEventsTable } from "./webhooks/schema";
97
101
 
98
102
  export default defineSchema({
103
+ usageDeliveryLocks,
104
+ usageDeliveryErrors,
99
105
  usageCatalog: usageCatalogTable,
100
106
  usageEvents: usageEventsTable,
101
107
  usageOutbox: usageOutboxTable,
@@ -1,3 +1,4 @@
1
+ import { deliveryFields } from "../usageDelivery/fields.js";
1
2
  import { defineTable } from "convex/server";
2
3
  import { v } from "convex/values";
3
4
 
@@ -32,7 +33,8 @@ export const eventDoc = v.object({
32
33
  export const usageEventsTable = defineTable(eventFields)
33
34
  .index("by_identity", ["identity"])
34
35
  .index("by_scope_time", ["scopeKey", "occurredAt"]);
35
- export const usageOutboxTable = defineTable({
36
+ export const outboxFields = {
37
+ ...deliveryFields,
36
38
  eventId: v.id("usageEvents"),
37
39
  scopeKey: v.string(),
38
40
  state: deliveryValidator,
@@ -40,7 +42,14 @@ export const usageOutboxTable = defineTable({
40
42
  nextAttemptAt: v.number(),
41
43
  providerIdentifier: v.string(),
42
44
  dispatch: v.optional(v.string()),
43
- })
45
+ };
46
+ export const outboxDoc = v.object({
47
+ _id: v.id("usageOutbox"),
48
+ _creationTime: v.number(),
49
+ ...outboxFields,
50
+ });
51
+ export const usageOutboxTable = defineTable(outboxFields)
52
+ .index("by_provider_identifier", ["providerIdentifier"])
44
53
  .index("by_event", ["eventId"])
45
54
  .index("by_state_next", ["state", "nextAttemptAt"])
46
55
  .index("by_scope_state", ["scopeKey", "state"]);
@@ -0,0 +1,56 @@
1
+ import { anyApi, type FunctionHandle } from "convex/server";
2
+ import { internalAction } from "../_generated/server.js";
3
+ import { request } from "./schema.js";
4
+ import { outcome } from "./fields.js";
5
+ import type { Infer } from "convex/values";
6
+ import { z } from "zod";
7
+ const accepted = z.strictObject({
8
+ status: z.literal("accepted"),
9
+ created: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
10
+ });
11
+ const parsedOutcome = z.union([
12
+ accepted,
13
+ z.strictObject({
14
+ status: z.enum(["rate_limited", "unavailable", "unknown", "rejected"]),
15
+ }),
16
+ ]);
17
+ export const invoke = internalAction({
18
+ args: request,
19
+ returns: outcome,
20
+ handler: async (ctx, args): Promise<Infer<typeof outcome>> => {
21
+ try {
22
+ const { outbox } = await ctx.runQuery(
23
+ anyApi.usageDelivery.queries.saved,
24
+ { scope: args.scope, eventId: args.eventId },
25
+ );
26
+ if (outbox.held) return { status: "unavailable" };
27
+ if (
28
+ !outbox.provider ||
29
+ outbox.attempts !== args.attempt ||
30
+ outbox.state !== "sending" ||
31
+ outbox.providerIdentifier !== args.identifier
32
+ )
33
+ return { status: "unknown" };
34
+ const raw: unknown = await ctx.runAction(
35
+ outbox.provider as FunctionHandle<"action">,
36
+ args,
37
+ );
38
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
39
+ return { status: "unknown" };
40
+ const result = raw as Record<string, unknown>;
41
+ if (
42
+ Object.keys(result).length !== Object.keys(args).length + 1 ||
43
+ Object.keys(args).some(
44
+ (key) =>
45
+ JSON.stringify(result[key]) !==
46
+ JSON.stringify(args[key as keyof typeof args]),
47
+ )
48
+ )
49
+ return { status: "unknown" };
50
+ const validated = parsedOutcome.safeParse(result.outcome);
51
+ return validated.success ? validated.data : { status: "unknown" };
52
+ } catch {
53
+ return { status: "unknown" };
54
+ }
55
+ },
56
+ });
@@ -0,0 +1,62 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it, vi } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+ const record = makeFunctionReference<"mutation">("usage/mutations:record"),
6
+ claim = makeFunctionReference<"mutation">("usageDelivery/steps:claim");
7
+ it("serializes the same native customer/meter even across distinct authorized payer scopes", async () => {
8
+ vi.useFakeTimers();
9
+ try {
10
+ const t = convexTest(schema, modules),
11
+ now = Math.floor(Date.now() / 1000);
12
+ const accepted = [];
13
+ for (const customerAccount of ["acct_aliasA", "acct_aliasB"]) {
14
+ const scope = {
15
+ stripeAccountId: "acct_platform",
16
+ customerAccount,
17
+ meterId: "mtr_calls",
18
+ livemode: false,
19
+ };
20
+ const receipt = await t.mutation(record, {
21
+ inputJson: JSON.stringify({
22
+ scope,
23
+ binding: {
24
+ stripeCustomerId: "cus_shared",
25
+ stripePriceId: "price_calls",
26
+ eventName: "calls",
27
+ plan: {
28
+ key: "calls",
29
+ version: "v1",
30
+ model: "pay_as_you_go",
31
+ unit: { name: "call", precision: 0 },
32
+ rate: { currency: "usd", unitAmountDecimal: "2" },
33
+ },
34
+ },
35
+ sourceEventId: "one",
36
+ quantity: "1",
37
+ occurredAt: now,
38
+ }),
39
+ subscriptionJson: JSON.stringify({
40
+ subscriptionId: "sub_calls",
41
+ subscriptionItemId: "si_calls",
42
+ stripePriceId: "price_calls",
43
+ period: { start: now - 1, end: now + 86400 },
44
+ interval: "month",
45
+ }),
46
+ });
47
+ accepted.push({ scope, eventId: receipt.eventId });
48
+ }
49
+ expect(await t.mutation(claim, accepted[0])).toMatchObject({
50
+ kind: "ready",
51
+ });
52
+ vi.setSystemTime(Date.now() + 2000);
53
+ expect(await t.mutation(claim, accepted[1])).toMatchObject({
54
+ kind: "wait",
55
+ delayMs: 60000,
56
+ });
57
+ const rows = await t.run((ctx) => ctx.db.query("usageOutbox").take(2));
58
+ expect(rows.map((r) => r.attempts)).toEqual([1, 0]);
59
+ } finally {
60
+ vi.useRealTimers();
61
+ }
62
+ });
@@ -0,0 +1,59 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ export const reason = v.union(
4
+ v.literal("rate_limited"),
5
+ v.literal("provider_unavailable"),
6
+ v.literal("provider_outcome_unknown"),
7
+ v.literal("provider_rejected"),
8
+ v.literal("retry_exhausted"),
9
+ v.literal("delivery_window_expired"),
10
+ v.literal("scope_busy"),
11
+ v.literal("administrative_hold"),
12
+ );
13
+ export { usageDeliveryOutcomeValidator as outcome } from "../../client/usage/deliveryProtocol.js";
14
+ export const deliveryFields = {
15
+ provider: v.optional(v.string()),
16
+ workflowId: v.optional(v.string()),
17
+ definitionVersion: v.optional(v.literal(1)),
18
+ firstSendAt: v.optional(v.number()),
19
+ leaseUntil: v.optional(v.number()),
20
+ held: v.optional(v.boolean()),
21
+ reason: v.optional(reason),
22
+ receipt: v.optional(
23
+ v.object({ identifier: v.string(), created: v.number() }),
24
+ ),
25
+ };
26
+ export const locksTable = defineTable({
27
+ key: v.string(),
28
+ eventId: v.optional(v.id("usageEvents")),
29
+ leaseUntil: v.number(),
30
+ nextAttemptAt: v.number(),
31
+ }).index("by_key", ["key"]);
32
+
33
+ export const errorCode = v.union(
34
+ v.literal("meter_event_customer_not_found"),
35
+ v.literal("meter_event_no_customer_defined"),
36
+ v.literal("meter_event_dimension_count_too_high"),
37
+ v.literal("archived_meter"),
38
+ v.literal("timestamp_too_far_in_past"),
39
+ v.literal("timestamp_in_future"),
40
+ v.literal("meter_event_value_not_found"),
41
+ v.literal("meter_event_invalid_value"),
42
+ v.literal("no_meter"),
43
+ );
44
+ export const errorFields = {
45
+ scopeKey: v.string(),
46
+ eventId: v.id("usageEvents"),
47
+ providerEventId: v.string(),
48
+ code: errorCode,
49
+ observedAt: v.number(),
50
+ dedupe: v.string(),
51
+ };
52
+ export const errorDoc = v.object({
53
+ _id: v.id("usageDeliveryErrors"),
54
+ _creationTime: v.number(),
55
+ ...errorFields,
56
+ });
57
+ export const errorsTable = defineTable(errorFields)
58
+ .index("by_dedupe", ["dedupe"])
59
+ .index("by_event", ["eventId"]);
@@ -0,0 +1,77 @@
1
+ import type { QueryCtx } from "../_generated/server.js";
2
+ import type { Doc, Id } from "../_generated/dataModel.js";
3
+ import type {
4
+ UsageScope,
5
+ PreparedUsageRecord,
6
+ } from "../../client/usage/records.js";
7
+ import { scopeKey } from "../usage/helpers.js";
8
+ export async function read(
9
+ ctx: QueryCtx,
10
+ args: { scope: UsageScope; eventId: Id<"usageEvents"> },
11
+ ) {
12
+ const event = await ctx.db.get("usageEvents", args.eventId);
13
+ if (!event || event.scopeKey !== scopeKey(args.scope))
14
+ throw new Error("Usage delivery scope unavailable");
15
+ const outbox = await ctx.db
16
+ .query("usageOutbox")
17
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
18
+ .unique();
19
+ if (!outbox) throw new Error("Usage outbox unavailable");
20
+ return {
21
+ event,
22
+ outbox,
23
+ record: JSON.parse(event.recordJson) as PreparedUsageRecord,
24
+ };
25
+ }
26
+ export function statusOf(outbox: Doc<"usageOutbox">) {
27
+ return {
28
+ validationErrors: [] as Array<{
29
+ providerEventId: string;
30
+ code: import("convex/values").Infer<
31
+ typeof import("./fields.js").errorCode
32
+ >;
33
+ observedAt: number;
34
+ }>,
35
+ validationHistoryComplete: true,
36
+ eventId: outbox.eventId,
37
+ state: outbox.state,
38
+ attempts: outbox.attempts,
39
+ held: outbox.held ?? false,
40
+ reason: outbox.reason,
41
+ providerIdentifier: outbox.providerIdentifier,
42
+ receipt: outbox.receipt,
43
+ };
44
+ }
45
+ export function lockKeys(record: PreparedUsageRecord) {
46
+ const realm = JSON.stringify([
47
+ record.scope.stripeAccountId,
48
+ record.scope.livemode,
49
+ ]);
50
+ return {
51
+ realm,
52
+ customer: JSON.stringify([
53
+ realm,
54
+ record.binding.stripeCustomerId,
55
+ record.scope.meterId,
56
+ ]),
57
+ };
58
+ }
59
+
60
+ export async function currentStatus(ctx: QueryCtx, outbox: Doc<"usageOutbox">) {
61
+ const errors = await ctx.db
62
+ .query("usageDeliveryErrors")
63
+ .withIndex("by_event", (q) => q.eq("eventId", outbox.eventId))
64
+ .order("desc")
65
+ .take(21);
66
+ return {
67
+ ...statusOf(outbox),
68
+ validationErrors: errors
69
+ .slice(0, 20)
70
+ .map(({ providerEventId, code, observedAt }) => ({
71
+ providerEventId,
72
+ code,
73
+ observedAt,
74
+ })),
75
+ validationHistoryComplete: errors.length <= 20,
76
+ };
77
+ }