Skip to content

g1t/services/repos/src/store.rs

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