main
ply4 git calls24 ms43 KiB3 cachedprotocol v2
160 lines7.1 KiBRaw
1// R2 compare-and-swap. A lost race returns a conflict and does not apply the caller's bytes.
2// The object's ETag is the revision. There is one key.
3import { captureGroup, chainGet } from '../absent.ts';
4import { murmur3_32 } from './hash.ts';
5import { ABSENT_REVISION, FLAGS_OBJECT_KEY } from './ttl.ts';
6import { diffDocuments, encodeDocument, parseDocumentText } from './document.ts';
7import type { DiffEntry, FlagDocument, ReadResult, WriteResult } from './types.ts';
9export type StoredObject = { readonly etag: string; readonly body: string };
11export type PutCondition =
12 | { readonly kind: 'etagMatches'; readonly etag: string }
13 | { readonly kind: 'absent' };
15export type FlagStore = {
16 get(key: string): Promise<StoredObject | null>;
17 put(key: string, body: string, condition: PutCondition): Promise<StoredObject | null>;
18};
20export type R2Object = { etag: string; text(): Promise<string> };
21export type R2Put = { etag: string } | null;
22export type R2BucketLike = {
23 get(key: string): Promise<R2Object | null>;
24 put(key: string, value: string, options: { onlyIf: { etagMatches: string } | Headers; httpMetadata: { contentType: string } }): Promise<R2Put>;
25};
27function quoted(object: { readonly etag: string }): string {
28 const httpEtag = chainGet(object, 'httpEtag');
29 if (httpEtag.tag === 'some' && typeof httpEtag.value === 'string' && httpEtag.value.length > 0) return httpEtag.value;
30 return object.etag.startsWith('"') ? object.etag : `"${object.etag}"`;
33function unquote(etag: string): string {
34 const inner = captureGroup(/^"(.*)"$/.exec(etag), 1);
35 if (inner.tag === 'none') return etag;
36 return inner.value;
39function etagFor(body: string): string {
40 return `"${murmur3_32(new TextEncoder().encode(body), 0).toString(16).padStart(8, '0')}"`;
43/** In-memory CAS with the same absent / etagMatches rules as the R2 adapter. Tests and the propagation bench use it. */
44export function memoryStore(initial: StoredObject | null = null): FlagStore & { snapshot(): StoredObject | null } {
45 let current = initial;
46 return {
47 snapshot: () => current,
48 async get() {
49 return current;
50 },
51 async put(_key, body, condition) {
52 if (condition.kind === 'absent') {
53 if (current) return null;
54 } else if (!current || current.etag !== condition.etag) {
55 return null;
56 }
57 current = { etag: etagFor(body), body };
58 return current;
59 },
60 };
63/** Adapter over the Workers R2 binding. `etagMatches` uses the raw etag; callers pass the quoted revision. */
64export function r2Store(bucket: R2BucketLike): FlagStore {
65 return {
66 async get(key) {
67 const object = await bucket.get(key);
68 if (!object) return null;
69 return { etag: quoted(object), body: await object.text() };
70 },
71 async put(key, body, condition) {
72 const onlyIf = condition.kind === 'etagMatches'
73 ? { etagMatches: unquote(condition.etag) }
74 : new Headers({ 'if-none-match': '*' });
75 const stored = await bucket.put(key, body, { onlyIf, httpMetadata: { contentType: 'application/json' } });
76 if (!stored) return null;
77 return { etag: quoted(stored), body };
78 },
79 };
82export type InvalidateResult = { readonly kind: 'ok' } | { readonly kind: 'failed'; readonly reason: string };
84export type Invalidator = {
85 invalidate(): Promise<InvalidateResult>;
86};
88export type WriteLog = {
89 readonly op: 'setRollout' | 'setTargeting';
90 readonly flag: string;
91 readonly oldRevision: string | null;
92 readonly newRevision: string;
93 readonly diff: readonly DiffEntry[];
94 readonly invalidated: boolean;
95};
97async function readCurrent(store: FlagStore): Promise<{ readonly kind: 'absent' } | { readonly kind: 'ok'; readonly revision: string; readonly document: FlagDocument } | { readonly kind: 'invalid'; readonly revision: string; readonly reason: string } | { readonly kind: 'unavailable'; readonly reason: string }> {
98 let stored: StoredObject | null;
99 try {
100 stored = await store.get(FLAGS_OBJECT_KEY);
101 } catch (error) {
102 return { kind: 'unavailable', reason: error instanceof Error ? error.message : 'flag store read failed' };
103 }
104 if (!stored) return { kind: 'absent' };
105 const parsed = parseDocumentText(stored.body);
106 if (parsed.kind === 'invalid') return { kind: 'invalid', revision: stored.etag, reason: parsed.reason };
107 return { kind: 'ok', revision: stored.etag, document: parsed.document };
110export async function readConfig(store: FlagStore): Promise<ReadResult> {
111 const current = await readCurrent(store);
112 if (current.kind === 'absent') return { kind: 'absent' };
113 if (current.kind === 'unavailable') return current;
114 if (current.kind === 'invalid') return current;
115 return { kind: 'ok', revision: current.revision, config: current.document };
118export async function commitChange(
119 store: FlagStore,
120 invalidator: Invalidator,
121 expectedRevision: string,
122 edit: (document: FlagDocument) => { readonly kind: 'ok'; readonly document: FlagDocument } | { readonly kind: 'invalid'; readonly reason: string },
123 op: WriteLog['op'],
124 flag: string,
125 log: (entry: WriteLog) => void = () => {},
126): Promise<WriteResult> {
127 const current = await readCurrent(store);
128 if (current.kind === 'unavailable') return current;
129 if (current.kind === 'invalid') return current;
130 if (expectedRevision === ABSENT_REVISION) {
131 if (current.kind !== 'absent') return { kind: 'conflict', expected: ABSENT_REVISION, actual: current.revision };
132 } else if (current.kind === 'absent') {
133 return { kind: 'conflict', expected: expectedRevision, actual: null };
134 } else if (current.revision !== expectedRevision) {
135 return { kind: 'conflict', expected: expectedRevision, actual: current.revision };
136 }
137 const base = current.kind === 'ok' ? current.document : { environment: 'production' as const, flags: [] };
138 const edited = edit(base);
139 if (edited.kind === 'invalid') return { kind: 'invalid', reason: edited.reason, revision: current.kind === 'ok' ? current.revision : null };
140 const body = encodeDocument(edited.document);
141 if (current.kind === 'ok' && body === encodeDocument(current.document)) {
142 return { kind: 'ok', revision: current.revision, config: current.document, unchanged: true, invalidated: true };
143 }
144 const condition = expectedRevision === ABSENT_REVISION ? { kind: 'absent' as const } : { kind: 'etagMatches' as const, etag: expectedRevision };
145 let stored: StoredObject | null;
146 try {
147 stored = await store.put(FLAGS_OBJECT_KEY, body, condition);
148 } catch (error) {
149 return { kind: 'unavailable', reason: error instanceof Error ? error.message : 'flag store write failed' };
150 }
151 if (!stored) {
152 const again = await readCurrent(store);
153 const actual = again.kind === 'ok' || again.kind === 'invalid' ? again.revision : null;
154 return { kind: 'conflict', expected: expectedRevision, actual };
155 }
156 const invalidated = await invalidator.invalidate();
157 const diff = diffDocuments(base, edited.document);
158 log({ op, flag, oldRevision: current.kind === 'ok' ? current.revision : null, newRevision: stored.etag, diff, invalidated: invalidated.kind === 'ok' });
159 return { kind: 'ok', revision: stored.etag, config: edited.document, unchanged: false, invalidated: invalidated.kind === 'ok' };
Diagnostics4 git calls · 24 ms
CallStatusSizeTime024 ms
discover200152 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
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 · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=41349
git.response.cache=HIT
git.response.duration_ms=3
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.1 KiB · hit18 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=18
git.response.bytes=2147
git.response.cache=HIT
git.response.duration_ms=18
git.fetch.wants=8d7db5307846cefdac2946c51f9b787fa1c916d9
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=2147
git.pkt.payload.max=2126
git.sideband.band1.bytes=2125
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
a5e2f1b78f34fda9
Request
da0d2ebe…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format