-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathvela-wallet.ts
More file actions
297 lines (275 loc) · 8.32 KB
/
Copy pathvela-wallet.ts
File metadata and controls
297 lines (275 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { createHash } from 'node:crypto';
import type { AmrWalletSnapshot } from '@open-design/contracts';
import {
readVelaControlApiContext,
readVelaLoginStatus,
type VelaUser,
} from './vela.js';
const DEFAULT_AMR_WALLET_CACHE_TTL_MS = 8_000;
const DEFAULT_AMR_WALLET_FETCH_TIMEOUT_MS = 8_000;
const DEFAULT_AMR_API_URL = 'https://amr-api.open-design.ai';
type FetchLike = typeof fetch;
interface VelaWalletReaderOptions {
fetch?: FetchLike;
now?: () => Date;
timeoutMs?: number;
ttlMs?: number;
}
interface ReadVelaWalletSnapshotOptions {
env?: NodeJS.ProcessEnv;
configuredEnv?: Record<string, string>;
refresh?: boolean;
}
interface CachedSnapshot {
createdAtMs: number;
snapshot: AmrWalletSnapshot;
}
interface VelaWalletBalanceResponse {
balanceUsd?: unknown;
updatedAt?: unknown;
}
function isValidUsdBalance(value: unknown): value is string {
return typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value);
}
function publicUser(user: VelaUser | null): AmrWalletSnapshot['user'] {
if (!user) return null;
return {
...(user.id ? { id: user.id } : {}),
...(user.email ? { email: user.email } : {}),
...(user.name ? { name: user.name } : {}),
...(user.plan ? { plan: user.plan } : {}),
};
}
function unavailableSnapshot(input: {
code: NonNullable<AmrWalletSnapshot['error']>['code'];
fetchedAt: string;
message: string;
profile: string;
user: AmrWalletSnapshot['user'];
}): AmrWalletSnapshot {
return {
status: input.code === 'signed_out' ? 'signed_out' : 'unavailable',
profile: input.profile,
user: input.user,
balanceUsd: null,
updatedAt: null,
fetchedAt: input.fetchedAt,
stale: false,
source: 'unavailable',
error: {
code: input.code,
message: input.message,
},
};
}
function cacheKey(input: {
apiUrl: string;
configMtimeMs: number | null;
controlKey: string;
profile: string;
user: AmrWalletSnapshot['user'];
}): string {
const controlKeyDigest = createHash('sha256')
.update(input.controlKey)
.digest('hex')
.slice(0, 16);
return JSON.stringify({
profile: input.profile,
userId: input.user?.id ?? '',
userEmail: input.user?.email ?? '',
apiUrl: input.apiUrl,
configMtimeMs: input.configMtimeMs,
controlKeyDigest,
});
}
function withCacheSource(snapshot: AmrWalletSnapshot, stale: boolean): AmrWalletSnapshot {
return {
...snapshot,
source: 'daemon_cache',
stale,
};
}
function readPositiveInteger(value: string | undefined, fallback: number): number {
if (!value) return fallback;
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
return Math.floor(parsed);
}
export function createVelaWalletSnapshotReader(options: VelaWalletReaderOptions = {}) {
const fetchImpl = options.fetch ?? fetch;
const now = options.now ?? (() => new Date());
const ttlMs = options.ttlMs ?? DEFAULT_AMR_WALLET_CACHE_TTL_MS;
const cache = new Map<string, CachedSnapshot>();
const inflight = new Map<string, Promise<AmrWalletSnapshot>>();
async function fetchSnapshot(
key: string,
input: {
apiUrl: string;
controlKey: string;
profile: string;
timeoutMs: number;
user: AmrWalletSnapshot['user'];
},
): Promise<AmrWalletSnapshot> {
const fetchedAt = now().toISOString();
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), input.timeoutMs);
try {
const url = new URL('/api/v1/wallet/balance', input.apiUrl || DEFAULT_AMR_API_URL);
const response = await fetchImpl(url, {
headers: {
authorization: `Bearer ${input.controlKey}`,
},
signal: controller.signal,
});
if (response.status === 401 || response.status === 403) {
cache.delete(key);
return unavailableSnapshot({
code: 'unauthorized',
fetchedAt,
message: 'AMR wallet authorization expired. Sign in again to refresh wallet access.',
profile: input.profile,
user: input.user,
});
}
if (!response.ok) {
const cached = cache.get(key);
if (cached) {
return {
...withCacheSource(cached.snapshot, true),
error: {
code: 'upstream',
message: `AMR wallet balance is temporarily unavailable (${response.status}).`,
},
};
}
return unavailableSnapshot({
code: 'upstream',
fetchedAt,
message: `AMR wallet balance is temporarily unavailable (${response.status}).`,
profile: input.profile,
user: input.user,
});
}
const body = (await response.json()) as VelaWalletBalanceResponse;
if (!isValidUsdBalance(body.balanceUsd)) {
const cached = cache.get(key);
if (cached) {
return {
...withCacheSource(cached.snapshot, true),
error: {
code: 'upstream',
message: 'AMR wallet balance response contained an invalid balanceUsd.',
},
};
}
return unavailableSnapshot({
code: 'upstream',
fetchedAt,
message: 'AMR wallet balance response contained an invalid balanceUsd.',
profile: input.profile,
user: input.user,
});
}
const balanceUsd = body.balanceUsd;
const snapshot: AmrWalletSnapshot = {
status: 'available',
profile: input.profile,
user: input.user,
balanceUsd,
updatedAt: typeof body.updatedAt === 'string' ? body.updatedAt : null,
fetchedAt,
stale: false,
source: 'vela_api',
};
cache.set(key, { createdAtMs: now().getTime(), snapshot });
return snapshot;
} catch {
const cached = cache.get(key);
if (cached) {
return {
...withCacheSource(cached.snapshot, true),
error: {
code: 'network',
message: 'AMR wallet balance is temporarily unavailable.',
},
};
}
return unavailableSnapshot({
code: 'network',
fetchedAt,
message: 'AMR wallet balance is temporarily unavailable.',
profile: input.profile,
user: input.user,
});
} finally {
clearTimeout(timeout);
}
}
async function read(
readOptions: ReadVelaWalletSnapshotOptions = {},
): Promise<AmrWalletSnapshot> {
const env = readOptions.env ?? process.env;
const configuredEnv = readOptions.configuredEnv ?? {};
const status = readVelaLoginStatus(env, configuredEnv);
const fetchedAt = now().toISOString();
if (!status.loggedIn) {
return unavailableSnapshot({
code: 'signed_out',
fetchedAt,
message: 'Sign in to AMR to view wallet balance.',
profile: status.profile,
user: null,
});
}
const context = readVelaControlApiContext(env, configuredEnv);
if (!context) {
return unavailableSnapshot({
code: 'missing_control_key',
fetchedAt,
message: 'Sign in again to refresh AMR wallet credentials.',
profile: status.profile,
user: publicUser(status.user),
});
}
const user = publicUser(context.user ?? status.user);
const key = cacheKey({
apiUrl: context.apiUrl,
configMtimeMs: context.configMtimeMs,
controlKey: context.controlKey,
profile: context.profile,
user,
});
const cached = cache.get(key);
if (!readOptions.refresh && cached && now().getTime() - cached.createdAtMs < ttlMs) {
return withCacheSource(cached.snapshot, false);
}
const current = inflight.get(key);
if (current) return current;
const timeoutMs =
options.timeoutMs ??
readPositiveInteger(env.OD_AMR_WALLET_FETCH_TIMEOUT_MS, DEFAULT_AMR_WALLET_FETCH_TIMEOUT_MS);
const promise = fetchSnapshot(key, {
apiUrl: context.apiUrl,
controlKey: context.controlKey,
profile: context.profile,
timeoutMs,
user,
}).finally(() => {
inflight.delete(key);
});
inflight.set(key, promise);
return promise;
}
return {
clear() {
cache.clear();
inflight.clear();
},
read,
};
}
export const velaWalletSnapshotReader = createVelaWalletSnapshotReader();
export function clearVelaWalletSnapshotCache(): void {
velaWalletSnapshotReader.clear();
}