main
1// Parse, validate, and edit the one ruleset. Edits are pure: the caller compare-and-swaps the encoded bytes.
2// Flag keys, unit ids, attribute tokens, and salts are branded once, in brand.ts.
3import {
4 parseAttributeName,
5 parseAttributeValue,
6 parseFlagKey,
7 parseFlagSalt,
8 parseUnitId,
9 type AttributeName,
10 type AttributeValue,
11 type FlagKey,
12 type UnitId,
13} from './brand.ts';
14import { BASIS_POINTS, DEFAULT_SALT, MAX_ATTRIBUTES, MAX_DOCUMENT_BYTES, MAX_FLAGS, MAX_RULES, MAX_UNITS } from './ttl.ts';
15import {
16 EMPTY_DOCUMENT,
17 type AttributeRule,
18 type DiffEntry,
19 type Flag,
20 type FlagDocument,
21 type Invalid,
22 type Rollout,
23 type Targeting,
24 type Variant,
25} from './types.ts';
27const ROLLBACK_REASON = /^[\x20-\x7e]{1,200}$/;
29type Obj = Record<string, unknown>;
31function invalid(reason: string): Invalid {
32 return { kind: 'invalid', reason };
33}
35function isInvalid(value: unknown): value is Invalid {
36 return !!value && typeof value === 'object' && (value as Invalid).kind === 'invalid' && typeof (value as Invalid).reason === 'string';
37}
39function isObj(value: unknown): value is Obj {
40 return !!value && typeof value === 'object' && !Array.isArray(value);
41}
43function exactKeys(value: Obj, allowed: readonly string[]): boolean {
44 const keys = Object.keys(value);
45 return keys.length === allowed.length && allowed.every(key => keys.includes(key));
46}
48function parseVariant(value: unknown): Variant | Invalid {
49 if (!isObj(value) || typeof value.kind !== 'string') return invalid('variant must be a typed object');
50 if (value.kind === 'boolean') {
51 if (!exactKeys(value, ['kind', 'value']) || typeof value.value !== 'boolean') return invalid('boolean variant is {kind, value}');
52 return { kind: 'boolean', value: value.value };
53 }
54 if (value.kind === 'string') {
55 if (!exactKeys(value, ['kind', 'value']) || typeof value.value !== 'string') return invalid('string variant is a short printable token');
56 const parsed = parseAttributeValue(value.value);
57 if (parsed.kind !== 'value') return invalid('string variant is a short printable token');
58 return { kind: 'string', value: parsed.value };
59 }
60 if (value.kind === 'number') {
61 if (!exactKeys(value, ['kind', 'value']) || typeof value.value !== 'number' || !Number.isFinite(value.value)) return invalid('number variant must be finite');
62 return { kind: 'number', value: value.value };
63 }
64 return invalid('variant kind must be boolean, string, or number');
65}
67function parseStringList(value: unknown, label: string): readonly UnitId[] | Invalid {
68 if (!Array.isArray(value)) return invalid(`${label} must be an array`);
69 if (value.length > MAX_UNITS) return invalid(`${label} is longer than ${MAX_UNITS}`);
70 const seen = new Set<UnitId>();
71 const ids: UnitId[] = [];
72 for (const item of value) {
73 if (typeof item !== 'string') return invalid(`${label} entries are unit ids`);
74 const parsed = parseUnitId(item);
75 if (parsed.kind !== 'id') return invalid(`${label} entries are unit ids`);
76 if (seen.has(parsed.value)) return invalid(`${label} contains a duplicate`);
77 seen.add(parsed.value);
78 ids.push(parsed.value);
79 }
80 return ids;
81}
83function parseRule(value: unknown): AttributeRule | Invalid {
84 if (!isObj(value)) return invalid('a rule must be an object');
85 if (!exactKeys(value, ['attribute', 'op', 'value', 'variant'])) return invalid('a rule is {attribute, op, value, variant}');
86 if (typeof value.attribute !== 'string') return invalid('rule attribute is a short name');
87 const attribute = parseAttributeName(value.attribute);
88 if (attribute.kind !== 'name') return invalid('rule attribute is a short name');
89 if (value.op !== 'eq' && value.op !== 'neq' && value.op !== 'in') return invalid('rule op must be eq, neq, or in');
90 const variant = parseVariant(value.variant);
91 if ('kind' in variant && variant.kind === 'invalid') return variant;
92 if (value.op === 'in') {
93 if (!Array.isArray(value.value) || value.value.length < 1 || value.value.length > 32) return invalid('in rules need a value list');
94 const items: AttributeValue[] = [];
95 for (const item of value.value) {
96 if (typeof item !== 'string') return invalid('in-rule values are short tokens');
97 const parsed = parseAttributeValue(item);
98 if (parsed.kind !== 'value') return invalid('in-rule values are short tokens');
99 items.push(parsed.value);
100 }
101 return { attribute: attribute.value, op: 'in', value: items, variant: variant as Variant };
102 }
103 if (typeof value.value !== 'string') return invalid('eq and neq compare one token');
104 const compared = parseAttributeValue(value.value);
105 if (compared.kind !== 'value') return invalid('eq and neq compare one token');
106 return { attribute: attribute.value, op: value.op, value: compared.value, variant: variant as Variant };
107}
109function basisPoint(value: unknown): number | Invalid {
110 if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value >= BASIS_POINTS) return invalid(`ramping basisPoints is an integer from 1 to ${BASIS_POINTS - 1}`);
111 return value;
112}
114function parseRollout(value: unknown): Rollout | Invalid {
115 if (!isObj(value) || typeof value.kind !== 'string') return invalid('rollout must be an object');
116 if (value.kind === 'rolled-back') {
117 if (!exactKeys(value, ['kind', 'reason'])) return invalid('rolled-back rollout is {kind, reason}');
118 if (typeof value.reason !== 'string' || !ROLLBACK_REASON.test(value.reason)) return invalid('rollback reason must be printable');
119 return { kind: 'rolled-back', reason: value.reason };
120 }
121 if (value.kind === 'complete') {
122 if (!exactKeys(value, ['kind'])) return invalid('complete rollout is {kind}');
123 return { kind: 'complete' };
124 }
125 if (value.kind === 'ramping') {
126 if (!exactKeys(value, ['kind', 'basisPoints'])) return invalid('ramping rollout is {kind, basisPoints}');
127 const basisPoints = basisPoint(value.basisPoints);
128 if (typeof basisPoints !== 'number') return basisPoints;
129 return { kind: 'ramping', basisPoints };
130 }
131 return invalid('rollout kind must be ramping, complete, or rolled-back');
132}
134function parseFlag(value: unknown): Flag | Invalid {
135 if (!isObj(value)) return invalid('a flag must be an object');
136 if (!exactKeys(value, ['key', 'salt', 'rollout', 'on', 'off', 'allow', 'deny', 'rules'])) return invalid('a flag has key, salt, rollout, on, off, allow, deny, rules');
137 if (typeof value.key !== 'string') return invalid('flag key must match ^[a-z][a-z0-9._-]{0,63}$');
138 const key = parseFlagKey(value.key);
139 if (key.kind !== 'key') return key;
140 if (typeof value.salt !== 'string') return invalid('flag salt is a short token');
141 const salt = parseFlagSalt(value.salt);
142 if (salt.kind !== 'salt') return invalid('flag salt is a short token');
143 const rollout = parseRollout(value.rollout);
144 if (isInvalid(rollout)) return rollout;
145 const on = parseVariant(value.on);
146 if (isInvalid(on)) return on;
147 const off = parseVariant(value.off);
148 if (isInvalid(off)) return off;
149 const allow = parseStringList(value.allow, 'allow');
150 if (isInvalid(allow)) return allow;
151 const deny = parseStringList(value.deny, 'deny');
152 if (isInvalid(deny)) return deny;
153 if (!Array.isArray(value.rules)) return invalid('rules must be an array');
154 if (value.rules.length > MAX_RULES) return invalid(`a flag has at most ${MAX_RULES} rules`);
155 const rules: AttributeRule[] = [];
156 for (const rule of value.rules) {
157 const parsed = parseRule(rule);
158 if (isInvalid(parsed)) return parsed;
159 rules.push(parsed);
160 }
161 return { key: key.value, salt: salt.value, rollout, on, off, allow, deny, rules };
162}
164export type ParsedDocument = { readonly kind: 'ok'; readonly document: FlagDocument } | Invalid;
166export function parseDocument(value: unknown): ParsedDocument {
167 if (!isObj(value)) return invalid('flag config must be an object');
168 if (!exactKeys(value, ['environment', 'flags'])) return invalid('flag config is {environment, flags}');
169 if (value.environment !== 'production') return invalid('environment must be production');
170 if (!Array.isArray(value.flags)) return invalid('flags must be an array');
171 if (value.flags.length > MAX_FLAGS) return invalid(`at most ${MAX_FLAGS} flags`);
172 const flags: Flag[] = [];
173 const seen = new Set<string>();
174 for (const item of value.flags) {
175 const flag = parseFlag(item);
176 if (isInvalid(flag)) return flag;
177 if (seen.has(flag.key)) return invalid(`duplicate flag ${flag.key}`);
178 seen.add(flag.key);
179 flags.push(flag);
180 }
181 return { kind: 'ok', document: { environment: 'production', flags } };
182}
184export function parseDocumentText(text: string): ParsedDocument {
185 if (text.length > MAX_DOCUMENT_BYTES) return invalid('flag config is over 64 KiB');
186 let value: unknown;
187 try {
188 value = JSON.parse(text) as unknown;
189 } catch {
190 return invalid('flag config is not JSON');
191 }
192 return parseDocument(value);
193}
195export function stableStringify(value: unknown): string {
196 if (Array.isArray(value)) return `[${value.map(item => stableStringify(item)).join(',')}]`;
197 if (value && typeof value === 'object') {
198 const record = value as Obj;
199 const keys = Object.keys(record).sort();
200 return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
201 }
202 return JSON.stringify(value);
203}
205export function encodeDocument(document: FlagDocument): string {
206 return stableStringify(document);
207}
209export type AttributeInput =
210 | { readonly kind: 'absent' }
211 | { readonly kind: 'present'; readonly value: Readonly<Record<string, unknown>> };
213export function parseUnit(id: string, attributes: AttributeInput): { readonly kind: 'ok'; readonly id: UnitId; readonly attributes: Readonly<Record<AttributeName, AttributeValue>> } | Invalid {
214 const parsedId = parseUnitId(id);
215 if (parsedId.kind !== 'id') return invalid(parsedId.reason);
216 const source = attributes.kind === 'present' ? attributes.value : {};
217 const names = Object.keys(source);
218 if (names.length > MAX_ATTRIBUTES) return invalid(`at most ${MAX_ATTRIBUTES} attributes`);
219 const clean: Record<AttributeName, AttributeValue> = {};
220 for (const name of names) {
221 const parsedName = parseAttributeName(name);
222 if (parsedName.kind !== 'name') return invalid('attribute names are short tokens');
223 const attr = source[name];
224 if (typeof attr !== 'string') return invalid('attribute values are short tokens');
225 const parsedValue = parseAttributeValue(attr);
226 if (parsedValue.kind !== 'value') return invalid('attribute values are short tokens');
227 clean[parsedName.value] = parsedValue.value;
228 }
229 return { kind: 'ok', id: parsedId.value, attributes: clean };
230}
232function findFlag(document: FlagDocument, key: FlagKey): Flag | null {
233 for (const flag of document.flags) {
234 if (flag.key === key) return flag;
235 }
236 return null;
237}
239export function freshFlag(key: FlagKey): Flag {
240 return {
241 key,
242 salt: DEFAULT_SALT,
243 rollout: { kind: 'rolled-back', reason: 'created' },
244 on: { kind: 'boolean', value: true },
245 off: { kind: 'boolean', value: false },
246 allow: [],
247 deny: [],
248 rules: [],
249 };
250}
252export function applyBasisPoints(basisPoints: number): { readonly kind: 'ok'; readonly rollout: Rollout } | Invalid {
253 if (!Number.isInteger(basisPoints) || basisPoints < 0 || basisPoints > BASIS_POINTS) return invalid(`basis points must be an integer from 0 to ${BASIS_POINTS}`);
254 if (basisPoints === 0) return { kind: 'ok', rollout: { kind: 'rolled-back', reason: 'basis points 0' } };
255 if (basisPoints === BASIS_POINTS) return { kind: 'ok', rollout: { kind: 'complete' } };
256 return { kind: 'ok', rollout: { kind: 'ramping', basisPoints } };
257}
259export type Changed = { readonly kind: 'ok'; readonly document: FlagDocument } | Invalid;
261export function applyRollout(document: FlagDocument, key: FlagKey, basisPoints: number): Changed {
262 const existing = findFlag(document, key);
263 const base = existing === null ? freshFlag(key) : existing;
264 const applied = applyBasisPoints(basisPoints);
265 if (applied.kind === 'invalid') return applied;
266 const next: Flag = { ...base, rollout: applied.rollout };
267 const flags = existing ? document.flags.map(flag => flag.key === key ? next : flag) : [...document.flags, next];
268 if (flags.length > MAX_FLAGS) return invalid(`at most ${MAX_FLAGS} flags`);
269 return { kind: 'ok', document: { environment: document.environment, flags } };
270}
272export function parseTargeting(value: unknown): Targeting | Invalid {
273 if (!isObj(value) || !exactKeys(value, ['allow', 'deny', 'rules'])) return invalid('targeting is {allow, deny, rules}');
274 const allow = parseStringList(value.allow, 'allow');
275 if (isInvalid(allow)) return allow;
276 const deny = parseStringList(value.deny, 'deny');
277 if (isInvalid(deny)) return deny;
278 if (!Array.isArray(value.rules)) return invalid('rules must be an array');
279 if (value.rules.length > MAX_RULES) return invalid(`a flag has at most ${MAX_RULES} rules`);
280 const rules: AttributeRule[] = [];
281 for (const rule of value.rules) {
282 const parsed = parseRule(rule);
283 if (isInvalid(parsed)) return parsed;
284 rules.push(parsed);
285 }
286 return { allow, deny, rules };
287}
289export function applyTargeting(document: FlagDocument, key: FlagKey, targeting: Targeting): Changed {
290 const existing = findFlag(document, key);
291 if (existing === null) return invalid(`unknown flag ${key}`);
292 const next: Flag = { ...existing, allow: targeting.allow, deny: targeting.deny, rules: targeting.rules };
293 return { kind: 'ok', document: { environment: document.environment, flags: document.flags.map(flag => flag.key === key ? next : flag) } };
294}
296function targetingOf(flag: Flag): Targeting {
297 return { allow: flag.allow, deny: flag.deny, rules: flag.rules };
298}
300export function diffDocuments(before: FlagDocument, after: FlagDocument): readonly DiffEntry[] {
301 const previous = new Map(before.flags.map(flag => [flag.key, flag]));
302 const diffs: DiffEntry[] = [];
303 for (const flag of after.flags) {
304 const old = previous.get(flag.key);
305 if (!old) {
306 diffs.push({ op: 'create', key: flag.key, after: { rollout: flag.rollout, allow: flag.allow, deny: flag.deny } });
307 continue;
308 }
309 if (stableStringify(old.rollout) !== stableStringify(flag.rollout)) diffs.push({ op: 'rollout', key: flag.key, before: old.rollout, after: flag.rollout });
310 if (stableStringify(targetingOf(old)) !== stableStringify(targetingOf(flag))) diffs.push({ op: 'targeting', key: flag.key, before: targetingOf(old), after: targetingOf(flag) });
311 }
312 return diffs;
313}
315export function emptyDocument(): FlagDocument {
316 return EMPTY_DOCUMENT;
317}
Diagnostics4 git calls · 61 ms
CallStatusSizeTime061 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=145 git.response.cache=HIT git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020040 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=41349 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=526b305930b8ef382f2d7a1f9c0238730a585921 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=41349 git.pkt.payload.max=41254 git.sideband.band1.bytes=41253 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=61 git.pack.bytes=41253 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=ab60efef4b7243678c75de64a4386986ee885c1c git.pack.full=61Open pack map
fetch2003.5 KiB · hit56 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=56 git.response.bytes=3542 git.response.cache=HIT git.response.duration_ms=56 git.fetch.wants=860f4a13343ebb0b10d83b6f4b2050c2c1d52725 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=3542 git.pkt.payload.max=3521 git.sideband.band1.bytes=3520 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply-web.git
- Ref
- refs/heads/main
- Commit
- 526b305930b8ef382f2d7a1f9c0238730a585921
- cf-ray
- a5e23d20ecb44bc2
- Request
- 4b8052a8…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format