-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathflagsFallbackProvider.ts
More file actions
570 lines (505 loc) · 13.6 KB
/
flagsFallbackProvider.ts
File metadata and controls
570 lines (505 loc) · 13.6 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
import { promises as fs } from "fs";
import path from "path";
import type {
FlagAPIResponse,
FlagsFallbackProvider,
FlagsFallbackProviderContext,
FlagsFallbackSnapshot,
} from "./types";
import { isObject } from "./utils";
export type FileFallbackProviderOptions = {
/**
* Directory where per-environment snapshots are stored.
*
* @defaultValue `path.join(process.cwd(), ".reflag")`
*/
directory?: string;
};
export type S3FallbackProviderOptions = {
/**
* Bucket where snapshots are stored.
*/
bucket: string;
/**
* Optional S3 client. A default client is created when omitted.
*/
client?: {
send(command: unknown): Promise<any>;
};
/**
* Prefix for generated per-environment keys.
*
* @defaultValue `reflag/flags-fallback`
*/
keyPrefix?: string;
};
export type GCSLegacyClient = {
bucket(name: string): {
file(path: string): {
exists(): Promise<[boolean]>;
download(): Promise<[Uint8Array]>;
save(body: string, options: { contentType: string }): Promise<unknown>;
};
};
};
export type GCSGoogleApisClient = {
objects: {
get(
params: {
bucket: string;
object: string;
alt?: string;
},
options?: {
responseType?: "arraybuffer";
},
): Promise<{
data: unknown;
}>;
insert(params: {
bucket: string;
name: string;
uploadType: "media";
media: {
mimeType: string;
body: string;
};
}): Promise<unknown>;
};
};
export type GCSFallbackProviderClient = GCSLegacyClient | GCSGoogleApisClient;
export type GCSFallbackProviderOptions = {
/**
* Bucket where snapshots are stored.
*/
bucket: string;
/**
* Optional GCS client. A default client is created when omitted.
*
* Accepts either a legacy `bucket().file()` client or a generated
* `@googleapis/storage` client.
*
* TODO(next major): Replace this with a simpler object-store interface.
*/
client?: GCSFallbackProviderClient;
/**
* Prefix for generated per-environment keys.
*
* @defaultValue `reflag/flags-fallback`
*/
keyPrefix?: string;
};
type GCSObjectStore = {
exists(bucket: string, objectPath: string): Promise<boolean>;
download(bucket: string, objectPath: string): Promise<Uint8Array>;
save(
bucket: string,
objectPath: string,
body: string,
options: { contentType: string },
): Promise<unknown>;
};
export type RedisFallbackProviderOptions = {
/**
* Optional Redis client. When omitted, a client is created using `REDIS_URL`.
*/
client?: {
get(key: string): Promise<string | null | undefined>;
set(key: string, value: string): Promise<unknown>;
};
/**
* Prefix for generated per-environment keys.
*
* @defaultValue `reflag:flags-fallback`
*/
keyPrefix?: string;
};
export type StaticFallbackProviderOptions = {
/**
* Static fallback flags keyed by flag key.
*/
flags: Record<string, boolean>;
};
function defaultSnapshotName(secretKeyHash: string) {
return `flags-fallback-${secretKeyHash.slice(0, 16)}.json`;
}
function snapshotFilePath(
context: FlagsFallbackProviderContext,
directory = path.join(process.cwd(), ".reflag"),
) {
return path.join(directory, defaultSnapshotName(context.secretKeyHash));
}
function trimTrailingCharacter(value: string, character: string) {
let endIndex = value.length;
while (endIndex > 0 && value[endIndex - 1] === character) {
endIndex -= 1;
}
return value.slice(0, endIndex);
}
function snapshotObjectKey(
context: FlagsFallbackProviderContext,
keyPrefix = "reflag/flags-fallback",
) {
return `${trimTrailingCharacter(keyPrefix, "/")}/${defaultSnapshotName(context.secretKeyHash)}`;
}
function snapshotRedisKey(
context: FlagsFallbackProviderContext,
keyPrefix = "reflag:flags-fallback",
) {
return `${trimTrailingCharacter(keyPrefix, ":")}:${context.secretKeyHash.slice(0, 16)}`;
}
export function isFlagsFallbackSnapshot(
value: unknown,
): value is FlagsFallbackSnapshot {
return (
isObject(value) &&
value.version === 1 &&
typeof value.savedAt === "string" &&
Array.isArray(value.flags) &&
value.flags.every(isFlagApiResponse)
);
}
function isFlagApiResponse(value: unknown): value is FlagAPIResponse {
return (
isObject(value) &&
typeof value.key === "string" &&
typeof value.description !== "undefined" &&
isObject(value.targeting) &&
typeof value.targeting.version === "number" &&
Array.isArray(value.targeting.rules) &&
(value.config === undefined ||
(isObject(value.config) &&
typeof value.config.version === "number" &&
Array.isArray(value.config.variants)))
);
}
async function readBodyAsString(body: unknown) {
if (typeof body === "string") return body;
if (body instanceof Uint8Array) return Buffer.from(body).toString("utf-8");
if (body instanceof ArrayBuffer) return Buffer.from(body).toString("utf-8");
if (ArrayBuffer.isView(body)) {
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString(
"utf-8",
);
}
if (body && typeof body === "object") {
if (
"transformToString" in body &&
typeof body.transformToString === "function"
) {
return await body.transformToString();
}
}
return undefined;
}
function parseSnapshot(raw: string) {
const parsed = JSON.parse(raw);
return isFlagsFallbackSnapshot(parsed) ? parsed : undefined;
}
function isNotFoundError(error: any) {
return (
error?.code === 404 ||
error?.status === 404 ||
error?.response?.status === 404 ||
error?.$metadata?.httpStatusCode === 404
);
}
function staticFlagApiResponse(
key: string,
isEnabled: boolean,
): FlagAPIResponse {
return {
key,
description: null,
targeting: {
version: 1,
rules: [
{
filter: {
type: "constant",
value: isEnabled,
},
},
],
},
};
}
async function createDefaultS3Client() {
const { S3Client } = await import("@aws-sdk/client-s3");
return new S3Client({});
}
function createLegacyGCSObjectStore(client: GCSLegacyClient): GCSObjectStore {
return {
async exists(bucket, objectPath) {
const [exists] = await client.bucket(bucket).file(objectPath).exists();
return exists;
},
async download(bucket, objectPath) {
const [contents] = await client
.bucket(bucket)
.file(objectPath)
.download();
return contents;
},
async save(bucket, objectPath, body, options) {
return client.bucket(bucket).file(objectPath).save(body, options);
},
};
}
function createGoogleApisGCSObjectStore(
client: GCSGoogleApisClient,
): GCSObjectStore {
return {
async exists(bucket, objectPath) {
try {
await client.objects.get({
bucket,
object: objectPath,
});
return true;
} catch (error) {
if (isNotFoundError(error)) {
return false;
}
throw error;
}
},
async download(bucket, objectPath) {
const response = await client.objects.get(
{
bucket,
object: objectPath,
alt: "media",
},
{
responseType: "arraybuffer",
},
);
if (response.data instanceof Uint8Array) {
return response.data;
}
if (response.data instanceof ArrayBuffer) {
return new Uint8Array(response.data);
}
throw new TypeError("Unexpected GCS download response body format");
},
async save(bucket, objectPath, body, options) {
await client.objects.insert({
bucket,
name: objectPath,
uploadType: "media",
media: {
mimeType: options.contentType,
body,
},
});
},
};
}
function isGoogleApisGCSClient(
client: GCSFallbackProviderClient,
): client is GCSGoogleApisClient {
return (
"objects" in client &&
isObject(client.objects) &&
typeof client.objects.get === "function" &&
typeof client.objects.insert === "function"
);
}
function createGCSObjectStore(
client: GCSFallbackProviderClient,
): GCSObjectStore {
if (isGoogleApisGCSClient(client)) {
return createGoogleApisGCSObjectStore(client);
}
return createLegacyGCSObjectStore(client);
}
async function createDefaultGCSObjectStore(): Promise<GCSObjectStore> {
const { auth, storage } = await import("@googleapis/storage");
return createGoogleApisGCSObjectStore(
storage({
version: "v1",
auth: new auth.GoogleAuth({
scopes: ["https://www.googleapis.com/auth/devstorage.read_write"],
}),
}),
);
}
export function createStaticFallbackProvider({
flags,
}: StaticFallbackProviderOptions): FlagsFallbackProvider {
return {
async load() {
return {
version: 0,
savedAt: new Date().toISOString(),
flags: Object.entries(flags).map(([key, isEnabled]) =>
staticFlagApiResponse(key, isEnabled),
),
};
},
async save() {
// no-op
},
};
}
export function createFileFallbackProvider({
directory,
}: FileFallbackProviderOptions = {}): FlagsFallbackProvider {
return {
async load(context) {
const resolvedPath = snapshotFilePath(context, directory);
try {
const fileContents = await fs.readFile(resolvedPath, "utf-8");
return parseSnapshot(fileContents);
} catch (error: any) {
if (error?.code === "ENOENT") {
return undefined;
}
throw error;
}
},
async save(context, snapshot) {
const resolvedPath = snapshotFilePath(context, directory);
await fs.mkdir(path.dirname(resolvedPath), { recursive: true });
const tempPath = `${resolvedPath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
await fs.writeFile(tempPath, JSON.stringify(snapshot), "utf-8");
await fs.rename(tempPath, resolvedPath);
},
};
}
export function createS3FallbackProvider({
bucket,
client,
keyPrefix,
}: S3FallbackProviderOptions): FlagsFallbackProvider {
let defaultClient:
| {
send(command: unknown): Promise<any>;
}
| undefined;
const getClient = async () => {
defaultClient ??= client ?? (await createDefaultS3Client());
return defaultClient;
};
return {
async load(context) {
const s3 = await getClient();
const { GetObjectCommand } = await import("@aws-sdk/client-s3");
try {
const response = await s3.send(
new GetObjectCommand({
Bucket: bucket,
Key: snapshotObjectKey(context, keyPrefix),
}),
);
const body = await readBodyAsString(response.Body);
if (!body) return undefined;
return parseSnapshot(body);
} catch (error: any) {
if (error?.name === "NoSuchKey" || isNotFoundError(error)) {
return undefined;
}
throw error;
}
},
async save(context, snapshot) {
const s3 = await getClient();
const { PutObjectCommand } = await import("@aws-sdk/client-s3");
await s3.send(
new PutObjectCommand({
Bucket: bucket,
Key: snapshotObjectKey(context, keyPrefix),
Body: JSON.stringify(snapshot),
ContentType: "application/json",
}),
);
},
};
}
export function createGCSFallbackProvider({
bucket,
client,
keyPrefix,
}: GCSFallbackProviderOptions): FlagsFallbackProvider {
let defaultClient: GCSObjectStore | undefined;
const getClient = async () => {
defaultClient ??= client
? createGCSObjectStore(client)
: await createDefaultGCSObjectStore();
return defaultClient;
};
return {
async load(context) {
const storage = await getClient();
const objectKey = snapshotObjectKey(context, keyPrefix);
const exists = await storage.exists(bucket, objectKey);
if (!exists) {
return undefined;
}
const contents = await storage.download(bucket, objectKey);
return parseSnapshot(Buffer.from(contents).toString("utf-8"));
},
async save(context, snapshot) {
const storage = await getClient();
await storage.save(
bucket,
snapshotObjectKey(context, keyPrefix),
JSON.stringify(snapshot),
{
contentType: "application/json",
},
);
},
};
}
export function createRedisFallbackProvider({
client,
keyPrefix,
}: RedisFallbackProviderOptions = {}): FlagsFallbackProvider {
let defaultClient:
| {
get(key: string): Promise<string | null | undefined>;
set(key: string, value: string): Promise<unknown>;
connect(): Promise<unknown>;
isOpen: boolean;
}
| undefined;
let connectPromise: Promise<unknown> | undefined;
const getClient = async () => {
if (client) {
return client;
}
if (!process.env.REDIS_URL) {
throw new Error(
"fallbackProviders.redis() requires REDIS_URL to be set when no client is provided",
);
}
if (!defaultClient) {
const { createClient } = await import("@redis/client");
defaultClient = createClient({ url: process.env.REDIS_URL });
}
if (!defaultClient.isOpen) {
connectPromise ??= defaultClient.connect();
await connectPromise;
}
return defaultClient;
};
return {
async load(context) {
const redis = await getClient();
const raw = await redis.get(snapshotRedisKey(context, keyPrefix));
if (!raw) {
return undefined;
}
return parseSnapshot(raw);
},
async save(context, snapshot) {
const redis = await getClient();
await redis.set(
snapshotRedisKey(context, keyPrefix),
JSON.stringify(snapshot),
);
},
};
}