@chipmobilesdk/rn-payment 0.4.0 → 0.5.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.
- package/CHANGELOG.md +482 -334
- package/README.md +925 -897
- package/package.json +52 -54
- package/skills/sdk-rn-payment/SKILL.md +175 -174
- package/src/adapter/createStoreProvider.ts +116 -118
- package/src/adapter/iap-adapter.ts +627 -660
- package/src/adapter/port.ts +209 -215
- package/src/config/types.ts +298 -310
- package/src/config/validate.ts +224 -232
- package/src/core/mutex.ts +25 -128
- package/src/core/retry.ts +95 -133
- package/src/core/timers.ts +272 -267
- package/src/diagnostics/errors.ts +124 -117
- package/src/diagnostics/events.ts +282 -266
- package/src/diagnostics/messageKeys.ts +93 -95
- package/src/engine/engine.ts +921 -999
- package/src/engine/finalize.ts +343 -346
- package/src/engine/foreground.ts +29 -0
- package/src/engine/products.ts +259 -259
- package/src/engine/purchase.ts +589 -614
- package/src/engine/subscriptions.ts +146 -157
- package/src/entitlements/aggregate.ts +261 -242
- package/src/entitlements/mapping.ts +67 -67
- package/src/entitlements/policy.ts +121 -129
- package/src/index.ts +5 -9
- package/src/persistence/mmkv-store.ts +158 -158
- package/src/persistence/snapshot.ts +220 -247
- package/src/react/PaymentProvider.tsx +90 -79
- package/src/react/hooks.ts +236 -274
- package/src/testing/conformance.ts +169 -0
- package/src/testing/fakeStore.ts +360 -393
- package/src/testing/index.ts +19 -10
package/src/config/validate.ts
CHANGED
|
@@ -1,232 +1,224 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Catalog validation (FR-011).
|
|
3
|
-
*
|
|
4
|
-
* Runs at `configure`, before any connection is opened, so a bad catalog fails
|
|
5
|
-
* at configuration time rather than at the moment a user taps Buy. Every failure
|
|
6
|
-
* **names the offending entry** — "invalid catalog" alone is useless in an app
|
|
7
|
-
* with thirty products.
|
|
8
|
-
*
|
|
9
|
-
* All problems are collected rather than thrown one at a time, so a developer
|
|
10
|
-
* fixes the catalog in one pass instead of rerunning to find the next fault.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import { PaymentConfigError } from '../diagnostics/errors';
|
|
14
|
-
import {
|
|
15
|
-
resolveForegroundSyncMinIntervalMs,
|
|
16
|
-
resolveProductCacheTtlMs,
|
|
17
|
-
resolveRetry,
|
|
18
|
-
resolveStaleAfterMs,
|
|
19
|
-
resolveTimeouts,
|
|
20
|
-
type ResolvedRetry,
|
|
21
|
-
type ResolvedTimeouts,
|
|
22
|
-
} from '../core/timers';
|
|
23
|
-
import type {
|
|
24
|
-
CatalogEntry,
|
|
25
|
-
EntitlementKey,
|
|
26
|
-
LapsePolicy,
|
|
27
|
-
PaymentConfig,
|
|
28
|
-
ProductKey,
|
|
29
|
-
ProductType,
|
|
30
|
-
ValidationUnavailablePolicy,
|
|
31
|
-
} from './types';
|
|
32
|
-
|
|
33
|
-
const PRODUCT_TYPES: readonly ProductType[] = [
|
|
34
|
-
'one_time_permanent',
|
|
35
|
-
'one_time_consumable',
|
|
36
|
-
'subscription',
|
|
37
|
-
];
|
|
38
|
-
|
|
39
|
-
/** The platform whose store identifiers a catalog must supply. */
|
|
40
|
-
export type TargetPlatform = 'android' | 'ios';
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* A validated, indexed catalog plus every resolved policy value.
|
|
44
|
-
*
|
|
45
|
-
* Produced once so the hot paths never re-derive it, and so `getEntitlement` can
|
|
46
|
-
* stay a synchronous in-memory read (PERF-001).
|
|
47
|
-
*/
|
|
48
|
-
export interface ResolvedConfig {
|
|
49
|
-
readonly entries: ReadonlyMap<ProductKey, CatalogEntry>;
|
|
50
|
-
/** productKey → entitlement keys it grants. */
|
|
51
|
-
readonly grants: ReadonlyMap<ProductKey, readonly EntitlementKey[]>;
|
|
52
|
-
/** entitlementKey → product keys that can grant it (FR-051, FR-052). */
|
|
53
|
-
readonly sources: ReadonlyMap<EntitlementKey, readonly ProductKey[]>;
|
|
54
|
-
/** storeProductId → productKey, for translating store callbacks back (FR-003). */
|
|
55
|
-
readonly byStoreId: ReadonlyMap<string, ProductKey>;
|
|
56
|
-
readonly entitlementKeys: readonly EntitlementKey[];
|
|
57
|
-
readonly platform: TargetPlatform;
|
|
58
|
-
readonly enabled: boolean;
|
|
59
|
-
readonly gracePolicy: LapsePolicy;
|
|
60
|
-
readonly holdPolicy: LapsePolicy;
|
|
61
|
-
readonly staleAfterMs: number;
|
|
62
|
-
readonly productCacheTtlMs: number;
|
|
63
|
-
readonly foregroundSyncMinIntervalMs: number;
|
|
64
|
-
readonly timeouts: ResolvedTimeouts;
|
|
65
|
-
readonly retry: ResolvedRetry;
|
|
66
|
-
readonly onValidationUnavailable: ValidationUnavailablePolicy;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export function validateConfig(
|
|
70
|
-
config: PaymentConfig,
|
|
71
|
-
platform: TargetPlatform = 'android',
|
|
72
|
-
): ResolvedConfig {
|
|
73
|
-
const problems: string[] = [];
|
|
74
|
-
const offenders: string[] = [];
|
|
75
|
-
|
|
76
|
-
const entries = new Map<ProductKey, CatalogEntry>();
|
|
77
|
-
const grants = new Map<ProductKey, readonly EntitlementKey[]>();
|
|
78
|
-
const sources = new Map<EntitlementKey, ProductKey[]>();
|
|
79
|
-
const byStoreId = new Map<string, ProductKey>();
|
|
80
|
-
|
|
81
|
-
if (config.catalog.length === 0) {
|
|
82
|
-
problems.push('catalog is empty');
|
|
83
|
-
offenders.push('catalog');
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
for (const entry of config.catalog) {
|
|
87
|
-
const key = entry.productKey;
|
|
88
|
-
|
|
89
|
-
if (!key || key.trim() === '') {
|
|
90
|
-
problems.push('a catalog entry has an empty productKey');
|
|
91
|
-
offenders.push('(empty productKey)');
|
|
92
|
-
continue;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
if (entries.has(key)) {
|
|
96
|
-
problems.push(`duplicate productKey "${key}"`);
|
|
97
|
-
offenders.push(key);
|
|
98
|
-
continue;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
if (!PRODUCT_TYPES.includes(entry.productType)) {
|
|
102
|
-
problems.push(
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
)
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
)
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
*
|
|
226
|
-
* False outside production regardless of what else is configured. The engine
|
|
227
|
-
* records each refusal in observable status so a test can assert the block
|
|
228
|
-
* happened — the difference between a guarantee and a hope.
|
|
229
|
-
*/
|
|
230
|
-
export function mayCreateRealTransaction(config: PaymentConfig): boolean {
|
|
231
|
-
return config.environment === 'production' && config.isProductionBuild;
|
|
232
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Catalog validation (FR-011).
|
|
3
|
+
*
|
|
4
|
+
* Runs at `configure`, before any connection is opened, so a bad catalog fails
|
|
5
|
+
* at configuration time rather than at the moment a user taps Buy. Every failure
|
|
6
|
+
* **names the offending entry** — "invalid catalog" alone is useless in an app
|
|
7
|
+
* with thirty products.
|
|
8
|
+
*
|
|
9
|
+
* All problems are collected rather than thrown one at a time, so a developer
|
|
10
|
+
* fixes the catalog in one pass instead of rerunning to find the next fault.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { PaymentConfigError } from '../diagnostics/errors';
|
|
14
|
+
import {
|
|
15
|
+
resolveForegroundSyncMinIntervalMs,
|
|
16
|
+
resolveProductCacheTtlMs,
|
|
17
|
+
resolveRetry,
|
|
18
|
+
resolveStaleAfterMs,
|
|
19
|
+
resolveTimeouts,
|
|
20
|
+
type ResolvedRetry,
|
|
21
|
+
type ResolvedTimeouts,
|
|
22
|
+
} from '../core/timers';
|
|
23
|
+
import type {
|
|
24
|
+
CatalogEntry,
|
|
25
|
+
EntitlementKey,
|
|
26
|
+
LapsePolicy,
|
|
27
|
+
PaymentConfig,
|
|
28
|
+
ProductKey,
|
|
29
|
+
ProductType,
|
|
30
|
+
ValidationUnavailablePolicy,
|
|
31
|
+
} from './types';
|
|
32
|
+
|
|
33
|
+
const PRODUCT_TYPES: readonly ProductType[] = [
|
|
34
|
+
'one_time_permanent',
|
|
35
|
+
'one_time_consumable',
|
|
36
|
+
'subscription',
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
/** The platform whose store identifiers a catalog must supply. */
|
|
40
|
+
export type TargetPlatform = 'android' | 'ios';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A validated, indexed catalog plus every resolved policy value.
|
|
44
|
+
*
|
|
45
|
+
* Produced once so the hot paths never re-derive it, and so `getEntitlement` can
|
|
46
|
+
* stay a synchronous in-memory read (PERF-001).
|
|
47
|
+
*/
|
|
48
|
+
export interface ResolvedConfig {
|
|
49
|
+
readonly entries: ReadonlyMap<ProductKey, CatalogEntry>;
|
|
50
|
+
/** productKey → entitlement keys it grants. */
|
|
51
|
+
readonly grants: ReadonlyMap<ProductKey, readonly EntitlementKey[]>;
|
|
52
|
+
/** entitlementKey → product keys that can grant it (FR-051, FR-052). */
|
|
53
|
+
readonly sources: ReadonlyMap<EntitlementKey, readonly ProductKey[]>;
|
|
54
|
+
/** storeProductId → productKey, for translating store callbacks back (FR-003). */
|
|
55
|
+
readonly byStoreId: ReadonlyMap<string, ProductKey>;
|
|
56
|
+
readonly entitlementKeys: readonly EntitlementKey[];
|
|
57
|
+
readonly platform: TargetPlatform;
|
|
58
|
+
readonly enabled: boolean;
|
|
59
|
+
readonly gracePolicy: LapsePolicy;
|
|
60
|
+
readonly holdPolicy: LapsePolicy;
|
|
61
|
+
readonly staleAfterMs: number;
|
|
62
|
+
readonly productCacheTtlMs: number;
|
|
63
|
+
readonly foregroundSyncMinIntervalMs: number;
|
|
64
|
+
readonly timeouts: ResolvedTimeouts;
|
|
65
|
+
readonly retry: ResolvedRetry;
|
|
66
|
+
readonly onValidationUnavailable: ValidationUnavailablePolicy;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function validateConfig(
|
|
70
|
+
config: PaymentConfig,
|
|
71
|
+
platform: TargetPlatform = 'android',
|
|
72
|
+
): ResolvedConfig {
|
|
73
|
+
const problems: string[] = [];
|
|
74
|
+
const offenders: string[] = [];
|
|
75
|
+
|
|
76
|
+
const entries = new Map<ProductKey, CatalogEntry>();
|
|
77
|
+
const grants = new Map<ProductKey, readonly EntitlementKey[]>();
|
|
78
|
+
const sources = new Map<EntitlementKey, ProductKey[]>();
|
|
79
|
+
const byStoreId = new Map<string, ProductKey>();
|
|
80
|
+
|
|
81
|
+
if (config.catalog.length === 0) {
|
|
82
|
+
problems.push('catalog is empty');
|
|
83
|
+
offenders.push('catalog');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
for (const entry of config.catalog) {
|
|
87
|
+
const key = entry.productKey;
|
|
88
|
+
|
|
89
|
+
if (!key || key.trim() === '') {
|
|
90
|
+
problems.push('a catalog entry has an empty productKey');
|
|
91
|
+
offenders.push('(empty productKey)');
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (entries.has(key)) {
|
|
96
|
+
problems.push(`duplicate productKey "${key}"`);
|
|
97
|
+
offenders.push(key);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (!PRODUCT_TYPES.includes(entry.productType)) {
|
|
102
|
+
problems.push(`productKey "${key}" has invalid productType "${String(entry.productType)}"`);
|
|
103
|
+
offenders.push(key);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const storeId = entry.storeProductIds[platform];
|
|
107
|
+
if (!storeId || storeId.trim() === '') {
|
|
108
|
+
problems.push(`productKey "${key}" is missing a store product id for platform "${platform}"`);
|
|
109
|
+
offenders.push(key);
|
|
110
|
+
} else {
|
|
111
|
+
const existing = byStoreId.get(storeId);
|
|
112
|
+
if (existing !== undefined) {
|
|
113
|
+
// Two product keys pointing at one store id would make a store callback
|
|
114
|
+
// ambiguous, so the wrong entitlement could be granted.
|
|
115
|
+
problems.push(`store product id "${storeId}" is used by both "${existing}" and "${key}"`);
|
|
116
|
+
offenders.push(key);
|
|
117
|
+
} else {
|
|
118
|
+
byStoreId.set(storeId, key);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (!Array.isArray(entry.grants) || entry.grants.length === 0) {
|
|
123
|
+
problems.push(`productKey "${key}" grants no entitlement`);
|
|
124
|
+
offenders.push(key);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
entries.set(key, entry);
|
|
128
|
+
grants.set(key, [...(entry.grants ?? [])]);
|
|
129
|
+
|
|
130
|
+
for (const entitlement of entry.grants ?? []) {
|
|
131
|
+
const list = sources.get(entitlement);
|
|
132
|
+
if (list) {
|
|
133
|
+
list.push(key);
|
|
134
|
+
} else {
|
|
135
|
+
sources.set(entitlement, [key]);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// An entitlement the app intends to query but no product can grant is almost
|
|
141
|
+
// always a typo, and it would otherwise sit at `not_entitled` forever with no
|
|
142
|
+
// indication why.
|
|
143
|
+
for (const entitlement of config.entitlements) {
|
|
144
|
+
if (!sources.has(entitlement)) {
|
|
145
|
+
problems.push(`entitlement "${entitlement}" is declared but no catalog product grants it`);
|
|
146
|
+
offenders.push(entitlement);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// A product granting something the app never declared is the mirror problem:
|
|
151
|
+
// harmless at runtime, but a strong signal of a rename half-applied.
|
|
152
|
+
const declared = new Set(config.entitlements);
|
|
153
|
+
for (const entitlement of sources.keys()) {
|
|
154
|
+
if (!declared.has(entitlement)) {
|
|
155
|
+
problems.push(
|
|
156
|
+
`entitlement "${entitlement}" is granted by a product but not declared in config.entitlements`,
|
|
157
|
+
);
|
|
158
|
+
offenders.push(entitlement);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (problems.length > 0) {
|
|
163
|
+
throw new PaymentConfigError({
|
|
164
|
+
code: 'PAYMENT_INVALID_CATALOG',
|
|
165
|
+
message: `Payment catalog is invalid: ${problems.join('; ')}`,
|
|
166
|
+
operation: 'configure',
|
|
167
|
+
offenders: [...new Set(offenders)],
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
entries,
|
|
173
|
+
grants,
|
|
174
|
+
sources: new Map([...sources].map(([k, v]) => [k, [...v]])),
|
|
175
|
+
byStoreId,
|
|
176
|
+
entitlementKeys: [...config.entitlements],
|
|
177
|
+
platform,
|
|
178
|
+
enabled: config.enabled ?? true,
|
|
179
|
+
gracePolicy: config.gracePolicy ?? 'grant',
|
|
180
|
+
holdPolicy: config.holdPolicy ?? 'withhold',
|
|
181
|
+
staleAfterMs: resolveStaleAfterMs(config.staleAfterMs),
|
|
182
|
+
productCacheTtlMs: resolveProductCacheTtlMs(config.productCacheTtlMs),
|
|
183
|
+
foregroundSyncMinIntervalMs: resolveForegroundSyncMinIntervalMs(
|
|
184
|
+
config.foregroundSyncMinIntervalMs,
|
|
185
|
+
),
|
|
186
|
+
timeouts: resolveTimeouts(config.timeouts),
|
|
187
|
+
retry: resolveRetry(config.retry),
|
|
188
|
+
onValidationUnavailable: config.onValidationUnavailable ?? 'grant_and_queue',
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The fail-closed environment guard (FR-015).
|
|
194
|
+
*
|
|
195
|
+
* Separate from catalog validation because it is not about the catalog's shape
|
|
196
|
+
* but about whether this binary is allowed to move real money at all. Checked
|
|
197
|
+
* before connecting, and it refuses rather than warns: a non-production build
|
|
198
|
+
* that declares `production` is one tap away from charging a real card, and
|
|
199
|
+
* continuing silently is exactly the failure this package exists to prevent.
|
|
200
|
+
*/
|
|
201
|
+
export function assertEnvironmentSafe(config: PaymentConfig): void {
|
|
202
|
+
if (config.environment === 'production' && !config.isProductionBuild) {
|
|
203
|
+
throw new PaymentConfigError({
|
|
204
|
+
code: 'PAYMENT_PRODUCTION_CONFIG_IN_NON_PRODUCTION_BUILD',
|
|
205
|
+
message:
|
|
206
|
+
'environment is "production" but isProductionBuild is false. Refusing to ' +
|
|
207
|
+
'initialize: a non-production build must not be able to create a real ' +
|
|
208
|
+
'transaction.',
|
|
209
|
+
operation: 'configure',
|
|
210
|
+
offenders: ['environment'],
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Whether this configuration may hand a real purchase to a real store (FR-014).
|
|
217
|
+
*
|
|
218
|
+
* False outside production regardless of what else is configured. The engine
|
|
219
|
+
* records each refusal in observable status so a test can assert the block
|
|
220
|
+
* happened — the difference between a guarantee and a hope.
|
|
221
|
+
*/
|
|
222
|
+
export function mayCreateRealTransaction(config: PaymentConfig): boolean {
|
|
223
|
+
return config.environment === 'production' && config.isProductionBuild;
|
|
224
|
+
}
|
package/src/core/mutex.ts
CHANGED
|
@@ -1,128 +1,25 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Concurrency primitives.
|
|
3
|
-
*
|
|
4
|
-
* These are what make three of the specification's guarantees structurally true
|
|
5
|
-
* rather than hoped for: concurrent initialization opens exactly one connection
|
|
6
|
-
* (FR-018), concurrent syncs make exactly one store request (FR-063), and a
|
|
7
|
-
* second purchase while one is open is refused rather than queued (FR-031).
|
|
8
|
-
*
|
|
9
|
-
* The distinction between the two primitives matters. `singleFlight` **joins**
|
|
10
|
-
* concurrent callers onto one operation — correct for init and sync, where every
|
|
11
|
-
* caller wants the same answer. `exclusive` **refuses** the second caller —
|
|
12
|
-
* correct for purchase, where joining would silently give two callers one
|
|
13
|
-
* transaction, and queueing would open a store surface the user no longer
|
|
14
|
-
* expects.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
inFlight(): boolean;
|
|
27
|
-
} {
|
|
28
|
-
let current: Promise<T> | undefined;
|
|
29
|
-
|
|
30
|
-
return {
|
|
31
|
-
run(operation: () => Promise<T>): Promise<T> {
|
|
32
|
-
if (current) {
|
|
33
|
-
return current;
|
|
34
|
-
}
|
|
35
|
-
const flight = operation().finally(() => {
|
|
36
|
-
if (current === flight) {
|
|
37
|
-
current = undefined;
|
|
38
|
-
}
|
|
39
|
-
});
|
|
40
|
-
current = flight;
|
|
41
|
-
return flight;
|
|
42
|
-
},
|
|
43
|
-
inFlight: () => current !== undefined,
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Distinguishes "refused because busy" from any other failure, without throwing. */
|
|
48
|
-
export type ExclusiveOutcome<T> =
|
|
49
|
-
| { acquired: true; value: T }
|
|
50
|
-
| { acquired: false };
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Admits one operation at a time and refuses the rest.
|
|
54
|
-
*
|
|
55
|
-
* Refusal is returned, not thrown, because for a purchase it is a normal
|
|
56
|
-
* outcome the app reports to the user — not an error to be caught.
|
|
57
|
-
*/
|
|
58
|
-
export function createExclusive(): {
|
|
59
|
-
run<T>(operation: () => Promise<T>): Promise<ExclusiveOutcome<T>>;
|
|
60
|
-
busy(): boolean;
|
|
61
|
-
} {
|
|
62
|
-
let held = false;
|
|
63
|
-
|
|
64
|
-
return {
|
|
65
|
-
async run<T>(operation: () => Promise<T>): Promise<ExclusiveOutcome<T>> {
|
|
66
|
-
if (held) {
|
|
67
|
-
return { acquired: false };
|
|
68
|
-
}
|
|
69
|
-
held = true;
|
|
70
|
-
try {
|
|
71
|
-
return { acquired: true, value: await operation() };
|
|
72
|
-
} finally {
|
|
73
|
-
held = false;
|
|
74
|
-
}
|
|
75
|
-
},
|
|
76
|
-
busy: () => held,
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Rate limiter for automatic foreground sync (PERF-002).
|
|
82
|
-
*
|
|
83
|
-
* Rejects rather than defers: a skipped automatic sync costs nothing because the
|
|
84
|
-
* next foreground event will try again, whereas a queue of deferred syncs would
|
|
85
|
-
* fire a burst the moment the interval elapsed — the exact storm this prevents.
|
|
86
|
-
*/
|
|
87
|
-
export function createRateLimiter(
|
|
88
|
-
minIntervalMs: number,
|
|
89
|
-
now: () => number = Date.now,
|
|
90
|
-
): { tryAcquire(): boolean; reset(): void } {
|
|
91
|
-
let lastAt: number | undefined;
|
|
92
|
-
|
|
93
|
-
return {
|
|
94
|
-
tryAcquire(): boolean {
|
|
95
|
-
const at = now();
|
|
96
|
-
if (lastAt !== undefined && at - lastAt < minIntervalMs) {
|
|
97
|
-
return false;
|
|
98
|
-
}
|
|
99
|
-
lastAt = at;
|
|
100
|
-
return true;
|
|
101
|
-
},
|
|
102
|
-
reset(): void {
|
|
103
|
-
lastAt = undefined;
|
|
104
|
-
},
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* Rejects with a `PAYMENT_TIMEOUT`-shaped error after `ms`.
|
|
110
|
-
*
|
|
111
|
-
* Always clears its timer, including on the success path: a package that leaks a
|
|
112
|
-
* timer per operation fails the cleanup guarantee (FR-082, PERF-002).
|
|
113
|
-
*/
|
|
114
|
-
export function withTimeout<T>(
|
|
115
|
-
promise: Promise<T>,
|
|
116
|
-
ms: number,
|
|
117
|
-
onTimeout: () => Error,
|
|
118
|
-
): Promise<T> {
|
|
119
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
120
|
-
const timeout = new Promise<never>((_, reject) => {
|
|
121
|
-
timer = setTimeout(() => reject(onTimeout()), ms);
|
|
122
|
-
});
|
|
123
|
-
return Promise.race([promise, timeout]).finally(() => {
|
|
124
|
-
if (timer !== undefined) {
|
|
125
|
-
clearTimeout(timer);
|
|
126
|
-
}
|
|
127
|
-
}) as Promise<T>;
|
|
128
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Concurrency primitives.
|
|
3
|
+
*
|
|
4
|
+
* These are what make three of the specification's guarantees structurally true
|
|
5
|
+
* rather than hoped for: concurrent initialization opens exactly one connection
|
|
6
|
+
* (FR-018), concurrent syncs make exactly one store request (FR-063), and a
|
|
7
|
+
* second purchase while one is open is refused rather than queued (FR-031).
|
|
8
|
+
*
|
|
9
|
+
* The distinction between the two primitives matters. `singleFlight` **joins**
|
|
10
|
+
* concurrent callers onto one operation — correct for init and sync, where every
|
|
11
|
+
* caller wants the same answer. `exclusive` **refuses** the second caller —
|
|
12
|
+
* correct for purchase, where joining would silently give two callers one
|
|
13
|
+
* transaction, and queueing would open a store surface the user no longer
|
|
14
|
+
* expects.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// The primitives themselves are rn-core's; the reasoning above is why rn-payment
|
|
18
|
+
// uses each where it does.
|
|
19
|
+
export {
|
|
20
|
+
createExclusive,
|
|
21
|
+
createRateLimiter,
|
|
22
|
+
createSingleFlight,
|
|
23
|
+
withTimeout,
|
|
24
|
+
type ExclusiveOutcome,
|
|
25
|
+
} from '@chipmobilesdk/rn-core';
|