main
ply4 git calls38 ms43 KiB3 cachedprotocol v2
139 lines7.0 KiBRaw
1// Read and eval over HTTP. Writes are FlagControl RPC, so PUT/POST of a ruleset is 405.
2// parse, then authorize, then execute each return a Result. json() is the only status mapping.
3import { loadRuleset, type FlagCacheEnv } from './cache.ts';
4import { flagRuntime, resolveFlags } from './client.ts';
5import { parseUnit, type AttributeInput } from './document.ts';
6import { parseFlagKey, type AttributeName, type AttributeValue, type FlagKey, type UnitId } from './brand.ts';
7import { headerNumber, jsonField, jsonRecord, readHeader } from '../http/inbound.ts';
8import { err, isUnexpected, ok, runRequest, type Result, type UnexpectedFailure } from '../http/machine.ts';
9import { variantKind, variantValue, type FlagEvaluation, type FlagSelection } from './types.ts';
11const NO_STORE = 'no-store';
12const MAX_BODY = 64 * 1024;
14function json(status: number, body: unknown): Response {
15 return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': NO_STORE } });
18function view(evaluation: FlagEvaluation) {
19 return {
20 key: evaluation.key,
21 variant: evaluation.variant,
22 variantKind: variantKind(evaluation.variant),
23 variantValue: variantValue(evaluation.variant),
24 reason: evaluation.reason,
25 bucket: evaluation.bucket,
26 };
29async function readBody(request: Request): Promise<{ readonly kind: 'ok'; readonly value: Record<string, unknown> } | { readonly kind: 'invalid'; readonly reason: string }> {
30 const length = headerNumber(readHeader(request.headers, 'content-length'));
31 if (Number.isFinite(length) && length > MAX_BODY) return { kind: 'invalid', reason: 'flag eval body is over 64 KiB' };
32 const text = await request.text();
33 if (text.length > MAX_BODY) return { kind: 'invalid', reason: 'flag eval body is over 64 KiB' };
34 if (!text.trim()) return { kind: 'invalid', reason: 'flag eval body is required' };
35 try {
36 const value = JSON.parse(text) as unknown;
37 const record = jsonRecord(value);
38 if (record.kind !== 'record') return { kind: 'invalid', reason: 'flag eval body must be an object' };
39 return { kind: 'ok', value: record.value };
40 } catch {
41 return { kind: 'invalid', reason: 'flag eval body must be JSON' };
42 }
45type FlagRoute =
46 | { readonly kind: 'rules' }
47 | { readonly kind: 'eval'; readonly id: UnitId; readonly attributes: Readonly<Record<AttributeName, AttributeValue>>; readonly keys: FlagSelection };
49type FlagBody = { readonly status: number; readonly body: unknown };
51type FlagFailure = { readonly kind: 'bad_request' | 'unsupported' | 'not_found' | 'unavailable'; readonly status: number; readonly body: unknown };
53function flagFailure(kind: FlagFailure['kind'], status: number, message: string, retry: 'yes' | 'no'): Result<never, FlagFailure> {
54 return err({ kind, status, body: { code: kind, message, retry } });
57async function parseFlagRoute(request: Request): Promise<Result<FlagRoute, FlagFailure>> {
58 const url = new URL(request.url);
59 if (url.pathname === '/v1/flags' && request.method === 'GET') return ok({ kind: 'rules' });
60 if (url.pathname === '/v1/flags' || url.pathname === '/v1/flags/eval') {
61 if (request.method !== 'POST' || url.pathname !== '/v1/flags/eval') {
62 return flagFailure('unsupported', 405, 'flag writes are FlagControl RPC (setRollout, setTargeting) via ply-flag-operator (scripts/flags), not HTTP', 'no');
63 }
64 } else {
65 return flagFailure('not_found', 404, 'no flag route', 'no');
66 }
67 const body = await readBody(request);
68 if (body.kind === 'invalid') return flagFailure('bad_request', 400, body.reason, 'no');
69 const unitField = jsonField(body.value, 'unit');
70 if (unitField.kind !== 'present' || typeof unitField.value !== 'string') return flagFailure('bad_request', 400, 'unit is required', 'no');
71 const attributesField = jsonField(body.value, 'attributes');
72 let attributes: AttributeInput = { kind: 'absent' };
73 if (attributesField.kind === 'present') {
74 const record = jsonRecord(attributesField.value);
75 if (record.kind !== 'record') return flagFailure('bad_request', 400, 'attributes must be an object', 'no');
76 attributes = { kind: 'present', value: record.value };
77 }
78 const parsed = parseUnit(unitField.value, attributes);
79 if (parsed.kind === 'invalid') return flagFailure('bad_request', 400, parsed.reason, 'no');
80 const keysField = jsonField(body.value, 'keys');
81 let keys: FlagSelection = { kind: 'all' };
82 if (keysField.kind === 'present') {
83 const listed = keysField.value;
84 if (!Array.isArray(listed) || listed.some(item => typeof item !== 'string')) {
85 return flagFailure('bad_request', 400, 'keys must be an array of flag names', 'no');
86 }
87 const values: FlagKey[] = [];
88 for (const item of listed) {
89 if (typeof item !== 'string') return flagFailure('bad_request', 400, 'keys must be an array of flag names', 'no');
90 const key = parseFlagKey(item);
91 if (key.kind !== 'key') return flagFailure('bad_request', 400, 'flag key is not valid', 'no');
92 values.push(key.value);
93 }
94 keys = { kind: 'listed', keys: values };
95 }
96 return ok({ kind: 'eval', id: parsed.id, attributes: parsed.attributes, keys });
99export async function handleFlagHttp(request: Request, env: FlagCacheEnv, ctx: unknown): Promise<Response> {
100 return runRequest(
101 {
102 parse: () => parseFlagRoute(request),
103 authorize: (route: FlagRoute) => {
104 if (!env.FLAGS) return flagFailure('unavailable', 503, 'FLAGS binding is not configured', 'yes');
105 return ok(route);
106 },
107 execute: (route: FlagRoute) => executeFlag(route, env, ctx),
108 },
109 result => flagResponse(result),
110 );
113async function executeFlag(route: FlagRoute, env: FlagCacheEnv, ctx: unknown): Promise<Result<FlagBody, FlagFailure>> {
114 const runtime = flagRuntime(env, ctx);
115 if (route.kind === 'rules') {
116 const loaded = await loadRuleset(env, runtime.cache);
117 if (loaded.kind === 'unavailable') return flagFailure('unavailable', 503, loaded.reason, 'yes');
118 if (loaded.kind === 'absent') return flagFailure('not_found', 404, 'no flag config', 'no');
119 return ok({ status: 200, body: { revision: loaded.revision, cache: loaded.cache, environment: loaded.document.environment, flags: loaded.document.flags } });
120 }
121 const resolved = await resolveFlags(
122 runtime,
123 { id: route.id, attributes: route.attributes },
124 route.keys,
125 );
126 if (resolved.kind === 'unavailable') return flagFailure('unavailable', 503, resolved.reason, 'yes');
127 return ok({ status: 200, body: { revision: resolved.revision, cache: resolved.cache, flags: resolved.evaluations.map(view) } });
130function flagResponse(result: Result<FlagBody, FlagFailure | UnexpectedFailure>): Response {
131 if (!result.ok) {
132 if (isUnexpected(result.error)) {
133 console.log(JSON.stringify({ msg: 'ply.flags', error_kind: result.error.kind, stage: result.error.stage, error_name: result.error.name }));
134 return json(500, { code: 'internal', message: 'The request hit an unexpected error.', retry: 'no' });
135 }
136 return json(result.error.status, result.error.body);
137 }
138 return json(result.value.status, result.value.body);
Diagnostics4 git calls · 38 ms
CallStatusSizeTime038 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=61
Open pack map
fetch2002.2 KiB · hit33 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=33
git.response.bytes=2281
git.response.cache=HIT
git.response.duration_ms=33
git.fetch.wants=bf75798c8b411a775958b1b100ed57a4a56db395
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=2281
git.pkt.payload.max=2260
git.sideband.band1.bytes=2259
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
a5e23d403fca4bc2
Request
22f81ed3…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format