-
Notifications
You must be signed in to change notification settings - Fork 522
Expand file tree
/
Copy pathroute.ts
More file actions
114 lines (108 loc) · 4.53 KB
/
Copy pathroute.ts
File metadata and controls
114 lines (108 loc) · 4.53 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
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import type { SmartResponse } from "@/route-handlers/smart-response";
import { _internal as hashingInternal } from "@stackframe/stack-shared/dist/feature-flags/hashing";
import type { FeatureFlagsConfig, FlagDef } from "@stackframe/stack-shared/dist/feature-flags/types";
import { adaptSchema, clientOrHigherAuthTypeSchema, yupArray, yupMixed, yupNumber, yupObject, yupString, yupUnion } from "@stackframe/stack-shared/dist/schema-fields";
import { stringCompare } from "@stackframe/stack-shared/dist/utils/strings";
import type { Schema } from "yup";
function deepSortKeys(value: unknown): unknown {
if (Array.isArray(value)) return value.map(deepSortKeys);
if (value == null || typeof value !== "object") return value;
return Object.fromEntries(
Object.entries(value)
.sort(([a], [b]) => stringCompare(a, b))
.map(([key, nestedValue]) => [key, deepSortKeys(nestedValue)]),
);
}
export const GET = createSmartRouteHandler({
metadata: {
hidden: true,
summary: "Bootstrap feature flag definitions for SDK local evaluation",
description: "Returns the full set of feature flag definitions for the resolved tenancy. Clients cache the payload and evaluate locally; the server's evaluator and the SDK's evaluator are byte-identical.",
tags: ["Feature Flags"],
},
request: yupObject({
auth: yupObject({
type: clientOrHigherAuthTypeSchema.defined(),
tenancy: adaptSchema.defined(),
}).defined(),
headers: yupObject({
"if-none-match": yupArray(yupString().defined()).optional(),
}).defined(),
method: yupString().oneOf(["GET"]).defined(),
}),
response: yupUnion(
yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["binary"]).defined(),
body: yupMixed<Uint8Array>().defined(),
headers: yupObject({
"content-type": yupArray(yupString().defined()).defined(),
etag: yupArray(yupString().defined()).defined(),
}).defined(),
}).defined(),
yupObject({
statusCode: yupNumber().oneOf([304]).defined(),
bodyType: yupString().oneOf(["empty"]).defined(),
headers: yupObject({
etag: yupArray(yupString().defined()).defined(),
}).defined(),
}).defined(),
) as unknown as Schema<SmartResponse>,
handler: async ({ auth, headers }) => {
const config: FeatureFlagsConfig = auth.tenancy.config.featureFlags;
const flagsById: Record<string, Omit<FlagDef, "ownerUserId">> = {};
const flagIdsByKey: Record<string, string> = {};
for (const [id, def] of Object.entries(config.flags ?? {})) {
if (!def?.key) continue;
// ownerUserId is operator-facing metadata, never needed for evaluation. Strip it from the
// bootstrap payload so we don't leak admin user ids to client SDKs.
const { ownerUserId: _ownerUserId, ...rest } = def;
flagsById[id] = rest;
flagIdsByKey[def.key] = id;
}
const holdouts = config.holdouts ?? {};
// Stable content-addressed version: SDKs hit this endpoint with `If-None-Match: <version>` and
// we (eventually) 304 when nothing changed. Using murmur3 keeps this fast enough to recompute
// per request without caching.
const versionPayload = deepSortKeys({ flags: flagsById, flagIdsByKey, holdouts });
const version = hashingInternal.murmur3_32(JSON.stringify(versionPayload)).toString(16);
const etag = `"${version}"`;
const ifNoneMatchTags = parseIfNoneMatch(headers["if-none-match"] ?? []);
if (ifNoneMatchTags.has("*") || ifNoneMatchTags.has(etag) || ifNoneMatchTags.has(version)) {
const responseHeaders: Record<string, string[]> = {
etag: [etag],
};
return {
statusCode: 304,
bodyType: "empty",
headers: responseHeaders,
};
}
const body = {
flags: flagsById,
flag_ids_by_key: flagIdsByKey,
holdouts,
version,
};
const responseHeaders: Record<string, string[]> = {
"content-type": ["application/json; charset=utf-8"],
etag: [etag],
};
return {
statusCode: 200,
bodyType: "binary",
body: new TextEncoder().encode(JSON.stringify(body)),
headers: responseHeaders,
};
},
});
function parseIfNoneMatch(values: string[]) {
return new Set(values.flatMap((value) => (
value
.split(",")
.map((tag) => tag.trim())
.map((tag) => tag.startsWith("W/") ? tag.slice(2).trim() : tag)
.map((tag) => tag.startsWith("\"") && tag.endsWith("\"") ? tag.slice(1, -1) : tag)
)));
}