mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-11-29 00:39:27 +03:00
feat(payment): add Dub attribution state machine
This commit is contained in:
1 parent
f783652012
commit
44550e9edd
8 files changed
+959
No files matched your search
@@ -79,3 +79,13 @@ test('should be able to acquire lock parallel', async t => {
|
||||
'should be able to acquire lock parallel'
|
||||
);
|
||||
});
|
||||
|
||||
test('tryAcquire should only attempt to acquire the lock once', async t => {
|
||||
const { locker } = t.context;
|
||||
const lock = Sinon.stub(locker, 'lock').rejects(new Error('contended'));
|
||||
t.teardown(() => lock.restore());
|
||||
const mutex = new Mutex(locker);
|
||||
|
||||
t.is(await mutex.tryAcquire(`${lockerPrefix}4`), undefined);
|
||||
t.is(lock.callCount, 1);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import '../../plugins/payment/config';
|
||||
|
||||
import test from 'ava';
|
||||
|
||||
import { ConfigFactory } from '../../base';
|
||||
|
||||
test('Dub affiliate runtime config defaults are isolated between factories', t => {
|
||||
const first = new ConfigFactory();
|
||||
|
||||
t.false(first.config.payment.dubAffiliateEnabled);
|
||||
t.deepEqual(first.config.payment.dubAffiliateExcludedPromotionCodes, []);
|
||||
|
||||
first.config.payment.dubAffiliateExcludedPromotionCodes.push('legacy-code');
|
||||
|
||||
const second = new ConfigFactory();
|
||||
t.false(second.config.payment.dubAffiliateEnabled);
|
||||
t.deepEqual(second.config.payment.dubAffiliateExcludedPromotionCodes, []);
|
||||
});
|
||||
|
||||
test('Dub affiliate runtime config can be overridden without sharing state', t => {
|
||||
const first = new ConfigFactory({
|
||||
payment: {
|
||||
dubAffiliateEnabled: true,
|
||||
dubAffiliateExcludedPromotionCodes: ['legacy-code'],
|
||||
},
|
||||
});
|
||||
|
||||
t.true(first.config.payment.dubAffiliateEnabled);
|
||||
t.deepEqual(first.config.payment.dubAffiliateExcludedPromotionCodes, [
|
||||
'legacy-code',
|
||||
]);
|
||||
|
||||
const second = new ConfigFactory();
|
||||
t.false(second.config.payment.dubAffiliateEnabled);
|
||||
t.deepEqual(second.config.payment.dubAffiliateExcludedPromotionCodes, []);
|
||||
});
|
||||
@@ -0,0 +1,554 @@
|
||||
import test from 'ava';
|
||||
import Sinon from 'sinon';
|
||||
import Stripe from 'stripe';
|
||||
|
||||
import { Config, Lock, Mutex } from '../../base';
|
||||
import {
|
||||
type DubAffiliatePrepareInput,
|
||||
DubAffiliateService,
|
||||
} from '../../plugins/payment/dub-affiliate';
|
||||
|
||||
type StripeStubs = {
|
||||
customers: {
|
||||
retrieve: Sinon.SinonStub;
|
||||
update: Sinon.SinonStub;
|
||||
};
|
||||
subscriptions: { list: Sinon.SinonStub };
|
||||
invoices: { list: Sinon.SinonStub };
|
||||
charges: { list: Sinon.SinonStub };
|
||||
};
|
||||
|
||||
type Harness = {
|
||||
config: Config;
|
||||
stripe: StripeStubs;
|
||||
mutex: { tryAcquire: Sinon.SinonStub };
|
||||
service: DubAffiliateService;
|
||||
releases: () => number;
|
||||
};
|
||||
|
||||
const input: DubAffiliatePrepareInput = {
|
||||
stripeCustomerId: 'cus_test',
|
||||
affineUserId: 'user_test',
|
||||
dubClickId: 'click_123-ABC',
|
||||
plan: 'pro',
|
||||
};
|
||||
|
||||
const emptyList = <T>(data: readonly T[] = [], hasMore = false) => ({
|
||||
object: 'list' as const,
|
||||
data: [...data],
|
||||
has_more: hasMore,
|
||||
url: '/v1/test',
|
||||
});
|
||||
|
||||
function createHarness(options?: {
|
||||
enabled?: boolean;
|
||||
excludedPromotionCodes?: string[];
|
||||
customer?: Record<string, unknown>;
|
||||
subscriptions?: readonly unknown[];
|
||||
invoices?: readonly unknown[];
|
||||
charges?: readonly unknown[];
|
||||
chargesHasMore?: boolean;
|
||||
}): Harness {
|
||||
let releaseCount = 0;
|
||||
const stripe: StripeStubs = {
|
||||
customers: {
|
||||
retrieve: Sinon.stub().resolves(
|
||||
options?.customer ?? {
|
||||
id: input.stripeCustomerId,
|
||||
deleted: false,
|
||||
metadata: {},
|
||||
}
|
||||
),
|
||||
update: Sinon.stub().resolves({
|
||||
id: input.stripeCustomerId,
|
||||
deleted: false,
|
||||
metadata: {},
|
||||
}),
|
||||
},
|
||||
subscriptions: {
|
||||
list: Sinon.stub().resolves(emptyList(options?.subscriptions ?? [])),
|
||||
},
|
||||
invoices: {
|
||||
list: Sinon.stub().resolves(emptyList(options?.invoices ?? [])),
|
||||
},
|
||||
charges: {
|
||||
list: Sinon.stub().resolves(
|
||||
emptyList(options?.charges ?? [], options?.chargesHasMore)
|
||||
),
|
||||
},
|
||||
};
|
||||
const mutex = {
|
||||
tryAcquire: Sinon.stub().resolves(
|
||||
new Lock(async () => {
|
||||
releaseCount += 1;
|
||||
})
|
||||
),
|
||||
};
|
||||
const config = {
|
||||
payment: {
|
||||
dubAffiliateEnabled: options?.enabled ?? true,
|
||||
dubAffiliateExcludedPromotionCodes: options?.excludedPromotionCodes ?? [],
|
||||
},
|
||||
} as Config;
|
||||
|
||||
return {
|
||||
config,
|
||||
stripe,
|
||||
mutex,
|
||||
service: new DubAffiliateService(
|
||||
stripe as unknown as Stripe,
|
||||
config,
|
||||
mutex as unknown as Mutex
|
||||
),
|
||||
releases: () => releaseCount,
|
||||
};
|
||||
}
|
||||
|
||||
function totalStripeCalls(stripe: StripeStubs) {
|
||||
return (
|
||||
stripe.customers.retrieve.callCount +
|
||||
stripe.customers.update.callCount +
|
||||
stripe.subscriptions.list.callCount +
|
||||
stripe.invoices.list.callCount +
|
||||
stripe.charges.list.callCount
|
||||
);
|
||||
}
|
||||
|
||||
test.afterEach.always(() => {
|
||||
Sinon.restore();
|
||||
});
|
||||
|
||||
test('skips before locking or Stripe calls when disabled', async t => {
|
||||
const h = createHarness({ enabled: false });
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'disabled',
|
||||
});
|
||||
t.is(h.mutex.tryAcquire.callCount, 0);
|
||||
t.is(totalStripeCalls(h.stripe), 0);
|
||||
});
|
||||
|
||||
for (const [name, dubClickId, reason] of [
|
||||
['missing', undefined, 'missing'],
|
||||
['invalid', 'contains spaces', 'invalid'],
|
||||
['too long', 'a'.repeat(256), 'invalid'],
|
||||
] as const) {
|
||||
test(`skips ${name} click id before locking or Stripe calls`, async t => {
|
||||
const h = createHarness();
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout({ ...input, dubClickId }), {
|
||||
status: 'skipped',
|
||||
reason,
|
||||
});
|
||||
t.is(h.mutex.tryAcquire.callCount, 0);
|
||||
t.is(totalStripeCalls(h.stripe), 0);
|
||||
});
|
||||
}
|
||||
|
||||
test('skips normalized excluded promotion code before lock and Stripe', async t => {
|
||||
const h = createHarness({ excludedPromotionCodes: [' Legacy-Code '] });
|
||||
|
||||
t.deepEqual(
|
||||
await h.service.prepareCheckout({
|
||||
...input,
|
||||
promotionCode: ' LEGACY-code ',
|
||||
}),
|
||||
{ status: 'skipped', reason: 'legacy_promotion_code' }
|
||||
);
|
||||
t.is(h.mutex.tryAcquire.callCount, 0);
|
||||
t.is(totalStripeCalls(h.stripe), 0);
|
||||
});
|
||||
|
||||
test('attributes an eligible customer with bounded Stripe requests', async t => {
|
||||
const h = createHarness();
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'attributed',
|
||||
sessionMetadata: { dubCustomerExternalId: input.affineUserId },
|
||||
});
|
||||
|
||||
t.deepEqual(h.stripe.customers.retrieve.firstCall.args, [
|
||||
input.stripeCustomerId,
|
||||
{ timeout: 1000, maxNetworkRetries: 0 },
|
||||
]);
|
||||
t.deepEqual(h.stripe.subscriptions.list.firstCall.args, [
|
||||
{ customer: input.stripeCustomerId, status: 'all', limit: 1 },
|
||||
{ timeout: 1000, maxNetworkRetries: 0 },
|
||||
]);
|
||||
t.deepEqual(h.stripe.invoices.list.firstCall.args, [
|
||||
{ customer: input.stripeCustomerId, limit: 1 },
|
||||
{ timeout: 1000, maxNetworkRetries: 0 },
|
||||
]);
|
||||
t.deepEqual(h.stripe.charges.list.firstCall.args, [
|
||||
{ customer: input.stripeCustomerId, limit: 10 },
|
||||
{ timeout: 1000, maxNetworkRetries: 0 },
|
||||
]);
|
||||
t.deepEqual(
|
||||
h.stripe.customers.update.firstCall.args[0],
|
||||
input.stripeCustomerId
|
||||
);
|
||||
t.deepEqual(h.stripe.customers.update.firstCall.args[1], {
|
||||
metadata: {
|
||||
dubCustomerExternalId: input.affineUserId,
|
||||
dubClickId: input.dubClickId,
|
||||
},
|
||||
});
|
||||
t.deepEqual(h.stripe.customers.update.firstCall.args[2], {
|
||||
timeout: 1500,
|
||||
maxNetworkRetries: 0,
|
||||
idempotencyKey: h.stripe.customers.update.firstCall.args[2].idempotencyKey,
|
||||
});
|
||||
t.regex(
|
||||
h.stripe.customers.update.firstCall.args[2].idempotencyKey,
|
||||
/^dub-affiliate:v1:[a-f0-9]{64}$/
|
||||
);
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
|
||||
test('uses a hashed customer lock key without exposing identifiers', async t => {
|
||||
const h = createHarness();
|
||||
|
||||
await h.service.prepareCheckout(input);
|
||||
|
||||
const key = h.mutex.tryAcquire.firstCall.args[0] as string;
|
||||
t.regex(key, /^dub-affiliate:customer:[a-f0-9]{64}$/);
|
||||
t.false(key.includes(input.stripeCustomerId));
|
||||
t.false(key.includes(input.affineUserId));
|
||||
t.false(key.includes(input.dubClickId!));
|
||||
});
|
||||
|
||||
test('keeps an existing click for the matching owner', async t => {
|
||||
const h = createHarness({
|
||||
customer: {
|
||||
id: input.stripeCustomerId,
|
||||
deleted: false,
|
||||
metadata: {
|
||||
dubCustomerExternalId: input.affineUserId,
|
||||
dubClickId: 'first_click',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
t.deepEqual(
|
||||
await h.service.prepareCheckout({ ...input, dubClickId: 'second_click' }),
|
||||
{
|
||||
status: 'existing_owner',
|
||||
sessionMetadata: { dubCustomerExternalId: input.affineUserId },
|
||||
}
|
||||
);
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
|
||||
test('fails open on conflicting ownership without overwriting metadata', async t => {
|
||||
const h = createHarness({
|
||||
customer: {
|
||||
id: input.stripeCustomerId,
|
||||
deleted: false,
|
||||
metadata: {
|
||||
dubCustomerExternalId: 'different_user',
|
||||
dubClickId: 'first_click',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'conflict',
|
||||
});
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
|
||||
test('treats non-empty malformed ownership metadata as a conflict', async t => {
|
||||
const h = createHarness({
|
||||
customer: {
|
||||
id: input.stripeCustomerId,
|
||||
deleted: false,
|
||||
metadata: {
|
||||
dubCustomerExternalId: ` ${input.affineUserId} `,
|
||||
dubClickId: 'first_click',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'conflict',
|
||||
});
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
|
||||
test('fails open for an existing click with missing ownership metadata', async t => {
|
||||
const h = createHarness({
|
||||
customer: {
|
||||
id: input.stripeCustomerId,
|
||||
deleted: false,
|
||||
metadata: { dubClickId: 'first_click' },
|
||||
},
|
||||
});
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'incomplete_metadata',
|
||||
});
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
|
||||
for (const existingClickId of [' ', 'invalid click value']) {
|
||||
test(`does not overwrite existing malformed click metadata: ${JSON.stringify(existingClickId)}`, async t => {
|
||||
const h = createHarness({
|
||||
customer: {
|
||||
id: input.stripeCustomerId,
|
||||
deleted: false,
|
||||
metadata: { dubClickId: existingClickId },
|
||||
},
|
||||
});
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'incomplete_metadata',
|
||||
});
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
for (const [name, options] of [
|
||||
['subscription', { subscriptions: [{ id: 'sub_1' }] }],
|
||||
['invoice', { invoices: [{ id: 'in_1' }] }],
|
||||
['succeeded charge', { charges: [{ id: 'ch_1', status: 'succeeded' }] }],
|
||||
[
|
||||
'paid and refunded charge',
|
||||
{ charges: [{ id: 'ch_1', paid: true, refunded: true }] },
|
||||
],
|
||||
[
|
||||
'paid and uncaptured charge',
|
||||
{ charges: [{ id: 'ch_1', paid: true, captured: false }] },
|
||||
],
|
||||
] as const) {
|
||||
test(`rejects prior billing from ${name}`, async t => {
|
||||
const h = createHarness(options);
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'prior_billing',
|
||||
});
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
test('allows only failed or pending charges when history is complete', async t => {
|
||||
const h = createHarness({
|
||||
charges: [
|
||||
{ id: 'ch_failed', paid: false, status: 'failed' },
|
||||
{ id: 'ch_pending', paid: false, status: 'pending' },
|
||||
],
|
||||
});
|
||||
|
||||
t.is((await h.service.prepareCheckout(input)).status, 'attributed');
|
||||
t.is(h.stripe.customers.update.callCount, 1);
|
||||
});
|
||||
|
||||
test('fails closed when incomplete charge history has no visible success', async t => {
|
||||
const h = createHarness({
|
||||
charges: [{ id: 'ch_failed', paid: false, status: 'failed' }],
|
||||
chargesHasMore: true,
|
||||
});
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'ambiguous_charge_history',
|
||||
});
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
});
|
||||
|
||||
test('skips a deleted customer', async t => {
|
||||
const h = createHarness({
|
||||
customer: { id: input.stripeCustomerId, deleted: true },
|
||||
});
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'deleted_customer',
|
||||
});
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
|
||||
test('reuses known subscriptions without listing them again', async t => {
|
||||
const h = createHarness();
|
||||
|
||||
t.deepEqual(
|
||||
await h.service.prepareCheckout({ ...input, knownSubscriptions: [] }),
|
||||
{
|
||||
status: 'attributed',
|
||||
sessionMetadata: { dubCustomerExternalId: input.affineUserId },
|
||||
}
|
||||
);
|
||||
t.is(h.stripe.subscriptions.list.callCount, 0);
|
||||
t.is(h.stripe.customers.update.callCount, 1);
|
||||
});
|
||||
|
||||
test('known subscriptions still trigger prior billing without a list call', async t => {
|
||||
const h = createHarness();
|
||||
|
||||
t.deepEqual(
|
||||
await h.service.prepareCheckout({
|
||||
...input,
|
||||
knownSubscriptions: [{ id: 'sub_known' } as Stripe.Subscription],
|
||||
}),
|
||||
{ status: 'skipped', reason: 'prior_billing' }
|
||||
);
|
||||
t.is(h.stripe.subscriptions.list.callCount, 0);
|
||||
t.is(h.stripe.customers.update.callCount, 0);
|
||||
});
|
||||
|
||||
test('lock contention fails open without Stripe calls', async t => {
|
||||
const h = createHarness();
|
||||
h.mutex.tryAcquire.resolves(undefined);
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'lock_contention',
|
||||
});
|
||||
t.is(h.mutex.tryAcquire.callCount, 1);
|
||||
t.is(totalStripeCalls(h.stripe), 0);
|
||||
});
|
||||
|
||||
test('lock errors fail open without Stripe calls', async t => {
|
||||
const h = createHarness();
|
||||
h.mutex.tryAcquire.rejects(new Error('redis unavailable'));
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'stripe_error',
|
||||
});
|
||||
t.is(totalStripeCalls(h.stripe), 0);
|
||||
});
|
||||
|
||||
for (const operation of [
|
||||
'retrieve',
|
||||
'subscriptions',
|
||||
'invoices',
|
||||
'charges',
|
||||
'update',
|
||||
] as const) {
|
||||
test(`${operation} Stripe errors fail open and release the lock`, async t => {
|
||||
const h = createHarness();
|
||||
const stub =
|
||||
operation === 'retrieve'
|
||||
? h.stripe.customers.retrieve
|
||||
: operation === 'subscriptions'
|
||||
? h.stripe.subscriptions.list
|
||||
: operation === 'invoices'
|
||||
? h.stripe.invoices.list
|
||||
: operation === 'charges'
|
||||
? h.stripe.charges.list
|
||||
: h.stripe.customers.update;
|
||||
stub.rejects(new Error('stripe unavailable'));
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'stripe_error',
|
||||
});
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
test('Stripe timeouts fail open as ambiguous without an unhandled rejection', async t => {
|
||||
const h = createHarness();
|
||||
h.stripe.customers.update.rejects(
|
||||
Object.assign(new Error('Request timed out'), { code: 'ETIMEDOUT' })
|
||||
);
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'ambiguous_timeout',
|
||||
});
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
|
||||
test('read timeouts fail open as ordinary Stripe errors', async t => {
|
||||
const h = createHarness();
|
||||
h.stripe.customers.retrieve.rejects(
|
||||
Object.assign(new Error('Request timed out'), { code: 'ETIMEDOUT' })
|
||||
);
|
||||
|
||||
t.deepEqual(await h.service.prepareCheckout(input), {
|
||||
status: 'skipped',
|
||||
reason: 'stripe_error',
|
||||
});
|
||||
t.is(h.releases(), 1);
|
||||
});
|
||||
|
||||
test('uses a stable idempotency key for the same attribution input', async t => {
|
||||
const first = createHarness();
|
||||
const second = createHarness();
|
||||
|
||||
await first.service.prepareCheckout(input);
|
||||
await second.service.prepareCheckout(input);
|
||||
|
||||
t.is(
|
||||
first.stripe.customers.update.firstCall.args[2].idempotencyKey,
|
||||
second.stripe.customers.update.firstCall.args[2].idempotencyKey
|
||||
);
|
||||
});
|
||||
|
||||
test('concurrent clicks update at most once and do not overwrite the owner', async t => {
|
||||
let locked = false;
|
||||
let releaseFirstUpdate!: () => void;
|
||||
let signalFirstUpdate!: () => void;
|
||||
const firstUpdateStarted = new Promise<void>(resolve => {
|
||||
signalFirstUpdate = resolve;
|
||||
});
|
||||
const permitFirstUpdate = new Promise<void>(resolve => {
|
||||
releaseFirstUpdate = resolve;
|
||||
});
|
||||
const customer = {
|
||||
id: input.stripeCustomerId,
|
||||
deleted: false,
|
||||
metadata: {} as Record<string, string>,
|
||||
};
|
||||
const h = createHarness({ customer });
|
||||
h.mutex.tryAcquire.callsFake(async () => {
|
||||
if (locked) return undefined;
|
||||
locked = true;
|
||||
return new Lock(async () => {
|
||||
locked = false;
|
||||
});
|
||||
});
|
||||
h.stripe.customers.retrieve.callsFake(async () => ({
|
||||
...customer,
|
||||
metadata: { ...customer.metadata },
|
||||
}));
|
||||
h.stripe.customers.update.callsFake(async (_id, params) => {
|
||||
signalFirstUpdate();
|
||||
await permitFirstUpdate;
|
||||
customer.metadata = { ...params.metadata };
|
||||
return customer;
|
||||
});
|
||||
|
||||
const first = h.service.prepareCheckout({
|
||||
...input,
|
||||
dubClickId: 'click_one',
|
||||
});
|
||||
await firstUpdateStarted;
|
||||
const second = await h.service.prepareCheckout({
|
||||
...input,
|
||||
dubClickId: 'click_two',
|
||||
});
|
||||
releaseFirstUpdate();
|
||||
|
||||
t.deepEqual(second, { status: 'skipped', reason: 'lock_contention' });
|
||||
t.is((await first).status, 'attributed');
|
||||
t.is(h.stripe.customers.update.callCount, 1);
|
||||
t.deepEqual(customer.metadata, {
|
||||
dubCustomerExternalId: input.affineUserId,
|
||||
dubClickId: 'click_one',
|
||||
});
|
||||
});
|
||||
@@ -63,6 +63,7 @@ export type KnownMetricScopes =
|
||||
| 'storage'
|
||||
| 'process'
|
||||
| 'permission'
|
||||
| 'payment'
|
||||
| 'search'
|
||||
| 'workspace';
|
||||
|
||||
|
||||
@@ -19,6 +19,23 @@ export class Mutex {
|
||||
|
||||
constructor(protected readonly locker: Locker) {}
|
||||
|
||||
/**
|
||||
* Attempt to lock a resource once, without the retries used by {@link acquire}.
|
||||
*
|
||||
* This is intended for best-effort work that must not delay the caller when
|
||||
* another request already owns the lock.
|
||||
*/
|
||||
async tryAcquire(
|
||||
key: string,
|
||||
owner: string = `${this.clusterIdentifier}:${nanoid()}`
|
||||
) {
|
||||
try {
|
||||
return await this.locker.lock(owner, key);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* lock an resource and return a lock guard, which will release the lock when disposed
|
||||
*
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Stripe } from 'stripe';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { defineModuleConfig } from '../../base';
|
||||
|
||||
@@ -20,6 +21,8 @@ export interface PaymentStartupConfig {
|
||||
|
||||
export interface PaymentRuntimeConfig {
|
||||
showLifetimePrice: boolean;
|
||||
dubAffiliateEnabled: boolean;
|
||||
dubAffiliateExcludedPromotionCodes: string[];
|
||||
}
|
||||
|
||||
declare global {
|
||||
@@ -27,6 +30,8 @@ declare global {
|
||||
payment: {
|
||||
enabled: boolean;
|
||||
showLifetimePrice: boolean;
|
||||
dubAffiliateEnabled: boolean;
|
||||
dubAffiliateExcludedPromotionCodes: ConfigItem<string[]>;
|
||||
stripe: ConfigItem<
|
||||
{
|
||||
/** Preferred place for Stripe API key */
|
||||
@@ -62,6 +67,15 @@ defineModuleConfig('payment', {
|
||||
desc: 'Whether enable lifetime price and allow user to pay for it.',
|
||||
default: true,
|
||||
},
|
||||
dubAffiliateEnabled: {
|
||||
desc: 'Whether to attribute eligible Stripe customers to Dub affiliates.',
|
||||
default: false,
|
||||
},
|
||||
dubAffiliateExcludedPromotionCodes: {
|
||||
desc: 'Promotion codes that must not also receive Dub attribution.',
|
||||
default: [],
|
||||
shape: z.array(z.string()),
|
||||
},
|
||||
stripe: {
|
||||
desc: 'Stripe sdk options and credentials',
|
||||
default: {
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import Stripe from 'stripe';
|
||||
|
||||
import { Config, Lock, metrics, Mutex } from '../../base';
|
||||
|
||||
const DUB_CLICK_ID_PATTERN = /^[A-Za-z0-9_-]{1,255}$/;
|
||||
const STRIPE_READ_OPTIONS = {
|
||||
timeout: 1000,
|
||||
maxNetworkRetries: 0,
|
||||
} satisfies Stripe.RequestOptions;
|
||||
const STRIPE_UPDATE_OPTIONS = {
|
||||
timeout: 1500,
|
||||
maxNetworkRetries: 0,
|
||||
} satisfies Stripe.RequestOptions;
|
||||
|
||||
export type DubAffiliatePlan = 'pro' | 'ai' | 'team' | 'lifetime' | 'unknown';
|
||||
|
||||
export type DubAffiliateSkipReason =
|
||||
| 'disabled'
|
||||
| 'missing'
|
||||
| 'invalid'
|
||||
| 'legacy_promotion_code'
|
||||
| 'lock_contention'
|
||||
| 'deleted_customer'
|
||||
| 'conflict'
|
||||
| 'incomplete_metadata'
|
||||
| 'prior_billing'
|
||||
| 'ambiguous_charge_history'
|
||||
| 'stripe_error'
|
||||
| 'ambiguous_timeout';
|
||||
|
||||
export type DubAffiliatePrepareInput = {
|
||||
stripeCustomerId: string;
|
||||
affineUserId: string;
|
||||
dubClickId?: string;
|
||||
promotionCode?: string;
|
||||
knownSubscriptions?: readonly Stripe.Subscription[];
|
||||
plan?: DubAffiliatePlan;
|
||||
};
|
||||
|
||||
type DubSessionMetadata = {
|
||||
dubCustomerExternalId: string;
|
||||
};
|
||||
|
||||
export type DubAffiliatePrepareResult =
|
||||
| {
|
||||
status: 'attributed' | 'existing_owner';
|
||||
sessionMetadata: DubSessionMetadata;
|
||||
}
|
||||
| { status: 'skipped'; reason: DubAffiliateSkipReason };
|
||||
|
||||
type StripeOperation =
|
||||
| 'customer_retrieve'
|
||||
| 'subscriptions_list'
|
||||
| 'invoices_list'
|
||||
| 'charges_list'
|
||||
| 'customer_update';
|
||||
|
||||
class StripeOperationError extends Error {
|
||||
constructor(
|
||||
readonly operation: StripeOperation,
|
||||
readonly originalError: unknown
|
||||
) {
|
||||
super(`Dub affiliate Stripe operation failed: ${operation}`);
|
||||
}
|
||||
}
|
||||
|
||||
const prepareCounter = metrics.payment.counter('dub_affiliate_prepare_total');
|
||||
const prepareDuration = metrics.payment.histogram(
|
||||
'dub_affiliate_prepare_duration_ms'
|
||||
);
|
||||
const stripeErrorCounter = metrics.payment.counter(
|
||||
'dub_affiliate_stripe_error_total'
|
||||
);
|
||||
const lockContentionCounter = metrics.payment.counter(
|
||||
'dub_affiliate_lock_contention_total'
|
||||
);
|
||||
const lockErrorCounter = metrics.payment.counter(
|
||||
'dub_affiliate_lock_error_total'
|
||||
);
|
||||
|
||||
function hash(value: string) {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
function normalizePromotionCode(value: string) {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function isNonEmpty(value: string | undefined): value is string {
|
||||
return typeof value === 'string' && value.trim().length > 0;
|
||||
}
|
||||
|
||||
function isRawNonEmpty(value: string | undefined): value is string {
|
||||
return typeof value === 'string' && value.length > 0;
|
||||
}
|
||||
|
||||
function stringProperty(value: unknown, property: string) {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return '';
|
||||
}
|
||||
|
||||
const candidate = Reflect.get(value, property);
|
||||
return typeof candidate === 'string' ? candidate : '';
|
||||
}
|
||||
|
||||
function isAmbiguousTimeout(error: unknown) {
|
||||
const code = stringProperty(error, 'code').toUpperCase();
|
||||
const type = stringProperty(error, 'type');
|
||||
const message = stringProperty(error, 'message');
|
||||
|
||||
return (
|
||||
['ETIMEDOUT', 'ESOCKETTIMEDOUT', 'ECONNRESET', 'EPIPE'].includes(code) ||
|
||||
type === 'StripeConnectionError' ||
|
||||
/timed?\s*out|timeout/i.test(message)
|
||||
);
|
||||
}
|
||||
|
||||
function outcome(result: DubAffiliatePrepareResult) {
|
||||
return result.status === 'skipped' ? result.reason : result.status;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class DubAffiliateService {
|
||||
constructor(
|
||||
private readonly stripe: Stripe,
|
||||
private readonly config: Config,
|
||||
private readonly mutex: Mutex
|
||||
) {}
|
||||
|
||||
async prepareCheckout(
|
||||
input: DubAffiliatePrepareInput
|
||||
): Promise<DubAffiliatePrepareResult> {
|
||||
const startedAt = performance.now();
|
||||
const plan = input.plan ?? 'unknown';
|
||||
const finish = (result: DubAffiliatePrepareResult) => {
|
||||
const attributes = { outcome: outcome(result), plan };
|
||||
prepareCounter.add(1, attributes);
|
||||
prepareDuration.record(performance.now() - startedAt, attributes);
|
||||
return result;
|
||||
};
|
||||
|
||||
if (!this.config.payment.dubAffiliateEnabled) {
|
||||
return finish({ status: 'skipped', reason: 'disabled' });
|
||||
}
|
||||
|
||||
if (!input.dubClickId) {
|
||||
return finish({ status: 'skipped', reason: 'missing' });
|
||||
}
|
||||
|
||||
const dubClickId = input.dubClickId.trim();
|
||||
if (!DUB_CLICK_ID_PATTERN.test(dubClickId)) {
|
||||
return finish({ status: 'skipped', reason: 'invalid' });
|
||||
}
|
||||
|
||||
const promotionCode = input.promotionCode
|
||||
? normalizePromotionCode(input.promotionCode)
|
||||
: undefined;
|
||||
const excludedPromotionCodes = new Set(
|
||||
this.config.payment.dubAffiliateExcludedPromotionCodes
|
||||
.map(normalizePromotionCode)
|
||||
.filter(Boolean)
|
||||
);
|
||||
if (promotionCode && excludedPromotionCodes.has(promotionCode)) {
|
||||
return finish({ status: 'skipped', reason: 'legacy_promotion_code' });
|
||||
}
|
||||
|
||||
let lock: Lock | undefined;
|
||||
try {
|
||||
lock = await this.mutex.tryAcquire(
|
||||
`dub-affiliate:customer:${hash(input.stripeCustomerId)}`
|
||||
);
|
||||
} catch {
|
||||
lockErrorCounter.add(1, { operation: 'acquire' });
|
||||
return finish({ status: 'skipped', reason: 'stripe_error' });
|
||||
}
|
||||
|
||||
if (!lock) {
|
||||
lockContentionCounter.add(1);
|
||||
return finish({ status: 'skipped', reason: 'lock_contention' });
|
||||
}
|
||||
|
||||
try {
|
||||
const subscriptionsPromise = input.knownSubscriptions
|
||||
? Promise.resolve({ data: input.knownSubscriptions })
|
||||
: this.stripeCall('subscriptions_list', () =>
|
||||
this.stripe.subscriptions.list(
|
||||
{
|
||||
customer: input.stripeCustomerId,
|
||||
status: 'all',
|
||||
limit: 1,
|
||||
},
|
||||
STRIPE_READ_OPTIONS
|
||||
)
|
||||
);
|
||||
|
||||
const [customer, subscriptions, invoices, charges] = await Promise.all([
|
||||
this.stripeCall('customer_retrieve', () =>
|
||||
this.stripe.customers.retrieve(
|
||||
input.stripeCustomerId,
|
||||
STRIPE_READ_OPTIONS
|
||||
)
|
||||
),
|
||||
subscriptionsPromise,
|
||||
this.stripeCall('invoices_list', () =>
|
||||
this.stripe.invoices.list(
|
||||
{ customer: input.stripeCustomerId, limit: 1 },
|
||||
STRIPE_READ_OPTIONS
|
||||
)
|
||||
),
|
||||
this.stripeCall('charges_list', () =>
|
||||
this.stripe.charges.list(
|
||||
{ customer: input.stripeCustomerId, limit: 10 },
|
||||
STRIPE_READ_OPTIONS
|
||||
)
|
||||
),
|
||||
]);
|
||||
|
||||
if (customer.deleted) {
|
||||
return finish({ status: 'skipped', reason: 'deleted_customer' });
|
||||
}
|
||||
|
||||
const existingExternalId = customer.metadata.dubCustomerExternalId;
|
||||
const existingClickId = customer.metadata.dubClickId;
|
||||
|
||||
if (
|
||||
isNonEmpty(existingExternalId) &&
|
||||
existingExternalId !== input.affineUserId
|
||||
) {
|
||||
return finish({ status: 'skipped', reason: 'conflict' });
|
||||
}
|
||||
|
||||
if (isRawNonEmpty(existingClickId)) {
|
||||
if (isNonEmpty(existingExternalId)) {
|
||||
return finish({
|
||||
status: 'existing_owner',
|
||||
sessionMetadata: {
|
||||
dubCustomerExternalId: input.affineUserId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return finish({ status: 'skipped', reason: 'incomplete_metadata' });
|
||||
}
|
||||
|
||||
const hasSuccessfulCharge = charges.data.some(
|
||||
charge => charge.paid === true || charge.status === 'succeeded'
|
||||
);
|
||||
if (
|
||||
subscriptions.data.length > 0 ||
|
||||
invoices.data.length > 0 ||
|
||||
hasSuccessfulCharge
|
||||
) {
|
||||
return finish({ status: 'skipped', reason: 'prior_billing' });
|
||||
}
|
||||
|
||||
if (charges.has_more) {
|
||||
return finish({
|
||||
status: 'skipped',
|
||||
reason: 'ambiguous_charge_history',
|
||||
});
|
||||
}
|
||||
|
||||
await this.stripeCall('customer_update', () =>
|
||||
this.stripe.customers.update(
|
||||
input.stripeCustomerId,
|
||||
{
|
||||
metadata: {
|
||||
dubCustomerExternalId: input.affineUserId,
|
||||
dubClickId,
|
||||
},
|
||||
},
|
||||
{
|
||||
...STRIPE_UPDATE_OPTIONS,
|
||||
idempotencyKey: `dub-affiliate:v1:${hash(
|
||||
[input.stripeCustomerId, input.affineUserId, dubClickId].join(
|
||||
'\0'
|
||||
)
|
||||
)}`,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
return finish({
|
||||
status: 'attributed',
|
||||
sessionMetadata: { dubCustomerExternalId: input.affineUserId },
|
||||
});
|
||||
} catch (error) {
|
||||
const stripeError =
|
||||
error instanceof StripeOperationError ? error : undefined;
|
||||
const originalError = stripeError?.originalError ?? error;
|
||||
const reason =
|
||||
stripeError?.operation === 'customer_update' &&
|
||||
isAmbiguousTimeout(originalError)
|
||||
? 'ambiguous_timeout'
|
||||
: 'stripe_error';
|
||||
stripeErrorCounter.add(1, {
|
||||
error: reason,
|
||||
operation: stripeError?.operation ?? 'unknown',
|
||||
});
|
||||
return finish({ status: 'skipped', reason });
|
||||
} finally {
|
||||
try {
|
||||
await lock.release();
|
||||
} catch {
|
||||
// The production Lock currently swallows release failures. Keep this
|
||||
// boundary fail-open for alternate implementations and test doubles.
|
||||
lockErrorCounter.add(1, { operation: 'release' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async stripeCall<T>(
|
||||
operation: StripeOperation,
|
||||
call: () => PromiseLike<T>
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await call();
|
||||
} catch (error) {
|
||||
throw new StripeOperationError(operation, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { UserModule } from '../../core/user';
|
||||
import { WorkspaceModule } from '../../core/workspaces';
|
||||
import { StripeWebhookController } from './controller';
|
||||
import { SubscriptionCronJobs } from './cron';
|
||||
import { DubAffiliateService } from './dub-affiliate';
|
||||
import { PaymentEventHandlers } from './event';
|
||||
import { LicenseController } from './license/controller';
|
||||
import {
|
||||
@@ -59,6 +60,7 @@ import { StripeWebhook } from './webhook';
|
||||
SubscriptionCronJobs,
|
||||
WorkspaceSubscriptionResolver,
|
||||
PaymentEventHandlers,
|
||||
DubAffiliateService,
|
||||
],
|
||||
controllers: [
|
||||
StripeWebhookController,
|
||||
|
||||
Reference in new issue
Block a user