LCOV - code coverage report
Current view: top level - packages/account-core/src/core/billing - capabilities.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 18.8 % 32 6
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : /**
       2              :  * The capabilities read: a server-authoritative answer to "what may this actor
       3              :  * be offered for this workspace", cached per scope.
       4              :  *
       5              :  * The SDK never derives a capability. It decodes what the server resolved and
       6              :  * caches it under the scope it was resolved for, so no entitlement rule is
       7              :  * reimplemented here and none can drift from the backend's.
       8              :  *
       9              :  * Freshness is pull-based on purpose: a snapshot carries the instant it stops
      10              :  * being fresh, and a caller learns it is stale by asking. The production
      11              :  * composable's timer, its visibility gating, and its retry backoff are all
      12              :  * push concerns that need a document and a scheduler, so they belong to the
      13              :  * view package that has both — not to a framework-free core.
      14              :  */
      15              : import {
      16              :   zAutoTopUpMemberView,
      17              :   zBillingCapabilities,
      18              :   zBillingCapabilitiesResponse,
      19              :   zBillingCapabilityRolloutDefaults,
      20              :   zBillingCapabilityScope
      21              : } from '@comfyorg/ingest-types/zod'
      22              : import { z } from 'zod'
      23              : 
      24              : import type { BillingResult, BillingTransport } from './billingContracts'
      25              : import type { BillingScope, BillingScopeSource } from './billingScope'
      26              : import { sameBillingScope } from './billingScope'
      27              : import type { CapabilityDenials } from './capabilityDenials'
      28              : import { decodeCapabilityDenials } from './capabilityDenials'
      29              : import { createScopedReader } from './scopedReader'
      30              : import type { ValidatedBillingResponse } from './sharedRead'
      31              : import { wireCents } from './wireCents'
      32              : 
      33         2356 : export const CAPABILITIES_ROUTE = '/billing/capabilities'
      34              : 
      35              : /** Production's own budget for this read (`workspaceApi.getBillingCapabilities`). */
      36         2356 : const CAPABILITIES_TIMEOUT_MS = 10_000
      37              : 
      38              : /**
      39              :  * A remaining lifetime below the floor means the client clock disagrees with
      40              :  * the server's, so `expires_at` cannot pace anything and the fixed interval is
      41              :  * used instead. The ceiling bounds the opposite skew, where a lagging clock
      42              :  * reads `expires_at` as far in the future. Both bounds, and the fallback, are
      43              :  * the production composable's.
      44              :  */
      45         2356 : const MIN_FRESH_MS = 5_000
      46         2356 : const MAX_FRESH_MS = 60 * 60 * 1000
      47         2356 : const FALLBACK_FRESH_MS = 60_000
      48              : 
      49              : export const CAPABILITY_REVISION_HEADER = 'X-Capability-Revision'
      50              : 
      51              : export type BillingCapabilities = z.infer<typeof zBillingCapabilities>
      52              : export type CapabilityRolloutDefaults = z.infer<
      53              :   typeof zBillingCapabilityRolloutDefaults
      54              : >
      55              : 
      56              : /**
      57              :  * The generated contract minus `denied_reasons`, which is decoded separately
      58              :  * and leniently. `revision` is read as a number rather than the generated
      59              :  * bigint: the server bounds it to the JavaScript-safe range precisely so
      60              :  * clients can compare it as one.
      61              :  */
      62         2356 : const CapabilitiesBodySchema = z.object({
      63              :   auto_top_up_enabled:
      64              :     zBillingCapabilitiesResponse.shape.auto_top_up_enabled.optional(),
      65              :   auto_top_up_member_view: zAutoTopUpMemberView
      66              :     .extend({
      67              :       target_credits: wireCents.nullable(),
      68              :       threshold_credits: wireCents.nullable()
      69              :     })
      70              :     .optional()
      71              :     .catch(undefined),
      72              :   auto_top_up_setup: zBillingCapabilitiesResponse.shape.auto_top_up_setup,
      73              :   billing_notice_audience:
      74              :     zBillingCapabilitiesResponse.shape.billing_notice_audience,
      75              :   billing_web_checkout_ui:
      76              :     zBillingCapabilitiesResponse.shape.billing_web_checkout_ui
      77              :       .optional()
      78              :       .catch(undefined),
      79              :   cancel_takes_effect_immediately:
      80              :     zBillingCapabilitiesResponse.shape.cancel_takes_effect_immediately,
      81              :   capabilities: zBillingCapabilities,
      82              :   ending_notice_starts_at:
      83              :     zBillingCapabilitiesResponse.shape.ending_notice_starts_at,
      84              :   expires_at: z.string(),
      85              :   has_parked_billing_operation:
      86              :     zBillingCapabilitiesResponse.shape.has_parked_billing_operation,
      87              :   payment_recovery_available:
      88              :     zBillingCapabilitiesResponse.shape.payment_recovery_available,
      89              :   plan_kind: zBillingCapabilitiesResponse.shape.plan_kind,
      90              :   resolved_for: zBillingCapabilityScope,
      91              :   revision: z.number(),
      92              :   rollout_defaults_applied: zBillingCapabilityRolloutDefaults
      93              : })
      94              : 
      95              : type CapabilitiesBody = z.infer<typeof CapabilitiesBodySchema>
      96              : 
      97              : export type CapabilityScope = BillingScope
      98              : 
      99              : export interface CapabilitiesSnapshot {
     100              :   readonly capabilities: BillingCapabilities
     101              :   /**
     102              :    * Present only for a capability the server refused and explained. An absent
     103              :    * key never implies the capability was granted — read `capabilities`.
     104              :    */
     105              :   readonly denials: CapabilityDenials
     106              :   /**
     107              :    * As received. Absent when the server omits it: unknown, not a refusal.
     108              :    */
     109              :   readonly autoTopUpEnabled?: boolean
     110              :   /** As received. Absent when the server omits or hides it. */
     111              :   readonly autoTopUpMemberView?: CapabilitiesBody['auto_top_up_member_view']
     112              :   readonly autoTopUpSetup?: z.infer<
     113              :     typeof zBillingCapabilitiesResponse.shape.auto_top_up_setup
     114              :   >
     115              :   readonly billingNoticeAudience?: CapabilitiesBody['billing_notice_audience']
     116              :   /** As received. Absent when the server omits it or sends an unknown variant. */
     117              :   readonly billingWebCheckoutUi?: CapabilitiesBody['billing_web_checkout_ui']
     118              :   /** As received. Absent when the server omits it: unknown, never false. */
     119              :   readonly cancelTakesEffectImmediately?: boolean
     120              :   readonly endingNoticeStartsAt?: string
     121              :   readonly hasParkedBillingOperation?: boolean
     122              :   readonly paymentRecoveryAvailable?: boolean
     123              :   readonly planKind?: z.infer<
     124              :     typeof zBillingCapabilitiesResponse.shape.plan_kind
     125              :   >
     126              :   /** True values are rollout guidance, not evidence a write will succeed. */
     127              :   readonly rolloutDefaultsApplied: CapabilityRolloutDefaults
     128              :   readonly revision: number
     129              :   readonly scope: CapabilityScope
     130              :   /** ms since epoch, after which `read` refetches rather than serving this. */
     131              :   readonly freshUntil: number
     132              : }
     133              : 
     134              : export interface CapabilitiesReadOptions {
     135              :   readonly signal?: AbortSignal
     136              :   /** Bypasses a fresh cached snapshot; still joins an in-flight read. */
     137              :   readonly forceRefresh?: boolean
     138              : }
     139              : 
     140              : export interface CapabilitiesReader {
     141              :   read: (
     142              :     options?: CapabilitiesReadOptions
     143              :   ) => Promise<BillingResult<CapabilitiesSnapshot>>
     144              :   /** The cached snapshot for the current scope, fresh or not. */
     145              :   getSnapshot: () => CapabilitiesSnapshot | undefined
     146              :   /**
     147              :    * Marks the cache stale for a revision a **mutation** reported. A read's own
     148              :    * revision must never be fed back here: the capabilities response echoes the
     149              :    * header it was built with, so republishing it would mark that read stale and
     150              :    * refetch forever.
     151              :    */
     152              :   invalidate: (revision?: number) => void
     153              :   /** Detaches the scope subscription. */
     154              :   dispose: () => void
     155              : }
     156              : 
     157              : export interface CapabilitiesReaderOptions {
     158              :   readonly transport: BillingTransport
     159              :   /** Where the core learns which user, workspace, and role it runs as. */
     160              :   readonly scopeSource: BillingScopeSource
     161              :   readonly now?: () => number
     162              : }
     163              : 
     164              : /**
     165              :  * Reads the revision a mutation reported. Absent whenever CORS is bypassed
     166              :  * (local desktop origins), so a missing header is "nothing reported" rather
     167              :  * than a reason to invalidate.
     168              :  */
     169              : export function readCapabilityRevision(
     170              :   header: (name: string) => string | null
     171              : ): number | undefined {
     172              :   const raw = header(CAPABILITY_REVISION_HEADER)
     173              :   if (raw === null) return undefined
     174              :   const revision = Number(raw)
     175              :   return Number.isSafeInteger(revision) && revision > 0 ? revision : undefined
     176              : }
     177              : 
     178            0 : function freshUntilFrom(expiresAt: string, now: number): number {
     179              :   // Date.parse yields NaN on an unparseable value; NaN fails the comparison
     180              :   // and lands on the fixed interval, which is the intended branch.
     181            0 :   const remaining = Date.parse(expiresAt) - now
     182            0 :   if (remaining >= MIN_FRESH_MS) {
     183            0 :     return now + Math.min(remaining, MAX_FRESH_MS)
     184              :   }
     185            0 :   return now + FALLBACK_FRESH_MS
     186              : }
     187              : 
     188            0 : function freshSnapshot(
     189              :   snapshot: CapabilitiesSnapshot | undefined,
     190              :   scope: CapabilityScope,
     191              :   forceRefresh: boolean,
     192              :   now: number
     193              : ): CapabilitiesSnapshot | undefined {
     194            0 :   if (forceRefresh || snapshot === undefined) return undefined
     195            0 :   if (!sameBillingScope(snapshot.scope, scope)) return undefined
     196            0 :   return snapshot.freshUntil > now ? snapshot : undefined
     197              : }
     198              : 
     199            0 : function snapshotAfterInvalidation(
     200              :   snapshot: CapabilitiesSnapshot,
     201              :   invalidated: boolean
     202              : ): CapabilitiesSnapshot {
     203            0 :   return invalidated ? { ...snapshot, freshUntil: 0 } : snapshot
     204              : }
     205              : 
     206            0 : export function createCapabilitiesReader(
     207              :   options: CapabilitiesReaderOptions
     208              : ): CapabilitiesReader {
     209            0 :   const { transport, scopeSource, now = Date.now } = options
     210              : 
     211            0 :   function projectCapabilities(
     212              :     response: ValidatedBillingResponse<CapabilitiesBody>,
     213              :     scope: CapabilityScope
     214              :   ): BillingResult<CapabilitiesSnapshot> {
     215            0 :     const { data, body, httpStatus } = response
     216              : 
     217            0 :     if (data.resolved_for.workspace_id !== scope.workspaceId) {
     218            0 :       return { status: 'error', code: 'REQUEST_FAILED', httpStatus }
     219              :     }
     220              : 
     221            0 :     const denials = decodeCapabilityDenials(
     222              :       (body as { denied_reasons?: unknown }).denied_reasons
     223              :     )
     224              : 
     225            0 :     return {
     226              :       status: 'ok',
     227              :       value: {
     228              :         autoTopUpEnabled: data.auto_top_up_enabled,
     229              :         autoTopUpMemberView: data.auto_top_up_member_view,
     230              :         autoTopUpSetup: data.auto_top_up_setup,
     231              :         billingNoticeAudience: data.billing_notice_audience,
     232              :         billingWebCheckoutUi: data.billing_web_checkout_ui,
     233              :         cancelTakesEffectImmediately: data.cancel_takes_effect_immediately,
     234              :         capabilities: data.capabilities,
     235              :         denials,
     236              :         endingNoticeStartsAt: data.ending_notice_starts_at,
     237              :         hasParkedBillingOperation: data.has_parked_billing_operation,
     238              :         paymentRecoveryAvailable: data.payment_recovery_available,
     239              :         planKind: data.plan_kind,
     240              :         rolloutDefaultsApplied: data.rollout_defaults_applied,
     241              :         revision: data.revision,
     242              :         scope,
     243              :         freshUntil: freshUntilFrom(data.expires_at, now())
     244              :       }
     245              :     }
     246              :   }
     247              : 
     248            0 :   const reader = createScopedReader<
     249              :     CapabilitiesBody,
     250              :     CapabilitiesSnapshot,
     251              :     CapabilitiesReadOptions
     252              :   >({
     253              :     transport,
     254              :     scopeSource,
     255              :     route: CAPABILITIES_ROUTE,
     256              :     parse: (body) => CapabilitiesBodySchema.safeParse(body),
     257              :     timeoutMs: () => CAPABILITIES_TIMEOUT_MS,
     258              :     cached: (snapshot, scope, readOptions) =>
     259              :       freshSnapshot(snapshot, scope, readOptions?.forceRefresh === true, now()),
     260              :     project: projectCapabilities,
     261              :     // A mutation committed while this read was in flight, and the revision the
     262              :     // read returns cannot rule out having missed it: the server mints that
     263              :     // number when it serializes, not when it read. The value is still the best
     264              :     // available, so it is published — as already stale, so the next read
     265              :     // refetches instead of serving it.
     266              :     publish: snapshotAfterInvalidation
     267              :   })
     268              : 
     269            0 :   return {
     270              :     read: reader.read,
     271              :     getSnapshot: reader.getSnapshot,
     272              :     invalidate: (revision?: number) => {
     273            0 :       reader.fenceInFlight()
     274            0 :       const snapshot = reader.getSnapshot()
     275            0 :       if (snapshot === undefined) return
     276            0 :       if (revision !== undefined && snapshot.revision === revision) return
     277            0 :       reader.setSnapshot({ ...snapshot, freshUntil: 0 })
     278              :     },
     279              :     dispose: reader.dispose
     280              :   }
     281              : }
        

Generated by: LCOV version 2.0-1