Skip to content

g1t/services/repos/src/store.rs

1,404 lines60,877 bytesCodeBlame
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/// Whether a ref is a full commit hash (SHA-1 or SHA-256), whose history
737/// can be kept for good.
738pub fn is_commit_hash(git_ref: &str) -> bool {
739 (git_ref.len() == 40 || git_ref.len() == 64) && git_ref.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
740}
741
742/// Where a read is kept: under the object it names for good, under the
743/// refs version for a name that can move, or nowhere.
744#[derive(Debug, PartialEq, Eq)]
745pub enum CacheKey {
746 Forever(String),
747 Versioned(String),
748}
749
750/// The cache key for `log(git_ref, limit)`.
751pub fn log_key(git_ref: &str, limit: u32, version: Option<u64>) -> Option<CacheKey> {
752 if is_commit_hash(git_ref) {
753 return Some(CacheKey::Forever(format!("log/{git_ref}-{limit}")));
754 }
755 version.map(|version| CacheKey::Versioned(format!("vlog/{version}/{}-{limit}", g1t_secrets::sha256_hex(git_ref))))
756}
757
758/// The cache key for `read_file(git_ref, path)`.
759pub fn file_key(git_ref: &str, path: &str, version: Option<u64>) -> Option<CacheKey> {
760 let path = g1t_secrets::sha256_hex(path);
761 if is_commit_hash(git_ref) {
762 return Some(CacheKey::Forever(format!("file/{git_ref}/{path}")));
763 }
764 version.map(|version| CacheKey::Versioned(format!("vfile/{version}/{}/{path}", g1t_secrets::sha256_hex(git_ref))))
765}
766
767/// Where `read_file` notes that its key is not a file (see `known_absent`).
768fn absent_path(key: &CacheKey) -> String {
769 match key {
770 CacheKey::Forever(path) | CacheKey::Versioned(path) => format!("absent/{path}"),
771 }
772}
773
774/// The cache key for the branch list.
775pub fn branches_key(version: Option<u64>) -> Option<CacheKey> {
776 version.map(|version| CacheKey::Versioned(format!("branches/{version}")))
777}
778
779/// Objects named by their content, kept in the isolate ahead of the Cache
780/// API, oldest out first past `MEMORY_CACHE_BYTES`. They never go stale,
781/// and each is under its repository's key.
782const MEMORY_CACHE_BYTES: usize = 16 * 1024 * 1024;
783
784#[derive(Default)]
785struct MemoryCache {
786 entries: HashMap<String, Rc<Vec<u8>>>,
787 order: std::collections::VecDeque<String>,
788 bytes: usize,
789}
790
791impl MemoryCache {
792 fn get(&self, url: &str) -> Option<Vec<u8>> {
793 self.entries.get(url).map(|bytes| bytes.as_ref().clone())
794 }
795
796 fn put(&mut self, url: String, bytes: &[u8]) {
797 if bytes.len() > MEMORY_CACHE_BYTES / 16 || self.entries.contains_key(&url) {
798 return;
799 }
800 self.bytes += bytes.len();
801 self.entries.insert(url.clone(), Rc::new(bytes.to_vec()));
802 self.order.push_back(url);
803 while self.bytes > MEMORY_CACHE_BYTES {
804 let Some(oldest) = self.order.pop_front() else { break };
805 if let Some(gone) = self.entries.remove(&oldest) {
806 self.bytes -= gone.len();
807 }
808 }
809 }
810}
811
812thread_local! {
813 static MEMORY: RefCell<MemoryCache> = RefCell::new(MemoryCache::default());
814}
815
816impl ArtifactsRepo {
817 fn cache_url(&self, path: &str) -> String {
818 format!("{OBJECT_CACHE}{}/{path}", self.key)
819 }
820
821 /// A kept answer: from the isolate for one kept for good, else the
822 /// Cache API. Each look is metered (`cache.memory_hit`, `cache.edge_hit`,
823 /// `cache.miss`), so the usage check shows which cache answers.
824 async fn cached_at(&self, path: &str, forever: bool) -> Option<Vec<u8>> {
825 let url = self.cache_url(path);
826 if forever && let Some(bytes) = MEMORY.with(|memory| memory.borrow().get(&url)) {
827 meters::record("cache.memory_hit", &self.key, 0, bytes.len() as u64);
828 return Some(bytes);
829 }
830 let found = match worker::Cache::default().get(url.clone(), false).await {
831 Ok(Some(mut response)) => response.bytes().await.ok(),
832 _ => None,
833 };
834 match &found {
835 Some(bytes) => {
836 meters::record("cache.edge_hit", &self.key, 0, bytes.len() as u64);
837 if forever {
838 MEMORY.with(|memory| memory.borrow_mut().put(url, bytes));
839 }
840 }
841 None => meters::record("cache.miss", &self.key, 0, 0),
842 }
843 found
844 }
845
846 async fn cached(&self, kind: &str, hash: &str) -> Option<Vec<u8>> {
847 self.cached_at(&format!("{kind}/{hash}"), true).await
848 }
849
850 async fn keep_at(&self, path: &str, bytes: Vec<u8>, max_age: &str) {
851 if max_age == OBJECT_MAX_AGE {
852 MEMORY.with(|memory| memory.borrow_mut().put(self.cache_url(path), &bytes));
853 }
854 let Ok(mut response) = worker::Response::from_bytes(bytes) else {
855 return;
856 };
857 let _ = response.headers_mut().set("cache-control", max_age);
858 let _ = worker::Cache::default().put(self.cache_url(path), response).await;
859 }
860
861 /// Whether `read_file`'s key was found not to be a file a little while
862 /// ago. Metered only when it was (`cache.absent_hit`): the lookup runs
863 /// beside the key's own, which already counts the miss.
864 async fn known_absent(&self, key: &CacheKey) -> bool {
865 let url = self.cache_url(&absent_path(key));
866 let found = matches!(worker::Cache::default().get(url, false).await, Ok(Some(_)));
867 if found {
868 meters::record("cache.absent_hit", &self.key, 0, 0);
869 }
870 found
871 }
872
873 /// Keeps an object for next time. A failure only costs a later read.
874 async fn keep(&self, kind: &str, hash: &str, bytes: Vec<u8>) {
875 self.keep_at(&format!("{kind}/{hash}"), bytes, OBJECT_MAX_AGE).await;
876 }
877
878 async fn get_key(&self, key: &CacheKey) -> Option<Vec<u8>> {
879 match key {
880 CacheKey::Forever(path) => self.cached_at(path, true).await,
881 CacheKey::Versioned(path) => self.cached_at(path, false).await,
882 }
883 }
884
885 async fn put_key(&self, key: &CacheKey, bytes: Vec<u8>) {
886 match key {
887 CacheKey::Forever(path) => self.keep_at(path, bytes, OBJECT_MAX_AGE).await,
888 CacheKey::Versioned(path) => self.keep_at(path, bytes, VERSIONED_MAX_AGE).await,
889 }
890 }
891
892 async fn call(&self, method: &str, args: &[JsValue], retry: bool) -> std::result::Result<JsValue, StoreError> {
893 let handle = self.handle().await?;
894 invoke(&self.namespace, &self.key, &handle, method, args, retry).await
895 }
896
897 /// The store's handle, asked for the first time it is needed.
898 async fn handle(&self) -> std::result::Result<Target, StoreError> {
899 if let Some(handle) = self.handle.borrow().as_ref() {
900 return Ok(handle.clone());
901 }
902 let found = invoke(&self.namespace, &self.key, &self.binding, "get", &[self.name.as_str().into()], true).await?;
903 let handle = match &self.binding {
904 Target::Js(_) => Target::Js(found),
905 // The fallback store said the repository is there.
906 Target::Fallback { settings, namespace, .. } => Target::Fallback {
907 settings: settings.clone(),
908 namespace: namespace.clone(),
909 repo: Some(self.name.clone()),
910 },
911 };
912 *self.handle.borrow_mut() = Some(handle.clone());
913 Ok(handle)
914 }
915
916 /// A new credential from the store. Its remote is worked out from the
917 /// key once this isolate knows where the namespace's remotes start;
918 /// until then the store is asked (`info()`) alongside the token. The
919 /// fallback store's remotes are known from its address.
920 pub async fn mint(&self, scope: Scope, using: Use) -> Result<GitAccess> {
921 let args = [scope.as_str().into(), using.ttl_seconds().into()];
922 if let Target::Fallback { settings, .. } = &self.binding {
923 let token: RawToken = js::from_js(&self.call("createToken", &args, true).await?)?;
924 return Ok(GitAccess { remote: settings.remote(&self.namespace, &self.name), token: token.plaintext });
925 }
926 let prefix = REMOTE_PREFIX.with(|prefixes| prefixes.borrow().get(&self.namespace).cloned());
927 if let Some(prefix) = prefix {
928 let token: RawToken = js::from_js(&self.call("createToken", &args, true).await?)?;
929 return Ok(GitAccess { remote: remote_from(&prefix, &self.name), token: token.plaintext });
930 }
931 self.handle().await?;
932 let (info, token) = futures_util::future::join(self.call("info", &[], true), self.call("createToken", &args, true)).await;
933 let info: RawInfo = js::from_js(&info?)?;
934 let token: RawToken = js::from_js(&token?)?;
935 match learn_prefix(&info.remote, &self.name) {
936 Some(prefix) => REMOTE_PREFIX.with(|prefixes| {
937 prefixes.borrow_mut().insert(self.namespace.clone(), prefix);
938 }),
939 None => worker::console_error!("the git store's remote {} does not end in {}.git", info.remote, self.name),
940 }
941 Ok(GitAccess { remote: info.remote, token: token.plaintext })
942 }
943}
944
945impl Drop for ArtifactsRepo {
946 fn drop(&mut self) {
947 let symbol = js::get(&worker::js_sys::global(), "Symbol");
948 let dispose = js::get(&symbol, "dispose");
949 let Some(Target::Js(handle)) = self.handle.borrow_mut().take() else { return };
950 if let Ok(function) = Reflect::get(&handle, &dispose).and_then(|value| value.dyn_into::<worker::js_sys::Function>()) {
951 let _ = function.call0(&handle);
952 }
953 }
954}
955
956#[derive(Deserialize)]
957#[serde(rename_all = "camelCase")]
958struct RawCommit {
959 hash: String,
960 tree_hash: String,
961 message: String,
962 author: Signature,
963 parents: Vec<String>,
964 /// Seconds since the epoch.
965 authored_at: u64,
966}
967
968#[derive(Deserialize)]
969struct RawEntry {
970 name: String,
971 hash: String,
972 #[serde(rename = "type")]
973 kind: EntryKind,
974}
975
976#[derive(Deserialize)]
977struct RawInfo {
978 remote: String,
979}
980
981#[derive(Deserialize)]
982struct RawToken {
983 plaintext: String,
984}
985
986/// The bytes of a `Blob` (or of the bytes the fallback store sent), or
987/// `None` for null.
988async fn blob_bytes(blob: JsValue) -> Result<Option<Vec<u8>>> {
989 if blob.is_null() || blob.is_undefined() {
990 return Ok(None);
991 }
992 if let Some(bytes) = blob.dyn_ref::<Uint8Array>() {
993 return Ok(Some(bytes.to_vec()));
994 }
995 let buffer = js::call(&blob, "arrayBuffer", &[]).await?;
996 Ok(Some(Uint8Array::new(&buffer).to_vec()))
997}
998
999impl GitRepo for ArtifactsRepo {
1000 /// One made a while ago, here or in another isolate, else a new one.
1001 async fn access(&self, scope: Scope) -> Result<GitAccess> {
1002 if let Some((access, _)) = kept(self.shared.as_deref(), &self.cred_key, scope, Use::Internal).await {
1003 return Ok(access);
1004 }
1005 let access = self.mint(scope, Use::Internal).await?;
1006 keep(self.shared.as_deref(), &self.cred_key, scope, Use::Internal, &access).await;
1007 Ok(access)
1008 }
1009
1010 async fn branches(&self) -> Result<Vec<Branch>> {
1011 let key = branches_key(self.refs_version);
1012 if let Some(key) = &key
1013 && let Some(bytes) = self.get_key(key).await
1014 && let Ok(branches) = serde_json::from_slice::<Vec<Branch>>(&bytes)
1015 {
1016 return Ok(branches);
1017 }
1018 let branches = crate::refs::branches(&self.access(Scope::Read).await?).await?;
1019 if let (Some(key), Ok(bytes)) = (&key, serde_json::to_vec(&branches)) {
1020 self.put_key(key, bytes).await;
1021 }
1022 Ok(branches)
1023 }
1024
1025 async fn log(&self, git_ref: &str, limit: u32) -> Result<Vec<Commit>> {
1026 // History from a commit never changes, so a log asked for by hash is
1027 // kept like an object: walking it is a read per commit. One asked
1028 // for by a branch's name is kept until the branch can have moved.
1029 let key = log_key(git_ref, limit, self.refs_version);
1030 if let Some(key) = &key
1031 && let Some(bytes) = self.get_key(key).await
1032 && let Ok(commits) = serde_json::from_slice::<Vec<Commit>>(&bytes)
1033 {
1034 return Ok(commits);
1035 }
1036 let options = js::to_js(&serde_json::json!({ "ref": git_ref, "limit": limit }))?;
1037 let raw: Vec<RawCommit> = js::from_js(&self.call("log", &[options], true).await?)?;
1038 let commits: Vec<Commit> = raw
1039 .into_iter()
1040 .map(|commit| Commit {
1041 hash: commit.hash,
1042 tree_hash: commit.tree_hash,
1043 message: commit.message,
1044 author: commit.author,
1045 parents: commit.parents,
1046 authored_at: rfc3339(commit.authored_at * 1000),
1047 })
1048 .collect();
1049 // An unknown ref logs nothing; that is not kept, in case it arrives.
1050 if !commits.is_empty()
1051 && let Ok(bytes) = serde_json::to_vec(&commits)
1052 {
1053 if let Some(key) = &key {
1054 self.put_key(key, bytes.clone()).await;
1055 }
1056 // The same history, by the commit the name led to.
1057 if !is_commit_hash(git_ref)
1058 && let Some(CacheKey::Forever(path)) = log_key(&commits[0].hash, limit, None)
1059 {
1060 self.keep_at(&path, bytes, OBJECT_MAX_AGE).await;
1061 }
1062 }
1063 Ok(commits)
1064 }
1065
1066 async fn parents(&self, commit_hash: &str) -> Result<Option<Vec<String>>> {
1067 // A commit never changes.
1068 if let Some(bytes) = self.cached("commit", commit_hash).await
1069 && let Ok(parents) = serde_json::from_slice::<Vec<String>>(&bytes)
1070 {
1071 return Ok(Some(parents));
1072 }
1073 let commit: Option<RawCommit> = js::from_js(&self.call("readCommit", &[commit_hash.into()], true).await?)?;
1074 let parents = commit.map(|commit| commit.parents);
1075 if let Some(parents) = &parents
1076 && let Ok(bytes) = serde_json::to_vec(parents)
1077 {
1078 self.keep("commit", commit_hash, bytes).await;
1079 }
1080 Ok(parents)
1081 }
1082
1083 async fn read_tree(&self, tree_hash: &str) -> Result<Option<Vec<TreeEntry>>> {
1084 if let Some(bytes) = self.cached("tree", tree_hash).await
1085 && let Ok(entries) = serde_json::from_slice::<Vec<TreeEntry>>(&bytes)
1086 {
1087 return Ok(Some(entries));
1088 }
1089 let entries: Option<Vec<RawEntry>> = js::from_js(&self.call("readTree", &[tree_hash.into()], true).await?)?;
1090 let entries: Option<Vec<TreeEntry>> = entries.map(|entries| {
1091 entries
1092 .into_iter()
1093 .map(|entry| TreeEntry {
1094 name: entry.name,
1095 hash: entry.hash,
1096 kind: entry.kind,
1097 })
1098 .collect()
1099 });
1100 if let Some(entries) = &entries
1101 && let Ok(bytes) = serde_json::to_vec(entries)
1102 {
1103 self.keep("tree", tree_hash, bytes).await;
1104 }
1105 Ok(entries)
1106 }
1107
1108 async fn read_blob(&self, blob_hash: &str) -> Result<Option<Vec<u8>>> {
1109 if let Some(bytes) = self.cached("blob", blob_hash).await {
1110 return Ok(Some(bytes));
1111 }
1112 let bytes = blob_bytes(self.call("readBlob", &[blob_hash.into()], true).await?).await?;
1113 if let Some(bytes) = &bytes {
1114 meters::record_bytes("binding.read_blob", &self.key, 0, bytes.len() as u64);
1115 }
1116 if let Some(bytes) = bytes.as_ref().filter(|bytes| bytes.len() <= MAX_CACHED_BLOB) {
1117 self.keep("blob", blob_hash, bytes.clone()).await;
1118 }
1119 Ok(bytes)
1120 }
1121
1122 /// Kept for good by hash, as a blob is: its bytes never cross into
1123 /// this isolate's memory, only the size of the store's answer.
1124 async fn blob_size(&self, blob_hash: &str) -> Result<Option<u64>> {
1125 let path = format!("size/{blob_hash}");
1126 if let Some(bytes) = self.cached_at(&path, true).await
1127 && let Some(size) = std::str::from_utf8(&bytes).ok().and_then(|text| text.parse().ok())
1128 {
1129 return Ok(Some(size));
1130 }
1131 let blob = self.call("readBlob", &[blob_hash.into()], true).await?;
1132 let size = if blob.is_null() || blob.is_undefined() {
1133 None
1134 } else if let Some(bytes) = blob.dyn_ref::<Uint8Array>() {
1135 Some(u64::from(bytes.length()))
1136 } else {
1137 js::get(&blob, "size").as_f64().map(|size| size as u64)
1138 };
1139 if let Some(size) = size {
1140 meters::record_bytes("binding.read_blob", &self.key, 0, size);
1141 self.keep_at(&path, size.to_string().into_bytes(), OBJECT_MAX_AGE).await;
1142 }
1143 Ok(size)
1144 }
1145
1146 async fn read_file(&self, git_ref: &str, path: &str) -> Result<Option<Vec<u8>>> {
1147 let key = file_key(git_ref, path, self.refs_version);
1148 // A path that is not a file is remembered too, briefly: the store
1149 // answers each such read as a rejected read (crawlers asking for
1150 // old or missing paths make most of them). Never for the fallback
1151 // store, which can be behind.
1152 let remember_absent = !self.binding.is_fallback();
1153 if let Some(key) = &key {
1154 let (found, absent) = futures_util::future::join(self.get_key(key), async {
1155 remember_absent && self.known_absent(key).await
1156 })
1157 .await;
1158 if let Some(bytes) = found {
1159 return Ok(Some(bytes));
1160 }
1161 if absent {
1162 return Ok(None);
1163 }
1164 }
1165 let args = js::to_js(&serde_json::json!({ "ref": git_ref, "path": path }))?;
1166 // The store answers a path that is not a file at the ref with
1167 // NOT_FOUND (its "read rejected"), not with nothing.
1168 let bytes = match self.call("readFile", &[args], true).await {
1169 Ok(blob) => blob_bytes(blob).await?,
1170 Err(failed) if failed.is("NOT_FOUND") => None,
1171 Err(failed) => return Err(failed.into()),
1172 };
1173 if let Some(bytes) = &bytes {
1174 meters::record_bytes("binding.read_file", &self.key, 0, bytes.len() as u64);
1175 } else if remember_absent && let Some(key) = &key {
1176 self.keep_at(&absent_path(key), vec![1], ABSENT_MAX_AGE).await;
1177 }
1178 if let (Some(key), Some(bytes)) = (&key, bytes.as_ref().filter(|bytes| bytes.len() <= MAX_CACHED_BLOB)) {
1179 self.put_key(key, bytes.clone()).await;
1180 }
1181 Ok(bytes)
1182 }
1183
1184 async fn fork(&self, target_key: &str) -> Result<()> {
1185 let (namespace, name) = locate(target_key);
1186 if namespace != self.namespace {
1187 return Err(worker::Error::RustError(format!(
1188 "a fork stays in its repository's namespace: {target_key} is not in {}",
1189 self.namespace
1190 )));
1191 }
1192 let options = js::to_js(&serde_json::json!({ "defaultBranchOnly": true }))?;
1193 match self.call("fork", &[name.as_str().into(), options], false).await {
1194 Err(failed) if !failed.is("ALREADY_EXISTS") => Err(failed.into()),
1195 _ => Ok(()),
1196 }
1197 }
1198
1199 fn at_refs_version(&mut self, version: Option<u64>) {
1200 // The fallback store holds what the last backup held, which may be
1201 // behind what was kept under the version: nothing is kept for it.
1202 self.refs_version = if self.binding.is_fallback() { None } else { version };
1203 }
1204}
1205
1206#[cfg(test)]
1207mod tests {
1208 use super::*;
1209
1210 fn access(token: &str) -> GitAccess {
1211 GitAccess {
1212 remote: "https://store.example/acme--rocket.git".to_owned(),
1213 token: token.to_owned(),
1214 }
1215 }
1216
1217 #[test]
1218 fn internal_credentials_live_an_hour_and_are_reused_for_fifty_minutes() {
1219 assert_eq!(Use::Internal.ttl_seconds(), 3_600);
1220 assert_eq!(Use::Internal.reuse_ms(), 50 * 60 * 1000);
1221 // Handed out: five minutes, reused three, so at least two are left.
1222 assert_eq!(Use::Handout.ttl_seconds(), 300);
1223 assert_eq!(Use::Handout.reuse_ms(), 180_000);
1224 assert_eq!(CREDENTIAL_LIFE_MS, 300_000);
1225 for using in [Use::Internal, Use::Handout] {
1226 assert!(u64::from(using.ttl_seconds()) * 1000 - using.reuse_ms() >= 120_000);
1227 }
1228 }
1229
1230 #[test]
1231 fn a_credential_is_reused_only_while_it_has_time_left() {
1232 let mut kept = Credentials::default();
1233 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
1234 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000).unwrap().token, "r1");
1235 let last = 1_000 + INTERNAL_REUSE_MS - 1;
1236 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Internal, last).unwrap().token, "r1");
1237 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, last + 1).is_none());
1238 }
1239
1240 #[test]
1241 fn a_credential_is_kept_for_its_own_repository_scope_and_use() {
1242 let mut kept = Credentials::default();
1243 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
1244 // A read credential never stands in for a write one.
1245 assert!(kept.get("acme--rocket", Scope::Write, Use::Internal, 1_000).is_none());
1246 assert!(kept.get("acme--booster", Scope::Read, Use::Internal, 1_000).is_none());
1247 // An hour-long credential is never handed out.
1248 assert!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000).is_none());
1249 kept.keep("acme--rocket", Scope::Read, Use::Handout, access("h1"), 1_000, 1_000);
1250 assert_eq!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000).unwrap().token, "h1");
1251 assert!(kept.get("acme--rocket", Scope::Read, Use::Handout, 1_000 + HANDOUT_REUSE_MS).is_none());
1252 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000 + HANDOUT_REUSE_MS).is_some());
1253 }
1254
1255 #[test]
1256 fn a_shared_credential_is_reused_only_in_its_own_window() {
1257 let value = serde_json::to_vec(&SharedCredential {
1258 remote: "https://store.example/acme--rocket.git".to_owned(),
1259 token: "r1".to_owned(),
1260 made: 10_000,
1261 })
1262 .unwrap();
1263 let (access, made) = shared_credential(&value, 10_000 + INTERNAL_REUSE_MS - 1, Use::Internal).unwrap();
1264 assert_eq!(access.token, "r1");
1265 // Kept here only for what is left of its window, not a new one.
1266 assert_eq!(made, 10_000);
1267 assert!(shared_credential(&value, 10_000 + INTERNAL_REUSE_MS, Use::Internal).is_none());
1268 assert!(shared_credential(&value, 10_000 + HANDOUT_REUSE_MS, Use::Handout).is_none());
1269 assert!(shared_credential(b"not json", 10_000, Use::Internal).is_none());
1270 // Each repository, scope and use has its own key, and none is read
1271 // from before uses differed.
1272 assert_eq!(shared_key("acme--rocket", Scope::Read, Use::Internal), "cred2:acme--rocket:read:internal");
1273 assert_ne!(shared_key("acme--rocket", Scope::Read, Use::Internal), shared_key("acme--rocket", Scope::Write, Use::Internal));
1274 assert_ne!(shared_key("acme--rocket", Scope::Read, Use::Internal), shared_key("acme--rocket", Scope::Read, Use::Handout));
1275 }
1276
1277 #[test]
1278 fn a_shared_credential_kept_here_expires_with_the_original() {
1279 let mut kept = Credentials::default();
1280 // Made at 1_000 elsewhere, found here at 100_000.
1281 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 100_000);
1282 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 100_000).is_some());
1283 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000 + INTERNAL_REUSE_MS).is_none());
1284 }
1285
1286 #[test]
1287 fn a_turned_down_credential_is_forgotten_and_old_ones_are_dropped() {
1288 let mut kept = Credentials::default();
1289 kept.keep("acme--rocket", Scope::Read, Use::Internal, access("r1"), 1_000, 1_000);
1290 kept.keep("acme--rocket", Scope::Write, Use::Handout, access("w1"), 1_000, 1_000);
1291 kept.keep("acme--booster", Scope::Read, Use::Internal, access("b1"), 1_000, 1_000);
1292 kept.forget("acme--rocket");
1293 assert!(kept.get("acme--rocket", Scope::Read, Use::Internal, 1_000).is_none());
1294 assert!(kept.get("acme--rocket", Scope::Write, Use::Handout, 1_000).is_none());
1295 assert!(kept.get("acme--booster", Scope::Read, Use::Internal, 1_000).is_some());
1296 // Keeping another later drops the expired one from the map.
1297 let later = 1_000 + INTERNAL_REUSE_MS;
1298 kept.keep("acme--other", Scope::Read, Use::Internal, access("o1"), later, later);
1299 assert_eq!(kept.kept.len(), 1);
1300 }
1301
1302 #[test]
1303 fn a_remote_is_worked_out_from_where_its_namespace_starts() {
1304 // As https://developers.cloudflare.com/artifacts/api/git-protocol/ documents.
1305 let remote = "https://1e6f2cffa3f445920836e8ebe446bb58.artifacts.cloudflare.net/git/g1t/acme--rocket.git";
1306 let prefix = learn_prefix(remote, "acme--rocket").unwrap();
1307 assert_eq!(prefix, "https://1e6f2cffa3f445920836e8ebe446bb58.artifacts.cloudflare.net/git/g1t/");
1308 assert_eq!(remote_from(&prefix, "pulls--pul_1"), prefix.clone() + "pulls--pul_1.git");
1309 assert_eq!(remote_from(&prefix, "acme--rocket"), remote);
1310 // A remote that does not end in the name teaches nothing.
1311 assert_eq!(learn_prefix(remote, "rocket"), None);
1312 assert_eq!(learn_prefix("https://x/acme--rocket", "acme--rocket"), None);
1313 // And back: a remote names its key.
1314 assert_eq!(key_from_remote(remote).as_deref(), Some("acme--rocket"));
1315 assert_eq!(
1316 key_from_remote("https://a.artifacts.cloudflare.net/git/g1t-us-1/acme--rocket.git").as_deref(),
1317 Some("g1t-us-1/acme--rocket")
1318 );
1319 assert_eq!(locate("g1t-us-1/acme--rocket"), ("g1t-us-1".to_owned(), "acme--rocket".to_owned()));
1320 assert_eq!(locate("acme--rocket"), ("g1t".to_owned(), "acme--rocket".to_owned()));
1321 }
1322
1323 #[test]
1324 fn the_fallback_stores_credentials_and_remotes_are_its_own() {
1325 assert_eq!(cred_key("acme--rocket", false), "acme--rocket");
1326 assert_eq!(cred_key("g1t-us-1/acme--rocket", true), "fallback:g1t-us-1/acme--rocket");
1327 // A credential Artifacts made is never handed out for the fallback
1328 // store, nor the reverse.
1329 assert_ne!(
1330 shared_key(&cred_key("acme--rocket", true), Scope::Write, Use::Internal),
1331 shared_key(&cred_key("acme--rocket", false), Scope::Write, Use::Internal)
1332 );
1333 // Its remotes name their keys as Artifacts' do.
1334 let settings = fallback::Settings::from_vars(Some("https://gitstore.example"), Some("0123456789abcdef"), Some("*"), None).unwrap();
1335 assert_eq!(key_from_remote(&settings.remote("g1t", "acme--rocket")).as_deref(), Some("acme--rocket"));
1336 assert_eq!(key_from_remote(&settings.remote("g1t-us-1", "pulls--pul_1")).as_deref(), Some("g1t-us-1/pulls--pul_1"));
1337 // Git requests to it count toward its own health, not Artifacts'.
1338 FALLBACK_BASE.with(|base| *base.borrow_mut() = Some(format!("{}/git/", settings.url)));
1339 assert_eq!(health_namespace(&settings.remote("g1t-us-1", "acme--rocket")), "g1t-us-1@fallback");
1340 assert_eq!(health_namespace("https://a.artifacts.cloudflare.net/git/g1t-us-1/acme--rocket.git"), "g1t-us-1");
1341 FALLBACK_BASE.with(|base| *base.borrow_mut() = None);
1342 }
1343
1344 #[test]
1345 fn the_memory_cache_drops_its_oldest_past_its_budget() {
1346 let mut cache = MemoryCache::default();
1347 let chunk = vec![7u8; MEMORY_CACHE_BYTES / 16];
1348 for n in 0..17 {
1349 cache.put(format!("k{n}"), &chunk);
1350 }
1351 // Sixteen chunks fit; the seventeenth pushed the first out.
1352 assert!(cache.get("k0").is_none());
1353 assert_eq!(cache.get("k16").map(|b| b.len()), Some(chunk.len()));
1354 assert!(cache.bytes <= MEMORY_CACHE_BYTES);
1355 // Too large to keep at all.
1356 cache.put("big".into(), &vec![0u8; MEMORY_CACHE_BYTES / 16 + 1]);
1357 assert!(cache.get("big").is_none());
1358 }
1359
1360 #[test]
1361 fn binding_methods_have_snake_case_meters() {
1362 assert_eq!(meter_of("createToken"), "binding.create_token");
1363 assert_eq!(meter_of("readBlob"), "binding.read_blob");
1364 assert_eq!(meter_of("get"), "binding.get");
1365 }
1366
1367 #[test]
1368 fn reads_by_name_are_kept_under_the_refs_version_and_by_hash_for_good() {
1369 let hash = "a".repeat(40);
1370 assert_eq!(log_key(&hash, 1, Some(3)), Some(CacheKey::Forever(format!("log/{hash}-1"))));
1371 assert_eq!(log_key(&hash, 1, None), Some(CacheKey::Forever(format!("log/{hash}-1"))));
1372 // A branch is kept only when the version is known.
1373 assert_eq!(log_key("main", 1, None), None);
1374 let v3 = log_key("main", 1, Some(3)).unwrap();
1375 assert!(matches!(&v3, CacheKey::Versioned(path) if path.starts_with("vlog/3/")));
1376 // A push moves the version and leaves the old answer behind.
1377 assert_ne!(Some(v3), log_key("main", 1, Some(4)));
1378 assert_ne!(log_key("main", 1, Some(3)), log_key("main", 50, Some(3)));
1379 assert_ne!(log_key("main", 1, Some(3)), log_key("dev", 1, Some(3)));
1380 // Odd branch names make a usable address.
1381 assert!(matches!(log_key("fix/#1 %20", 1, Some(3)), Some(CacheKey::Versioned(path)) if !path.contains('#') && !path.contains(' ')));
1382 assert_eq!(branches_key(None), None);
1383 assert_ne!(branches_key(Some(1)), branches_key(Some(2)));
1384 assert!(matches!(file_key(&hash, "src/main.rs", None), Some(CacheKey::Forever(_))));
1385 assert_eq!(file_key("main", "src/main.rs", None), None);
1386 assert_ne!(file_key("main", "a", Some(1)), file_key("main", "b", Some(1)));
1387 assert_ne!(file_key("main", "a", Some(1)), file_key("main", "a", Some(2)));
1388 // A path noted as not a file sits beside the file's own key, and a
1389 // push (a new refs version) leaves the old note behind.
1390 let at = |version| absent_path(&file_key("main", "a", Some(version)).unwrap());
1391 assert!(at(1).starts_with("absent/vfile/1/"));
1392 assert_ne!(at(1), at(2));
1393 assert_eq!(absent_path(&file_key(&hash, "a", None).unwrap()), format!("absent/file/{hash}/{}", g1t_secrets::sha256_hex("a")));
1394 }
1395
1396 #[test]
1397 fn only_full_lowercase_hashes_are_kept() {
1398 assert!(is_commit_hash(&"a".repeat(40)));
1399 assert!(is_commit_hash(&"0123456789abcdef".repeat(4)));
1400 assert!(!is_commit_hash("main"));
1401 assert!(!is_commit_hash(&"A".repeat(40)));
1402 assert!(!is_commit_hash(&"a".repeat(39)));
1403 }
1404}