|
| 1 | +import { uuidv7 } from 'uuidv7'; |
| 2 | + |
| 3 | +import { Err, Ok, flagHasUsage, networkError, report, retryFlexible } from '@nangohq/utils'; |
| 4 | + |
| 5 | +import type { BillingClient, BillingIngestEvent, BillingMetric } from './types.js'; |
| 6 | +import type { Result } from '@nangohq/utils'; |
| 7 | + |
| 8 | +export class Billing { |
| 9 | + constructor(private client: BillingClient) { |
| 10 | + this.client = client; |
| 11 | + } |
| 12 | + |
| 13 | + async send(type: BillingMetric['type'], value: number, props: BillingMetric['properties']): Promise<Result<void>> { |
| 14 | + return this.sendAll([{ type, value, properties: props }]); |
| 15 | + } |
| 16 | + |
| 17 | + async sendAll(events: BillingMetric[]): Promise<Result<void>> { |
| 18 | + const mapped = events.flatMap((event) => { |
| 19 | + if (event.value === 0) { |
| 20 | + return []; |
| 21 | + } |
| 22 | + |
| 23 | + return [ |
| 24 | + { |
| 25 | + type: event.type, |
| 26 | + accountId: event.properties.accountId, |
| 27 | + idempotencyKey: event.properties.idempotencyKey || uuidv7(), |
| 28 | + timestamp: event.properties.timestamp || new Date(), |
| 29 | + properties: { |
| 30 | + count: event.value |
| 31 | + } |
| 32 | + } |
| 33 | + ]; |
| 34 | + }); |
| 35 | + |
| 36 | + return this.ingest(mapped); |
| 37 | + } |
| 38 | + |
| 39 | + // Note: Events are sent immediately |
| 40 | + private async ingest(events: BillingIngestEvent[]): Promise<Result<void>> { |
| 41 | + if (!flagHasUsage) { |
| 42 | + return Ok(undefined); |
| 43 | + } |
| 44 | + |
| 45 | + try { |
| 46 | + await retryFlexible( |
| 47 | + async () => { |
| 48 | + await this.client.ingest(events); |
| 49 | + }, |
| 50 | + { |
| 51 | + max: 3, |
| 52 | + onError: ({ err }) => { |
| 53 | + if ( |
| 54 | + err instanceof TypeError && |
| 55 | + err.cause && |
| 56 | + typeof err.cause === 'object' && |
| 57 | + 'code' in err.cause && |
| 58 | + networkError.includes(err.cause.code as string) |
| 59 | + ) { |
| 60 | + return { retry: true, reason: 'maybe_unreachable' }; |
| 61 | + } |
| 62 | + if (err instanceof Response && err.status >= 500) { |
| 63 | + return { retry: true, reason: 'status_code' }; |
| 64 | + } |
| 65 | + return { retry: false, reason: 'unknown' }; |
| 66 | + } |
| 67 | + } |
| 68 | + ); |
| 69 | + return Ok(undefined); |
| 70 | + } catch (err: unknown) { |
| 71 | + const e = new Error(`Failed to send billing event`, { cause: err }); |
| 72 | + report(e); |
| 73 | + return Err(e); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments