@antelopejs/payment-subscriptions 0.0.0-stage → 0.0.1
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/LICENSE +190 -0
- package/README.md +102 -2
- package/dist/calendar.d.ts +2 -0
- package/dist/calendar.js +33 -0
- package/dist/calendar.js.map +1 -0
- package/dist/clock.d.ts +7 -0
- package/dist/clock.js +18 -0
- package/dist/clock.js.map +1 -0
- package/dist/config.d.ts +13 -0
- package/dist/config.js +28 -0
- package/dist/config.js.map +1 -0
- package/dist/engine.d.ts +38 -0
- package/dist/engine.js +250 -0
- package/dist/engine.js.map +1 -0
- package/dist/events.d.ts +6 -0
- package/dist/events.js +47 -0
- package/dist/events.js.map +1 -0
- package/dist/implementation.d.ts +19 -0
- package/dist/implementation.js +233 -0
- package/dist/implementation.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +75 -0
- package/dist/index.js.map +1 -0
- package/dist/initial.d.ts +11 -0
- package/dist/initial.js +86 -0
- package/dist/initial.js.map +1 -0
- package/dist/records.d.ts +60 -0
- package/dist/records.js +68 -0
- package/dist/records.js.map +1 -0
- package/dist/runtime.d.ts +10 -0
- package/dist/runtime.js +14 -0
- package/dist/runtime.js.map +1 -0
- package/dist/schedule.d.ts +15 -0
- package/dist/schedule.js +35 -0
- package/dist/schedule.js.map +1 -0
- package/dist/transitions.d.ts +25 -0
- package/dist/transitions.js +197 -0
- package/dist/transitions.js.map +1 -0
- package/dist/triggers.d.ts +10 -0
- package/dist/triggers.js +129 -0
- package/dist/triggers.js.map +1 -0
- package/dist/view.d.ts +3 -0
- package/dist/view.js +34 -0
- package/dist/view.js.map +1 -0
- package/docs/1.introduction.md +61 -0
- package/docs/2.renewal-clock.md +95 -0
- package/docs/3.failed-renewals.md +126 -0
- package/docs/4.provider-schedule.md +31 -0
- package/package.json +85 -4
- package/skills/payment-subscriptions/SKILL.md +73 -0
package/dist/triggers.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.ChooseTrigger = ChooseTrigger;
|
|
37
|
+
const logging_1 = require("@antelopejs/interface-core/logging");
|
|
38
|
+
const interface_core_1 = require("@antelopejs/interface-core");
|
|
39
|
+
const clock_1 = require("./clock");
|
|
40
|
+
const REDIS_INTERFACE = "@antelopejs/interface-redis";
|
|
41
|
+
const SCHEDULER_INTERFACE = "@antelopejs/interface-redis-scheduler";
|
|
42
|
+
const HANDLER_NAME = "payment-subscriptions";
|
|
43
|
+
const LISTENER_STOP_TIMEOUT_MS = 2_000;
|
|
44
|
+
class Sweeper {
|
|
45
|
+
engine;
|
|
46
|
+
intervalMs;
|
|
47
|
+
timer;
|
|
48
|
+
running;
|
|
49
|
+
constructor(engine, intervalMs) {
|
|
50
|
+
this.engine = engine;
|
|
51
|
+
this.intervalMs = intervalMs;
|
|
52
|
+
}
|
|
53
|
+
start() {
|
|
54
|
+
this.tick();
|
|
55
|
+
this.timer = setInterval(() => this.tick(), this.intervalMs);
|
|
56
|
+
this.timer.unref();
|
|
57
|
+
}
|
|
58
|
+
async stop() {
|
|
59
|
+
clearInterval(this.timer);
|
|
60
|
+
this.timer = undefined;
|
|
61
|
+
await this.running;
|
|
62
|
+
}
|
|
63
|
+
tick() {
|
|
64
|
+
if (this.running)
|
|
65
|
+
return;
|
|
66
|
+
this.running = this.engine
|
|
67
|
+
.sweep()
|
|
68
|
+
.catch((error) => logging_1.Logging.Error("payment-subscriptions: sweep failed", error))
|
|
69
|
+
.finally(() => {
|
|
70
|
+
this.running = undefined;
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function pollingTrigger(engine, settings) {
|
|
75
|
+
const sweeper = new Sweeper(engine, settings.pollIntervalMs);
|
|
76
|
+
return {
|
|
77
|
+
kind: "polling",
|
|
78
|
+
start: () => sweeper.start(),
|
|
79
|
+
stop: () => sweeper.stop(),
|
|
80
|
+
schedule: () => undefined,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function report(action) {
|
|
84
|
+
return (error) => logging_1.Logging.Warn(`payment-subscriptions: Redis scheduler ${action} failed`, error);
|
|
85
|
+
}
|
|
86
|
+
function withTimeout(work, ms) {
|
|
87
|
+
return Promise.race([
|
|
88
|
+
work,
|
|
89
|
+
new Promise((resolve) => setTimeout(resolve, ms).unref()),
|
|
90
|
+
]);
|
|
91
|
+
}
|
|
92
|
+
function RedisTrigger(engine, settings, scheduler) {
|
|
93
|
+
const sweeper = new Sweeper(engine, settings.sweepIntervalMs);
|
|
94
|
+
return {
|
|
95
|
+
kind: "redis",
|
|
96
|
+
start: () => {
|
|
97
|
+
scheduler.enableListener().catch(report("listener"));
|
|
98
|
+
sweeper.start();
|
|
99
|
+
},
|
|
100
|
+
stop: async () => {
|
|
101
|
+
await sweeper.stop();
|
|
102
|
+
await withTimeout(scheduler.disableListener().catch(report("shutdown")), LISTENER_STOP_TIMEOUT_MS);
|
|
103
|
+
},
|
|
104
|
+
schedule: (record) => {
|
|
105
|
+
const task = record.dueAt === null
|
|
106
|
+
? scheduler.removeTask(HANDLER_NAME, record._id)
|
|
107
|
+
: scheduler.addTask(HANDLER_NAME, Date.now() + (0, clock_1.RealDelayUntil)(record.dueAt), record._id);
|
|
108
|
+
task.catch(report("scheduling"));
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function isWired(interfaceId) {
|
|
113
|
+
return (0, interface_core_1.GetInterfaceInstances)(interfaceId).length > 0;
|
|
114
|
+
}
|
|
115
|
+
async function ChooseTrigger(engine, settings) {
|
|
116
|
+
if (!isWired(SCHEDULER_INTERFACE) || !isWired(REDIS_INTERFACE)) {
|
|
117
|
+
return pollingTrigger(engine, settings);
|
|
118
|
+
}
|
|
119
|
+
const scheduler = await Promise.resolve().then(() => __importStar(require("@antelopejs/interface-redis-scheduler")));
|
|
120
|
+
try {
|
|
121
|
+
scheduler.setHandler(HANDLER_NAME, (id) => engine.process(id));
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
logging_1.Logging.Warn("payment-subscriptions: the Redis scheduler refused the renewal handler; polling the database instead", error);
|
|
125
|
+
return pollingTrigger(engine, settings);
|
|
126
|
+
}
|
|
127
|
+
return RedisTrigger(engine, settings, scheduler);
|
|
128
|
+
}
|
|
129
|
+
//# sourceMappingURL=triggers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"triggers.js","sourceRoot":"","sources":["../src/triggers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsHA,sCAmBC;AAzID,gEAA6D;AAC7D,+DAAmE;AAGnE,mCAAyC;AAMzC,MAAM,eAAe,GAAG,6BAA6B,CAAC;AACtD,MAAM,mBAAmB,GAAG,uCAAuC,CAAC;AACpE,MAAM,YAAY,GAAG,uBAAuB,CAAC;AAC7C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AASvC,MAAM,OAAO;IAKQ;IACA;IALX,KAAK,CAA6B;IAClC,OAAO,CAA4B;IAE3C,YACmB,MAAc,EACd,UAAkB;QADlB,WAAM,GAAN,MAAM,CAAQ;QACd,eAAU,GAAV,UAAU,CAAQ;IAClC,CAAC;IAEJ,KAAK;QACH,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,IAAI,CAAC,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;QAC7D,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,IAAI;QACR,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACvB,MAAM,IAAI,CAAC,OAAO,CAAC;IACrB,CAAC;IAEO,IAAI;QACV,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QACzB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,MAAM;aACvB,KAAK,EAAE;aACP,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE,CACxB,iBAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,K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C;QACF,OAAO,cAAc,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,YAAY,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;AACnD,CAAC"}
|
package/dist/view.d.ts
ADDED
package/dist/view.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ToSubscription = ToSubscription;
|
|
4
|
+
function present(key, value) {
|
|
5
|
+
return value === null ? {} : { [key]: value };
|
|
6
|
+
}
|
|
7
|
+
function ToSubscription(record) {
|
|
8
|
+
return {
|
|
9
|
+
vendorData: {
|
|
10
|
+
reconciliationRequired: record.reconciliationRequired ?? false,
|
|
11
|
+
attemptStartedAt: record.attemptStartedAt ?? null,
|
|
12
|
+
attemptReplayUntil: record.attemptReplayUntil ?? null,
|
|
13
|
+
phase: record.phase,
|
|
14
|
+
},
|
|
15
|
+
id: record._id,
|
|
16
|
+
reference: record.reference,
|
|
17
|
+
customer: record.customer,
|
|
18
|
+
paymentMethod: record.paymentMethod,
|
|
19
|
+
amount: { ...record.amount },
|
|
20
|
+
interval: record.interval,
|
|
21
|
+
intervalCount: record.intervalCount,
|
|
22
|
+
status: record.status,
|
|
23
|
+
currentPeriodStart: record.currentPeriodStart,
|
|
24
|
+
currentPeriodEnd: record.currentPeriodEnd,
|
|
25
|
+
cancelAtPeriodEnd: record.cancelAtPeriodEnd,
|
|
26
|
+
createdAt: record.createdAt,
|
|
27
|
+
...present("trialEnd", record.trialEnd),
|
|
28
|
+
...present("endedAt", record.endedAt),
|
|
29
|
+
...present("endReason", record.endReason),
|
|
30
|
+
...present("latestPayment", record.latestPayment),
|
|
31
|
+
...present("metadata", record.metadata === null ? null : { ...record.metadata }),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=view.js.map
|
package/dist/view.js.map
ADDED
|
@@ -0,0 +1 @@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CAAC;QACjD,GAAG,OAAO,CACR,UAAU,EACV,MAAM,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,CACzD;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Introduction
|
|
2
|
+
|
|
3
|
+
`@antelopejs/payment-subscriptions` implements
|
|
4
|
+
`@antelopejs/interface-subscriptions` for any provider wired behind
|
|
5
|
+
`@antelopejs/interface-payment`. It is the implementation for providers that
|
|
6
|
+
leave each renewal charge to the merchant — Adyen, Checkout.com, Mangopay — and
|
|
7
|
+
it is an explicit fallback. Stripe users should use Stripe's native subscription
|
|
8
|
+
implementation by default rather than run two competing renewal engines.
|
|
9
|
+
|
|
10
|
+
## What it needs
|
|
11
|
+
|
|
12
|
+
| Interface | Why | Required |
|
|
13
|
+
| --------------------------------------- | ------------------------------------------------------------- | -------- |
|
|
14
|
+
| `@antelopejs/interface-payment` | Every charge is an off-session payment against a saved method | Yes |
|
|
15
|
+
| `@antelopejs/interface-database` | Every subscription is a record there, and nowhere else | Yes |
|
|
16
|
+
| `@antelopejs/interface-redis-scheduler` | Fires each renewal on time instead of within one poll | No |
|
|
17
|
+
|
|
18
|
+
The database adapter must implement `atomicMutation`, the interface-database
|
|
19
|
+
conditional single-record write. `@antelopejs/mongodb` 1.4 does, and the suite
|
|
20
|
+
runs against it.
|
|
21
|
+
|
|
22
|
+
## What it charges
|
|
23
|
+
|
|
24
|
+
Each period is one `CreatePayment` with `offSession: true` against the
|
|
25
|
+
subscription's saved method, under the subscription's `reference`, with the
|
|
26
|
+
subscription's metadata plus `antelopeSubscription` set to its identifier. The
|
|
27
|
+
idempotency key is
|
|
28
|
+
`payment-subscriptions:<subscription>:<period>:<attempt>`: stable across
|
|
29
|
+
anything that might repeat a charge, and different for each deliberate retry.
|
|
30
|
+
|
|
31
|
+
The optional `provider` passed when a subscription is created selects the
|
|
32
|
+
payment account, exactly as on the payment interface, and is stored with the
|
|
33
|
+
subscription: every later charge goes to the same account, because the
|
|
34
|
+
customer and the method exist only there. Reading the subscription back needs
|
|
35
|
+
the same `provider`.
|
|
36
|
+
|
|
37
|
+
## What it records
|
|
38
|
+
|
|
39
|
+
One record per subscription, in the schema `payment-subscriptions`, table
|
|
40
|
+
`subscriptions`, default instance:
|
|
41
|
+
|
|
42
|
+
- the request — customer, method, amount, interval, reference, metadata;
|
|
43
|
+
- the billing state — anchor, current period, status, attempt, the latest
|
|
44
|
+
charge and any charge still settling;
|
|
45
|
+
- `nextActionAt`, when it next needs attention, and `dueAt`, what the sweep
|
|
46
|
+
queries: the same, or now while events are waiting;
|
|
47
|
+
- the claim — which instance holds it, and until when;
|
|
48
|
+
- the attempt's persisted start and replay deadline, and any reconciliation hold;
|
|
49
|
+
- the outbox — events raised but not yet delivered;
|
|
50
|
+
- the idempotency keys of recent cancellations and method changes.
|
|
51
|
+
|
|
52
|
+
A subscription's identifier is derived from the creation's idempotency key and
|
|
53
|
+
the `provider`, which is what lets two racing creations with one key find each
|
|
54
|
+
other.
|
|
55
|
+
|
|
56
|
+
## Events
|
|
57
|
+
|
|
58
|
+
Each change records its events in the same write as the change itself, and they
|
|
59
|
+
are delivered from there to the handlers registered on `SubscriptionEvents`.
|
|
60
|
+
Delivery is retried until every handler accepts, so it is at least once, and an
|
|
61
|
+
event survives a crash between the change and its delivery.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# The renewal clock
|
|
2
|
+
|
|
3
|
+
The module decides on its own when a subscription needs charging. That is the
|
|
4
|
+
whole reason it exists, and the part that has to be right when several instances
|
|
5
|
+
run at once and when any of them can die mid-charge.
|
|
6
|
+
|
|
7
|
+
## The database decides, the clock only knocks
|
|
8
|
+
|
|
9
|
+
Every subscription record carries `dueAt`: when it next needs attention. A
|
|
10
|
+
trigger's only job is to make an instance look at records whose `dueAt` has
|
|
11
|
+
passed. What to do is read from the record — charge the next period, retry a
|
|
12
|
+
failed one, read a settling charge again, end it at period end — never from the
|
|
13
|
+
trigger.
|
|
14
|
+
|
|
15
|
+
So whichever trigger runs, the database holds the same information, and a
|
|
16
|
+
renewal Redis never fires is still made by the next sweep.
|
|
17
|
+
|
|
18
|
+
## Choosing the trigger
|
|
19
|
+
|
|
20
|
+
At start, before touching Redis at all:
|
|
21
|
+
|
|
22
|
+
1. If no module implements both `@antelopejs/interface-redis` and
|
|
23
|
+
`@antelopejs/interface-redis-scheduler`, **poll**: sweep the database every
|
|
24
|
+
`pollIntervalMs`. A renewal is charged at most one interval late.
|
|
25
|
+
2. Otherwise **use the Redis scheduler**: each subscription is one task, named
|
|
26
|
+
after it and fired at its `dueAt`. Rescheduling replaces the task. A sweep
|
|
27
|
+
still runs every `sweepIntervalMs`, because the scheduler drops a task whose
|
|
28
|
+
handler dies mid-run and the database alone must be enough.
|
|
29
|
+
|
|
30
|
+
The Redis interfaces are optional dependencies, imported lazily after the wiring
|
|
31
|
+
check. Nothing on a request path or in `start()` awaits a Redis connection. A
|
|
32
|
+
Redis that is wired but unreachable delays renewals until the next database
|
|
33
|
+
sweep; it blocks nothing.
|
|
34
|
+
|
|
35
|
+
With AntelopeJS core 1.16.0 and `@antelopejs/redis` 1.0.3, the suite verifies
|
|
36
|
+
the published scheduler through normal interface routing, without a test-only
|
|
37
|
+
handler-registration bypass. If a scheduler refuses handler registration, the
|
|
38
|
+
module logs a warning and falls back to polling.
|
|
39
|
+
|
|
40
|
+
## Claiming a renewal
|
|
41
|
+
|
|
42
|
+
Several instances may find the same renewal due. Each record is changed only by
|
|
43
|
+
a conditional write against its current revision (`atomicMutation`), and
|
|
44
|
+
charging starts with one:
|
|
45
|
+
|
|
46
|
+
1. Read the record. If it is not due, or another instance's claim on it has not
|
|
47
|
+
expired, leave it.
|
|
48
|
+
2. Write a claim — this instance, until now plus `leaseMs` — against the revision
|
|
49
|
+
just read. Of several instances that read the same revision, exactly one
|
|
50
|
+
succeeds. The rest stand down without reaching the provider.
|
|
51
|
+
3. Charge.
|
|
52
|
+
4. Write the outcome against the claimed revision, then deliver the events and
|
|
53
|
+
release the claim.
|
|
54
|
+
|
|
55
|
+
If a cancellation lands between 2 and 4, the write in 4 conflicts. The record is
|
|
56
|
+
read again and the outcome applied to what is there now: a charge that went
|
|
57
|
+
through on a subscription just cancelled is recorded and reported, and the
|
|
58
|
+
subscription stays cancelled.
|
|
59
|
+
|
|
60
|
+
## When an instance dies mid-charge
|
|
61
|
+
|
|
62
|
+
Its claim expires after `leaseMs`, and another instance claims the renewal.
|
|
63
|
+
Before the first provider call, the module persists the payment method,
|
|
64
|
+
`attemptStartedAt` and `attemptReplayUntil`. A takeover sends the same key only
|
|
65
|
+
strictly before that deadline. The deadline uses `guaranteedReplayMs` (default
|
|
66
|
+
zero) and is never extended by later configuration changes. A lease is not an
|
|
67
|
+
idempotency guarantee. Configure a conservative retention duration with enough
|
|
68
|
+
margin for clock skew, request latency and process stalls across all instances.
|
|
69
|
+
|
|
70
|
+
If the result is unknown after protection expires, processing halts with
|
|
71
|
+
`vendorData.reconciliationRequired: true` and a log containing the subscription
|
|
72
|
+
ID. Legacy records without attempt timing are treated conservatively, not given
|
|
73
|
+
a new replay window. A known pending payment is read by ID, even after expiry;
|
|
74
|
+
reading it never submits a charge. See the operational recovery procedure in
|
|
75
|
+
[Failed renewals](./3.failed-renewals.md#reconciliation-and-operational-recovery).
|
|
76
|
+
|
|
77
|
+
That is the second guard. The first, the claim, means the provider normally never
|
|
78
|
+
sees the second request at all.
|
|
79
|
+
|
|
80
|
+
## Several instances
|
|
81
|
+
|
|
82
|
+
Nothing is held in memory that another instance needs. Each instance has its own
|
|
83
|
+
claim identity, sweeps on its own, and delivers the events of the records it
|
|
84
|
+
processed to the handlers registered in it. Any number can run against one
|
|
85
|
+
database.
|
|
86
|
+
|
|
87
|
+
## Testing the clock
|
|
88
|
+
|
|
89
|
+
The clock the module reads is replaceable (`UseClock`), and the suite drives a
|
|
90
|
+
manual one through trials, renewals, failures, retries and period ends. The real
|
|
91
|
+
triggers are tested separately in real time: a renewal made by polling with
|
|
92
|
+
nobody calling, and — with Redis — a task scheduled for a trial end and fired by
|
|
93
|
+
Redis while the sweep is an hour away, and a task deleted from Redis whose
|
|
94
|
+
renewal the sweep still makes. A boot test launches a project the production
|
|
95
|
+
way, without the test harness, and checks it starts and renews.
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Failed renewals
|
|
2
|
+
|
|
3
|
+
The interface promises only that a failed renewal is reported as `past_due`. What
|
|
4
|
+
happens next is each implementation's policy. This is this module's.
|
|
5
|
+
|
|
6
|
+
## The policy
|
|
7
|
+
|
|
8
|
+
When charging a period is declined:
|
|
9
|
+
|
|
10
|
+
1. The period advances anyway, the subscription goes `past_due`, and
|
|
11
|
+
`subscription.payment_failed` is raised. The unpaid period is the current one.
|
|
12
|
+
2. It is retried after each entry of `retryDelaysMs`, measured from the failure
|
|
13
|
+
before it. By default: one day, three days, seven days — four attempts over
|
|
14
|
+
eleven days.
|
|
15
|
+
3. A retry that succeeds makes it `active` again, in the same period. The cycle
|
|
16
|
+
does not move.
|
|
17
|
+
4. When the last retry fails, the subscription ends: `canceled`, with
|
|
18
|
+
`endReason: "payment_failed"`, and both `subscription.payment_failed` and
|
|
19
|
+
`subscription.canceled` are raised.
|
|
20
|
+
|
|
21
|
+
Each new attempt uses the subscription's payment method at the time it is made,
|
|
22
|
+
so `UpdateSubscriptionPaymentMethod` during `past_due` is how a payer recovers.
|
|
23
|
+
Each attempt has its own idempotency key; a retry is a new charge, not a replay
|
|
24
|
+
of the decline.
|
|
25
|
+
|
|
26
|
+
A subscription set to end at period end keeps being retried until its period
|
|
27
|
+
ends, and then ends instead of being retried further.
|
|
28
|
+
|
|
29
|
+
## A charge that is still settling
|
|
30
|
+
|
|
31
|
+
A bank debit can report `pending` for days. The subscription stays as it was —
|
|
32
|
+
`active` after a trial or a paid period, `past_due` during retries — and the
|
|
33
|
+
charge is read again every `settlementPollMs` until it settles, then treated as
|
|
34
|
+
succeeded or declined. Nothing is reported until it settles.
|
|
35
|
+
|
|
36
|
+
If the subscription is cancelled while a charge is settling, the charge is still
|
|
37
|
+
followed; a charge that then succeeds is recorded and reported, so the money can
|
|
38
|
+
be refunded.
|
|
39
|
+
|
|
40
|
+
## A provider that refuses the charge
|
|
41
|
+
|
|
42
|
+
`CustomerNotFoundError`, `PaymentNotFoundError`, `InvalidPaymentStateError` and
|
|
43
|
+
`UnsupportedOperationError` from the payment interface mean the provider will
|
|
44
|
+
not make this charge — most often because the saved method has been removed.
|
|
45
|
+
They count as a declined attempt: `past_due`, retried under the policy, ended
|
|
46
|
+
when the retries are spent. The `subscription.payment_failed` event has no
|
|
47
|
+
`payment`, since none was made.
|
|
48
|
+
|
|
49
|
+
## A provider that cannot be reached
|
|
50
|
+
|
|
51
|
+
Any other `PaymentError` is not a decline: the charge is in doubt. The same
|
|
52
|
+
attempt can be made again after `errorBackoffMs` only within its persisted
|
|
53
|
+
provider guarantee, with the same idempotency key **and the same payment method**,
|
|
54
|
+
recorded before the first try — so if the first request did reach the provider,
|
|
55
|
+
the retry finds that charge instead of making another, even if the method was
|
|
56
|
+
changed meanwhile. The new method is used from the next attempt.
|
|
57
|
+
|
|
58
|
+
If the subscription is cancelled while a charge is in doubt, the attempt is not
|
|
59
|
+
made again. A charge that did land then reaches the merchant only as the payment
|
|
60
|
+
interface's `payment.succeeded` webhook, carrying `antelopeSubscription`.
|
|
61
|
+
|
|
62
|
+
## After a stall
|
|
63
|
+
|
|
64
|
+
Periods are anchored, so a subscription that could not be processed for longer
|
|
65
|
+
than a period — the database or every instance was down — has every missed
|
|
66
|
+
period charged on recovery, one after another.
|
|
67
|
+
|
|
68
|
+
## The first period
|
|
69
|
+
|
|
70
|
+
The first period is charged inside `CreateSubscription`, and a decline there
|
|
71
|
+
creates nothing: it rejects with `SubscriptionPaymentError`. A payer with no
|
|
72
|
+
subscription is not `past_due`.
|
|
73
|
+
|
|
74
|
+
A creation that ends without an answer — the provider could not be reached, or
|
|
75
|
+
the instance died mid-call — must be replayed with the same idempotency key.
|
|
76
|
+
The replay resumes it only within its persisted replay window. After expiry it
|
|
77
|
+
rejects with a reconciliation-required error naming the subscription ID,
|
|
78
|
+
without charging again. A refused creation remains refused on replay.
|
|
79
|
+
A creation nobody replays is never completed by the module, and a charge it made
|
|
80
|
+
belongs to no subscription; it still reaches the merchant as a payment-interface
|
|
81
|
+
webhook carrying `antelopeSubscription`.
|
|
82
|
+
|
|
83
|
+
## Reconciliation and operational recovery
|
|
84
|
+
|
|
85
|
+
`guaranteedReplayMs` defaults to zero: the first call is allowed, but an uncertain
|
|
86
|
+
result is not blindly replayed. Set a positive value only from a documented
|
|
87
|
+
provider guarantee that covers every account using this module, with a safety
|
|
88
|
+
margin. Transient errors are retried only strictly before the saved deadline;
|
|
89
|
+
declines follow the separate finite `retryDelaysMs` policy with new attempt keys.
|
|
90
|
+
|
|
91
|
+
Live subscriptions expose `reconciliationRequired`, `attemptStartedAt`,
|
|
92
|
+
`attemptReplayUntil` and `phase` in `vendorData`. A halted record has no next
|
|
93
|
+
charge scheduled. Cancellation and payment-method changes do not clear that
|
|
94
|
+
hold. Initial creations expose the hold through the replay error and persisted
|
|
95
|
+
record because they are not yet public live subscriptions.
|
|
96
|
+
|
|
97
|
+
For operational recovery:
|
|
98
|
+
|
|
99
|
+
1. Stop all module instances/triggers and drain in-flight requests. Back up the
|
|
100
|
+
record and retain its revision, provider account, attempt key, timing and
|
|
101
|
+
payment method. Never delete the record or reset timing to force a replay.
|
|
102
|
+
2. Search the provider's authoritative ledger, including webhooks and metadata
|
|
103
|
+
`antelopeSubscription`, using the original account and attempt key. If the
|
|
104
|
+
result is still unknown, leave the hold in place and escalate to the provider.
|
|
105
|
+
3. If a payment is found, verify its customer, method, amount, currency,
|
|
106
|
+
subscription metadata and original attempt key. Recover the target period
|
|
107
|
+
index from that key (`payment-subscriptions:<id>:<period>:<attempt>`), not
|
|
108
|
+
from the record's last paid period. If the target cannot be established,
|
|
109
|
+
leave the hold in place.
|
|
110
|
+
An operator-reviewed, revision-conditional database repair can attach that ID
|
|
111
|
+
as `pendingPayment`, clear `reconciliationRequired`, and set `nextActionAt`
|
|
112
|
+
and `dueAt` to now with the lease cleared. Set `periodIndex` to the recovered
|
|
113
|
+
target for every record, including renewals; the initial charge targets `0`.
|
|
114
|
+
For a `creating` record, replay the original creation key: it reads that
|
|
115
|
+
payment instead of charging. For a live
|
|
116
|
+
record, restart processing to read and apply its actual status. Keep the
|
|
117
|
+
original attempt identity and timing intact.
|
|
118
|
+
4. If the provider conclusively proves no charge exists, prefer retiring the
|
|
119
|
+
held subscription and creating a replacement with a new key under an audited
|
|
120
|
+
merchant decision. Do not silently retry the uncertain attempt. Resolve any
|
|
121
|
+
provider schedule registration as well. Refunds and entitlement corrections
|
|
122
|
+
remain merchant operations.
|
|
123
|
+
|
|
124
|
+
There is intentionally no portable force-retry or reconciliation API. Database
|
|
125
|
+
repair requires provider-specific evidence and an audit trail; an elapsed lease,
|
|
126
|
+
a method update or a longer configuration value is not evidence of non-payment.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# The provider schedule
|
|
2
|
+
|
|
3
|
+
This module always owns the clock. Some providers that leave the merchant to
|
|
4
|
+
fire each charge will still store the schedule, and handle the authentication
|
|
5
|
+
chain between charges, if asked. Mangopay's Recurring PayIn Registration stores
|
|
6
|
+
frequency, dates and amounts and chains the customer-initiated first payment to
|
|
7
|
+
the merchant-initiated ones; Mangopay still does not fire them.
|
|
8
|
+
|
|
9
|
+
For those, part of a subscription's state can live with the provider as well as
|
|
10
|
+
in this module's database. The seam for it is `ProviderSchedule`:
|
|
11
|
+
|
|
12
|
+
| Call | When | The default |
|
|
13
|
+
| ---------- | ---------------------------------------------- | ------------------------------ |
|
|
14
|
+
| `register` | Once, as a subscription is created | Records nothing |
|
|
15
|
+
| `charge` | Each time a period is charged | An off-session `CreatePayment` |
|
|
16
|
+
| `release` | Once, when a subscription ends, for any reason | Does nothing |
|
|
17
|
+
|
|
18
|
+
What `register` returns is stored with the subscription and handed to every
|
|
19
|
+
`charge` and `release`. A schedule never decides when to charge, and never
|
|
20
|
+
throws for a decline: a declined charge resolves with a `failed` payment, as
|
|
21
|
+
`CreatePayment` does.
|
|
22
|
+
|
|
23
|
+
`register` runs before the subscription is stored and is given no idempotency
|
|
24
|
+
key, so two creations racing on one key may both call it. A schedule that
|
|
25
|
+
registers anything real must tolerate that, or derive its own key from the
|
|
26
|
+
subscription identifier it is handed.
|
|
27
|
+
|
|
28
|
+
The schedule is chosen by the `providerSchedule` setting. Only the default,
|
|
29
|
+
`payment-interface`, exists. A Mangopay schedule would charge against the
|
|
30
|
+
registration through the Mangopay module's own interface, which is the escape
|
|
31
|
+
hatch for provider-specific behaviour everywhere else in AntelopeJS.
|
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@antelopejs/payment-subscriptions",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Generic AntelopeJS subscriptions on top of any payment interface provider: saved methods charged off-session, on a renewal clock the module owns",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"antelopejs",
|
|
7
|
+
"billing",
|
|
8
|
+
"payment",
|
|
9
|
+
"recurring",
|
|
10
|
+
"subscription"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/AntelopeJS/payment-subscriptions/tree/main/docs",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/AntelopeJS/payment-subscriptions/issues"
|
|
15
|
+
},
|
|
16
|
+
"license": "Apache-2.0",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/AntelopeJS/payment-subscriptions.git"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"!dist/test",
|
|
24
|
+
"docs",
|
|
25
|
+
"skills"
|
|
26
|
+
],
|
|
27
|
+
"main": "dist/index.js",
|
|
28
|
+
"types": "dist/index.d.ts",
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public",
|
|
31
|
+
"provenance": false
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "rimraf dist && tsc",
|
|
35
|
+
"format": "oxfmt .",
|
|
36
|
+
"lint": "oxlint",
|
|
37
|
+
"lint:fix": "oxlint --fix",
|
|
38
|
+
"prepack": "pnpm run build",
|
|
39
|
+
"release": "pnpm run lint && pnpm run test && pnpm run prepack && release-it",
|
|
40
|
+
"test": "pnpm run build && pnpm run test:polling && pnpm run test:redis",
|
|
41
|
+
"test:polling": "ajs module test .",
|
|
42
|
+
"test:redis": "ANTELOPE_SUBSCRIPTIONS_TEST_CLOCK=redis ajs module test .",
|
|
43
|
+
"typecheck": "tsc --noEmit",
|
|
44
|
+
"format:check": "oxfmt --check .",
|
|
45
|
+
"knip": "knip"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@antelopejs/interface-core": ">=0.0.5 <1.0.0",
|
|
49
|
+
"@antelopejs/interface-database": "^0.1.8",
|
|
50
|
+
"@antelopejs/interface-payment": ">=0.0.2 <1.0.0",
|
|
51
|
+
"@antelopejs/interface-subscriptions": ">=0.0.2 <0.1.0"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@antelopejs/core": "1.16.0",
|
|
55
|
+
"@antelopejs/mongodb": "^1.4.0",
|
|
56
|
+
"@antelopejs/redis": "^1.0.3",
|
|
57
|
+
"@antelopejs/tooling-configs": "^0.0.8",
|
|
58
|
+
"@types/mocha": "^10.0.10",
|
|
59
|
+
"@types/node": "^22.19.15",
|
|
60
|
+
"eslint-plugin-perfectionist": "^5.11.0",
|
|
61
|
+
"knip": "^6.34.0",
|
|
62
|
+
"mongodb-memory-server-core": "^11.3.0",
|
|
63
|
+
"oxfmt": "^0.66.0",
|
|
64
|
+
"oxlint": "1.81.0",
|
|
65
|
+
"oxlint-tsgolint": "^7.0.2001",
|
|
66
|
+
"redis-memory-server": "^0.17.1",
|
|
67
|
+
"release-it": "^19.2.4",
|
|
68
|
+
"release-it-changelogen": "^0.1.0",
|
|
69
|
+
"rimraf": "^6.1.3",
|
|
70
|
+
"typescript": "^5.9.3"
|
|
71
|
+
},
|
|
72
|
+
"optionalDependencies": {
|
|
73
|
+
"@antelopejs/interface-redis": ">=0.0.6 <1.0.0",
|
|
74
|
+
"@antelopejs/interface-redis-scheduler": ">=0.0.7 <1.0.0"
|
|
75
|
+
},
|
|
76
|
+
"packageManager": "pnpm@10.6.5",
|
|
77
|
+
"antelopeJs": {
|
|
78
|
+
"implements": [
|
|
79
|
+
"@antelopejs/interface-subscriptions"
|
|
80
|
+
],
|
|
81
|
+
"defaultConfig": {},
|
|
82
|
+
"test": "src/test/antelope.test.ts",
|
|
83
|
+
"skills": [
|
|
84
|
+
"./skills"
|
|
85
|
+
]
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: payment-subscriptions
|
|
3
|
+
description: Guides wiring the generic payment-subscriptions fallback, configuring bounded charge recovery, and diagnosing stalled renewals or reconciliation holds. Use when a payment provider lacks native subscriptions or the merchant explicitly chooses a locally owned renewal clock.
|
|
4
|
+
metadata:
|
|
5
|
+
category: antelopejs-module
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# payment-subscriptions
|
|
9
|
+
|
|
10
|
+
Implements the subscriptions interface for any payment provider. Consumers code
|
|
11
|
+
against `@antelopejs/interface-subscriptions` (see its skill); this module is
|
|
12
|
+
what you wire.
|
|
13
|
+
|
|
14
|
+
Prefer Stripe's native subscriptions for Stripe users. Use this module only as
|
|
15
|
+
an explicit fallback, disabling Stripe's subscriptions export or configuring
|
|
16
|
+
consumer import overrides so just one implementation owns each subscription.
|
|
17
|
+
|
|
18
|
+
## Wiring
|
|
19
|
+
|
|
20
|
+
Run `ajs project modules add @antelopejs/payment-subscriptions` in a project.
|
|
21
|
+
For an embedded runtime, add the module to the host runtime configuration instead.
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
modules: {
|
|
25
|
+
subscriptions: { source: { type: "package", package: "@antelopejs/payment-subscriptions" }, config: {} },
|
|
26
|
+
payments: { ... }, // anything implementing @antelopejs/interface-payment
|
|
27
|
+
mongodb: { ... }, // anything implementing @antelopejs/interface-database with atomicMutation
|
|
28
|
+
redis: { ... }, // optional
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Config (all optional)
|
|
33
|
+
|
|
34
|
+
| Field | Default | Meaning |
|
|
35
|
+
| -------------------- | ------------------- | --------------------------------------------------------------------------------- |
|
|
36
|
+
| `pollIntervalMs` | 60 000 | Database poll without Redis: max lateness of a renewal |
|
|
37
|
+
| `sweepIntervalMs` | 900 000 | Database sweep with Redis: catches tasks Redis lost |
|
|
38
|
+
| `leaseMs` | 300 000 | How long one instance's claim on a renewal lasts |
|
|
39
|
+
| `retryDelaysMs` | 1d, 3d, 7d | Retries after a failed renewal, then it ends |
|
|
40
|
+
| `settlementPollMs` | 3 600 000 | How often a still-settling charge is read again |
|
|
41
|
+
| `errorBackoffMs` | 300 000 | Retry delay when the payment provider is unreachable |
|
|
42
|
+
| `batchSize` | 100 | Due subscriptions handled per sweep |
|
|
43
|
+
| `providerSchedule` | `payment-interface` | Mirror the schedule with the provider (seam; one schedule) |
|
|
44
|
+
| `guaranteedReplayMs` | `0` | Verified provider replay retention with a safety margin; default allows no replay |
|
|
45
|
+
|
|
46
|
+
## Facts to reason from when debugging
|
|
47
|
+
|
|
48
|
+
- **The database is the truth.** Schema `payment-subscriptions`, table
|
|
49
|
+
`subscriptions`; `dueAt` is what the sweep queries, `nextActionAt` is the next
|
|
50
|
+
renewal, retry or settlement read, `outbox` holds undelivered events,
|
|
51
|
+
`leaseOwner`/`leaseUntil` is the current claim.
|
|
52
|
+
- **Charged at most once per attempt.** A claim (conditional write) precedes every
|
|
53
|
+
charge; the charge's idempotency key is
|
|
54
|
+
`payment-subscriptions:<id>:<period>:<attempt>`. Two payments for one period
|
|
55
|
+
with different attempts are deliberate retries, not duplicates.
|
|
56
|
+
- **Late renewal without Redis** is expected up to `pollIntervalMs`.
|
|
57
|
+
- **The log line `renewal clock is polling|redis`** at start says which trigger
|
|
58
|
+
is in use. Core 1.16.0 supports the published Redis scheduler through normal
|
|
59
|
+
routing; a handler-registration failure logs a warning and falls back to polling.
|
|
60
|
+
- **An uncertain charge** retries with the pinned method and same key only
|
|
61
|
+
strictly before persisted `attemptReplayUntil`. Verify retention for every
|
|
62
|
+
account before setting `guaranteedReplayMs`; never assume Stripe's duration.
|
|
63
|
+
- **A reconciliation hold** appears in `vendorData.reconciliationRequired` and
|
|
64
|
+
logs. Unknown expired or legacy attempts halt; known pending IDs are read only.
|
|
65
|
+
Method updates and cancellation do not restart held charges. Before repairing
|
|
66
|
+
state, follow [operational recovery](../../docs/3.failed-renewals.md#reconciliation-and-operational-recovery).
|
|
67
|
+
- **Payment charges carry `metadata.antelopeSubscription`.**
|
|
68
|
+
|
|
69
|
+
## Not in this module
|
|
70
|
+
|
|
71
|
+
Proration, dunning beyond the retry list, tax, coupons, metered billing, several
|
|
72
|
+
items per subscription. A Mangopay provider schedule is a seam
|
|
73
|
+
(`ProviderSchedule`), not an implementation.
|