Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.
| Rust repos service with shipping; pull requests kept in the model | 1 | //! Repository metadata in D1. |
| 2 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 3 | use std::cell::RefCell; |
| 4 | use std::collections::HashMap; | |
| 5 | ||
| Rust repos service with shipping; pull requests kept in the model | 6 | use g1t_contracts::Viewer; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 7 | use g1t_contracts::access::{self, Capability, RepoRole}; |
| Rust repos service with shipping; pull requests kept in the model | 8 | use g1t_contracts::repos::{Repo, RepoPath}; |
| 9 | use serde::Deserialize; | |
| 10 | use worker::wasm_bindgen::JsValue; | |
| 11 | use worker::{D1Database, Result}; | |
| 12 | ||
| 13 | #[derive(Deserialize)] | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 14 | pub(crate) struct RepoRow { |
| Rust repos service with shipping; pull requests kept in the model | 15 | id: String, |
| 16 | namespace: String, | |
| 17 | name: String, | |
| 18 | description: Option<String>, | |
| 19 | is_private: u8, | |
| 20 | owner_id: String, | |
| 21 | default_branch: String, | |
| 22 | fork_of: Option<String>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 23 | protected: u8, |
| RFC 3339 timestamps in identity and repos | 24 | created_at: String, |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 25 | /// Null only on rows written before the column existed and not yet |
| 26 | /// migrated; their key is the one worked out from the path. | |
| 27 | #[serde(default)] | |
| 28 | store: Option<String>, | |
| Search across all of g1t, Explore, and a command palette | 29 | /// JSON; absent on rows read before the column existed. |
| 30 | #[serde(default)] | |
| 31 | topics: Option<String>, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 32 | #[serde(default)] |
| 33 | website: Option<String>, | |
| 34 | #[serde(default)] | |
| 35 | archived_at: Option<String>, | |
| 36 | #[serde(default)] | |
| 37 | deleted_at: Option<String>, | |
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 38 | /// Bumped by everything that changes the repository's refs; see |
| 39 | /// [`RefsState`]. Absent on rows read before the column existed. | |
| 40 | #[serde(default)] | |
| 41 | refs_version: Option<f64>, | |
| 42 | #[serde(default)] | |
| 43 | refs_open_until: Option<f64>, | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 44 | /// A pull request working copy whose git data was removed, and the |
| 45 | /// head it had (forks.rs). Absent before the columns existed. | |
| 46 | #[serde(default)] | |
| 47 | retired_at: Option<String>, | |
| 48 | #[serde(default)] | |
| 49 | retired_head: Option<String>, | |
| Merge branch 'worktree-agent-a2013627e5ea4ab13' | 50 | /// Until when writes wait, and why: a move between namespaces |
| 51 | /// (moves.rs). Absent before the columns existed. | |
| 52 | #[serde(default)] | |
| 53 | writes_paused_until: Option<f64>, | |
| 54 | #[serde(default)] | |
| 55 | writes_paused_for: Option<String>, | |
| 56 | } | |
| 57 | ||
| 58 | thread_local! { | |
| 59 | /// Repositories whose writes wait, by id: until when, and why. Filled | |
| 60 | /// whenever a row is read. | |
| 61 | static PAUSED: RefCell<HashMap<String, (u64, String)>> = RefCell::new(HashMap::new()); | |
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 62 | } |
| 63 | ||
| Merge branch 'worktree-agent-a2013627e5ea4ab13' | 64 | /// Records whether writes to the repository with this id wait, as its row says. |
| 65 | pub fn note_paused(id: &str, until: Option<u64>, reason: Option<&str>) { | |
| 66 | PAUSED.with(|paused| { | |
| 67 | let mut paused = paused.borrow_mut(); | |
| 68 | match until { | |
| 69 | Some(until) => { | |
| 70 | paused.insert(id.to_owned(), (until, reason.unwrap_or("maintenance").to_owned())); | |
| 71 | } | |
| 72 | None => { | |
| 73 | paused.remove(id); | |
| 74 | } | |
| 75 | } | |
| 76 | }); | |
| 77 | } | |
| 78 | ||
| 79 | /// Why writes to the repository with this id wait at `now`, if they do, as | |
| 80 | /// its row last read here said. | |
| 81 | pub fn paused(id: &str, now: u64) -> Option<String> { | |
| 82 | PAUSED.with(|paused| paused.borrow().get(id).filter(|(until, _)| *until > now).map(|(_, reason)| reason.clone())) | |
| 83 | } | |
| 84 | ||
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 85 | /// Where a repository's refs stand, as its row last said: `version` goes up |
| 86 | /// with every change g1t makes to them, so an answer that lists them (see | |
| 87 | /// refs_cache.rs) is kept under the version it was made at, and a change | |
| 88 | /// leaves it behind. Until `open_until` (milliseconds) a credential that | |
| 89 | /// can change them is out of g1t's hands, and nothing is kept. | |
| 90 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | |
| 91 | pub struct RefsState { | |
| 92 | pub version: u64, | |
| 93 | pub open_until: u64, | |
| 94 | } | |
| 95 | ||
| 96 | /// The newest [`RefsState`] this isolate has read or written, by | |
| 97 | /// repository id. A version only goes up, so an older read finishing late | |
| 98 | /// never takes a newer one back. | |
| 99 | #[derive(Default)] | |
| 100 | pub struct RefsStates { | |
| 101 | states: HashMap<String, RefsState>, | |
| Rust repos service with shipping; pull requests kept in the model | 102 | } |
| 103 | ||
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 104 | impl RefsStates { |
| 105 | pub fn note(&mut self, id: &str, state: RefsState) { | |
| 106 | let kept = self.states.entry(id.to_owned()).or_default(); | |
| 107 | kept.version = kept.version.max(state.version); | |
| 108 | kept.open_until = kept.open_until.max(state.open_until); | |
| 109 | } | |
| 110 | ||
| 111 | pub fn get(&self, id: &str) -> Option<RefsState> { | |
| 112 | self.states.get(id).copied() | |
| 113 | } | |
| 114 | } | |
| 115 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 116 | thread_local! { |
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 117 | static REFS: RefCell<RefsStates> = RefCell::new(RefsStates::default()); |
| 118 | } | |
| 119 | ||
| 120 | /// Where the refs of the repository with this id stand, as this isolate | |
| 121 | /// last read them; `None` before the column existed or before its row was | |
| 122 | /// read here. | |
| 123 | pub fn refs_state(id: &str) -> Option<RefsState> { | |
| 124 | REFS.with(|refs| refs.borrow().get(id)) | |
| 125 | } | |
| 126 | ||
| 127 | fn note_refs(id: &str, version: Option<f64>, open_until: Option<f64>) { | |
| 128 | if let Some(version) = version { | |
| 129 | let state = RefsState { | |
| 130 | version: version as u64, | |
| 131 | open_until: open_until.unwrap_or(0.0) as u64, | |
| 132 | }; | |
| 133 | REFS.with(|refs| refs.borrow_mut().note(id, state)); | |
| 134 | } | |
| 135 | } | |
| 136 | ||
| 137 | thread_local! { | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 138 | /// Working copies whose git data was removed, by id, with the head |
| 139 | /// each had (forks.rs). Filled whenever a row is read. | |
| 140 | static RETIRED: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new()); | |
| 141 | } | |
| 142 | ||
| 143 | /// The head a removed working copy had, if the repository with this id is one. | |
| 144 | pub fn retired(id: &str) -> Option<String> { | |
| 145 | RETIRED.with(|retired| retired.borrow().get(id).cloned()) | |
| 146 | } | |
| 147 | ||
| 148 | /// Records whether the repository with this id is a removed working copy. | |
| 149 | pub fn note_retired(id: &str, head: Option<&str>) { | |
| 150 | RETIRED.with(|retired| { | |
| 151 | let mut retired = retired.borrow_mut(); | |
| 152 | match head { | |
| 153 | Some(head) => { | |
| 154 | retired.insert(id.to_owned(), head.to_owned()); | |
| 155 | } | |
| 156 | None => { | |
| 157 | retired.remove(id); | |
| 158 | } | |
| 159 | } | |
| 160 | }); | |
| 161 | } | |
| 162 | ||
| 163 | thread_local! { | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 164 | /// Store keys that differ from the one a repository's path gives: those |
| 165 | /// of repositories whose workspace was renamed after they were made. | |
| 166 | /// Filled whenever a row is read or written, so every `Repo` this | |
| Merge branch 'worktree-agent-a2013627e5ea4ab13' | 167 | /// service holds has its key here. A key changes only when a move |
| 168 | /// between namespaces switches it (moves.rs), and every row read | |
| 169 | /// after that brings the new one, so requests sharing the isolate can | |
| 170 | /// share the map. | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 171 | static MOVED: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new()); |
| 172 | } | |
| 173 | ||
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 174 | /// How long a fetch may go by a repository's row as it was read a moment |
| 175 | /// ago: a clone is two or three requests in quick succession, and each | |
| 176 | /// would otherwise read the same row. Short enough that making a repository | |
| 177 | /// private, archiving or deleting it applies within seconds. | |
| 178 | pub const RECENT_MS: u64 = 5_000; | |
| 179 | ||
| 180 | /// Repositories read in the last [`RECENT_MS`], by path. Only rows that | |
| 181 | /// were found are kept, so a repository just made is never missed. | |
| 182 | #[derive(Default)] | |
| 183 | pub struct Recent { | |
| 184 | rows: HashMap<(String, String), (Repo, u64)>, | |
| 185 | } | |
| 186 | ||
| 187 | impl Recent { | |
| 188 | fn key(path: &RepoPath) -> (String, String) { | |
| 189 | (path.namespace.to_lowercase(), path.name.to_lowercase()) | |
| 190 | } | |
| 191 | ||
| 192 | pub fn get(&self, path: &RepoPath, now: u64) -> Option<Repo> { | |
| 193 | self.rows | |
| 194 | .get(&Self::key(path)) | |
| 195 | .filter(|(_, read)| now.saturating_sub(*read) < RECENT_MS) | |
| 196 | .map(|(repo, _)| repo.clone()) | |
| 197 | } | |
| 198 | ||
| 199 | pub fn keep(&mut self, path: &RepoPath, repo: &Repo, now: u64) { | |
| 200 | self.rows.retain(|_, (_, read)| now.saturating_sub(*read) < RECENT_MS); | |
| 201 | self.rows.insert(Self::key(path), (repo.clone(), now)); | |
| 202 | } | |
| 203 | } | |
| 204 | ||
| 205 | thread_local! { | |
| 206 | static RECENT: RefCell<Recent> = RefCell::new(Recent::default()); | |
| 207 | } | |
| 208 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 209 | /// The key a repository's path gives: what every repository was stored |
| 210 | /// under before workspaces could be renamed. | |
| 211 | pub fn path_key(repo: &Repo) -> String { | |
| 212 | format!("{}--{}", repo.namespace, repo.name) | |
| 213 | } | |
| 214 | ||
| Merge branch 'worktree-agent-a2013627e5ea4ab13' | 215 | /// Records where a repository is stored, when its path does not say. A |
| 216 | /// key changes when the repository moves between namespaces (moves.rs), | |
| 217 | /// so one that is the path's again is forgotten. | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 218 | pub fn remember_store(repo: &Repo, store: &str) { |
| Merge branch 'worktree-agent-a2013627e5ea4ab13' | 219 | MOVED.with(|moved| { |
| 220 | let mut moved = moved.borrow_mut(); | |
| 221 | if store != path_key(repo) { | |
| 222 | moved.insert(repo.id.clone(), store.to_owned()); | |
| 223 | } else { | |
| 224 | moved.remove(&repo.id); | |
| 225 | } | |
| 226 | }); | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 227 | } |
| 228 | ||
| Rust repos service with shipping; pull requests kept in the model | 229 | impl From<RepoRow> for Repo { |
| 230 | fn from(row: RepoRow) -> Self { | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 231 | let repo = Repo { |
| Rust repos service with shipping; pull requests kept in the model | 232 | id: row.id, |
| 233 | namespace: row.namespace, | |
| 234 | name: row.name, | |
| 235 | description: row.description, | |
| 236 | is_private: row.is_private != 0, | |
| 237 | owner_id: row.owner_id, | |
| 238 | default_branch: row.default_branch, | |
| 239 | fork_of: row.fork_of, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 240 | protected: row.protected != 0, |
| RFC 3339 timestamps in identity and repos | 241 | created_at: row.created_at, |
| Search across all of g1t, Explore, and a command palette | 242 | topics: row |
| 243 | .topics | |
| 244 | .as_deref() | |
| 245 | .and_then(|topics| serde_json::from_str(topics).ok()) | |
| 246 | .unwrap_or_default(), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 247 | website: row.website, |
| 248 | archived_at: row.archived_at, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 249 | }; |
| 250 | if let Some(store) = &row.store { | |
| 251 | remember_store(&repo, store); | |
| Rust repos service with shipping; pull requests kept in the model | 252 | } |
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 253 | note_refs(&repo.id, row.refs_version, row.refs_open_until); |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 254 | note_retired(&repo.id, row.retired_at.as_ref().and(row.retired_head.as_deref())); |
| Merge branch 'worktree-agent-a2013627e5ea4ab13' | 255 | note_paused(&repo.id, row.writes_paused_until.map(|until| until as u64), row.writes_paused_for.as_deref()); |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 256 | repo |
| Rust repos service with shipping; pull requests kept in the model | 257 | } |
| 258 | } | |
| 259 | ||
| 260 | /// The key a repo is stored under in the git store. | |
| 261 | pub fn store_key(repo: &Repo) -> String { | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 262 | let key = MOVED |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 263 | .with(|moved| moved.borrow().get(&repo.id).cloned()) |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 264 | .unwrap_or_else(|| path_key(repo)); |
| 265 | // Its interactions with the store are metered for its workspace. | |
| 266 | crate::meters::note_owner(&key, &repo.namespace); | |
| 267 | key | |
| Rust repos service with shipping; pull requests kept in the model | 268 | } |
| 269 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 270 | /// The viewer's role on `repo` (see `g1t_contracts::access`): ownership of |
| 271 | /// its workspace, the workspace's base permission, a direct grant, or | |
| 272 | /// Read on a public repository. A pull request's fork is its author's to | |
| 273 | /// write; whoever can read the repository it came from can read it too, | |
| 274 | /// which `Repos::may_read` checks. | |
| 275 | pub fn role(repo: &Repo, viewer: &Viewer) -> Option<RepoRole> { | |
| 276 | if repo.fork_of.is_some() { | |
| 277 | let author = viewer.as_ref().is_some_and(|user| user.id == repo.owner_id); | |
| 278 | return if author { | |
| 279 | Some(RepoRole::Write) | |
| 280 | } else if repo.is_private { | |
| 281 | None | |
| 282 | } else { | |
| 283 | Some(RepoRole::Read) | |
| 284 | }; | |
| 285 | } | |
| 286 | access::permission(viewer.as_ref(), repo) | |
| 287 | } | |
| 288 | ||
| 289 | /// Whether the viewer may read `repo`, going by the repository alone. | |
| Rust repos service with shipping; pull requests kept in the model | 290 | pub fn can_read(repo: &Repo, viewer: &Viewer) -> bool { |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 291 | role(repo, viewer).is_some() |
| Rust repos service with shipping; pull requests kept in the model | 292 | } |
| 293 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 294 | /// Whether the viewer may push to `repo`: Write or higher, or the author |
| 295 | /// of a pull request's fork. | |
| Rust repos service with shipping; pull requests kept in the model | 296 | pub fn can_write(repo: &Repo, viewer: &Viewer) -> bool { |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 297 | can(repo, viewer, Capability::Push) |
| Rust repos service with shipping; pull requests kept in the model | 298 | } |
| 299 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 300 | /// Whether the viewer may do `capability` in `repo`. A fork has only its |
| 301 | /// author's Write. | |
| 302 | pub fn can(repo: &Repo, viewer: &Viewer, capability: Capability) -> bool { | |
| 303 | if repo.fork_of.is_some() { | |
| 304 | return role(repo, viewer).is_some_and(|role| access::allows(role, capability)) | |
| 305 | && !access::OWNER_ONLY.contains(&capability); | |
| 306 | } | |
| 307 | access::can(viewer.as_ref(), repo, capability) | |
| 308 | } | |
| 309 | ||
| Rust repos service with shipping; pull requests kept in the model | 310 | fn optional(value: &Option<String>) -> JsValue { |
| 311 | value.as_deref().map_or(JsValue::NULL, JsValue::from) | |
| 312 | } | |
| 313 | ||
| 314 | pub struct Registry { | |
| 315 | pub db: D1Database, | |
| 316 | } | |
| 317 | ||
| 318 | impl Registry { | |
| 319 | pub async fn by_path(&self, path: &RepoPath) -> Result<Option<Repo>> { | |
| 320 | Ok(self | |
| 321 | .db | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 322 | .prepare("SELECT * FROM repos WHERE namespace = ? AND name = ? AND deleted_at IS NULL") |
| Rust repos service with shipping; pull requests kept in the model | 323 | .bind(&[ |
| 324 | path.namespace.to_lowercase().into(), | |
| 325 | path.name.to_lowercase().into(), | |
| 326 | ])? | |
| 327 | .first::<RepoRow>(None) | |
| 328 | .await? | |
| 329 | .map(Repo::from)) | |
| 330 | } | |
| 331 | ||
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 332 | /// The repository at `path`, as read in the last few seconds if it was |
| 333 | /// (see [`RECENT_MS`]). For fetches only: a push always reads the row. | |
| 334 | pub async fn by_path_recent(&self, path: &RepoPath) -> Result<Option<Repo>> { | |
| 335 | let now = g1t_kit::now_ms(); | |
| 336 | if let Some(repo) = RECENT.with(|recent| recent.borrow().get(path, now)) { | |
| 337 | return Ok(Some(repo)); | |
| 338 | } | |
| 339 | let found = self.by_path(path).await?; | |
| 340 | if let Some(repo) = &found { | |
| 341 | RECENT.with(|recent| recent.borrow_mut().keep(path, repo, now)); | |
| 342 | } | |
| 343 | Ok(found) | |
| 344 | } | |
| 345 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 346 | /// Its details; who can see it changes with `set_private`. |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 347 | pub async fn update( |
| 348 | &self, | |
| 349 | id: &str, | |
| 350 | description: Option<&str>, | |
| 351 | protected: bool, | |
| Search across all of g1t, Explore, and a command palette | 352 | topics: &[String], |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 353 | website: Option<&str>, |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 354 | ) -> Result<()> { |
| 355 | self.db | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 356 | .prepare("UPDATE repos SET description = ?, protected = ?, topics = ?, website = ? WHERE id = ?") |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 357 | .bind(&[ |
| 358 | description.map_or(JsValue::NULL, JsValue::from), | |
| 359 | u32::from(protected).into(), | |
| Search across all of g1t, Explore, and a command palette | 360 | serde_json::to_string(topics)?.into(), |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 361 | website.map_or(JsValue::NULL, JsValue::from), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 362 | id.into(), |
| 363 | ])? | |
| 364 | .run() | |
| 365 | .await?; | |
| 366 | Ok(()) | |
| 367 | } | |
| 368 | ||
| Rust repos service with shipping; pull requests kept in the model | 369 | pub async fn by_id(&self, id: &str) -> Result<Option<Repo>> { |
| 370 | Ok(self | |
| 371 | .db | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 372 | .prepare("SELECT * FROM repos WHERE id = ? AND deleted_at IS NULL") |
| Rust repos service with shipping; pull requests kept in the model | 373 | .bind(&[id.into()])? |
| 374 | .first::<RepoRow>(None) | |
| 375 | .await? | |
| 376 | .map(Repo::from)) | |
| 377 | } | |
| 378 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 379 | /// The repository at `path`, deleted or not: what holds the name. |
| 380 | pub async fn by_path_any(&self, path: &RepoPath) -> Result<Option<(Repo, Option<String>)>> { | |
| 381 | Ok(self | |
| 382 | .db | |
| 383 | .prepare("SELECT * FROM repos WHERE namespace = ? AND name = ?") | |
| 384 | .bind(&[ | |
| 385 | path.namespace.to_lowercase().into(), | |
| 386 | path.name.to_lowercase().into(), | |
| 387 | ])? | |
| 388 | .first::<RepoRow>(None) | |
| 389 | .await? | |
| 390 | .map(|mut row| { | |
| 391 | let deleted_at = row.deleted_at.take(); | |
| 392 | (Repo::from(row), deleted_at) | |
| 393 | })) | |
| 394 | } | |
| 395 | ||
| Issues and pull requests replace intents and attempts | 396 | /// Repos the viewer may see, newest first. Excludes pull request forks. |
| Workspaces own repositories | 397 | /// With `member_only`, only repos in the viewer's own workspaces. |
| Rust repos service with shipping; pull requests kept in the model | 398 | pub async fn list( |
| 399 | &self, | |
| 400 | viewer: &Viewer, | |
| 401 | query: Option<&str>, | |
| 402 | namespace: Option<&str>, | |
| Workspaces own repositories | 403 | member_only: bool, |
| Rust repos service with shipping; pull requests kept in the model | 404 | ) -> Result<Vec<Repo>> { |
| Workspaces own repositories | 405 | let workspaces: Vec<&str> = viewer |
| 406 | .iter() | |
| 407 | .flat_map(|user| &user.workspaces) | |
| 408 | .map(|membership| membership.slug.as_str()) | |
| 409 | .collect(); | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 410 | // The workspaces whose private repositories the viewer reads all |
| 411 | // of (an owner, or a base permission other than none), and the | |
| 412 | // repositories they were given a role on: see access.rs. A probe | |
| 413 | // repository in each workspace stands for all of them. | |
| 414 | let reading: Vec<&str> = viewer | |
| 415 | .iter() | |
| 416 | .flat_map(|user| { | |
| 417 | user.workspaces.iter().filter(move |membership| { | |
| 418 | let probe = access::RepoRef { id: "", namespace: &membership.slug, private: true }; | |
| 419 | access::granted(user, probe).is_some() | |
| 420 | }) | |
| 421 | }) | |
| 422 | .map(|membership| membership.slug.as_str()) | |
| 423 | .collect(); | |
| 424 | let granted: Vec<&str> = viewer | |
| 425 | .iter() | |
| 426 | .flat_map(|user| &user.grants) | |
| 427 | .map(|grant| grant.repo_id.as_str()) | |
| 428 | .collect(); | |
| 429 | let mut params: Vec<JsValue> = vec![ | |
| 430 | serde_json::to_string(&reading)?.into(), | |
| 431 | serde_json::to_string(&granted)?.into(), | |
| 432 | ]; | |
| 433 | let private_ok = "(namespace IN (SELECT value FROM json_each(?)) OR id IN (SELECT value FROM json_each(?)))"; | |
| Workspaces own repositories | 434 | let mut conditions = vec![ |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 435 | "fork_of IS NULL AND deleted_at IS NULL".to_owned(), |
| 436 | format!("(is_private = 0 OR {private_ok})"), | |
| Workspaces own repositories | 437 | ]; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 438 | if member_only { |
| 439 | conditions.push("namespace IN (SELECT value FROM json_each(?))".to_owned()); | |
| 440 | params.push(serde_json::to_string(&workspaces)?.into()); | |
| 441 | } | |
| Rust repos service with shipping; pull requests kept in the model | 442 | if let Some(namespace) = namespace { |
| Workspaces own repositories | 443 | conditions.push("namespace = ?".to_owned()); |
| Rust repos service with shipping; pull requests kept in the model | 444 | params.push(namespace.to_lowercase().into()); |
| 445 | } | |
| 446 | if let Some(query) = query.map(str::trim).filter(|query| !query.is_empty()) { | |
| Workspaces own repositories | 447 | conditions |
| 448 | .push("(name LIKE ? ESCAPE '\\' OR description LIKE ? ESCAPE '\\')".to_owned()); | |
| Rust repos service with shipping; pull requests kept in the model | 449 | // LIKE wildcards in the query are matched literally. |
| 450 | let escaped: String = query | |
| 451 | .chars() | |
| 452 | .flat_map(|c| match c { | |
| 453 | '\\' | '%' | '_' => vec!['\\', c], | |
| 454 | _ => vec![c], | |
| 455 | }) | |
| 456 | .collect(); | |
| 457 | let pattern = format!("%{escaped}%"); | |
| 458 | params.push(pattern.as_str().into()); | |
| 459 | params.push(pattern.into()); | |
| 460 | } | |
| 461 | let sql = format!( | |
| 462 | "SELECT * FROM repos WHERE {} ORDER BY created_at DESC, id DESC LIMIT 50", | |
| 463 | conditions.join(" AND ") | |
| 464 | ); | |
| 465 | let rows = self | |
| 466 | .db | |
| 467 | .prepare(sql) | |
| 468 | .bind(¶ms)? | |
| 469 | .all() | |
| 470 | .await? | |
| 471 | .results::<RepoRow>()?; | |
| 472 | Ok(rows.into_iter().map(Repo::from).collect()) | |
| 473 | } | |
| 474 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 475 | /// Of these ids, the repositories (not forks) the viewer may read. |
| 476 | pub async fn readable(&self, ids: &[String], viewer: &Viewer) -> Result<Vec<Repo>> { | |
| 477 | let ids: Vec<&String> = ids.iter().take(g1t_contracts::repos::MAX_READABLE).collect(); | |
| 478 | if ids.is_empty() { | |
| 479 | return Ok(Vec::new()); | |
| 480 | } | |
| 481 | // One parameter however many ids: D1 binds at most 100. | |
| 482 | let rows = self | |
| 483 | .db | |
| 484 | .prepare( | |
| 485 | "SELECT * FROM repos | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 486 | WHERE id IN (SELECT value FROM json_each(?)) AND fork_of IS NULL AND deleted_at IS NULL", |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 487 | ) |
| 488 | .bind(&[serde_json::to_string(&ids)?.into()])? | |
| 489 | .all() | |
| 490 | .await? | |
| 491 | .results::<RepoRow>()?; | |
| 492 | Ok(rows | |
| 493 | .into_iter() | |
| 494 | .map(Repo::from) | |
| 495 | .filter(|repo| can_read(repo, viewer)) | |
| 496 | .collect()) | |
| 497 | } | |
| 498 | ||
| 499 | /// The workspaces in which this account made a public repository. | |
| 500 | pub async fn public_namespaces(&self, owner_id: &str) -> Result<Vec<String>> { | |
| 501 | #[derive(Deserialize)] | |
| 502 | struct Row { | |
| 503 | namespace: String, | |
| 504 | } | |
| 505 | Ok(self | |
| 506 | .db | |
| 507 | .prepare( | |
| 508 | "SELECT DISTINCT namespace FROM repos | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 509 | WHERE owner_id = ? AND is_private = 0 AND fork_of IS NULL AND deleted_at IS NULL |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 510 | ORDER BY namespace", |
| 511 | ) | |
| 512 | .bind(&[owner_id.into()])? | |
| 513 | .all() | |
| 514 | .await? | |
| 515 | .results::<Row>()? | |
| 516 | .into_iter() | |
| 517 | .map(|row| row.namespace) | |
| 518 | .collect()) | |
| 519 | } | |
| 520 | ||
| Search across all of g1t, Explore, and a command palette | 521 | /// Repositories that are not forks, by id, a page at a time. |
| 522 | pub async fn ids_after(&self, after: Option<&str>, limit: u32) -> Result<Vec<String>> { | |
| 523 | #[derive(Deserialize)] | |
| 524 | struct Row { | |
| 525 | id: String, | |
| 526 | } | |
| 527 | Ok(self | |
| 528 | .db | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 529 | .prepare("SELECT id FROM repos WHERE fork_of IS NULL AND deleted_at IS NULL AND id > ? ORDER BY id LIMIT ?") |
| Search across all of g1t, Explore, and a command palette | 530 | .bind(&[after.unwrap_or("").into(), limit.into()])? |
| 531 | .all() | |
| 532 | .await? | |
| 533 | .results::<Row>()? | |
| 534 | .into_iter() | |
| 535 | .map(|row| row.id) | |
| 536 | .collect()) | |
| 537 | } | |
| 538 | ||
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 539 | /// Adds a pushed pack's bytes to what the repository is counted as |
| 540 | /// holding: its own, or, for a pull request's working copy, the | |
| 541 | /// repository it is a copy of, whose storage it is. | |
| 542 | pub async fn add_stored_bytes(&self, repo: &Repo, bytes: u64) -> Result<()> { | |
| 543 | if bytes == 0 { | |
| 544 | return Ok(()); | |
| 545 | } | |
| 546 | let root = repo.fork_of.as_deref().unwrap_or(&repo.id); | |
| 547 | self.db | |
| 548 | .prepare("UPDATE repos SET stored_bytes = stored_bytes + ? WHERE id = ?") | |
| 549 | .bind(&[(bytes as f64).into(), root.into()])? | |
| 550 | .run() | |
| 551 | .await?; | |
| 552 | Ok(()) | |
| 553 | } | |
| 554 | ||
| 555 | /// Which of these `namespace/name` paths are private. A working copy | |
| 556 | /// answers as its repository. Unknown paths are left out. | |
| 557 | pub async fn visibility(&self, paths: &[String]) -> Result<Vec<g1t_contracts::repos::RepoVisibility>> { | |
| 558 | let mut out = Vec::new(); | |
| 559 | for path in paths.iter().take(50) { | |
| 560 | let Some((namespace, name)) = path.split_once('/') else { continue }; | |
| 561 | let Some(repo) = self | |
| 562 | .by_path(&RepoPath { namespace: namespace.to_owned(), name: name.to_owned() }) | |
| 563 | .await? | |
| 564 | else { | |
| 565 | continue; | |
| 566 | }; | |
| 567 | let is_private = match &repo.fork_of { | |
| 568 | Some(parent) => self.by_id(parent).await?.map_or(repo.is_private, |parent| parent.is_private), | |
| 569 | None => repo.is_private, | |
| 570 | }; | |
| 571 | out.push(g1t_contracts::repos::RepoVisibility { path: path.clone(), is_private }); | |
| 572 | } | |
| 573 | Ok(out) | |
| 574 | } | |
| 575 | ||
| 576 | /// What each workspace's repositories are counted as holding, private | |
| 577 | /// and public apart. Working copies count toward their repository. | |
| 578 | pub async fn storage(&self) -> Result<Vec<g1t_contracts::repos::WorkspaceStorage>> { | |
| 579 | #[derive(Deserialize)] | |
| 580 | struct Row { | |
| 581 | namespace: String, | |
| 582 | private_bytes: Option<f64>, | |
| 583 | public_bytes: Option<f64>, | |
| 584 | } | |
| 585 | Ok(self | |
| 586 | .db | |
| 587 | .prepare( | |
| 588 | "SELECT namespace, | |
| 589 | SUM(CASE WHEN is_private = 1 THEN stored_bytes ELSE 0 END) AS private_bytes, | |
| 590 | SUM(CASE WHEN is_private = 0 THEN stored_bytes ELSE 0 END) AS public_bytes | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 591 | FROM repos WHERE fork_of IS NULL AND deleted_at IS NULL AND stored_bytes > 0 GROUP BY namespace", |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 592 | ) |
| 593 | .all() | |
| 594 | .await? | |
| 595 | .results::<Row>()? | |
| 596 | .into_iter() | |
| 597 | .map(|row| g1t_contracts::repos::WorkspaceStorage { | |
| 598 | namespace: row.namespace, | |
| 599 | private_bytes: row.private_bytes.unwrap_or(0.0) as i64, | |
| 600 | public_bytes: row.public_bytes.unwrap_or(0.0) as i64, | |
| 601 | }) | |
| 602 | .collect()) | |
| 603 | } | |
| 604 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 605 | /// What one workspace's private repositories are counted as holding. |
| 606 | pub async fn private_bytes(&self, namespace: &str) -> Result<i64> { | |
| 607 | #[derive(Deserialize)] | |
| 608 | struct Row { | |
| 609 | bytes: Option<f64>, | |
| 610 | } | |
| 611 | Ok(self | |
| 612 | .db | |
| 613 | .prepare("SELECT SUM(stored_bytes) AS bytes FROM repos WHERE namespace = ? AND is_private = 1 AND fork_of IS NULL AND deleted_at IS NULL") | |
| 614 | .bind(&[namespace.into()])? | |
| 615 | .first::<Row>(None) | |
| 616 | .await? | |
| 617 | .and_then(|row| row.bytes) | |
| 618 | .unwrap_or(0.0) as i64) | |
| 619 | } | |
| 620 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 621 | /// Forgets a repository that could not be filled. |
| 622 | pub async fn remove(&self, id: &str) -> Result<()> { | |
| 623 | self.db | |
| 624 | .prepare("DELETE FROM repos WHERE id = ?") | |
| 625 | .bind(&[id.into()])? | |
| 626 | .run() | |
| 627 | .await?; | |
| 628 | Ok(()) | |
| 629 | } | |
| 630 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 631 | /// Picks the store key for a repository about to be made, and |
| 632 | /// remembers it: the one its path gives, unless a repository already | |
| 633 | /// holds that (one made in a workspace that has since been renamed, | |
| 634 | /// whose old name this workspace now has), when its id. | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 635 | /// |
| 636 | /// `namespace` is the git store namespace it goes in (shards.rs), or | |
| 637 | /// `None` for the default, `default`. A name is taken in any of them. | |
| 638 | pub async fn claim_store_key(&self, repo: &Repo, namespace: Option<&str>, default: &str) -> Result<String> { | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 639 | let wanted = path_key(repo); |
| 640 | let held = self | |
| 641 | .db | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 642 | .prepare( |
| 643 | "SELECT 1 AS held FROM repos | |
| Merge branch 'worktree-agent-a2013627e5ea4ab13' | 644 | WHERE store = ?1 OR (instr(store, '/') > 0 AND substr(store, instr(store, '/') + 1) = ?1) |
| 645 | UNION ALL | |
| 646 | SELECT 1 AS held FROM repo_move_copies WHERE name = ?1 AND cleaned_ms IS NULL", | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 647 | ) |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 648 | .bind(&[wanted.as_str().into()])? |
| 649 | .first::<serde_json::Value>(None) | |
| 650 | .await? | |
| 651 | .is_some(); | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 652 | let name = if held { repo.id.clone() } else { wanted }; |
| 653 | let key = crate::shards::compose(namespace, &name, default); | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 654 | remember_store(repo, &key); |
| 655 | Ok(key) | |
| 656 | } | |
| 657 | ||
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 658 | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 659 | /// Moves a renamed workspace's repositories to its current slug, from |
| 660 | /// any of `stale`. A repository whose name the current slug already has | |
| 661 | /// (one pushed there in the moment before this ran) stays where it is; | |
| 662 | /// returns how many did. | |
| 663 | pub async fn rename_namespace(&self, stale: &[String], current: &str) -> Result<usize> { | |
| 664 | if stale.is_empty() { | |
| 665 | return Ok(0); | |
| 666 | } | |
| 667 | let marks = vec!["?"; stale.len()].join(", "); | |
| 668 | let mut moved: Vec<JsValue> = vec![current.into()]; | |
| 669 | moved.extend(stale.iter().map(|slug| JsValue::from(slug.as_str()))); | |
| 670 | let left: Vec<JsValue> = stale.iter().map(|slug| JsValue::from(slug.as_str())).collect(); | |
| 671 | let results = self | |
| 672 | .db | |
| 673 | .batch(vec![ | |
| 674 | self.db | |
| 675 | .prepare(format!( | |
| 676 | "UPDATE OR IGNORE repos SET namespace = ? WHERE namespace IN ({marks})" | |
| 677 | )) | |
| 678 | .bind(&moved)?, | |
| 679 | self.db | |
| 680 | .prepare(format!( | |
| 681 | "SELECT count(*) AS left FROM repos WHERE namespace IN ({marks})" | |
| 682 | )) | |
| 683 | .bind(&left)?, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 684 | // Git operations follow the workspace, added together. |
| 685 | self.db | |
| 686 | .prepare(format!( | |
| 687 | "INSERT INTO git_operations (namespace, hour, operations) | |
| 688 | SELECT ?, hour, SUM(operations) FROM git_operations WHERE namespace IN ({marks}) GROUP BY hour | |
| 689 | ON CONFLICT (namespace, hour) DO UPDATE SET operations = git_operations.operations + excluded.operations" | |
| 690 | )) | |
| 691 | .bind(&moved)?, | |
| 692 | self.db | |
| 693 | .prepare(format!("DELETE FROM git_operations WHERE namespace IN ({marks})")) | |
| 694 | .bind(&left)?, | |
| 695 | // Paths repositories were transferred away from follow the | |
| 696 | // workspace too, so the old slug's redirect then finds them. | |
| 697 | self.db | |
| 698 | .prepare(format!( | |
| 699 | "UPDATE OR IGNORE repo_redirects SET namespace = ? WHERE namespace IN ({marks})" | |
| 700 | )) | |
| 701 | .bind(&moved)?, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 702 | ]) |
| 703 | .await?; | |
| 704 | #[derive(Deserialize)] | |
| 705 | struct Left { | |
| 706 | left: usize, | |
| 707 | } | |
| 708 | Ok(results | |
| 709 | .get(1) | |
| 710 | .map(|result| result.results::<Left>()) | |
| 711 | .transpose()? | |
| 712 | .and_then(|rows| rows.into_iter().next()) | |
| 713 | .map_or(0, |row| row.left)) | |
| 714 | } | |
| 715 | ||
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 716 | /// Records that the refs of the repository with this id changed, after |
| 717 | /// they did: what anything that lists them keeps goes stale. | |
| 718 | pub async fn refs_moved(&self, id: &str) -> Result<()> { | |
| 719 | self.bump_refs( | |
| 720 | "UPDATE repos SET refs_version = refs_version + 1 WHERE id = ? | |
| 721 | RETURNING refs_version, refs_open_until", | |
| 722 | &[id.into()], | |
| 723 | id, | |
| 724 | ) | |
| 725 | .await | |
| 726 | } | |
| 727 | ||
| 728 | /// Records that a credential able to change the refs of the repository | |
| 729 | /// with this id was handed out of g1t's hands, until `until` | |
| 730 | /// (milliseconds): until then, nothing that lists them is kept. | |
| 731 | pub async fn refs_open(&self, id: &str, until: u64) -> Result<()> { | |
| 732 | self.bump_refs( | |
| 733 | "UPDATE repos SET refs_version = refs_version + 1, | |
| 734 | refs_open_until = max(coalesce(refs_open_until, 0), ?) | |
| 735 | WHERE id = ? RETURNING refs_version, refs_open_until", | |
| 736 | &[(until as f64).into(), id.into()], | |
| 737 | id, | |
| 738 | ) | |
| 739 | .await | |
| 740 | } | |
| 741 | ||
| 742 | async fn bump_refs(&self, sql: &str, params: &[JsValue], id: &str) -> Result<()> { | |
| 743 | #[derive(Deserialize)] | |
| 744 | struct Bumped { | |
| 745 | refs_version: Option<f64>, | |
| 746 | refs_open_until: Option<f64>, | |
| 747 | } | |
| 748 | let bumped = self | |
| 749 | .db | |
| 750 | .prepare(sql) | |
| 751 | .bind(params)? | |
| 752 | .first::<Bumped>(None) | |
| 753 | .await?; | |
| 754 | if let Some(bumped) = bumped { | |
| 755 | note_refs(id, bumped.refs_version, bumped.refs_open_until); | |
| 756 | } | |
| 757 | Ok(()) | |
| 758 | } | |
| 759 | ||
| Rust repos service with shipping; pull requests kept in the model | 760 | pub async fn insert(&self, repo: &Repo) -> Result<()> { |
| 761 | self.db | |
| 762 | .prepare( | |
| 763 | "INSERT INTO repos | |
| 764 | (id, namespace, name, description, is_private, owner_id, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 765 | default_branch, fork_of, created_at, store) |
| 766 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", | |
| Rust repos service with shipping; pull requests kept in the model | 767 | ) |
| 768 | .bind(&[ | |
| 769 | repo.id.as_str().into(), | |
| 770 | repo.namespace.as_str().into(), | |
| 771 | repo.name.as_str().into(), | |
| 772 | optional(&repo.description), | |
| 773 | (repo.is_private as u8).into(), | |
| 774 | repo.owner_id.as_str().into(), | |
| 775 | repo.default_branch.as_str().into(), | |
| 776 | optional(&repo.fork_of), | |
| RFC 3339 timestamps in identity and repos | 777 | repo.created_at.as_str().into(), |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 778 | store_key(repo).into(), |
| Rust repos service with shipping; pull requests kept in the model | 779 | ])? |
| 780 | .run() | |
| 781 | .await?; | |
| 782 | Ok(()) | |
| 783 | } | |
| 784 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 785 | |
| 786 | #[cfg(test)] | |
| 787 | mod tests { | |
| 788 | use super::*; | |
| 789 | use g1t_contracts::access::{BasePermission, RepoGrant}; | |
| 790 | use g1t_contracts::{Membership, Role, User}; | |
| 791 | ||
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 792 | #[test] |
| 793 | fn the_refs_state_kept_only_moves_forward() { | |
| 794 | let mut states = RefsStates::default(); | |
| 795 | assert_eq!(states.get("rep_1"), None); | |
| 796 | states.note("rep_1", RefsState { version: 3, open_until: 0 }); | |
| 797 | // A read that started before a bump and finished after it. | |
| 798 | states.note("rep_1", RefsState { version: 2, open_until: 0 }); | |
| 799 | assert_eq!(states.get("rep_1").unwrap().version, 3); | |
| 800 | states.note("rep_1", RefsState { version: 4, open_until: 9_000 }); | |
| 801 | states.note("rep_1", RefsState { version: 5, open_until: 0 }); | |
| 802 | assert_eq!(states.get("rep_1"), Some(RefsState { version: 5, open_until: 9_000 })); | |
| 803 | assert_eq!(states.get("rep_2"), None); | |
| 804 | } | |
| 805 | ||
| 806 | #[test] | |
| 807 | fn a_row_from_before_the_column_has_no_refs_state() { | |
| 808 | let row = |version: Option<f64>| RepoRow { | |
| 809 | id: format!("rep_row_{}", version.is_some()), | |
| 810 | namespace: "acme".into(), | |
| 811 | name: "rocket".into(), | |
| 812 | description: None, | |
| 813 | is_private: 0, | |
| 814 | owner_id: "usr_owner".into(), | |
| 815 | default_branch: "main".into(), | |
| 816 | fork_of: None, | |
| 817 | protected: 0, | |
| 818 | created_at: String::new(), | |
| 819 | store: None, | |
| 820 | topics: None, | |
| 821 | website: None, | |
| 822 | archived_at: None, | |
| 823 | deleted_at: None, | |
| 824 | refs_version: version, | |
| 825 | refs_open_until: None, | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 826 | retired_at: None, |
| 827 | retired_head: None, | |
| Merge branch 'worktree-agent-a2013627e5ea4ab13' | 828 | writes_paused_until: None, |
| 829 | writes_paused_for: None, | |
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 830 | }; |
| 831 | let old = Repo::from(row(None)); | |
| 832 | assert_eq!(refs_state(&old.id), None); | |
| 833 | let new = Repo::from(row(Some(7.0))); | |
| 834 | assert_eq!(refs_state(&new.id), Some(RefsState { version: 7, open_until: 0 })); | |
| 835 | } | |
| 836 | ||
| 837 | #[test] | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 838 | fn a_removed_working_copy_is_known_by_its_row() { |
| 839 | note_retired("rep_fork", Some("abc")); | |
| 840 | assert_eq!(retired("rep_fork").as_deref(), Some("abc")); | |
| 841 | note_retired("rep_fork", None); | |
| 842 | assert_eq!(retired("rep_fork"), None); | |
| 843 | } | |
| 844 | ||
| 845 | #[test] | |
| Mission control shows where you are needed and what agents landed without you; git answers in about 200ms | 846 | fn a_repository_read_a_moment_ago_is_reused_for_a_few_seconds() { |
| 847 | let mut recent = Recent::default(); | |
| 848 | let path = RepoPath { | |
| 849 | namespace: "Acme".into(), | |
| 850 | name: "Rocket".into(), | |
| 851 | }; | |
| 852 | recent.keep(&path, &repo(false), 1_000); | |
| 853 | // Paths are matched as the table matches them, ignoring case. | |
| 854 | let lower = RepoPath { | |
| 855 | namespace: "acme".into(), | |
| 856 | name: "rocket".into(), | |
| 857 | }; | |
| 858 | assert_eq!(recent.get(&lower, 1_000 + RECENT_MS - 1).unwrap().id, "rep_1"); | |
| 859 | assert!(recent.get(&lower, 1_000 + RECENT_MS).is_none()); | |
| 860 | let other = RepoPath { | |
| 861 | namespace: "acme".into(), | |
| 862 | name: "booster".into(), | |
| 863 | }; | |
| 864 | assert!(recent.get(&other, 1_000).is_none()); | |
| 865 | // Keeping another later drops the stale row. | |
| 866 | recent.keep(&other, &repo(true), 1_000 + RECENT_MS); | |
| 867 | assert_eq!(recent.rows.len(), 1); | |
| 868 | } | |
| 869 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 870 | fn repo(private: bool) -> Repo { |
| 871 | Repo { | |
| 872 | id: "rep_1".into(), | |
| 873 | namespace: "acme".into(), | |
| 874 | name: "rocket".into(), | |
| 875 | description: None, | |
| 876 | is_private: private, | |
| 877 | owner_id: "usr_owner".into(), | |
| 878 | default_branch: "main".into(), | |
| 879 | fork_of: None, | |
| 880 | protected: false, | |
| 881 | created_at: String::new(), | |
| 882 | topics: Vec::new(), | |
| 883 | website: None, | |
| 884 | archived_at: None, | |
| 885 | } | |
| 886 | } | |
| 887 | ||
| 888 | fn person(id: &str, memberships: Vec<Membership>, grants: Vec<(&str, RepoRole)>) -> Viewer { | |
| 889 | Some(User { | |
| 890 | id: id.into(), | |
| 891 | username: id.into(), | |
| 892 | verified: true, | |
| 893 | workspaces: memberships, | |
| 894 | grants: grants | |
| 895 | .into_iter() | |
| 896 | .map(|(repo_id, role)| RepoGrant { repo_id: repo_id.into(), workspace: "acme".into(), role }) | |
| 897 | .collect(), | |
| 898 | ..User::default() | |
| 899 | }) | |
| 900 | } | |
| 901 | ||
| 902 | /// What git asks: clone and fetch need Read on a private repository, | |
| 903 | /// push needs Write. | |
| 904 | #[test] | |
| 905 | fn git_reads_with_read_and_pushes_with_write() { | |
| 906 | let private = repo(true); | |
| 907 | let reader = person("usr_r", vec![], vec![("rep_1", RepoRole::Read)]); | |
| 908 | assert!(can_read(&private, &reader)); | |
| 909 | assert!(!can_write(&private, &reader)); | |
| 910 | let writer = person("usr_w", vec![], vec![("rep_1", RepoRole::Write)]); | |
| 911 | assert!(can_read(&private, &writer) && can_write(&private, &writer)); | |
| 912 | let stranger = person("usr_s", vec![], vec![("rep_2", RepoRole::Admin)]); | |
| 913 | assert!(!can_read(&private, &stranger) && !can_write(&private, &stranger)); | |
| 914 | assert!(!can_read(&private, &None)); | |
| 915 | // A public repository: anyone clones, nobody without Write pushes. | |
| 916 | let public = repo(false); | |
| 917 | assert!(can_read(&public, &None) && !can_write(&public, &None)); | |
| 918 | assert!(can_read(&public, &stranger) && !can_write(&public, &stranger)); | |
| 919 | } | |
| 920 | ||
| 921 | #[test] | |
| 922 | fn members_follow_the_base_permission_and_owners_have_admin() { | |
| 923 | let private = repo(true); | |
| 924 | let default_member = person("usr_m", vec![Membership::member("acme")], vec![]); | |
| 925 | assert!(can_write(&private, &default_member)); | |
| 926 | assert!(!can(&private, &default_member, Capability::ManageIntegrations)); | |
| 927 | let none = Membership { base_permission: Some(BasePermission::None), ..Membership::member("acme") }; | |
| 928 | let locked_out = person("usr_n", vec![none.clone()], vec![]); | |
| 929 | assert!(!can_read(&private, &locked_out)); | |
| 930 | let given = person("usr_g", vec![none], vec![("rep_1", RepoRole::Triage)]); | |
| 931 | assert!(can_read(&private, &given) && !can_write(&private, &given)); | |
| 932 | let owner = person("usr_o", vec![Membership { role: Role::Owner, ..Membership::member("acme") }], vec![]); | |
| 933 | assert_eq!(role(&private, &owner), Some(RepoRole::Admin)); | |
| 934 | assert!(can(&private, &owner, Capability::Delete)); | |
| 935 | } | |
| 936 | ||
| 937 | #[test] | |
| 938 | fn a_pull_requests_fork_is_its_authors() { | |
| 939 | let fork = Repo { | |
| 940 | namespace: "pulls".into(), | |
| 941 | fork_of: Some("rep_1".into()), | |
| 942 | owner_id: "usr_a".into(), | |
| 943 | ..repo(true) | |
| 944 | }; | |
| 945 | let author = person("usr_a", vec![], vec![]); | |
| 946 | assert!(can_write(&fork, &author)); | |
| 947 | assert!(!can(&fork, &author, Capability::ManageSettings)); | |
| 948 | let other = person("usr_b", vec![Membership::member("acme")], vec![]); | |
| 949 | assert!(!can_write(&fork, &other)); | |
| 950 | } | |
| 951 | } |
This file's history is long; its oldest lines are credited to the oldest commit read.