Skip to content
1,507 linesCodeBlameRaw
1//! 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.
5//!
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).
11
12use g1t_contracts::repos::{Branch, Commit, EntryKind, GitAccess, Signature, TreeEntry};
13use g1t_contracts::time::rfc3339;
14use g1t_kit::js::{self, Thrown};
15use serde::{Deserialize, Serialize};
16use std::cell::RefCell;
17use std::collections::HashMap;
18use std::rc::Rc;
19use worker::js_sys::{Reflect, Uint8Array};
20use worker::wasm_bindgen::{JsCast, JsValue};
21use worker::{Env, Result};
22
23use crate::fallback;
24use 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;
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.
37const 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;
41
42#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
43pub enum Scope {
44 Read,
45 Write,
46}
47
48impl Scope {
49 fn as_str(self) -> &'static str {
50 match self {
51 Scope::Read => "read",
52 Scope::Write => "write",
53 }
54 }
55}
56
57/// 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
89/// 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
107/// 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.
113 async fn create(&self, key: &str, description: Option<&str>, default_branch: &str) -> Result<()>;
114 async fn open(&self, key: &str) -> Result<Self::Repo>;
115 /// 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 }
123 /// A remote URL and credential for this service's own use. A store may
124 /// hand out one it made a moment ago.
125 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 }
131 /// 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 }
135 /// 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) {}
138 /// Removes a repository and everything in it, for good. Succeeds if it
139 /// is already gone.
140 async fn delete(&self, key: &str) -> Result<()>;
141 /// 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 }
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 }
160}
161
162/// One open repository.
163#[allow(async_fn_in_trait)]
164pub trait GitRepo {
165 /// A remote URL and credential for git itself, for this service.
166 async fn access(&self, scope: Scope) -> Result<GitAccess>;
167 /// Every branch and the commit it points to.
168 async fn branches(&self) -> Result<Vec<Branch>>;
169 /// 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 /// A blob's size in bytes, `None` when it is missing. By default its
176 /// bytes are read; a store that can say less does.
177 async fn blob_size(&self, blob_hash: &str) -> Result<Option<u64>> {
178 Ok(self.read_blob(blob_hash).await?.map(|bytes| bytes.len() as u64))
179 }
180 /// `None` when the ref or path does not resolve to a file.
181 async fn read_file(&self, git_ref: &str, path: &str) -> Result<Option<Vec<u8>>>;
182 /// Makes a copy of this repository under `target_key`, in the same
183 /// namespace.
184 async fn fork(&self, target_key: &str) -> Result<()>;
185 /// The version of the repository's refs (registry.rs `RefsState`),
186 /// when answers about branches may be kept under it (R9). Reads by
187 /// branch name are then kept until the version moves.
188 fn at_refs_version(&mut self, _version: Option<u64>) {}
189}
190
191thread_local! {
192 /// The namespace bound to `ARTIFACTS`, for keys that name none.
193 static DEFAULT_NS: RefCell<String> = RefCell::new(shards::DEFAULT_NAMESPACE.to_owned());
194 /// Where each namespace's remotes start: `https://<account>.artifacts.cloudflare.net/git/<namespace>/`.
195 static REMOTE_PREFIX: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
196}
197
198/// The namespace and name a store key stands for.
199pub fn locate(key: &str) -> (String, String) {
200 let (namespace, name) = shards::split(key);
201 let namespace = namespace.map_or_else(|| DEFAULT_NS.with(|ns| ns.borrow().clone()), str::to_owned);
202 (namespace, name.to_owned())
203}
204
205thread_local! {
206 /// Where the fallback store's remotes start, when one is configured.
207 static FALLBACK_BASE: RefCell<Option<String>> = const { RefCell::new(None) };
208}
209
210/// Whose breaker and health git requests to `remote` count toward: its
211/// namespace's, or `<namespace>@fallback` for the fallback store's.
212pub fn health_namespace(remote: &str) -> String {
213 let (namespace, _) = locate(&key_from_remote(remote).unwrap_or_default());
214 let on_fallback = FALLBACK_BASE.with(|base| base.borrow().as_deref().is_some_and(|base| remote.starts_with(base)));
215 if on_fallback { format!("{namespace}@fallback") } else { namespace }
216}
217
218/// The store key a git remote is for, from its last two path segments.
219pub fn key_from_remote(remote: &str) -> Option<String> {
220 let path = remote.trim_end_matches('/');
221 let path = path.strip_suffix(".git").unwrap_or(path);
222 let (rest, name) = path.rsplit_once('/')?;
223 let namespace = rest.rsplit('/').next()?;
224 let default = DEFAULT_NS.with(|ns| ns.borrow().clone());
225 Some(shards::compose(Some(namespace), name, &default))
226}
227
228/// Where a namespace's remotes start, learned from one remote the store
229/// gave for `name`.
230fn learn_prefix(remote: &str, name: &str) -> Option<String> {
231 remote.strip_suffix(&format!("{name}.git")).filter(|prefix| prefix.ends_with('/')).map(str::to_owned)
232}
233
234/// A repository's remote, from where its namespace's remotes start.
235fn remote_from(prefix: &str, name: &str) -> String {
236 format!("{prefix}{name}.git")
237}
238
239struct Namespace {
240 name: String,
241 /// Its binding, for every call: Artifacts, or the fallback store.
242 target: Target,
243}
244
245/// What a call on the store goes to: an Artifacts binding or one of its
246/// repository handles, or the fallback store (fallback.rs) for a
247/// namespace, or for one repository in it.
248#[derive(Clone)]
249enum Target {
250 Js(JsValue),
251 Fallback {
252 settings: Rc<fallback::Settings>,
253 namespace: String,
254 repo: Option<String>,
255 },
256}
257
258impl Target {
259 fn is_fallback(&self) -> bool {
260 matches!(self, Target::Fallback { .. })
261 }
262
263 /// Whose breaker and health a call counts toward: the fallback store's
264 /// own, so an Artifacts outage never holds it back.
265 fn health_name(&self, namespace: &str) -> String {
266 if self.is_fallback() { format!("{namespace}@fallback") } else { namespace.to_owned() }
267 }
268}
269
270pub struct ArtifactsStore {
271 namespaces: Rc<Vec<Namespace>>,
272 /// Where isolates share the credentials they make; see shared.rs.
273 shared: Option<Rc<crate::shared::Shared>>,
274}
275
276impl ArtifactsStore {
277 pub fn new(env: &Env, shared: Option<Rc<crate::shared::Shared>>) -> Result<Self> {
278 let config = env.var("ARTIFACTS_NAMESPACES").ok().map(|value| value.to_string());
279 let text = |name: &str| env.var(name).ok().map(|value| value.to_string());
280 let secret = env.secret("GIT_FALLBACK_SECRET").ok().map(|value| value.to_string());
281 let fallback = fallback::Settings::from_vars(
282 text("GIT_FALLBACK_URL").as_deref(),
283 secret.as_deref(),
284 text("GIT_FALLBACK_NAMESPACES").as_deref(),
285 text("GIT_FALLBACK_WRITES").as_deref(),
286 )
287 .map(Rc::new);
288 FALLBACK_BASE.with(|base| *base.borrow_mut() = fallback.as_ref().map(|settings| format!("{}/git/", settings.url)));
289 let mut namespaces = Vec::new();
290 for (binding, name) in shards::bindings(config.as_deref()) {
291 // Served from the fallback store, by configuration.
292 if let Some(settings) = fallback.as_ref().filter(|settings| settings.serves(&name)) {
293 worker::console_log!("git store {name}: served from the fallback store");
294 let target = Target::Fallback { settings: settings.clone(), namespace: name.clone(), repo: None };
295 namespaces.push(Namespace { name, target });
296 continue;
297 }
298 match js::binding(env, &binding) {
299 Ok(value) => namespaces.push(Namespace { name, target: Target::Js(value) }),
300 // The default binding is required; the others are optional.
301 Err(error) if binding == shards::DEFAULT_BINDING => return Err(error),
302 Err(_) => worker::console_error!("ARTIFACTS_NAMESPACES names {binding}, which is not bound"),
303 }
304 }
305 if let Some(default) = namespaces.first() {
306 DEFAULT_NS.with(|ns| ns.borrow_mut().clone_from(&default.name));
307 }
308 // Optional: where remotes start, `https://<account>.artifacts.cloudflare.net/git`,
309 // so the first credential an isolate makes needs no `info()` either.
310 if let Ok(base) = env.var("ARTIFACTS_REMOTE_BASE") {
311 let base = base.to_string().trim_end_matches('/').to_owned();
312 if base.starts_with("https://") {
313 REMOTE_PREFIX.with(|prefixes| {
314 let mut prefixes = prefixes.borrow_mut();
315 for namespace in &namespaces {
316 prefixes.entry(namespace.name.clone()).or_insert_with(|| format!("{base}/{}/", namespace.name));
317 }
318 });
319 }
320 }
321 Ok(Self { namespaces: Rc::new(namespaces), shared })
322 }
323
324 fn binding(&self, namespace: &str) -> Result<&Target> {
325 self.namespaces
326 .iter()
327 .find(|candidate| candidate.name == namespace)
328 .map(|found| &found.target)
329 .ok_or_else(|| worker::Error::RustError(format!("git store namespace {namespace} is not bound")))
330 }
331
332 /// The fallback store's settings, when `namespace` is served from it.
333 fn fallback_of(&self, namespace: &str) -> Option<&fallback::Settings> {
334 match self.binding(namespace).ok()? {
335 Target::Fallback { settings, .. } => Some(settings),
336 Target::Js(_) => None,
337 }
338 }
339
340 /// The name credentials for `key` are kept under: those of the
341 /// fallback store never stand in for Artifacts' own, nor the reverse.
342 fn cred_key(&self, key: &str) -> String {
343 let (namespace, _) = locate(key);
344 cred_key(key, self.fallback_of(&namespace).is_some())
345 }
346}
347
348/// See [`ArtifactsStore::cred_key`].
349fn cred_key(key: &str, on_fallback: bool) -> String {
350 if on_fallback { format!("fallback:{key}") } else { key.to_owned() }
351}
352
353/// A failed call on the binding.
354pub struct StoreError {
355 pub thrown: Thrown,
356 pub busy: Option<Busy>,
357}
358
359impl StoreError {
360 pub fn is(&self, code: &str) -> bool {
361 self.thrown.is(code)
362 }
363}
364
365impl From<StoreError> for worker::Error {
366 fn from(error: StoreError) -> Self {
367 match error.busy {
368 Some(busy) => busy.error(&error.thrown.to_string()),
369 None => error.thrown.into(),
370 }
371 }
372}
373
374/// The meter for a binding method: `binding.create_token`.
375fn meter_of(method: &str) -> String {
376 let mut out = String::from("binding.");
377 for c in method.chars() {
378 if c.is_ascii_uppercase() {
379 out.push('_');
380 out.push(c.to_ascii_lowercase());
381 } else {
382 out.push(c);
383 }
384 }
385 out
386}
387
388/// Seconds a caller is told to wait when the store is busy.
389const BUSY_RETRY_AFTER: u64 = 5;
390
391/// Calls `target[method](...args)` on namespace `namespace`'s binding, for
392/// the repository at `key`. `retry`: whether a failure that may pass is
393/// tried again (reads and credentials only).
394async fn invoke(
395 namespace: &str,
396 key: &str,
397 target: &Target,
398 method: &str,
399 args: &[JsValue],
400 retry: bool,
401) -> std::result::Result<JsValue, StoreError> {
402 let meter = meter_of(method);
403 let health = target.health_name(namespace);
404 let namespace = health.as_str();
405 // A read-only fallback refuses writes before asking (fallback.rs).
406 if let Target::Fallback { settings, repo, .. } = target
407 && !settings.writes
408 {
409 let values: Vec<serde_json::Value> = args.iter().map(|arg| js::from_js(arg).unwrap_or(serde_json::Value::Null)).collect();
410 if fallback::writes(repo.as_deref(), method, &values) {
411 return Err(StoreError {
412 thrown: Thrown { code: Some("READ_ONLY".to_owned()), message: format!("{method} refused: the git store is read-only") },
413 busy: Some(Busy::read_only()),
414 });
415 }
416 }
417 let mut attempt = 0;
418 loop {
419 let now = g1t_kit::now_ms();
420 let admit = resilience::with_breaker(namespace, |breaker| breaker.admit(now));
421 if let Admit::Wait(ms) = admit {
422 meters::record_health(namespace, Outcome::Rejected, 0);
423 return Err(StoreError {
424 thrown: Thrown { code: None, message: format!("{method} not asked: the git store has been failing") },
425 busy: Some(Busy { rate_limited: false, retry_after: resilience::seconds(ms).max(BUSY_RETRY_AFTER), read_only: false }),
426 });
427 }
428 // Calls on Artifacts are metered; the fallback store costs nothing
429 // per call.
430 if !target.is_fallback() {
431 meters::record(&meter, key, 0, 0);
432 }
433 let called = dispatch(target, method, args).await;
434 let ms = g1t_kit::now_ms().saturating_sub(now);
435 match called {
436 Ok(value) => {
437 resilience::with_breaker(namespace, |breaker| breaker.succeeded());
438 meters::record_health(namespace, Outcome::Ok, ms);
439 return Ok(value);
440 }
441 Err(thrown) => {
442 let failure = resilience::classify(thrown.code.as_deref(), &thrown.message);
443 if failure == Failure::Permanent {
444 // An answer (NOT_FOUND, ALREADY_EXISTS): the store is up.
445 resilience::with_breaker(namespace, |breaker| breaker.succeeded());
446 meters::record_health(namespace, Outcome::Ok, ms);
447 return Err(StoreError { thrown, busy: None });
448 }
449 if retry && resilience::retry(failure, attempt) {
450 let wait = resilience::backoff_ms(failure, attempt, worker::js_sys::Math::random());
451 worker::Delay::from(std::time::Duration::from_millis(wait)).await;
452 attempt += 1;
453 continue;
454 }
455 resilience::with_breaker(namespace, |breaker| breaker.failed(failure, g1t_kit::now_ms()));
456 let outcome = if failure == Failure::RateLimited { Outcome::RateLimited } else { Outcome::Failed };
457 meters::record_health(namespace, outcome, ms);
458 worker::console_error!("git store {namespace}: {method} for {key} failed: {thrown}");
459 return Err(StoreError {
460 thrown,
461 busy: Some(Busy { rate_limited: failure == Failure::RateLimited, retry_after: BUSY_RETRY_AFTER, read_only: false }),
462 });
463 }
464 }
465 }
466}
467
468/// Makes one call: on the binding, or as a request to the fallback store.
469async fn dispatch(target: &Target, method: &str, args: &[JsValue]) -> std::result::Result<JsValue, Thrown> {
470 let (settings, namespace, repo) = match target {
471 Target::Js(value) => return js::call(value, method, args).await,
472 Target::Fallback { settings, namespace, repo } => (settings, namespace, repo),
473 };
474 let values: Vec<serde_json::Value> = args.iter().map(|arg| js::from_js(arg).unwrap_or(serde_json::Value::Null)).collect();
475 let route = fallback::route(namespace, repo.as_deref(), method, &values)
476 .map_err(|refused| Thrown { code: Some(refused.code.to_owned()), message: refused.message })?;
477 let unreachable = |error: worker::Error| Thrown { code: None, message: format!("the fallback store could not be reached: {error}") };
478 let headers = worker::Headers::new();
479 headers.set("x-gitstore-secret", &settings.secret).map_err(unreachable)?;
480 let mut init = worker::RequestInit::new();
481 init.with_method(match route.method {
482 "POST" => worker::Method::Post,
483 "DELETE" => worker::Method::Delete,
484 _ => worker::Method::Get,
485 });
486 if let Some(body) = &route.body {
487 headers.set("content-type", "application/json").map_err(unreachable)?;
488 init.with_body(Some(JsValue::from_str(&body.to_string())));
489 }
490 init.with_headers(headers);
491 let request = worker::Request::new_with_init(&format!("{}{}", settings.url, route.path), &init).map_err(unreachable)?;
492 let mut response = worker::Fetch::Request(request).send().await.map_err(unreachable)?;
493 let status = response.status_code();
494 let body = response.bytes().await.map_err(unreachable)?;
495 match fallback::answer(&route, status, body) {
496 fallback::Answer::Json(value) => js::to_js(&value).map_err(|error| Thrown { code: None, message: error.to_string() }),
497 fallback::Answer::Bytes(bytes) => Ok(Uint8Array::from(bytes.as_slice()).into()),
498 fallback::Answer::Null => Ok(JsValue::NULL),
499 fallback::Answer::Error { code, message } => Err(Thrown { code, message }),
500 }
501}
502
503/// A credential as isolates share it, sealed (see shared.rs): with when it
504/// was made, so that one shared is reused no longer than one kept here.
505#[derive(Serialize, Deserialize)]
506struct SharedCredential {
507 remote: String,
508 token: String,
509 made: u64,
510}
511
512/// The shared cache's key for a credential: the store's key for the
513/// repository, the scope, and who it is for. (`cred2`: credentials kept
514/// before their lives differed by use are not read.)
515fn shared_key(key: &str, scope: Scope, using: Use) -> String {
516 format!("cred2:{key}:{}:{}", scope.as_str(), using.as_str())
517}
518
519/// A shared credential, if it was made less than its reuse window before
520/// `now`; with when it was made.
521fn shared_credential(bytes: &[u8], now: u64, using: Use) -> Option<(GitAccess, u64)> {
522 let kept: SharedCredential = serde_json::from_slice(bytes).ok()?;
523 (now.saturating_sub(kept.made) < using.reuse_ms()).then_some((
524 GitAccess {
525 remote: kept.remote,
526 token: kept.token,
527 },
528 kept.made,
529 ))
530}
531
532/// Credentials made a while ago, by repository, scope and use. Making one
533/// is a round trip to the store; reusing it saves that, and the store's
534/// lookup of the repository with it.
535#[derive(Default)]
536pub struct Credentials {
537 kept: HashMap<(String, Scope, Use), (GitAccess, u64)>,
538}
539
540impl Credentials {
541 /// One made for `key`, `scope` and `using` within its reuse window of `now`.
542 pub fn get(&self, key: &str, scope: Scope, using: Use, now: u64) -> Option<GitAccess> {
543 self.kept
544 .get(&(key.to_owned(), scope, using))
545 .filter(|(_, made)| now.saturating_sub(*made) < using.reuse_ms())
546 .map(|(access, _)| access.clone())
547 }
548
549 pub fn keep(&mut self, key: &str, scope: Scope, using: Use, access: GitAccess, made: u64, now: u64) {
550 // Expired ones go first, so the map stays as small as the isolate's
551 // recent repositories.
552 self.kept
553 .retain(|(_, _, kept_use), (_, at)| now.saturating_sub(*at) < kept_use.reuse_ms());
554 self.kept.insert((key.to_owned(), scope, using), (access, made));
555 }
556
557 pub fn forget(&mut self, key: &str) {
558 self.kept.retain(|(kept, _, _), _| kept != key);
559 }
560}
561
562thread_local! {
563 static CREDENTIALS: RefCell<Credentials> = RefCell::new(Credentials::default());
564}
565
566/// A credential kept in this isolate, else one another isolate shared.
567async fn kept(shared: Option<&crate::shared::Shared>, key: &str, scope: Scope, using: Use) -> Option<(GitAccess, Kept)> {
568 let now = g1t_kit::now_ms();
569 if let Some(access) = CREDENTIALS.with(|kept| kept.borrow().get(key, scope, using, now)) {
570 return Some((access, Kept::Isolate));
571 }
572 let bytes = shared?.get(&shared_key(key, scope, using)).await?;
573 let (access, made) = shared_credential(&bytes, now, using)?;
574 CREDENTIALS.with(|kept| kept.borrow_mut().keep(key, scope, using, access.clone(), made, now));
575 Some((access, Kept::Shared))
576}
577
578/// Keeps a credential just made here, and shares it.
579async fn keep(shared: Option<&crate::shared::Shared>, key: &str, scope: Scope, using: Use, access: &GitAccess) {
580 let now = g1t_kit::now_ms();
581 CREDENTIALS.with(|kept| kept.borrow_mut().keep(key, scope, using, access.clone(), now, now));
582 if let Some(shared) = shared {
583 let value = SharedCredential {
584 remote: access.remote.clone(),
585 token: access.token.clone(),
586 made: now,
587 };
588 if let Ok(bytes) = serde_json::to_vec(&value) {
589 shared.put(&shared_key(key, scope, using), &bytes, using.reuse_ms() / 1000).await;
590 }
591 }
592}
593
594impl GitStore for ArtifactsStore {
595 type Repo = ArtifactsRepo;
596
597 async fn kept_access(&self, key: &str, scope: Scope) -> Option<(GitAccess, Kept)> {
598 kept(self.shared.as_deref(), &self.cred_key(key), scope, Use::Internal).await
599 }
600
601 async fn mint_access(&self, key: &str, scope: Scope) -> Result<GitAccess> {
602 let repo = self.open(key).await?;
603 let access = repo.mint(scope, Use::Internal).await?;
604 keep(self.shared.as_deref(), &self.cred_key(key), scope, Use::Internal, &access).await;
605 Ok(access)
606 }
607
608 async fn handout(&self, key: &str, scope: Scope) -> Result<GitAccess> {
609 let cred_key = self.cred_key(key);
610 if let Some((access, _)) = kept(self.shared.as_deref(), &cred_key, scope, Use::Handout).await {
611 return Ok(access);
612 }
613 let access = self.open(key).await?.mint(scope, Use::Handout).await?;
614 keep(self.shared.as_deref(), &cred_key, scope, Use::Handout, &access).await;
615 Ok(access)
616 }
617
618 async fn forget_access(&self, key: &str) {
619 // Both stores' credentials: whichever serves the key now.
620 let names = [cred_key(key, false), cred_key(key, true)];
621 CREDENTIALS.with(|kept| {
622 let mut kept = kept.borrow_mut();
623 for name in &names {
624 kept.forget(name);
625 }
626 });
627 if let Some(shared) = &self.shared {
628 let keys: Vec<String> = names
629 .iter()
630 .flat_map(|name| {
631 [Scope::Read, Scope::Write]
632 .into_iter()
633 .flat_map(move |scope| [Use::Internal, Use::Handout].map(|using| shared_key(name, scope, using)))
634 })
635 .collect();
636 futures_util::future::join_all(keys.iter().map(|shared_key| shared.delete(shared_key))).await;
637 }
638 }
639
640 async fn create(&self, key: &str, description: Option<&str>, default_branch: &str) -> Result<()> {
641 let (namespace, name) = locate(key);
642 let options = js::to_js(&serde_json::json!({
643 "description": description,
644 "setDefaultBranch": default_branch,
645 }))?;
646 match invoke(&namespace, key, self.binding(&namespace)?, "create", &[name.as_str().into(), options], true).await {
647 // Left behind by an earlier failed attempt; adopt it.
648 Err(failed) if !failed.is("ALREADY_EXISTS") => Err(failed.into()),
649 _ => Ok(()),
650 }
651 }
652
653 async fn delete(&self, key: &str) -> Result<()> {
654 let (namespace, name) = locate(key);
655 // Nothing is forgotten while the store refuses to delete.
656 if self.writable(&namespace) {
657 self.forget_access(key).await;
658 }
659 match invoke(&namespace, key, self.binding(&namespace)?, "delete", &[name.as_str().into()], true).await {
660 // Gone already: an earlier purge got this far.
661 Err(failed) if !failed.is("NOT_FOUND") => Err(failed.into()),
662 _ => Ok(()),
663 }
664 }
665
666 async fn open(&self, key: &str) -> Result<ArtifactsRepo> {
667 let (namespace, name) = locate(key);
668 let binding = self.binding(&namespace)?.clone();
669 Ok(ArtifactsRepo {
670 handle: RefCell::new(None),
671 cred_key: cred_key(key, binding.is_fallback()),
672 binding,
673 key: key.to_owned(),
674 name,
675 namespace,
676 shared: self.shared.clone(),
677 refs_version: None,
678 })
679 }
680
681 fn namespaces(&self) -> Vec<String> {
682 self.namespaces.iter().map(|namespace| namespace.name.clone()).collect()
683 }
684
685 fn default_namespace(&self) -> String {
686 DEFAULT_NS.with(|ns| ns.borrow().clone())
687 }
688
689 fn on_fallback(&self, key: &str) -> bool {
690 let (namespace, _) = locate(key);
691 self.fallback_of(&namespace).is_some()
692 }
693
694 fn writable(&self, namespace: &str) -> bool {
695 self.fallback_of(namespace).is_none_or(|settings| settings.writes)
696 }
697}
698
699/// A handle to one repository in the store. On Artifacts it is an RPC
700/// stub, so it is released when dropped.
701pub struct ArtifactsRepo {
702 /// The store's handle, asked for (`get`) on the first call that needs
703 /// the store: an answer from a cache, or a fetch over git with a kept
704 /// credential, never costs a `get`.
705 handle: RefCell<Option<Target>>,
706 /// The namespace's binding, for that `get`.
707 binding: Target,
708 /// The repository's store key, which scopes its cached objects.
709 key: String,
710 /// What its credentials are kept under (`ArtifactsStore::cred_key`).
711 cred_key: String,
712 /// Its name in its namespace.
713 name: String,
714 namespace: String,
715 shared: Option<Rc<crate::shared::Shared>>,
716 /// See [`GitRepo::at_refs_version`].
717 refs_version: Option<u64>,
718}
719
720/// Where cached git objects live. Trees and blobs are named by their
721/// content, so a cached one is never stale; each is kept under its own
722/// repository's key, so a repository only ever finds its own objects.
723const OBJECT_CACHE: &str = "https://objects.g1t.internal/";
724/// Blobs and files larger than this are not cached.
725const MAX_CACHED_BLOB: usize = 1024 * 1024;
726const OBJECT_MAX_AGE: &str = "public, max-age=31536000, immutable";
727/// Answers kept under a refs version: until the version moves, and no
728/// longer than this, which bounds how stale one can be should a change
729/// ever fail to move it.
730const VERSIONED_MAX_AGE: &str = "public, max-age=300";
731/// How long a path found not to be a file at a ref is remembered. Short:
732/// a miss by commit hash is true for good, but one for a commit not yet in
733/// the store would not be.
734const ABSENT_MAX_AGE: &str = "public, max-age=600";
735
736/// Histories by hash at least this long are put together from a short
737/// read and one kept before, where they can be (`spliced_log`).
738const SPLICE_FROM: u32 = 100;
739/// How many commits that short read takes.
740const SPLICE_PROBE: u32 = 16;
741
742/// `short[..at]` followed by `kept` (the history from `short[at]`), cut
743/// to `limit` commits.
744pub fn splice(short: &[Commit], at: usize, kept: Vec<Commit>, limit: u32) -> Vec<Commit> {
745 let mut out: Vec<Commit> = short[..at.min(short.len())].to_vec();
746 out.extend(kept);
747 out.truncate(limit as usize);
748 out
749}
750
751/// Whether a ref is a full commit hash (SHA-1 or SHA-256), whose history
752/// can be kept for good.
753pub fn is_commit_hash(git_ref: &str) -> bool {
754 (git_ref.len() == 40 || git_ref.len() == 64) && git_ref.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
755}
756
757/// Where a read is kept: under the object it names for good, under the
758/// refs version for a name that can move, or nowhere.
759#[derive(Debug, PartialEq, Eq)]
760pub enum CacheKey {
761 Forever(String),
762 Versioned(String),
763}
764
765/// The cache key for `log(git_ref, limit)`.
766pub fn log_key(git_ref: &str, limit: u32, version: Option<u64>) -> Option<CacheKey> {
767 if is_commit_hash(git_ref) {
768 return Some(CacheKey::Forever(format!("log/{git_ref}-{limit}")));
769 }
770 version.map(|version| CacheKey::Versioned(format!("vlog/{version}/{}-{limit}", g1t_secrets::sha256_hex(git_ref))))
771}
772
773/// The cache key for `read_file(git_ref, path)`.
774pub fn file_key(git_ref: &str, path: &str, version: Option<u64>) -> Option<CacheKey> {
775 let path = g1t_secrets::sha256_hex(path);
776 if is_commit_hash(git_ref) {
777 return Some(CacheKey::Forever(format!("file/{git_ref}/{path}")));
778 }
779 version.map(|version| CacheKey::Versioned(format!("vfile/{version}/{}/{path}", g1t_secrets::sha256_hex(git_ref))))
780}
781
782/// Where `read_file` notes that its key is not a file (see `known_absent`).
783fn absent_path(key: &CacheKey) -> String {
784 match key {
785 CacheKey::Forever(path) | CacheKey::Versioned(path) => format!("absent/{path}"),
786 }
787}
788
789/// The cache key for the branch list.
790pub fn branches_key(version: Option<u64>) -> Option<CacheKey> {
791 version.map(|version| CacheKey::Versioned(format!("branches/{version}")))
792}
793
794/// Objects named by their content, kept in the isolate ahead of the Cache
795/// API, oldest out first past `MEMORY_CACHE_BYTES`. They never go stale,
796/// and each is under its repository's key.
797const MEMORY_CACHE_BYTES: usize = 16 * 1024 * 1024;
798
799#[derive(Default)]
800struct MemoryCache {
801 entries: HashMap<String, Rc<Vec<u8>>>,
802 order: std::collections::VecDeque<String>,
803 bytes: usize,
804}
805
806impl MemoryCache {
807 fn get(&self, url: &str) -> Option<Vec<u8>> {
808 self.entries.get(url).map(|bytes| bytes.as_ref().clone())
809 }
810
811 fn put(&mut self, url: String, bytes: &[u8]) {
812 if bytes.len() > MEMORY_CACHE_BYTES / 16 || self.entries.contains_key(&url) {
813 return;
814 }
815 self.bytes += bytes.len();
816 self.entries.insert(url.clone(), Rc::new(bytes.to_vec()));
817 self.order.push_back(url);
818 while self.bytes > MEMORY_CACHE_BYTES {
819 let Some(oldest) = self.order.pop_front() else { break };
820 if let Some(gone) = self.entries.remove(&oldest) {
821 self.bytes -= gone.len();
822 }
823 }
824 }
825}
826
827thread_local! {
828 static MEMORY: RefCell<MemoryCache> = RefCell::new(MemoryCache::default());
829}
830
831impl ArtifactsRepo {
832 fn cache_url(&self, path: &str) -> String {
833 format!("{OBJECT_CACHE}{}/{path}", self.key)
834 }
835
836 /// A kept answer: from the isolate for one kept for good, else the
837 /// Cache API. Each look is metered (`cache.memory_hit`, `cache.edge_hit`,
838 /// `cache.miss`), so the usage check shows which cache answers.
839 async fn cached_at(&self, path: &str, forever: bool) -> Option<Vec<u8>> {
840 let url = self.cache_url(path);
841 if forever && let Some(bytes) = MEMORY.with(|memory| memory.borrow().get(&url)) {
842 meters::record("cache.memory_hit", &self.key, 0, bytes.len() as u64);
843 return Some(bytes);
844 }
845 let found = match worker::Cache::default().get(url.clone(), false).await {
846 Ok(Some(mut response)) => response.bytes().await.ok(),
847 _ => None,
848 };
849 match &found {
850 Some(bytes) => {
851 meters::record("cache.edge_hit", &self.key, 0, bytes.len() as u64);
852 if forever {
853 MEMORY.with(|memory| memory.borrow_mut().put(url, bytes));
854 }
855 }
856 None => meters::record("cache.miss", &self.key, 0, 0),
857 }
858 found
859 }
860
861 /// A history from the store itself.
862 async fn read_log(&self, git_ref: &str, limit: u32) -> Result<Vec<Commit>> {
863 let options = js::to_js(&serde_json::json!({ "ref": git_ref, "limit": limit }))?;
864 let raw: Vec<RawCommit> = js::from_js(&self.call("log", &[options], true).await?)?;
865 Ok(raw
866 .into_iter()
867 .map(|commit| Commit {
868 hash: commit.hash,
869 tree_hash: commit.tree_hash,
870 message: commit.message,
871 author: commit.author,
872 parents: commit.parents,
873 authored_at: rfc3339(commit.authored_at * 1000),
874 })
875 .collect())
876 }
877
878 /// A long history by commit hash, from a short read and one kept
879 /// before: when a branch moves a few commits, the history from its new
880 /// head is those commits, then the history kept from its old one (the
881 /// first-parent chain from a commit never changes). Only when none of
882 /// the short read's commits has the same history kept is the whole of
883 /// it read. A default branch that moved by a merge then costs a read
884 /// of [`SPLICE_PROBE`] commits instead of a thousand.
885 async fn spliced_log(&self, hash: &str, limit: u32) -> Result<Vec<Commit>> {
886 let short = self.read_log(hash, SPLICE_PROBE).await?;
887 if (short.len() as u32) < SPLICE_PROBE {
888 // The whole history fits in the short read.
889 return Ok(short);
890 }
891 let kept = futures_util::future::join_all(short.iter().enumerate().skip(1).map(|(at, commit)| async move {
892 let Some(CacheKey::Forever(path)) = log_key(&commit.hash, limit, None) else {
893 return None;
894 };
895 let bytes = self.peek(&path).await?;
896 serde_json::from_slice::<Vec<Commit>>(&bytes).ok().map(|kept| (at, kept))
897 }))
898 .await;
899 match kept.into_iter().flatten().next() {
900 Some((at, kept)) => Ok(splice(&short, at, kept, limit)),
901 None => self.read_log(hash, limit).await,
902 }
903 }
904
905 /// A kept answer, if there is one, without counting a miss: the
906 /// splice looks for many and expects most to be absent.
907 async fn peek(&self, path: &str) -> Option<Vec<u8>> {
908 let url = self.cache_url(path);
909 if let Some(bytes) = MEMORY.with(|memory| memory.borrow().get(&url)) {
910 meters::record("cache.memory_hit", &self.key, 0, bytes.len() as u64);
911 return Some(bytes);
912 }
913 let mut response = worker::Cache::default().get(url.clone(), false).await.ok()??;
914 let bytes = response.bytes().await.ok()?;
915 meters::record("cache.edge_hit", &self.key, 0, bytes.len() as u64);
916 MEMORY.with(|memory| memory.borrow_mut().put(url, &bytes));
917 Some(bytes)
918 }
919
920 async fn cached(&self, kind: &str, hash: &str) -> Option<Vec<u8>> {
921 self.cached_at(&format!("{kind}/{hash}"), true).await
922 }
923
924 async fn keep_at(&self, path: &str, bytes: Vec<u8>, max_age: &str) {
925 if max_age == OBJECT_MAX_AGE {
926 MEMORY.with(|memory| memory.borrow_mut().put(self.cache_url(path), &bytes));
927 }
928 let Ok(mut response) = worker::Response::from_bytes(bytes) else {
929 return;
930 };
931 let _ = response.headers_mut().set("cache-control", max_age);
932 let _ = worker::Cache::default().put(self.cache_url(path), response).await;
933 }
934
935 /// Whether `read_file`'s key was found not to be a file a little while
936 /// ago. Metered only when it was (`cache.absent_hit`): the lookup runs
937 /// beside the key's own, which already counts the miss.
938 async fn known_absent(&self, key: &CacheKey) -> bool {
939 let url = self.cache_url(&absent_path(key));
940 let found = matches!(worker::Cache::default().get(url, false).await, Ok(Some(_)));
941 if found {
942 meters::record("cache.absent_hit", &self.key, 0, 0);
943 }
944 found
945 }
946
947 /// Keeps an object for next time. A failure only costs a later read.
948 async fn keep(&self, kind: &str, hash: &str, bytes: Vec<u8>) {
949 self.keep_at(&format!("{kind}/{hash}"), bytes, OBJECT_MAX_AGE).await;
950 }
951
952 async fn get_key(&self, key: &CacheKey) -> Option<Vec<u8>> {
953 match key {
954 CacheKey::Forever(path) => self.cached_at(path, true).await,
955 CacheKey::Versioned(path) => self.cached_at(path, false).await,
956 }
957 }
958
959 async fn put_key(&self, key: &CacheKey, bytes: Vec<u8>) {
960 match key {
961 CacheKey::Forever(path) => self.keep_at(path, bytes, OBJECT_MAX_AGE).await,
962 CacheKey::Versioned(path) => self.keep_at(path, bytes, VERSIONED_MAX_AGE).await,
963 }
964 }
965
966 async fn call(&self, method: &str, args: &[JsValue], retry: bool) -> std::result::Result<JsValue, StoreError> {
967 let handle = self.handle().await?;
968 invoke(&self.namespace, &self.key, &handle, method, args, retry).await
969 }
970
971 /// The store's handle, asked for the first time it is needed.
972 async fn handle(&self) -> std::result::Result<Target, StoreError> {
973 if let Some(handle) = self.handle.borrow().as_ref() {
974 return Ok(handle.clone());
975 }
976 let found = invoke(&self.namespace, &self.key, &self.binding, "get", &[self.name.as_str().into()], true).await?;
977 let handle = match &self.binding {
978 Target::Js(_) => Target::Js(found),
979 // The fallback store said the repository is there.
980 Target::Fallback { settings, namespace, .. } => Target::Fallback {
981 settings: settings.clone(),
982 namespace: namespace.clone(),
983 repo: Some(self.name.clone()),
984 },
985 };
986 *self.handle.borrow_mut() = Some(handle.clone());
987 Ok(handle)
988 }
989
990 /// A new credential from the store. Its remote is worked out from the
991 /// key once this isolate knows where the namespace's remotes start;
992 /// until then the store is asked (`info()`) alongside the token. The
993 /// fallback store's remotes are known from its address.
994 pub async fn mint(&self, scope: Scope, using: Use) -> Result<GitAccess> {
995 let args = [scope.as_str().into(), using.ttl_seconds().into()];
996 if let Target::Fallback { settings, .. } = &self.binding {
997 let token: RawToken = js::from_js(&self.call("createToken", &args, true).await?)?;
998 return Ok(GitAccess { remote: settings.remote(&self.namespace, &self.name), token: token.plaintext });
999 }
1000 let prefix = REMOTE_PREFIX.with(|prefixes| prefixes.borrow().get(&self.namespace).cloned());
1001 if let Some(prefix) = prefix {
1002 let token: RawToken = js::from_js(&self.call("createToken", &args, true).await?)?;
1003 return Ok(GitAccess { remote: remote_from(&prefix, &self.name), token: token.plaintext });
1004 }
1005 self.handle().await?;
1006 let (info, token) = futures_util::future::join(self.call("info", &[], true), self.call("createToken", &args, true)).await;
1007 let info: RawInfo = js::from_js(&info?)?;
1008 let token: RawToken = js::from_js(&token?)?;
1009 match learn_prefix(&info.remote, &self.name) {
1010 Some(prefix) => REMOTE_PREFIX.with(|prefixes| {
1011 prefixes.borrow_mut().insert(self.namespace.clone(), prefix);
1012 }),
1013 None => worker::console_error!("the git store's remote {} does not end in {}.git", info.remote, self.name),
1014 }
1015 Ok(GitAccess { remote: info.remote, token: token.plaintext })
1016 }
1017}
1018
1019impl Drop for ArtifactsRepo {
1020 fn drop(&mut self) {
1021 let symbol = js::get(&worker::js_sys::global(), "Symbol");
1022 let dispose = js::get(&symbol, "dispose");
1023 let Some(Target::Js(handle)) = self.handle.borrow_mut().take() else { return };
1024 if let Ok(function) = Reflect::get(&handle, &dispose).and_then(|value| value.dyn_into::<worker::js_sys::Function>()) {
1025 let _ = function.call0(&handle);
1026 }
1027 }
1028}
1029
1030#[derive(Deserialize)]
1031#[serde(rename_all = "camelCase")]
1032struct RawCommit {
1033 hash: String,
1034 tree_hash: String,
1035 message: String,
1036 author: Signature,
1037 parents: Vec<String>,
1038 /// Seconds since the epoch.
1039 authored_at: u64,
1040}
1041
1042#[derive(Deserialize)]
1043struct RawEntry {
1044 name: String,
1045 hash: String,
1046 #[serde(rename = "type")]
1047 kind: EntryKind,
1048}
1049
1050#[derive(Deserialize)]
1051struct RawInfo {
1052 remote: String,
1053}
1054
1055#[derive(Deserialize)]
1056struct RawToken {
1057 plaintext: String,
1058}
1059
1060/// The bytes of a `Blob` (or of the bytes the fallback store sent), or
1061/// `None` for null.
1062async fn blob_bytes(blob: JsValue) -> Result<Option<Vec<u8>>> {
1063 if blob.is_null() || blob.is_undefined() {
1064 return Ok(None);
1065 }
1066 if let Some(bytes) = blob.dyn_ref::<Uint8Array>() {
1067 return Ok(Some(bytes.to_vec()));
1068 }
1069 let buffer = js::call(&blob, "arrayBuffer", &[]).await?;
1070 Ok(Some(Uint8Array::new(&buffer).to_vec()))
1071}
1072
1073impl GitRepo for ArtifactsRepo {
1074 /// One made a while ago, here or in another isolate, else a new one.
1075 async fn access(&self, scope: Scope) -> Result<GitAccess> {
1076 if let Some((access, _)) = kept(self.shared.as_deref(), &self.cred_key, scope, Use::Internal).await {
1077 return Ok(access);
1078 }
1079 let access = self.mint(scope, Use::Internal).await?;
1080 keep(self.shared.as_deref(), &self.cred_key, scope, Use::Internal, &access).await;
1081 Ok(access)
1082 }
1083
1084 async fn branches(&self) -> Result<Vec<Branch>> {
1085 let key = branches_key(self.refs_version);
1086 if let Some(key) = &key
1087 && let Some(bytes) = self.get_key(key).await
1088 && let Ok(branches) = serde_json::from_slice::<Vec<Branch>>(&bytes)
1089 {
1090 return Ok(branches);
1091 }
1092 let branches = crate::refs::branches(&self.access(Scope::Read).await?).await?;
1093 if let (Some(key), Ok(bytes)) = (&key, serde_json::to_vec(&branches)) {
1094 self.put_key(key, bytes).await;
1095 }
1096 Ok(branches)
1097 }
1098
1099 async fn log(&self, git_ref: &str, limit: u32) -> Result<Vec<Commit>> {
1100 // History from a commit never changes, so a log asked for by hash is
1101 // kept like an object: walking it is a read per commit. One asked
1102 // for by a branch's name is kept until the branch can have moved.
1103 let key = log_key(git_ref, limit, self.refs_version);
1104 if let Some(key) = &key
1105 && let Some(bytes) = self.get_key(key).await
1106 && let Ok(commits) = serde_json::from_slice::<Vec<Commit>>(&bytes)
1107 {
1108 return Ok(commits);
1109 }
1110 let commits = match &key {
1111 Some(CacheKey::Forever(_)) if limit >= SPLICE_FROM => self.spliced_log(git_ref, limit).await?,
1112 _ => self.read_log(git_ref, limit).await?,
1113 };
1114 // An unknown ref logs nothing; that is not kept, in case it arrives.
1115 if !commits.is_empty()
1116 && let Ok(bytes) = serde_json::to_vec(&commits)
1117 {
1118 if let Some(key) = &key {
1119 self.put_key(key, bytes.clone()).await;
1120 }
1121 // The same history, by the commit the name led to.
1122 if !is_commit_hash(git_ref)
1123 && let Some(CacheKey::Forever(path)) = log_key(&commits[0].hash, limit, None)
1124 {
1125 self.keep_at(&path, bytes, OBJECT_MAX_AGE).await;
1126 }
1127 }
1128 Ok(commits)
1129 }
1130
1131 async fn parents(&self, commit_hash: &str) -> Result<Option<Vec<String>>> {
1132 // A commit never changes.
1133 if let Some(bytes) = self.cached("commit", commit_hash).await
1134 && let Ok(parents) = serde_json::from_slice::<Vec<String>>(&bytes)
1135 {
1136 return Ok(Some(parents));
1137 }
1138 let commit: Option<RawCommit> = js::from_js(&self.call("readCommit", &[commit_hash.into()], true).await?)?;
1139 let parents = commit.map(|commit| commit.parents);
1140 if let Some(parents) = &parents
1141 && let Ok(bytes) = serde_json::to_vec(parents)
1142 {
1143 self.keep("commit", commit_hash, bytes).await;
1144 }
1145 Ok(parents)
1146 }
1147
1148 async fn read_tree(&self, tree_hash: &str) -> Result<Option<Vec<TreeEntry>>> {
1149 if let Some(bytes) = self.cached("tree", tree_hash).await
1150 && let Ok(entries) = serde_json::from_slice::<Vec<TreeEntry>>(&bytes)
1151 {
1152 return Ok(Some(entries));
1153 }
1154 let entries: Option<Vec<RawEntry>> = js::from_js(&self.call("readTree", &[tree_hash.into()], true).await?)?;
1155 let entries: Option<Vec<TreeEntry>> = entries.map(|entries| {
1156 entries
1157 .into_iter()
1158 .map(|entry| TreeEntry {
1159 name: entry.name,
1160 hash: entry.hash,
1161 kind: entry.kind,
1162 })
1163 .collect()
1164 });
1165 if let Some(entries) = &entries
1166 && let Ok(bytes) = serde_json::to_vec(entries)
1167 {
1168 self.keep("tree", tree_hash, bytes).await;
1169 }
1170 Ok(entries)
1171 }
1172
1173 async fn read_blob(&self, blob_hash: &str) -> Result<Option<Vec<u8>>> {
1174 if let Some(bytes) = self.cached("blob", blob_hash).await {
1175 return Ok(Some(bytes));
1176 }
1177 let bytes = blob_bytes(self.call("readBlob", &[blob_hash.into()], true).await?).await?;
1178 if let Some(bytes) = &bytes {
1179 meters::record_bytes("binding.read_blob", &self.key, 0, bytes.len() as u64);
1180 }
1181 if let Some(bytes) = bytes.as_ref().filter(|bytes| bytes.len() <= MAX_CACHED_BLOB) {
1182 self.keep("blob", blob_hash, bytes.clone()).await;
1183 }
1184 Ok(bytes)
1185 }
1186
1187 /// Kept for good by hash, as a blob is: its bytes never cross into
1188 /// this isolate's memory, only the size of the store's answer.
1189 async fn blob_size(&self, blob_hash: &str) -> Result<Option<u64>> {
1190 let path = format!("size/{blob_hash}");
1191 if let Some(bytes) = self.cached_at(&path, true).await
1192 && let Some(size) = std::str::from_utf8(&bytes).ok().and_then(|text| text.parse().ok())
1193 {
1194 return Ok(Some(size));
1195 }
1196 let blob = self.call("readBlob", &[blob_hash.into()], true).await?;
1197 let size = if blob.is_null() || blob.is_undefined() {
1198 None
1199 } else if let Some(bytes) = blob.dyn_ref::<Uint8Array>() {
1200 Some(u64::from(bytes.length()))
1201 } else {
1202 js::get(&blob, "size").as_f64().map(|size| size as u64)
1203 };
1204 if let Some(size) = size {
1205 meters::record_bytes("binding.read_blob", &self.key, 0, size);
1206 self.keep_at(&path, size.to_string().into_bytes(), OBJECT_MAX_AGE).await;
1207 }
1208 Ok(size)
1209 }
1210
1211 async fn read_file(&self, git_ref: &str, path: &str) -> Result<Option<Vec<u8>>> {
1212 let key = file_key(git_ref, path, self.refs_version);
1213 // A path that is not a file is remembered too, briefly: the store
1214 // answers each such read as a rejected read (crawlers asking for
1215 // old or missing paths make most of them). Never for the fallback
1216 // store, which can be behind.
1217 let remember_absent = !self.binding.is_fallback();
1218 if let Some(key) = &key {
1219 let (found, absent) = futures_util::future::join(self.get_key(key), async {
1220 remember_absent && self.known_absent(key).await
1221 })
1222 .await;
1223 if let Some(bytes) = found {
1224 return Ok(Some(bytes));
1225 }
1226 if absent {
1227 return Ok(None);
1228 }
1229 }
1230 let args = js::to_js(&serde_json::json!({ "ref": git_ref, "path": path }))?;
1231 // The store answers a path that is not a file at the ref with
1232 // NOT_FOUND (its "read rejected"), not with nothing.
1233 let bytes = match self.call("readFile", &[args], true).await {
1234 Ok(blob) => blob_bytes(blob).await?,
1235 Err(failed) if failed.is("NOT_FOUND") => None,
1236 Err(failed) => return Err(failed.into()),
1237 };
1238 if let Some(bytes) = &bytes {
1239 meters::record_bytes("binding.read_file", &self.key, 0, bytes.len() as u64);
1240 } else if remember_absent && let Some(key) = &key {
1241 self.keep_at(&absent_path(key), vec![1], ABSENT_MAX_AGE).await;
1242 }
1243 if let (Some(key), Some(bytes)) = (&key, bytes.as_ref().filter(|bytes| bytes.len() <= MAX_CACHED_BLOB)) {
1244 self.put_key(key, bytes.clone()).await;
1245 }
1246 Ok(bytes)
1247 }
1248
1249 async fn fork(&self, target_key: &str) -> Result<()> {
1250 let (namespace, name) = locate(target_key);
1251 if namespace != self.namespace {
1252 return Err(worker::Error::RustError(format!(
1253 "a fork stays in its repository's namespace: {target_key} is not in {}",
1254 self.namespace
1255 )));
1256 }
1257 let options = js::to_js(&serde_json::json!({ "defaultBranchOnly": true }))?;
1258 match self.call("fork", &[name.as_str().into(), options], false).await {
1259 Err(failed) if !failed.is("ALREADY_EXISTS") => Err(failed.into()),
1260 _ => Ok(()),
1261 }
1262 }
1263
1264 fn at_refs_version(&mut self, version: Option<u64>) {
1265 // The fallback store holds what the last backup held, which may be
1266 // behind what was kept under the version: nothing is kept for it.
1267 self.refs_version = if self.binding.is_fallback() { None } else { version };
1268 }
1269}
1270
1271#[cfg(test)]
1272mod tests {
1273 use super::*;
1274
1275 fn chain(names: &[&str]) -> Vec<Commit> {
1276 names
1277 .iter()
1278 .enumerate()
1279 .map(|(at, name)| Commit {
1280 hash: (*name).to_owned(),
1281 tree_hash: String::new(),
1282 message: String::new(),
1283 author: g1t_contracts::repos::Signature { name: "a".into(), email: "a@example.com".into() },
1284 parents: names.get(at + 1).map(|parent| vec![(*parent).to_owned()]).unwrap_or_default(),
1285 authored_at: String::new(),
1286 })
1287 .collect()
1288 }
1289
1290 fn hashes(commits: &[Commit]) -> Vec<&str> {
1291 commits.iter().map(|commit| commit.hash.as_str()).collect()
1292 }
1293
1294 #[test]
1295 fn a_history_is_the_new_commits_then_the_one_kept_from_an_old_head() {
1296 // The branch moved from c3 to c5; c3's history (limit 4) was kept.
1297 let short = chain(&["c5", "c4", "c3", "c2"]);
1298 let kept = chain(&["c3", "c2", "c1", "c0"]);
1299 assert_eq!(hashes(&splice(&short, 2, kept.clone(), 4)), ["c5", "c4", "c3", "c2"]);
1300 assert_eq!(hashes(&splice(&short, 2, kept.clone(), 6)), ["c5", "c4", "c3", "c2", "c1", "c0"]);
1301 // A kept history that reached the first commit ends there.
1302 assert_eq!(hashes(&splice(&short, 2, chain(&["c3", "c2"]), 10)), ["c5", "c4", "c3", "c2"]);
1303 }
1304
1305 #[test]
1306 fn only_long_histories_by_hash_are_spliced() {
1307 assert!(SPLICE_PROBE < SPLICE_FROM);
1308 let hash = "a".repeat(40);
1309 assert!(matches!(log_key(&hash, SPLICE_FROM, None), Some(CacheKey::Forever(_))));
1310 assert!(matches!(log_key("main", SPLICE_FROM, Some(1)), Some(CacheKey::Versioned(_))));
1311 }
1312
1313 fn access(token: &str) -> GitAccess {
1314 GitAccess {
1315 remote: "https://store.example/acme--rocket.git".to_owned(),
1316 token: token.to_owned(),
1317 }
1318 }
1319
1320 #[test]
1321 fn internal_credentials_live_an_hour_and_are_reused_for_fifty_minutes() {
1322 assert_eq!(Use::Internal.ttl_seconds(), 3_600);
1323 assert_eq!(Use::Internal.reuse_ms(), 50 * 60 * 1000);
1324 // Handed out: five minutes, reused three, so at least two are left.
1325 assert_eq!(Use::Handout.ttl_seconds(), 300);
1326 assert_eq!(Use::Handout.reuse_ms(), 180_000);
1327 assert_eq!(CREDENTIAL_LIFE_MS, 300_000);
1328 for using in [Use::Internal, Use::Handout] {
1329 assert!(u64::from(using.ttl_seconds()) * 1000 - using.reuse_ms() >= 120_000);
1330 }
1331 }
1332
1333 #[test]
1334 fn a_credential_is_reused_only_while_it_has_time_left() {
1335 let mut kept = Credentials::default();
1336 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
1337 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000).unwrap().token, "r1");
1338 let last = 1_000 + INTERNAL_REUSE_MS - 1;
1339 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Internal, last).unwrap().token, "r1");
1340 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, last + 1).is_none());
1341 }
1342
1343 #[test]
1344 fn a_credential_is_kept_for_its_own_repository_scope_and_use() {
1345 let mut kept = Credentials::default();
1346 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
1347 // A read credential never stands in for a write one.
1348 assert!(kept.get("acme--rocket", Scope::Write, Use::Internal, 1_000).is_none());
1349 assert!(kept.get("acme--booster", Scope::Read, Use::Internal, 1_000).is_none());
1350 // An hour-long credential is never handed out.
1351 assert!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000).is_none());
1352 kept.keep("acme--rocket", Scope::Read, Use::Handout, access("h1"), 1_000, 1_000);
1353 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000).unwrap().token, "h1");
1354 assert!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000 + HANDOUT_REUSE_MS).is_none());
1355 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000 + HANDOUT_REUSE_MS).is_some());
1356 }
1357
1358 #[test]
1359 fn a_shared_credential_is_reused_only_in_its_own_window() {
1360 let value = serde_json::to_vec(&SharedCredential {
1361 remote: "https://store.example/acme--rocket.git".to_owned(),
1362 token: "r1".to_owned(),
1363 made: 10_000,
1364 })
1365 .unwrap();
1366 let (access, made) = shared_credential(&value, 10_000 + INTERNAL_REUSE_MS - 1, Use::Internal).unwrap();
1367 assert_eq!(access.token, "r1");
1368 // Kept here only for what is left of its window, not a new one.
1369 assert_eq!(made, 10_000);
1370 assert!(shared_credential(&value, 10_000 + INTERNAL_REUSE_MS, Use::Internal).is_none());
1371 assert!(shared_credential(&value, 10_000 + HANDOUT_REUSE_MS, Use::Handout).is_none());
1372 assert!(shared_credential(b"not json", 10_000, Use::Internal).is_none());
1373 // Each repository, scope and use has its own key, and none is read
1374 // from before uses differed.
1375 assert_eq!(shared_key("acme--rocket", Scope::Read, Use::Internal), "cred2:acme--rocket:read:internal");
1376 assert_ne!(shared_key("acme--rocket", Scope::Read, Use::Internal), shared_key("acme--rocket", Scope::Write, Use::Internal));
1377 assert_ne!(shared_key("acme--rocket", Scope::Read, Use::Internal), shared_key("acme--rocket", Scope::Read, Use::Handout));
1378 }
1379
1380 #[test]
1381 fn a_shared_credential_kept_here_expires_with_the_original() {
1382 let mut kept = Credentials::default();
1383 // Made at 1_000 elsewhere, found here at 100_000.
1384 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 100_000);
1385 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 100_000).is_some());
1386 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000 + INTERNAL_REUSE_MS).is_none());
1387 }
1388
1389 #[test]
1390 fn a_turned_down_credential_is_forgotten_and_old_ones_are_dropped() {
1391 let mut kept = Credentials::default();
1392 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
1393 kept.keep("acme--rocket", Scope::Write, Use::Handout, access("w1"), 1_000, 1_000);
1394 kept.keep("acme--booster", Scope::Read, Use::Internal, access("b1"), 1_000, 1_000);
1395 kept.forget("acme--rocket");
1396 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000).is_none());
1397 assert!(kept.get("acme--rocket", Scope::Write, Use::Handout, 1_000).is_none());
1398 assert!(kept.get("acme--booster", Scope::Read, Use::Internal, 1_000).is_some());
1399 // Keeping another later drops the expired one from the map.
1400 let later = 1_000 + INTERNAL_REUSE_MS;
1401 kept.keep("acme--other", Scope::Read, Use::Internal, access("o1"), later, later);
1402 assert_eq!(kept.kept.len(), 1);
1403 }
1404
1405 #[test]
1406 fn a_remote_is_worked_out_from_where_its_namespace_starts() {
1407 // As https://developers.cloudflare.com/artifacts/api/git-protocol/ documents.
1408 let remote = "https://1e6f2cffa3f445920836e8ebe446bb58.artifacts.cloudflare.net/git/g1t/acme--rocket.git";
1409 let prefix = learn_prefix(remote, "acme--rocket").unwrap();
1410 assert_eq!(prefix, "https://1e6f2cffa3f445920836e8ebe446bb58.artifacts.cloudflare.net/git/g1t/");
1411 assert_eq!(remote_from(&prefix, "pulls--pul_1"), prefix.clone() + "pulls--pul_1.git");
1412 assert_eq!(remote_from(&prefix, "acme--rocket"), remote);
1413 // A remote that does not end in the name teaches nothing.
1414 assert_eq!(learn_prefix(remote, "rocket"), None);
1415 assert_eq!(learn_prefix("https://x/acme--rocket", "acme--rocket"), None);
1416 // And back: a remote names its key.
1417 assert_eq!(key_from_remote(remote).as_deref(), Some("acme--rocket"));
1418 assert_eq!(
1419 key_from_remote("https://a.artifacts.cloudflare.net/git/g1t-us-1/acme--rocket.git").as_deref(),
1420 Some("g1t-us-1/acme--rocket")
1421 );
1422 assert_eq!(locate("g1t-us-1/acme--rocket"), ("g1t-us-1".to_owned(), "acme--rocket".to_owned()));
1423 assert_eq!(locate("acme--rocket"), ("g1t".to_owned(), "acme--rocket".to_owned()));
1424 }
1425
1426 #[test]
1427 fn the_fallback_stores_credentials_and_remotes_are_its_own() {
1428 assert_eq!(cred_key("acme--rocket", false), "acme--rocket");
1429 assert_eq!(cred_key("g1t-us-1/acme--rocket", true), "fallback:g1t-us-1/acme--rocket");
1430 // A credential Artifacts made is never handed out for the fallback
1431 // store, nor the reverse.
1432 assert_ne!(
1433 shared_key(&cred_key("acme--rocket", true), Scope::Write, Use::Internal),
1434 shared_key(&cred_key("acme--rocket", false), Scope::Write, Use::Internal)
1435 );
1436 // Its remotes name their keys as Artifacts' do.
1437 let settings = fallback::Settings::from_vars(Some("https://gitstore.example"), Some("0123456789abcdef"), Some("*"), None).unwrap();
1438 assert_eq!(key_from_remote(&settings.remote("g1t", "acme--rocket")).as_deref(), Some("acme--rocket"));
1439 assert_eq!(key_from_remote(&settings.remote("g1t-us-1", "pulls--pul_1")).as_deref(), Some("g1t-us-1/pulls--pul_1"));
1440 // Git requests to it count toward its own health, not Artifacts'.
1441 FALLBACK_BASE.with(|base| *base.borrow_mut() = Some(format!("{}/git/", settings.url)));
1442 assert_eq!(health_namespace(&settings.remote("g1t-us-1", "acme--rocket")), "g1t-us-1@fallback");
1443 assert_eq!(health_namespace("https://a.artifacts.cloudflare.net/git/g1t-us-1/acme--rocket.git"), "g1t-us-1");
1444 FALLBACK_BASE.with(|base| *base.borrow_mut() = None);
1445 }
1446
1447 #[test]
1448 fn the_memory_cache_drops_its_oldest_past_its_budget() {
1449 let mut cache = MemoryCache::default();
1450 let chunk = vec![7u8; MEMORY_CACHE_BYTES / 16];
1451 for n in 0..17 {
1452 cache.put(format!("k{n}"), &chunk);
1453 }
1454 // Sixteen chunks fit; the seventeenth pushed the first out.
1455 assert!(cache.get("k0").is_none());
1456 assert_eq!(cache.get("k16").map(|b| b.len()), Some(chunk.len()));
1457 assert!(cache.bytes <= MEMORY_CACHE_BYTES);
1458 // Too large to keep at all.
1459 cache.put("big".into(), &vec![0u8; MEMORY_CACHE_BYTES / 16 + 1]);
1460 assert!(cache.get("big").is_none());
1461 }
1462
1463 #[test]
1464 fn binding_methods_have_snake_case_meters() {
1465 assert_eq!(meter_of("createToken"), "binding.create_token");
1466 assert_eq!(meter_of("readBlob"), "binding.read_blob");
1467 assert_eq!(meter_of("get"), "binding.get");
1468 }
1469
1470 #[test]
1471 fn reads_by_name_are_kept_under_the_refs_version_and_by_hash_for_good() {
1472 let hash = "a".repeat(40);
1473 assert_eq!(log_key(&hash, 1, Some(3)), Some(CacheKey::Forever(format!("log/{hash}-1"))));
1474 assert_eq!(log_key(&hash, 1, None), Some(CacheKey::Forever(format!("log/{hash}-1"))));
1475 // A branch is kept only when the version is known.
1476 assert_eq!(log_key("main", 1, None), None);
1477 let v3 = log_key("main", 1, Some(3)).unwrap();
1478 assert!(matches!(&v3, CacheKey::Versioned(path) if path.starts_with("vlog/3/")));
1479 // A push moves the version and leaves the old answer behind.
1480 assert_ne!(Some(v3), log_key("main", 1, Some(4)));
1481 assert_ne!(log_key("main", 1, Some(3)), log_key("main", 50, Some(3)));
1482 assert_ne!(log_key("main", 1, Some(3)), log_key("dev", 1, Some(3)));
1483 // Odd branch names make a usable address.
1484 assert!(matches!(log_key("fix/#1 %20", 1, Some(3)), Some(CacheKey::Versioned(path)) if !path.contains('#') && !path.contains(' ')));
1485 assert_eq!(branches_key(None), None);
1486 assert_ne!(branches_key(Some(1)), branches_key(Some(2)));
1487 assert!(matches!(file_key(&hash, "src/main.rs", None), Some(CacheKey::Forever(_))));
1488 assert_eq!(file_key("main", "src/main.rs", None), None);
1489 assert_ne!(file_key("main", "a", Some(1)), file_key("main", "b", Some(1)));
1490 assert_ne!(file_key("main", "a", Some(1)), file_key("main", "a", Some(2)));
1491 // A path noted as not a file sits beside the file's own key, and a
1492 // push (a new refs version) leaves the old note behind.
1493 let at = |version| absent_path(&file_key("main", "a", Some(version)).unwrap());
1494 assert!(at(1).starts_with("absent/vfile/1/"));
1495 assert_ne!(at(1), at(2));
1496 assert_eq!(absent_path(&file_key(&hash, "a", None).unwrap()), format!("absent/file/{hash}/{}", g1t_secrets::sha256_hex("a")));
1497 }
1498
1499 #[test]
1500 fn only_full_lowercase_hashes_are_kept() {
1501 assert!(is_commit_hash(&"a".repeat(40)));
1502 assert!(is_commit_hash(&"0123456789abcdef".repeat(4)));
1503 assert!(!is_commit_hash("main"));
1504 assert!(!is_commit_hash(&"A".repeat(40)));
1505 assert!(!is_commit_hash(&"a".repeat(39)));
1506 }
1507}