g1t/services/repos/src/store.rs

1,326 lines57,071 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Rust repos service with shipping; pull requests kept in the model1//! The storage that actually holds git repositories.
2//!
3//! The service depends on the [`GitStore`] and [`GitRepo`] ports;
4//! [`ArtifactsStore`] is the adapter for Cloudflare Artifacts.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily5//!
6//! Every call on the binding goes through [`invoke`]: it is counted
7//! (meters.rs), timed for the store's health, refused at once while its
8//! namespace's breaker is open, and tried again after a failure that may
9//! pass when it only reads (resilience.rs). Repositories may live in
10//! several namespaces (shards.rs).
Rust repos service with shipping; pull requests kept in the model11
Pull requests from branches12use g1t_contracts::repos::{Branch, Commit, EntryKind, GitAccess, Signature, TreeEntry};
RFC 3339 timestamps in identity and repos13use g1t_contracts::time::rfc3339;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily14use g1t_kit::js::{self, Thrown};
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms15use serde::{Deserialize, Serialize};
16use std::cell::RefCell;
17use std::collections::HashMap;
18use std::rc::Rc;
Rust repos service with shipping; pull requests kept in the model19use worker::js_sys::{Reflect, Uint8Array};
20use worker::wasm_bindgen::{JsCast, JsValue};
21use worker::{Env, Result};
22
Merge branch 'worktree-agent-a2013627e5ea4ab13'23use crate::fallback;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily24use crate::meters::{self, Outcome};
25use crate::resilience::{self, Admit, Busy, Failure};
26use crate::shards;
27
28/// Credentials that never leave this service: g1t has already decided who
29/// may do what before one is used. They live an hour and are used for 50
30/// minutes, so each one used has at least ten minutes left.
31const INTERNAL_TTL_SECONDS: u32 = 3_600;
32const INTERNAL_REUSE_MS: u64 = 50 * 60 * 1000;
Merge branch 'worktree-agent-a57ff9fecefa1eaf7'33/// Credentials handed out: to a nightly backup's sandbox (backups.rs), and
34/// by `git_access`, which nothing deployed asks yet (git over SSH will).
35/// Other sandboxes never get one: they use g1t's git endpoints. Five
36/// minutes, used for three, so whoever gets one has at least two.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily37const HANDOUT_TTL_SECONDS: u32 = 300;
38const HANDOUT_REUSE_MS: u64 = 180_000;
39/// How long a handed-out credential stays valid, in milliseconds.
40pub const CREDENTIAL_LIFE_MS: u64 = HANDOUT_TTL_SECONDS as u64 * 1000;
Rust repos service with shipping; pull requests kept in the model41
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms42#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
Rust repos service with shipping; pull requests kept in the model43pub enum Scope {
44 Read,
45 Write,
46}
47
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms48impl Scope {
49 fn as_str(self) -> &'static str {
50 match self {
51 Scope::Read => "read",
52 Scope::Write => "write",
53 }
54 }
55}
56
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily57/// Who a credential is for.
58#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
59pub enum Use {
60 /// This service, talking to the store itself.
61 Internal,
62 /// Someone outside it, through `git_access`.
63 Handout,
64}
65
66impl Use {
67 pub fn ttl_seconds(self) -> u32 {
68 match self {
69 Use::Internal => INTERNAL_TTL_SECONDS,
70 Use::Handout => HANDOUT_TTL_SECONDS,
71 }
72 }
73
74 pub fn reuse_ms(self) -> u64 {
75 match self {
76 Use::Internal => INTERNAL_REUSE_MS,
77 Use::Handout => HANDOUT_REUSE_MS,
78 }
79 }
80
81 fn as_str(self) -> &'static str {
82 match self {
83 Use::Internal => "internal",
84 Use::Handout => "handout",
85 }
86 }
87}
88
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms89/// Where a credential handed out came from, for `Server-Timing`.
90#[derive(Clone, Copy, PartialEq, Eq, Debug)]
91pub enum Kept {
92 /// This isolate made it, or had it from another, a moment ago.
93 Isolate,
94 /// Another isolate made it and shared it.
95 Shared,
96}
97
98impl Kept {
99 pub fn as_str(self) -> &'static str {
100 match self {
101 Kept::Isolate => "isolate",
102 Kept::Shared => "shared",
103 }
104 }
105}
106
Rust repos service with shipping; pull requests kept in the model107/// A place repositories live. `key` is the store's own name for a repo.
108#[allow(async_fn_in_trait)]
109pub trait GitStore {
110 type Repo: GitRepo;
111
112 /// Creates an empty repository. Succeeds if it already exists.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily113 async fn create(&self, key: &str, description: Option<&str>, default_branch: &str) -> Result<()>;
Rust repos service with shipping; pull requests kept in the model114 async fn open(&self, key: &str) -> Result<Self::Repo>;
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms115 /// A credential for `key` made a moment ago, if the store keeps one.
116 async fn kept_access(&self, _key: &str, _scope: Scope) -> Option<(GitAccess, Kept)> {
117 None
118 }
119 /// A new credential for `key`, which the store may keep for next time.
120 async fn mint_access(&self, key: &str, scope: Scope) -> Result<GitAccess> {
121 self.open(key).await?.access(scope).await
122 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily123 /// A remote URL and credential for this service's own use. A store may
124 /// hand out one it made a moment ago.
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms125 async fn access(&self, key: &str, scope: Scope) -> Result<GitAccess> {
126 match self.kept_access(key, scope).await {
127 Some((access, _)) => Ok(access),
128 None => self.mint_access(key, scope).await,
129 }
130 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily131 /// A short-lived credential for someone outside this service.
132 async fn handout(&self, key: &str, scope: Scope) -> Result<GitAccess> {
133 self.access(key, scope).await
134 }
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms135 /// Stops handing out the credentials it keeps for `key`: the store
136 /// turned one down, or the repository is gone.
137 async fn forget_access(&self, _key: &str) {}
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look138 /// Removes a repository and everything in it, for good. Succeeds if it
139 /// is already gone.
140 async fn delete(&self, key: &str) -> Result<()>;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily141 /// The namespaces new repositories may be placed in (shards.rs).
142 fn namespaces(&self) -> Vec<String> {
143 vec![shards::DEFAULT_NAMESPACE.to_owned()]
144 }
145 /// The namespace bound as the default.
146 fn default_namespace(&self) -> String {
147 shards::DEFAULT_NAMESPACE.to_owned()
148 }
Merge branch 'worktree-agent-a2013627e5ea4ab13'149 /// Whether the repository at `key` is served from the fallback store
150 /// now (fallback.rs): answers kept from the usual store may name refs
151 /// it does not have, so none are used.
152 fn on_fallback(&self, _key: &str) -> bool {
153 false
154 }
155 /// Whether `namespace` takes writes now: not while it is served from a
156 /// read-only fallback.
157 fn writable(&self, _namespace: &str) -> bool {
158 true
159 }
Rust repos service with shipping; pull requests kept in the model160}
161
162/// One open repository.
163#[allow(async_fn_in_trait)]
164pub trait GitRepo {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily165 /// A remote URL and credential for git itself, for this service.
Rust repos service with shipping; pull requests kept in the model166 async fn access(&self, scope: Scope) -> Result<GitAccess>;
Pull requests from branches167 /// Every branch and the commit it points to.
168 async fn branches(&self) -> Result<Vec<Branch>>;
Rust repos service with shipping; pull requests kept in the model169 /// Newest first along the first-parent chain; empty for an unknown ref.
170 async fn log(&self, git_ref: &str, limit: u32) -> Result<Vec<Commit>>;
171 /// The parents of a commit, or `None` if the commit does not exist.
172 async fn parents(&self, commit_hash: &str) -> Result<Option<Vec<String>>>;
173 async fn read_tree(&self, tree_hash: &str) -> Result<Option<Vec<TreeEntry>>>;
174 async fn read_blob(&self, blob_hash: &str) -> Result<Option<Vec<u8>>>;
175 /// `None` when the ref or path does not resolve to a file.
176 async fn read_file(&self, git_ref: &str, path: &str) -> Result<Option<Vec<u8>>>;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily177 /// Makes a copy of this repository under `target_key`, in the same
178 /// namespace.
Rust repos service with shipping; pull requests kept in the model179 async fn fork(&self, target_key: &str) -> Result<()>;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily180 /// The version of the repository's refs (registry.rs `RefsState`),
181 /// when answers about branches may be kept under it (R9). Reads by
182 /// branch name are then kept until the version moves.
183 fn at_refs_version(&mut self, _version: Option<u64>) {}
184}
185
186thread_local! {
187 /// The namespace bound to `ARTIFACTS`, for keys that name none.
188 static DEFAULT_NS: RefCell<String> = RefCell::new(shards::DEFAULT_NAMESPACE.to_owned());
189 /// Where each namespace's remotes start: `https://<account>.artifacts.cloudflare.net/git/<namespace>/`.
190 static REMOTE_PREFIX: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
191}
192
193/// The namespace and name a store key stands for.
194pub fn locate(key: &str) -> (String, String) {
195 let (namespace, name) = shards::split(key);
196 let namespace = namespace.map_or_else(|| DEFAULT_NS.with(|ns| ns.borrow().clone()), str::to_owned);
197 (namespace, name.to_owned())
198}
199
Merge branch 'worktree-agent-a2013627e5ea4ab13'200thread_local! {
201 /// Where the fallback store's remotes start, when one is configured.
202 static FALLBACK_BASE: RefCell<Option<String>> = const { RefCell::new(None) };
203}
204
205/// Whose breaker and health git requests to `remote` count toward: its
206/// namespace's, or `<namespace>@fallback` for the fallback store's.
207pub fn health_namespace(remote: &str) -> String {
208 let (namespace, _) = locate(&key_from_remote(remote).unwrap_or_default());
209 let on_fallback = FALLBACK_BASE.with(|base| base.borrow().as_deref().is_some_and(|base| remote.starts_with(base)));
210 if on_fallback { format!("{namespace}@fallback") } else { namespace }
211}
212
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily213/// The store key a git remote is for, from its last two path segments.
214pub fn key_from_remote(remote: &str) -> Option<String> {
215 let path = remote.trim_end_matches('/');
216 let path = path.strip_suffix(".git").unwrap_or(path);
217 let (rest, name) = path.rsplit_once('/')?;
218 let namespace = rest.rsplit('/').next()?;
219 let default = DEFAULT_NS.with(|ns| ns.borrow().clone());
220 Some(shards::compose(Some(namespace), name, &default))
221}
222
223/// Where a namespace's remotes start, learned from one remote the store
224/// gave for `name`.
225fn learn_prefix(remote: &str, name: &str) -> Option<String> {
226 remote.strip_suffix(&format!("{name}.git")).filter(|prefix| prefix.ends_with('/')).map(str::to_owned)
Rust repos service with shipping; pull requests kept in the model227}
228
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily229/// A repository's remote, from where its namespace's remotes start.
230fn remote_from(prefix: &str, name: &str) -> String {
231 format!("{prefix}{name}.git")
232}
233
234struct Namespace {
235 name: String,
Merge branch 'worktree-agent-a2013627e5ea4ab13'236 /// Its binding, for every call: Artifacts, or the fallback store.
237 target: Target,
238}
239
240/// What a call on the store goes to: an Artifacts binding or one of its
241/// repository handles, or the fallback store (fallback.rs) for a
242/// namespace, or for one repository in it.
243#[derive(Clone)]
244enum Target {
245 Js(JsValue),
246 Fallback {
247 settings: Rc<fallback::Settings>,
248 namespace: String,
249 repo: Option<String>,
250 },
251}
252
253impl Target {
254 fn is_fallback(&self) -> bool {
255 matches!(self, Target::Fallback { .. })
256 }
257
258 /// Whose breaker and health a call counts toward: the fallback store's
259 /// own, so an Artifacts outage never holds it back.
260 fn health_name(&self, namespace: &str) -> String {
261 if self.is_fallback() { format!("{namespace}@fallback") } else { namespace.to_owned() }
262 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily263}
264
265pub struct ArtifactsStore {
266 namespaces: Rc<Vec<Namespace>>,
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms267 /// Where isolates share the credentials they make; see shared.rs.
268 shared: Option<Rc<crate::shared::Shared>>,
Rust repos service with shipping; pull requests kept in the model269}
270
271impl ArtifactsStore {
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms272 pub fn new(env: &Env, shared: Option<Rc<crate::shared::Shared>>) -> Result<Self> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily273 let config = env.var("ARTIFACTS_NAMESPACES").ok().map(|value| value.to_string());
Merge branch 'worktree-agent-a2013627e5ea4ab13'274 let text = |name: &str| env.var(name).ok().map(|value| value.to_string());
275 let secret = env.secret("GIT_FALLBACK_SECRET").ok().map(|value| value.to_string());
276 let fallback = fallback::Settings::from_vars(
277 text("GIT_FALLBACK_URL").as_deref(),
278 secret.as_deref(),
279 text("GIT_FALLBACK_NAMESPACES").as_deref(),
280 text("GIT_FALLBACK_WRITES").as_deref(),
281 )
282 .map(Rc::new);
283 FALLBACK_BASE.with(|base| *base.borrow_mut() = fallback.as_ref().map(|settings| format!("{}/git/", settings.url)));
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily284 let mut namespaces = Vec::new();
285 for (binding, name) in shards::bindings(config.as_deref()) {
Merge branch 'worktree-agent-a2013627e5ea4ab13'286 // Served from the fallback store, by configuration.
287 if let Some(settings) = fallback.as_ref().filter(|settings| settings.serves(&name)) {
288 worker::console_log!("git store {name}: served from the fallback store");
289 let target = Target::Fallback { settings: settings.clone(), namespace: name.clone(), repo: None };
290 namespaces.push(Namespace { name, target });
291 continue;
292 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily293 match js::binding(env, &binding) {
Merge branch 'worktree-agent-a2013627e5ea4ab13'294 Ok(value) => namespaces.push(Namespace { name, target: Target::Js(value) }),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily295 // The default binding is required; the others are optional.
296 Err(error) if binding == shards::DEFAULT_BINDING => return Err(error),
297 Err(_) => worker::console_error!("ARTIFACTS_NAMESPACES names {binding}, which is not bound"),
298 }
299 }
300 if let Some(default) = namespaces.first() {
301 DEFAULT_NS.with(|ns| ns.borrow_mut().clone_from(&default.name));
302 }
303 // Optional: where remotes start, `https://<account>.artifacts.cloudflare.net/git`,
304 // so the first credential an isolate makes needs no `info()` either.
305 if let Ok(base) = env.var("ARTIFACTS_REMOTE_BASE") {
306 let base = base.to_string().trim_end_matches('/').to_owned();
307 if base.starts_with("https://") {
308 REMOTE_PREFIX.with(|prefixes| {
309 let mut prefixes = prefixes.borrow_mut();
310 for namespace in &namespaces {
311 prefixes.entry(namespace.name.clone()).or_insert_with(|| format!("{base}/{}/", namespace.name));
312 }
313 });
314 }
315 }
316 Ok(Self { namespaces: Rc::new(namespaces), shared })
317 }
318
Merge branch 'worktree-agent-a2013627e5ea4ab13'319 fn binding(&self, namespace: &str) -> Result<&Target> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily320 self.namespaces
321 .iter()
322 .find(|candidate| candidate.name == namespace)
Merge branch 'worktree-agent-a2013627e5ea4ab13'323 .map(|found| &found.target)
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily324 .ok_or_else(|| worker::Error::RustError(format!("git store namespace {namespace} is not bound")))
325 }
Merge branch 'worktree-agent-a2013627e5ea4ab13'326
327 /// The fallback store's settings, when `namespace` is served from it.
328 fn fallback_of(&self, namespace: &str) -> Option<&fallback::Settings> {
329 match self.binding(namespace).ok()? {
330 Target::Fallback { settings, .. } => Some(settings),
331 Target::Js(_) => None,
332 }
333 }
334
335 /// The name credentials for `key` are kept under: those of the
336 /// fallback store never stand in for Artifacts' own, nor the reverse.
337 fn cred_key(&self, key: &str) -> String {
338 let (namespace, _) = locate(key);
339 cred_key(key, self.fallback_of(&namespace).is_some())
340 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily341}
342
Merge branch 'worktree-agent-a2013627e5ea4ab13'343/// See [`ArtifactsStore::cred_key`].
344fn cred_key(key: &str, on_fallback: bool) -> String {
345 if on_fallback { format!("fallback:{key}") } else { key.to_owned() }
346}
347
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily348/// A failed call on the binding.
349pub struct StoreError {
350 pub thrown: Thrown,
351 pub busy: Option<Busy>,
352}
353
354impl StoreError {
355 pub fn is(&self, code: &str) -> bool {
356 self.thrown.is(code)
Rust repos service with shipping; pull requests kept in the model357 }
358}
359
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily360impl From<StoreError> for worker::Error {
361 fn from(error: StoreError) -> Self {
362 match error.busy {
363 Some(busy) => busy.error(&error.thrown.to_string()),
364 None => error.thrown.into(),
365 }
366 }
367}
368
369/// The meter for a binding method: `binding.create_token`.
370fn meter_of(method: &str) -> String {
371 let mut out = String::from("binding.");
372 for c in method.chars() {
373 if c.is_ascii_uppercase() {
374 out.push('_');
375 out.push(c.to_ascii_lowercase());
376 } else {
377 out.push(c);
378 }
379 }
380 out
381}
382
383/// Seconds a caller is told to wait when the store is busy.
384const BUSY_RETRY_AFTER: u64 = 5;
385
386/// Calls `target[method](...args)` on namespace `namespace`'s binding, for
387/// the repository at `key`. `retry`: whether a failure that may pass is
388/// tried again (reads and credentials only).
389async fn invoke(
390 namespace: &str,
391 key: &str,
Merge branch 'worktree-agent-a2013627e5ea4ab13'392 target: &Target,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily393 method: &str,
394 args: &[JsValue],
395 retry: bool,
396) -> std::result::Result<JsValue, StoreError> {
397 let meter = meter_of(method);
Merge branch 'worktree-agent-a2013627e5ea4ab13'398 let health = target.health_name(namespace);
399 let namespace = health.as_str();
400 // A read-only fallback refuses writes before asking (fallback.rs).
401 if let Target::Fallback { settings, repo, .. } = target
402 && !settings.writes
403 {
404 let values: Vec<serde_json::Value> = args.iter().map(|arg| js::from_js(arg).unwrap_or(serde_json::Value::Null)).collect();
405 if fallback::writes(repo.as_deref(), method, &values) {
406 return Err(StoreError {
407 thrown: Thrown { code: Some("READ_ONLY".to_owned()), message: format!("{method} refused: the git store is read-only") },
408 busy: Some(Busy::read_only()),
409 });
410 }
411 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily412 let mut attempt = 0;
413 loop {
414 let now = g1t_kit::now_ms();
415 let admit = resilience::with_breaker(namespace, |breaker| breaker.admit(now));
416 if let Admit::Wait(ms) = admit {
417 meters::record_health(namespace, Outcome::Rejected, 0);
418 return Err(StoreError {
419 thrown: Thrown { code: None, message: format!("{method} not asked: the git store has been failing") },
Merge branch 'worktree-agent-a2013627e5ea4ab13'420 busy: Some(Busy { rate_limited: false, retry_after: resilience::seconds(ms).max(BUSY_RETRY_AFTER), read_only: false }),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily421 });
422 }
Merge branch 'worktree-agent-a2013627e5ea4ab13'423 // Calls on Artifacts are metered; the fallback store costs nothing
424 // per call.
425 if !target.is_fallback() {
426 meters::record(&meter, key, 0, 0);
427 }
428 let called = dispatch(target, method, args).await;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily429 let ms = g1t_kit::now_ms().saturating_sub(now);
430 match called {
431 Ok(value) => {
432 resilience::with_breaker(namespace, |breaker| breaker.succeeded());
433 meters::record_health(namespace, Outcome::Ok, ms);
434 return Ok(value);
435 }
436 Err(thrown) => {
437 let failure = resilience::classify(thrown.code.as_deref(), &thrown.message);
438 if failure == Failure::Permanent {
439 // An answer (NOT_FOUND, ALREADY_EXISTS): the store is up.
440 resilience::with_breaker(namespace, |breaker| breaker.succeeded());
441 meters::record_health(namespace, Outcome::Ok, ms);
442 return Err(StoreError { thrown, busy: None });
443 }
444 if retry && resilience::retry(failure, attempt) {
445 let wait = resilience::backoff_ms(failure, attempt, worker::js_sys::Math::random());
446 worker::Delay::from(std::time::Duration::from_millis(wait)).await;
447 attempt += 1;
448 continue;
449 }
450 resilience::with_breaker(namespace, |breaker| breaker.failed(failure, g1t_kit::now_ms()));
451 let outcome = if failure == Failure::RateLimited { Outcome::RateLimited } else { Outcome::Failed };
452 meters::record_health(namespace, outcome, ms);
453 worker::console_error!("git store {namespace}: {method} for {key} failed: {thrown}");
454 return Err(StoreError {
455 thrown,
Merge branch 'worktree-agent-a2013627e5ea4ab13'456 busy: Some(Busy { rate_limited: failure == Failure::RateLimited, retry_after: BUSY_RETRY_AFTER, read_only: false }),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily457 });
458 }
459 }
460 }
461}
462
Merge branch 'worktree-agent-a2013627e5ea4ab13'463/// Makes one call: on the binding, or as a request to the fallback store.
464async fn dispatch(target: &Target, method: &str, args: &[JsValue]) -> std::result::Result<JsValue, Thrown> {
465 let (settings, namespace, repo) = match target {
466 Target::Js(value) => return js::call(value, method, args).await,
467 Target::Fallback { settings, namespace, repo } => (settings, namespace, repo),
468 };
469 let values: Vec<serde_json::Value> = args.iter().map(|arg| js::from_js(arg).unwrap_or(serde_json::Value::Null)).collect();
470 let route = fallback::route(namespace, repo.as_deref(), method, &values)
471 .map_err(|refused| Thrown { code: Some(refused.code.to_owned()), message: refused.message })?;
472 let unreachable = |error: worker::Error| Thrown { code: None, message: format!("the fallback store could not be reached: {error}") };
473 let headers = worker::Headers::new();
474 headers.set("x-gitstore-secret", &settings.secret).map_err(unreachable)?;
475 let mut init = worker::RequestInit::new();
476 init.with_method(match route.method {
477 "POST" => worker::Method::Post,
478 "DELETE" => worker::Method::Delete,
479 _ => worker::Method::Get,
480 });
481 if let Some(body) = &route.body {
482 headers.set("content-type", "application/json").map_err(unreachable)?;
483 init.with_body(Some(JsValue::from_str(&body.to_string())));
484 }
485 init.with_headers(headers);
486 let request = worker::Request::new_with_init(&format!("{}{}", settings.url, route.path), &init).map_err(unreachable)?;
487 let mut response = worker::Fetch::Request(request).send().await.map_err(unreachable)?;
488 let status = response.status_code();
489 let body = response.bytes().await.map_err(unreachable)?;
490 match fallback::answer(&route, status, body) {
491 fallback::Answer::Json(value) => js::to_js(&value).map_err(|error| Thrown { code: None, message: error.to_string() }),
492 fallback::Answer::Bytes(bytes) => Ok(Uint8Array::from(bytes.as_slice()).into()),
493 fallback::Answer::Null => Ok(JsValue::NULL),
494 fallback::Answer::Error { code, message } => Err(Thrown { code, message }),
495 }
496}
497
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms498/// A credential as isolates share it, sealed (see shared.rs): with when it
499/// was made, so that one shared is reused no longer than one kept here.
500#[derive(Serialize, Deserialize)]
501struct SharedCredential {
502 remote: String,
503 token: String,
504 made: u64,
505}
506
507/// The shared cache's key for a credential: the store's key for the
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily508/// repository, the scope, and who it is for. (`cred2`: credentials kept
509/// before their lives differed by use are not read.)
510fn shared_key(key: &str, scope: Scope, using: Use) -> String {
511 format!("cred2:{key}:{}:{}", scope.as_str(), using.as_str())
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms512}
513
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily514/// A shared credential, if it was made less than its reuse window before
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms515/// `now`; with when it was made.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily516fn shared_credential(bytes: &[u8], now: u64, using: Use) -> Option<(GitAccess, u64)> {
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms517 let kept: SharedCredential = serde_json::from_slice(bytes).ok()?;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily518 (now.saturating_sub(kept.made) < using.reuse_ms()).then_some((
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms519 GitAccess {
520 remote: kept.remote,
521 token: kept.token,
522 },
523 kept.made,
524 ))
525}
526
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily527/// Credentials made a while ago, by repository, scope and use. Making one
528/// is a round trip to the store; reusing it saves that, and the store's
529/// lookup of the repository with it.
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms530#[derive(Default)]
531pub struct Credentials {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily532 kept: HashMap<(String, Scope, Use), (GitAccess, u64)>,
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms533}
534
535impl Credentials {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily536 /// One made for `key`, `scope` and `using` within its reuse window of `now`.
537 pub fn get(&self, key: &str, scope: Scope, using: Use, now: u64) -> Option<GitAccess> {
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms538 self.kept
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily539 .get(&(key.to_owned(), scope, using))
540 .filter(|(_, made)| now.saturating_sub(*made) < using.reuse_ms())
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms541 .map(|(access, _)| access.clone())
542 }
543
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily544 pub fn keep(&mut self, key: &str, scope: Scope, using: Use, access: GitAccess, made: u64, now: u64) {
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms545 // Expired ones go first, so the map stays as small as the isolate's
546 // recent repositories.
547 self.kept
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily548 .retain(|(_, _, kept_use), (_, at)| now.saturating_sub(*at) < kept_use.reuse_ms());
549 self.kept.insert((key.to_owned(), scope, using), (access, made));
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms550 }
551
552 pub fn forget(&mut self, key: &str) {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily553 self.kept.retain(|(kept, _, _), _| kept != key);
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms554 }
555}
556
557thread_local! {
558 static CREDENTIALS: RefCell<Credentials> = RefCell::new(Credentials::default());
559}
560
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily561/// A credential kept in this isolate, else one another isolate shared.
562async fn kept(shared: Option<&crate::shared::Shared>, key: &str, scope: Scope, using: Use) -> Option<(GitAccess, Kept)> {
563 let now = g1t_kit::now_ms();
564 if let Some(access) = CREDENTIALS.with(|kept| kept.borrow().get(key, scope, using, now)) {
565 return Some((access, Kept::Isolate));
566 }
567 let bytes = shared?.get(&shared_key(key, scope, using)).await?;
568 let (access, made) = shared_credential(&bytes, now, using)?;
569 CREDENTIALS.with(|kept| kept.borrow_mut().keep(key, scope, using, access.clone(), made, now));
570 Some((access, Kept::Shared))
571}
572
573/// Keeps a credential just made here, and shares it.
574async fn keep(shared: Option<&crate::shared::Shared>, key: &str, scope: Scope, using: Use, access: &GitAccess) {
575 let now = g1t_kit::now_ms();
576 CREDENTIALS.with(|kept| kept.borrow_mut().keep(key, scope, using, access.clone(), now, now));
577 if let Some(shared) = shared {
578 let value = SharedCredential {
579 remote: access.remote.clone(),
580 token: access.token.clone(),
581 made: now,
582 };
583 if let Ok(bytes) = serde_json::to_vec(&value) {
584 shared.put(&shared_key(key, scope, using), &bytes, using.reuse_ms() / 1000).await;
585 }
586 }
587}
588
Rust repos service with shipping; pull requests kept in the model589impl GitStore for ArtifactsStore {
590 type Repo = ArtifactsRepo;
591
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms592 async fn kept_access(&self, key: &str, scope: Scope) -> Option<(GitAccess, Kept)> {
Merge branch 'worktree-agent-a2013627e5ea4ab13'593 kept(self.shared.as_deref(), &self.cred_key(key), scope, Use::Internal).await
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms594 }
595
596 async fn mint_access(&self, key: &str, scope: Scope) -> Result<GitAccess> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily597 let repo = self.open(key).await?;
598 let access = repo.mint(scope, Use::Internal).await?;
Merge branch 'worktree-agent-a2013627e5ea4ab13'599 keep(self.shared.as_deref(), &self.cred_key(key), scope, Use::Internal, &access).await;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily600 Ok(access)
601 }
602
603 async fn handout(&self, key: &str, scope: Scope) -> Result<GitAccess> {
Merge branch 'worktree-agent-a2013627e5ea4ab13'604 let cred_key = self.cred_key(key);
605 if let Some((access, _)) = kept(self.shared.as_deref(), &cred_key, scope, Use::Handout).await {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily606 return Ok(access);
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms607 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily608 let access = self.open(key).await?.mint(scope, Use::Handout).await?;
Merge branch 'worktree-agent-a2013627e5ea4ab13'609 keep(self.shared.as_deref(), &cred_key, scope, Use::Handout, &access).await;
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms610 Ok(access)
611 }
612
613 async fn forget_access(&self, key: &str) {
Merge branch 'worktree-agent-a2013627e5ea4ab13'614 // Both stores' credentials: whichever serves the key now.
615 let names = [cred_key(key, false), cred_key(key, true)];
616 CREDENTIALS.with(|kept| {
617 let mut kept = kept.borrow_mut();
618 for name in &names {
619 kept.forget(name);
620 }
621 });
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms622 if let Some(shared) = &self.shared {
Merge branch 'worktree-agent-a2013627e5ea4ab13'623 let keys: Vec<String> = names
624 .iter()
625 .flat_map(|name| {
626 [Scope::Read, Scope::Write]
627 .into_iter()
628 .flat_map(move |scope| [Use::Internal, Use::Handout].map(|using| shared_key(name, scope, using)))
629 })
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily630 .collect();
631 futures_util::future::join_all(keys.iter().map(|shared_key| shared.delete(shared_key))).await;
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms632 }
633 }
634
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily635 async fn create(&self, key: &str, description: Option<&str>, default_branch: &str) -> Result<()> {
636 let (namespace, name) = locate(key);
Rust repos service with shipping; pull requests kept in the model637 let options = js::to_js(&serde_json::json!({
638 "description": description,
639 "setDefaultBranch": default_branch,
640 }))?;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily641 match invoke(&namespace, key, self.binding(&namespace)?, "create", &[name.as_str().into(), options], true).await {
Rust repos service with shipping; pull requests kept in the model642 // Left behind by an earlier failed attempt; adopt it.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily643 Err(failed) if !failed.is("ALREADY_EXISTS") => Err(failed.into()),
Rust repos service with shipping; pull requests kept in the model644 _ => Ok(()),
645 }
646 }
647
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look648 async fn delete(&self, key: &str) -> Result<()> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily649 let (namespace, name) = locate(key);
Merge branch 'worktree-agent-a2013627e5ea4ab13'650 // Nothing is forgotten while the store refuses to delete.
651 if self.writable(&namespace) {
652 self.forget_access(key).await;
653 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily654 match invoke(&namespace, key, self.binding(&namespace)?, "delete", &[name.as_str().into()], true).await {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look655 // Gone already: an earlier purge got this far.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily656 Err(failed) if !failed.is("NOT_FOUND") => Err(failed.into()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look657 _ => Ok(()),
658 }
659 }
660
Rust repos service with shipping; pull requests kept in the model661 async fn open(&self, key: &str) -> Result<ArtifactsRepo> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily662 let (namespace, name) = locate(key);
Merge branch 'worktree-agent-a2013627e5ea4ab13'663 let binding = self.binding(&namespace)?.clone();
Rust repos service with shipping; pull requests kept in the model664 Ok(ArtifactsRepo {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for665 handle: RefCell::new(None),
Merge branch 'worktree-agent-a2013627e5ea4ab13'666 cred_key: cred_key(key, binding.is_fallback()),
667 binding,
Agents as a team: lifecycle, merge queue, billing and a new shell668 key: key.to_owned(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily669 name,
670 namespace,
671 shared: self.shared.clone(),
672 refs_version: None,
Rust repos service with shipping; pull requests kept in the model673 })
674 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily675
676 fn namespaces(&self) -> Vec<String> {
677 self.namespaces.iter().map(|namespace| namespace.name.clone()).collect()
678 }
679
680 fn default_namespace(&self) -> String {
681 DEFAULT_NS.with(|ns| ns.borrow().clone())
682 }
Merge branch 'worktree-agent-a2013627e5ea4ab13'683
684 fn on_fallback(&self, key: &str) -> bool {
685 let (namespace, _) = locate(key);
686 self.fallback_of(&namespace).is_some()
687 }
688
689 fn writable(&self, namespace: &str) -> bool {
690 self.fallback_of(namespace).is_none_or(|settings| settings.writes)
691 }
Rust repos service with shipping; pull requests kept in the model692}
693
Merge branch 'worktree-agent-a2013627e5ea4ab13'694/// A handle to one repository in the store. On Artifacts it is an RPC
695/// stub, so it is released when dropped.
Rust repos service with shipping; pull requests kept in the model696pub struct ArtifactsRepo {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for697 /// The store's handle, asked for (`get`) on the first call that needs
698 /// the store: an answer from a cache, or a fetch over git with a kept
699 /// credential, never costs a `get`.
Merge branch 'worktree-agent-a2013627e5ea4ab13'700 handle: RefCell<Option<Target>>,
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for701 /// The namespace's binding, for that `get`.
Merge branch 'worktree-agent-a2013627e5ea4ab13'702 binding: Target,
Agents as a team: lifecycle, merge queue, billing and a new shell703 /// The repository's store key, which scopes its cached objects.
704 key: String,
Merge branch 'worktree-agent-a2013627e5ea4ab13'705 /// What its credentials are kept under (`ArtifactsStore::cred_key`).
706 cred_key: String,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily707 /// Its name in its namespace.
708 name: String,
709 namespace: String,
710 shared: Option<Rc<crate::shared::Shared>>,
711 /// See [`GitRepo::at_refs_version`].
712 refs_version: Option<u64>,
Agents as a team: lifecycle, merge queue, billing and a new shell713}
714
715/// Where cached git objects live. Trees and blobs are named by their
716/// content, so a cached one is never stale; each is kept under its own
717/// repository's key, so a repository only ever finds its own objects.
718const OBJECT_CACHE: &str = "https://objects.g1t.internal/";
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily719/// Blobs and files larger than this are not cached.
Agents as a team: lifecycle, merge queue, billing and a new shell720const MAX_CACHED_BLOB: usize = 1024 * 1024;
721const OBJECT_MAX_AGE: &str = "public, max-age=31536000, immutable";
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily722/// Answers kept under a refs version: until the version moves, and no
723/// longer than this, which bounds how stale one can be should a change
724/// ever fail to move it.
725const VERSIONED_MAX_AGE: &str = "public, max-age=300";
Agents as a team: lifecycle, merge queue, billing and a new shell726
Fast pages, required checks on the branch, self-hosted runners, honest incidents727/// Whether a ref is a full commit hash (SHA-1 or SHA-256), whose history
728/// can be kept for good.
729pub fn is_commit_hash(git_ref: &str) -> bool {
730 (git_ref.len() == 40 || git_ref.len() == 64) && git_ref.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
731}
732
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily733/// Where a read is kept: under the object it names for good, under the
734/// refs version for a name that can move, or nowhere.
735#[derive(Debug, PartialEq, Eq)]
736pub enum CacheKey {
737 Forever(String),
738 Versioned(String),
739}
740
741/// The cache key for `log(git_ref, limit)`.
742pub fn log_key(git_ref: &str, limit: u32, version: Option<u64>) -> Option<CacheKey> {
743 if is_commit_hash(git_ref) {
744 return Some(CacheKey::Forever(format!("log/{git_ref}-{limit}")));
745 }
746 version.map(|version| CacheKey::Versioned(format!("vlog/{version}/{}-{limit}", g1t_secrets::sha256_hex(git_ref))))
747}
748
749/// The cache key for `read_file(git_ref, path)`.
750pub fn file_key(git_ref: &str, path: &str, version: Option<u64>) -> Option<CacheKey> {
751 let path = g1t_secrets::sha256_hex(path);
752 if is_commit_hash(git_ref) {
753 return Some(CacheKey::Forever(format!("file/{git_ref}/{path}")));
754 }
755 version.map(|version| CacheKey::Versioned(format!("vfile/{version}/{}/{path}", g1t_secrets::sha256_hex(git_ref))))
756}
757
758/// The cache key for the branch list.
759pub fn branches_key(version: Option<u64>) -> Option<CacheKey> {
760 version.map(|version| CacheKey::Versioned(format!("branches/{version}")))
761}
762
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for763/// Objects named by their content, kept in the isolate ahead of the Cache
764/// API, oldest out first past `MEMORY_CACHE_BYTES`. They never go stale,
765/// and each is under its repository's key.
766const MEMORY_CACHE_BYTES: usize = 16 * 1024 * 1024;
767
768#[derive(Default)]
769struct MemoryCache {
770 entries: HashMap<String, Rc<Vec<u8>>>,
771 order: std::collections::VecDeque<String>,
772 bytes: usize,
773}
774
775impl MemoryCache {
776 fn get(&self, url: &str) -> Option<Vec<u8>> {
777 self.entries.get(url).map(|bytes| bytes.as_ref().clone())
778 }
779
780 fn put(&mut self, url: String, bytes: &[u8]) {
781 if bytes.len() > MEMORY_CACHE_BYTES / 16 || self.entries.contains_key(&url) {
782 return;
783 }
784 self.bytes += bytes.len();
785 self.entries.insert(url.clone(), Rc::new(bytes.to_vec()));
786 self.order.push_back(url);
787 while self.bytes > MEMORY_CACHE_BYTES {
788 let Some(oldest) = self.order.pop_front() else { break };
789 if let Some(gone) = self.entries.remove(&oldest) {
790 self.bytes -= gone.len();
791 }
792 }
793 }
794}
795
796thread_local! {
797 static MEMORY: RefCell<MemoryCache> = RefCell::new(MemoryCache::default());
798}
799
Agents as a team: lifecycle, merge queue, billing and a new shell800impl ArtifactsRepo {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily801 fn cache_url(&self, path: &str) -> String {
802 format!("{OBJECT_CACHE}{}/{path}", self.key)
803 }
804
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for805 /// A kept answer: from the isolate for one kept for good, else the
806 /// Cache API. Each look is metered (`cache.memory_hit`, `cache.edge_hit`,
807 /// `cache.miss`), so the usage check shows which cache answers.
808 async fn cached_at(&self, path: &str, forever: bool) -> Option<Vec<u8>> {
809 let url = self.cache_url(path);
810 if forever && let Some(bytes) = MEMORY.with(|memory| memory.borrow().get(&url)) {
Cache hits are counted, not only their bytes811 meters::record("cache.memory_hit", &self.key, 0, bytes.len() as u64);
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for812 return Some(bytes);
813 }
814 let found = match worker::Cache::default().get(url.clone(), false).await {
815 Ok(Some(mut response)) => response.bytes().await.ok(),
816 _ => None,
817 };
818 match &found {
819 Some(bytes) => {
Cache hits are counted, not only their bytes820 meters::record("cache.edge_hit", &self.key, 0, bytes.len() as u64);
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for821 if forever {
822 MEMORY.with(|memory| memory.borrow_mut().put(url, bytes));
823 }
824 }
825 None => meters::record("cache.miss", &self.key, 0, 0),
826 }
827 found
Agents as a team: lifecycle, merge queue, billing and a new shell828 }
829
830 async fn cached(&self, kind: &str, hash: &str) -> Option<Vec<u8>> {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for831 self.cached_at(&format!("{kind}/{hash}"), true).await
Agents as a team: lifecycle, merge queue, billing and a new shell832 }
833
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily834 async fn keep_at(&self, path: &str, bytes: Vec<u8>, max_age: &str) {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for835 if max_age == OBJECT_MAX_AGE {
836 MEMORY.with(|memory| memory.borrow_mut().put(self.cache_url(path), &bytes));
837 }
Agents as a team: lifecycle, merge queue, billing and a new shell838 let Ok(mut response) = worker::Response::from_bytes(bytes) else {
839 return;
840 };
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily841 let _ = response.headers_mut().set("cache-control", max_age);
842 let _ = worker::Cache::default().put(self.cache_url(path), response).await;
Agents as a team: lifecycle, merge queue, billing and a new shell843 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily844
845 /// Keeps an object for next time. A failure only costs a later read.
846 async fn keep(&self, kind: &str, hash: &str, bytes: Vec<u8>) {
847 self.keep_at(&format!("{kind}/{hash}"), bytes, OBJECT_MAX_AGE).await;
848 }
849
850 async fn get_key(&self, key: &CacheKey) -> Option<Vec<u8>> {
851 match key {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for852 CacheKey::Forever(path) => self.cached_at(path, true).await,
853 CacheKey::Versioned(path) => self.cached_at(path, false).await,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily854 }
855 }
856
857 async fn put_key(&self, key: &CacheKey, bytes: Vec<u8>) {
858 match key {
859 CacheKey::Forever(path) => self.keep_at(path, bytes, OBJECT_MAX_AGE).await,
860 CacheKey::Versioned(path) => self.keep_at(path, bytes, VERSIONED_MAX_AGE).await,
861 }
862 }
863
864 async fn call(&self, method: &str, args: &[JsValue], retry: bool) -> std::result::Result<JsValue, StoreError> {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for865 let handle = self.handle().await?;
866 invoke(&self.namespace, &self.key, &handle, method, args, retry).await
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily867 }
868
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for869 /// The store's handle, asked for the first time it is needed.
Merge branch 'worktree-agent-a2013627e5ea4ab13'870 async fn handle(&self) -> std::result::Result<Target, StoreError> {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for871 if let Some(handle) = self.handle.borrow().as_ref() {
872 return Ok(handle.clone());
873 }
Merge branch 'worktree-agent-a2013627e5ea4ab13'874 let found = invoke(&self.namespace, &self.key, &self.binding, "get", &[self.name.as_str().into()], true).await?;
875 let handle = match &self.binding {
876 Target::Js(_) => Target::Js(found),
877 // The fallback store said the repository is there.
878 Target::Fallback { settings, namespace, .. } => Target::Fallback {
879 settings: settings.clone(),
880 namespace: namespace.clone(),
881 repo: Some(self.name.clone()),
882 },
883 };
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for884 *self.handle.borrow_mut() = Some(handle.clone());
885 Ok(handle)
886 }
887
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily888 /// A new credential from the store. Its remote is worked out from the
889 /// key once this isolate knows where the namespace's remotes start;
Merge branch 'worktree-agent-a2013627e5ea4ab13'890 /// until then the store is asked (`info()`) alongside the token. The
891 /// fallback store's remotes are known from its address.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily892 pub async fn mint(&self, scope: Scope, using: Use) -> Result<GitAccess> {
893 let args = [scope.as_str().into(), using.ttl_seconds().into()];
Merge branch 'worktree-agent-a2013627e5ea4ab13'894 if let Target::Fallback { settings, .. } = &self.binding {
895 let token: RawToken = js::from_js(&self.call("createToken", &args, true).await?)?;
896 return Ok(GitAccess { remote: settings.remote(&self.namespace, &self.name), token: token.plaintext });
897 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily898 let prefix = REMOTE_PREFIX.with(|prefixes| prefixes.borrow().get(&self.namespace).cloned());
899 if let Some(prefix) = prefix {
900 let token: RawToken = js::from_js(&self.call("createToken", &args, true).await?)?;
901 return Ok(GitAccess { remote: remote_from(&prefix, &self.name), token: token.plaintext });
902 }
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for903 self.handle().await?;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily904 let (info, token) = futures_util::future::join(self.call("info", &[], true), self.call("createToken", &args, true)).await;
905 let info: RawInfo = js::from_js(&info?)?;
906 let token: RawToken = js::from_js(&token?)?;
907 match learn_prefix(&info.remote, &self.name) {
908 Some(prefix) => REMOTE_PREFIX.with(|prefixes| {
909 prefixes.borrow_mut().insert(self.namespace.clone(), prefix);
910 }),
911 None => worker::console_error!("the git store's remote {} does not end in {}.git", info.remote, self.name),
912 }
913 Ok(GitAccess { remote: info.remote, token: token.plaintext })
914 }
Rust repos service with shipping; pull requests kept in the model915}
916
917impl Drop for ArtifactsRepo {
918 fn drop(&mut self) {
919 let symbol = js::get(&worker::js_sys::global(), "Symbol");
920 let dispose = js::get(&symbol, "dispose");
Merge branch 'worktree-agent-a2013627e5ea4ab13'921 let Some(Target::Js(handle)) = self.handle.borrow_mut().take() else { return };
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for922 if let Ok(function) = Reflect::get(&handle, &dispose).and_then(|value| value.dyn_into::<worker::js_sys::Function>()) {
923 let _ = function.call0(&handle);
Rust repos service with shipping; pull requests kept in the model924 }
925 }
926}
927
928#[derive(Deserialize)]
929#[serde(rename_all = "camelCase")]
930struct RawCommit {
931 hash: String,
932 tree_hash: String,
933 message: String,
934 author: Signature,
935 parents: Vec<String>,
936 /// Seconds since the epoch.
937 authored_at: u64,
938}
939
940#[derive(Deserialize)]
941struct RawEntry {
942 name: String,
943 hash: String,
944 #[serde(rename = "type")]
945 kind: EntryKind,
946}
947
948#[derive(Deserialize)]
949struct RawInfo {
950 remote: String,
951}
952
953#[derive(Deserialize)]
954struct RawToken {
955 plaintext: String,
956}
957
Merge branch 'worktree-agent-a2013627e5ea4ab13'958/// The bytes of a `Blob` (or of the bytes the fallback store sent), or
959/// `None` for null.
Rust repos service with shipping; pull requests kept in the model960async fn blob_bytes(blob: JsValue) -> Result<Option<Vec<u8>>> {
961 if blob.is_null() || blob.is_undefined() {
962 return Ok(None);
963 }
Merge branch 'worktree-agent-a2013627e5ea4ab13'964 if let Some(bytes) = blob.dyn_ref::<Uint8Array>() {
965 return Ok(Some(bytes.to_vec()));
966 }
Rust repos service with shipping; pull requests kept in the model967 let buffer = js::call(&blob, "arrayBuffer", &[]).await?;
968 Ok(Some(Uint8Array::new(&buffer).to_vec()))
969}
970
971impl GitRepo for ArtifactsRepo {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily972 /// One made a while ago, here or in another isolate, else a new one.
Rust repos service with shipping; pull requests kept in the model973 async fn access(&self, scope: Scope) -> Result<GitAccess> {
Merge branch 'worktree-agent-a2013627e5ea4ab13'974 if let Some((access, _)) = kept(self.shared.as_deref(), &self.cred_key, scope, Use::Internal).await {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily975 return Ok(access);
976 }
977 let access = self.mint(scope, Use::Internal).await?;
Merge branch 'worktree-agent-a2013627e5ea4ab13'978 keep(self.shared.as_deref(), &self.cred_key, scope, Use::Internal, &access).await;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily979 Ok(access)
Rust repos service with shipping; pull requests kept in the model980 }
981
Pull requests from branches982 async fn branches(&self) -> Result<Vec<Branch>> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily983 let key = branches_key(self.refs_version);
984 if let Some(key) = &key
985 && let Some(bytes) = self.get_key(key).await
986 && let Ok(branches) = serde_json::from_slice::<Vec<Branch>>(&bytes)
987 {
988 return Ok(branches);
989 }
990 let branches = crate::refs::branches(&self.access(Scope::Read).await?).await?;
991 if let (Some(key), Ok(bytes)) = (&key, serde_json::to_vec(&branches)) {
992 self.put_key(key, bytes).await;
993 }
994 Ok(branches)
Pull requests from branches995 }
996
Rust repos service with shipping; pull requests kept in the model997 async fn log(&self, git_ref: &str, limit: u32) -> Result<Vec<Commit>> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents998 // History from a commit never changes, so a log asked for by hash is
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily999 // kept like an object: walking it is a read per commit. One asked
1000 // for by a branch's name is kept until the branch can have moved.
1001 let key = log_key(git_ref, limit, self.refs_version);
1002 if let Some(key) = &key
1003 && let Some(bytes) = self.get_key(key).await
Fast pages, required checks on the branch, self-hosted runners, honest incidents1004 && let Ok(commits) = serde_json::from_slice::<Vec<Commit>>(&bytes)
1005 {
1006 return Ok(commits);
1007 }
Rust repos service with shipping; pull requests kept in the model1008 let options = js::to_js(&serde_json::json!({ "ref": git_ref, "limit": limit }))?;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1009 let raw: Vec<RawCommit> = js::from_js(&self.call("log", &[options], true).await?)?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents1010 let commits: Vec<Commit> = raw
Rust repos service with shipping; pull requests kept in the model1011 .into_iter()
1012 .map(|commit| Commit {
1013 hash: commit.hash,
1014 tree_hash: commit.tree_hash,
1015 message: commit.message,
1016 author: commit.author,
1017 parents: commit.parents,
RFC 3339 timestamps in identity and repos1018 authored_at: rfc3339(commit.authored_at * 1000),
Rust repos service with shipping; pull requests kept in the model1019 })
Fast pages, required checks on the branch, self-hosted runners, honest incidents1020 .collect();
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1021 // An unknown ref logs nothing; that is not kept, in case it arrives.
1022 if !commits.is_empty()
Fast pages, required checks on the branch, self-hosted runners, honest incidents1023 && let Ok(bytes) = serde_json::to_vec(&commits)
1024 {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1025 if let Some(key) = &key {
1026 self.put_key(key, bytes.clone()).await;
1027 }
1028 // The same history, by the commit the name led to.
1029 if !is_commit_hash(git_ref)
1030 && let Some(CacheKey::Forever(path)) = log_key(&commits[0].hash, limit, None)
1031 {
1032 self.keep_at(&path, bytes, OBJECT_MAX_AGE).await;
1033 }
Fast pages, required checks on the branch, self-hosted runners, honest incidents1034 }
1035 Ok(commits)
Rust repos service with shipping; pull requests kept in the model1036 }
1037
1038 async fn parents(&self, commit_hash: &str) -> Result<Option<Vec<String>>> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1039 // A commit never changes.
1040 if let Some(bytes) = self.cached("commit", commit_hash).await
1041 && let Ok(parents) = serde_json::from_slice::<Vec<String>>(&bytes)
1042 {
1043 return Ok(Some(parents));
1044 }
1045 let commit: Option<RawCommit> = js::from_js(&self.call("readCommit", &[commit_hash.into()], true).await?)?;
1046 let parents = commit.map(|commit| commit.parents);
1047 if let Some(parents) = &parents
1048 && let Ok(bytes) = serde_json::to_vec(parents)
1049 {
1050 self.keep("commit", commit_hash, bytes).await;
1051 }
1052 Ok(parents)
Rust repos service with shipping; pull requests kept in the model1053 }
1054
1055 async fn read_tree(&self, tree_hash: &str) -> Result<Option<Vec<TreeEntry>>> {
Polish: phones, copy boxes, the plan page, the landing page, a real glide1056 if let Some(bytes) = self.cached("tree", tree_hash).await
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1057 && let Ok(entries) = serde_json::from_slice::<Vec<TreeEntry>>(&bytes)
1058 {
1059 return Ok(Some(entries));
1060 }
1061 let entries: Option<Vec<RawEntry>> = js::from_js(&self.call("readTree", &[tree_hash.into()], true).await?)?;
Agents as a team: lifecycle, merge queue, billing and a new shell1062 let entries: Option<Vec<TreeEntry>> = entries.map(|entries| {
Rust repos service with shipping; pull requests kept in the model1063 entries
1064 .into_iter()
1065 .map(|entry| TreeEntry {
1066 name: entry.name,
1067 hash: entry.hash,
1068 kind: entry.kind,
1069 })
1070 .collect()
Agents as a team: lifecycle, merge queue, billing and a new shell1071 });
Polish: phones, copy boxes, the plan page, the landing page, a real glide1072 if let Some(entries) = &entries
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1073 && let Ok(bytes) = serde_json::to_vec(entries)
1074 {
1075 self.keep("tree", tree_hash, bytes).await;
1076 }
Agents as a team: lifecycle, merge queue, billing and a new shell1077 Ok(entries)
Rust repos service with shipping; pull requests kept in the model1078 }
1079
1080 async fn read_blob(&self, blob_hash: &str) -> Result<Option<Vec<u8>>> {
Agents as a team: lifecycle, merge queue, billing and a new shell1081 if let Some(bytes) = self.cached("blob", blob_hash).await {
1082 return Ok(Some(bytes));
1083 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1084 let bytes = blob_bytes(self.call("readBlob", &[blob_hash.into()], true).await?).await?;
1085 if let Some(bytes) = &bytes {
1086 meters::record_bytes("binding.read_blob", &self.key, 0, bytes.len() as u64);
1087 }
Agents as a team: lifecycle, merge queue, billing and a new shell1088 if let Some(bytes) = bytes.as_ref().filter(|bytes| bytes.len() <= MAX_CACHED_BLOB) {
1089 self.keep("blob", blob_hash, bytes.clone()).await;
1090 }
1091 Ok(bytes)
Rust repos service with shipping; pull requests kept in the model1092 }
1093
1094 async fn read_file(&self, git_ref: &str, path: &str) -> Result<Option<Vec<u8>>> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1095 let key = file_key(git_ref, path, self.refs_version);
1096 if let Some(key) = &key
1097 && let Some(bytes) = self.get_key(key).await
1098 {
1099 return Ok(Some(bytes));
1100 }
Rust repos service with shipping; pull requests kept in the model1101 let args = js::to_js(&serde_json::json!({ "ref": git_ref, "path": path }))?;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1102 let bytes = blob_bytes(self.call("readFile", &[args], true).await?).await?;
1103 if let Some(bytes) = &bytes {
1104 meters::record_bytes("binding.read_file", &self.key, 0, bytes.len() as u64);
1105 }
1106 if let (Some(key), Some(bytes)) = (&key, bytes.as_ref().filter(|bytes| bytes.len() <= MAX_CACHED_BLOB)) {
1107 self.put_key(key, bytes.clone()).await;
1108 }
1109 Ok(bytes)
Rust repos service with shipping; pull requests kept in the model1110 }
1111
1112 async fn fork(&self, target_key: &str) -> Result<()> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1113 let (namespace, name) = locate(target_key);
1114 if namespace != self.namespace {
1115 return Err(worker::Error::RustError(format!(
1116 "a fork stays in its repository's namespace: {target_key} is not in {}",
1117 self.namespace
1118 )));
1119 }
Rust repos service with shipping; pull requests kept in the model1120 let options = js::to_js(&serde_json::json!({ "defaultBranchOnly": true }))?;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1121 match self.call("fork", &[name.as_str().into(), options], false).await {
1122 Err(failed) if !failed.is("ALREADY_EXISTS") => Err(failed.into()),
Rust repos service with shipping; pull requests kept in the model1123 _ => Ok(()),
1124 }
1125 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1126
1127 fn at_refs_version(&mut self, version: Option<u64>) {
Merge branch 'worktree-agent-a2013627e5ea4ab13'1128 // The fallback store holds what the last backup held, which may be
1129 // behind what was kept under the version: nothing is kept for it.
1130 self.refs_version = if self.binding.is_fallback() { None } else { version };
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1131 }
Rust repos service with shipping; pull requests kept in the model1132}
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1133
1134#[cfg(test)]
1135mod tests {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1136 use super::*;
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1137
1138 fn access(token: &str) -> GitAccess {
1139 GitAccess {
1140 remote: "https://store.example/acme--rocket.git".to_owned(),
1141 token: token.to_owned(),
1142 }
1143 }
1144
1145 #[test]
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1146 fn internal_credentials_live_an_hour_and_are_reused_for_fifty_minutes() {
1147 assert_eq!(Use::Internal.ttl_seconds(), 3_600);
1148 assert_eq!(Use::Internal.reuse_ms(), 50 * 60 * 1000);
1149 // Handed out: five minutes, reused three, so at least two are left.
1150 assert_eq!(Use::Handout.ttl_seconds(), 300);
1151 assert_eq!(Use::Handout.reuse_ms(), 180_000);
1152 assert_eq!(CREDENTIAL_LIFE_MS, 300_000);
1153 for using in [Use::Internal, Use::Handout] {
1154 assert!(u64::from(using.ttl_seconds()) * 1000 - using.reuse_ms() >= 120_000);
1155 }
1156 }
1157
1158 #[test]
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1159 fn a_credential_is_reused_only_while_it_has_time_left() {
1160 let mut kept = Credentials::default();
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1161 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
1162 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000).unwrap().token, "r1");
1163 let last = 1_000 + INTERNAL_REUSE_MS - 1;
1164 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Internal, last).unwrap().token, "r1");
1165 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, last + 1).is_none());
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1166 }
1167
1168 #[test]
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1169 fn a_credential_is_kept_for_its_own_repository_scope_and_use() {
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1170 let mut kept = Credentials::default();
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1171 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1172 // A read credential never stands in for a write one.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1173 assert!(kept.get("acme--rocket", Scope::Write, Use::Internal, 1_000).is_none());
1174 assert!(kept.get("acme--booster", Scope::Read, Use::Internal, 1_000).is_none());
1175 // An hour-long credential is never handed out.
1176 assert!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000).is_none());
1177 kept.keep("acme--rocket", Scope::Read, Use::Handout, access("h1"), 1_000, 1_000);
1178 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000).unwrap().token, "h1");
1179 assert!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000 + HANDOUT_REUSE_MS).is_none());
1180 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000 + HANDOUT_REUSE_MS).is_some());
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1181 }
1182
1183 #[test]
1184 fn a_shared_credential_is_reused_only_in_its_own_window() {
1185 let value = serde_json::to_vec(&SharedCredential {
1186 remote: "https://store.example/acme--rocket.git".to_owned(),
1187 token: "r1".to_owned(),
1188 made: 10_000,
1189 })
1190 .unwrap();
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1191 let (access, made) = shared_credential(&value, 10_000 + INTERNAL_REUSE_MS - 1, Use::Internal).unwrap();
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1192 assert_eq!(access.token, "r1");
1193 // Kept here only for what is left of its window, not a new one.
1194 assert_eq!(made, 10_000);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1195 assert!(shared_credential(&value, 10_000 + INTERNAL_REUSE_MS, Use::Internal).is_none());
1196 assert!(shared_credential(&value, 10_000 + HANDOUT_REUSE_MS, Use::Handout).is_none());
1197 assert!(shared_credential(b"not json", 10_000, Use::Internal).is_none());
1198 // Each repository, scope and use has its own key, and none is read
1199 // from before uses differed.
1200 assert_eq!(shared_key("acme--rocket", Scope::Read, Use::Internal), "cred2:acme--rocket:read:internal");
1201 assert_ne!(shared_key("acme--rocket", Scope::Read, Use::Internal), shared_key("acme--rocket", Scope::Write, Use::Internal));
1202 assert_ne!(shared_key("acme--rocket", Scope::Read, Use::Internal), shared_key("acme--rocket", Scope::Read, Use::Handout));
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1203 }
1204
1205 #[test]
1206 fn a_shared_credential_kept_here_expires_with_the_original() {
1207 let mut kept = Credentials::default();
1208 // Made at 1_000 elsewhere, found here at 100_000.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1209 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 100_000);
1210 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 100_000).is_some());
1211 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000 + INTERNAL_REUSE_MS).is_none());
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1212 }
1213
1214 #[test]
1215 fn a_turned_down_credential_is_forgotten_and_old_ones_are_dropped() {
1216 let mut kept = Credentials::default();
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1217 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
1218 kept.keep("acme--rocket", Scope::Write, Use::Handout, access("w1"), 1_000, 1_000);
1219 kept.keep("acme--booster", Scope::Read, Use::Internal, access("b1"), 1_000, 1_000);
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1220 kept.forget("acme--rocket");
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1221 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000).is_none());
1222 assert!(kept.get("acme--rocket", Scope::Write, Use::Handout, 1_000).is_none());
1223 assert!(kept.get("acme--booster", Scope::Read, Use::Internal, 1_000).is_some());
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1224 // Keeping another later drops the expired one from the map.
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1225 let later = 1_000 + INTERNAL_REUSE_MS;
1226 kept.keep("acme--other", Scope::Read, Use::Internal, access("o1"), later, later);
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms1227 assert_eq!(kept.kept.len(), 1);
1228 }
Fast pages, required checks on the branch, self-hosted runners, honest incidents1229
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1230 #[test]
1231 fn a_remote_is_worked_out_from_where_its_namespace_starts() {
1232 // As https://developers.cloudflare.com/artifacts/api/git-protocol/ documents.
1233 let remote = "https://1e6f2cffa3f445920836e8ebe446bb58.artifacts.cloudflare.net/git/g1t/acme--rocket.git";
1234 let prefix = learn_prefix(remote, "acme--rocket").unwrap();
1235 assert_eq!(prefix, "https://1e6f2cffa3f445920836e8ebe446bb58.artifacts.cloudflare.net/git/g1t/");
1236 assert_eq!(remote_from(&prefix, "pulls--pul_1"), prefix.clone() + "pulls--pul_1.git");
1237 assert_eq!(remote_from(&prefix, "acme--rocket"), remote);
1238 // A remote that does not end in the name teaches nothing.
1239 assert_eq!(learn_prefix(remote, "rocket"), None);
1240 assert_eq!(learn_prefix("https://x/acme--rocket", "acme--rocket"), None);
1241 // And back: a remote names its key.
1242 assert_eq!(key_from_remote(remote).as_deref(), Some("acme--rocket"));
1243 assert_eq!(
1244 key_from_remote("https://a.artifacts.cloudflare.net/git/g1t-us-1/acme--rocket.git").as_deref(),
1245 Some("g1t-us-1/acme--rocket")
1246 );
1247 assert_eq!(locate("g1t-us-1/acme--rocket"), ("g1t-us-1".to_owned(), "acme--rocket".to_owned()));
1248 assert_eq!(locate("acme--rocket"), ("g1t".to_owned(), "acme--rocket".to_owned()));
1249 }
1250
1251 #[test]
Merge branch 'worktree-agent-a2013627e5ea4ab13'1252 fn the_fallback_stores_credentials_and_remotes_are_its_own() {
1253 assert_eq!(cred_key("acme--rocket", false), "acme--rocket");
1254 assert_eq!(cred_key("g1t-us-1/acme--rocket", true), "fallback:g1t-us-1/acme--rocket");
1255 // A credential Artifacts made is never handed out for the fallback
1256 // store, nor the reverse.
1257 assert_ne!(
1258 shared_key(&cred_key("acme--rocket", true), Scope::Write, Use::Internal),
1259 shared_key(&cred_key("acme--rocket", false), Scope::Write, Use::Internal)
1260 );
1261 // Its remotes name their keys as Artifacts' do.
1262 let settings = fallback::Settings::from_vars(Some("https://gitstore.example"), Some("0123456789abcdef"), Some("*"), None).unwrap();
1263 assert_eq!(key_from_remote(&settings.remote("g1t", "acme--rocket")).as_deref(), Some("acme--rocket"));
1264 assert_eq!(key_from_remote(&settings.remote("g1t-us-1", "pulls--pul_1")).as_deref(), Some("g1t-us-1/pulls--pul_1"));
1265 // Git requests to it count toward its own health, not Artifacts'.
1266 FALLBACK_BASE.with(|base| *base.borrow_mut() = Some(format!("{}/git/", settings.url)));
1267 assert_eq!(health_namespace(&settings.remote("g1t-us-1", "acme--rocket")), "g1t-us-1@fallback");
1268 assert_eq!(health_namespace("https://a.artifacts.cloudflare.net/git/g1t-us-1/acme--rocket.git"), "g1t-us-1");
1269 FALLBACK_BASE.with(|base| *base.borrow_mut() = None);
1270 }
1271
1272 #[test]
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for1273 fn the_memory_cache_drops_its_oldest_past_its_budget() {
1274 let mut cache = MemoryCache::default();
1275 let chunk = vec![7u8; MEMORY_CACHE_BYTES / 16];
1276 for n in 0..17 {
1277 cache.put(format!("k{n}"), &chunk);
1278 }
1279 // Sixteen chunks fit; the seventeenth pushed the first out.
1280 assert!(cache.get("k0").is_none());
1281 assert_eq!(cache.get("k16").map(|b| b.len()), Some(chunk.len()));
1282 assert!(cache.bytes <= MEMORY_CACHE_BYTES);
1283 // Too large to keep at all.
1284 cache.put("big".into(), &vec![0u8; MEMORY_CACHE_BYTES / 16 + 1]);
1285 assert!(cache.get("big").is_none());
1286 }
1287
1288 #[test]
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1289 fn binding_methods_have_snake_case_meters() {
1290 assert_eq!(meter_of("createToken"), "binding.create_token");
1291 assert_eq!(meter_of("readBlob"), "binding.read_blob");
1292 assert_eq!(meter_of("get"), "binding.get");
1293 }
1294
1295 #[test]
1296 fn reads_by_name_are_kept_under_the_refs_version_and_by_hash_for_good() {
1297 let hash = "a".repeat(40);
1298 assert_eq!(log_key(&hash, 1, Some(3)), Some(CacheKey::Forever(format!("log/{hash}-1"))));
1299 assert_eq!(log_key(&hash, 1, None), Some(CacheKey::Forever(format!("log/{hash}-1"))));
1300 // A branch is kept only when the version is known.
1301 assert_eq!(log_key("main", 1, None), None);
1302 let v3 = log_key("main", 1, Some(3)).unwrap();
1303 assert!(matches!(&v3, CacheKey::Versioned(path) if path.starts_with("vlog/3/")));
1304 // A push moves the version and leaves the old answer behind.
1305 assert_ne!(Some(v3), log_key("main", 1, Some(4)));
1306 assert_ne!(log_key("main", 1, Some(3)), log_key("main", 50, Some(3)));
1307 assert_ne!(log_key("main", 1, Some(3)), log_key("dev", 1, Some(3)));
1308 // Odd branch names make a usable address.
1309 assert!(matches!(log_key("fix/#1 %20", 1, Some(3)), Some(CacheKey::Versioned(path)) if !path.contains('#') && !path.contains(' ')));
1310 assert_eq!(branches_key(None), None);
1311 assert_ne!(branches_key(Some(1)), branches_key(Some(2)));
1312 assert!(matches!(file_key(&hash, "src/main.rs", None), Some(CacheKey::Forever(_))));
1313 assert_eq!(file_key("main", "src/main.rs", None), None);
1314 assert_ne!(file_key("main", "a", Some(1)), file_key("main", "b", Some(1)));
1315 assert_ne!(file_key("main", "a", Some(1)), file_key("main", "a", Some(2)));
1316 }
Fast pages, required checks on the branch, self-hosted runners, honest incidents1317
1318 #[test]
1319 fn only_full_lowercase_hashes_are_kept() {
1320 assert!(is_commit_hash(&"a".repeat(40)));
1321 assert!(is_commit_hash(&"0123456789abcdef".repeat(4)));
1322 assert!(!is_commit_hash("main"));
1323 assert!(!is_commit_hash(&"A".repeat(40)));
1324 assert!(!is_commit_hash(&"a".repeat(39)));
1325 }
1326}

This file's history is long; its oldest lines are credited to the oldest commit read.