Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 5 |
| 6 | use anyhow::{Result, anyhow}; |
| 7 | use rusqlite::{OptionalExtension, params}; |
| 8 | use sha2::{Digest, Sha256}; |
| 9 | use vcs_cli::db::Db; |
| 10 | use vcs_cli::host::{LandRequest, Landed}; |
| 11 | use vcs_cli::objects::Store; |
| 12 | use vcs_cli::wire::{Can, ChangeRecord, Me, MineFile, Rule, SaveRecord, Share}; |
| 13 | use vcs_core::version::Version; |
| 14 | use vcs_core::{Id, tree}; |
| 15 |
| 16 | const SCHEMA: &str = r#" |
| 17 | CREATE TABLE IF NOT EXISTS s_users (handle TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL, created INTEGER NOT NULL); |
| 18 | CREATE TABLE IF NOT EXISTS s_tokens (hash TEXT PRIMARY KEY, handle TEXT NOT NULL, created INTEGER NOT NULL); |
| 19 | CREATE TABLE IF NOT EXISTS s_projects (key TEXT PRIMARY KEY, public INTEGER NOT NULL DEFAULT 0, created INTEGER NOT NULL); |
| 20 | CREATE TABLE IF NOT EXISTS s_members (project TEXT NOT NULL, handle TEXT NOT NULL, role TEXT NOT NULL, PRIMARY KEY (project, handle)); |
| 21 | CREATE TABLE IF NOT EXISTS s_changes ( |
| 22 | project TEXT NOT NULL, id TEXT NOT NULL, owner TEXT NOT NULL, record TEXT NOT NULL, |
| 23 | holder TEXT, holder_label TEXT, state TEXT NOT NULL, updated INTEGER NOT NULL, |
| 24 | PRIMARY KEY (project, id) |
| 25 | ); |
| 26 | CREATE TABLE IF NOT EXISTS s_saves (project TEXT NOT NULL, change TEXT NOT NULL, n INTEGER NOT NULL, tree TEXT NOT NULL, base_tree TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (project, change, n)); |
| 27 | CREATE TABLE IF NOT EXISTS s_roots (project TEXT NOT NULL, tree TEXT NOT NULL, change TEXT NOT NULL, PRIMARY KEY (project, tree, change)); |
| 28 | CREATE TABLE IF NOT EXISTS s_rules (project TEXT NOT NULL, path TEXT NOT NULL, who TEXT NOT NULL, PRIMARY KEY (project, path)); |
| 29 | CREATE TABLE IF NOT EXISTS s_visible (project TEXT NOT NULL, key TEXT NOT NULL, visible TEXT NOT NULL, full TEXT NOT NULL, PRIMARY KEY (project, key, visible)); |
| 30 | CREATE INDEX IF NOT EXISTS s_visible_full ON s_visible(project, key, full); |
| 31 | CREATE TABLE IF NOT EXISTS s_namespaces (name TEXT PRIMARY KEY, handle TEXT NOT NULL); |
| 32 | CREATE TABLE IF NOT EXISTS s_mine (project TEXT NOT NULL, handle TEXT NOT NULL, files TEXT NOT NULL, PRIMARY KEY (project, handle)); |
| 33 | CREATE TABLE IF NOT EXISTS s_groups (project TEXT NOT NULL, name TEXT NOT NULL, members TEXT NOT NULL, PRIMARY KEY (project, name)); |
| 34 | CREATE TABLE IF NOT EXISTS s_settings (project TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (project, key)); |
| 35 | CREATE TABLE IF NOT EXISTS s_approvals (project TEXT NOT NULL, change TEXT NOT NULL, handle TEXT NOT NULL, tree TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (project, change, handle)); |
| 36 | "#; |
| 37 |
| 38 | pub struct State { |
| 39 | pub db: Db, |
| 40 | pub store: Store, |
| 41 | } |
| 42 |
| 43 | #[derive(Debug)] |
| 44 | pub struct Problem { |
| 45 | pub status: u16, |
| 46 | pub code: &'static str, |
| 47 | pub message: String, |
| 48 | pub holder: Option<String>, |
| 49 | } |
| 50 |
| 51 | pub fn problem(status: u16, code: &'static str, message: impl Into<String>) -> Problem { |
| 52 | Problem { status, code, message: message.into(), holder: None } |
| 53 | } |
| 54 |
| 55 | impl From<anyhow::Error> for Problem { |
| 56 | fn from(e: anyhow::Error) -> Problem { |
| 57 | problem(500, "failed", format!("{e:#}")) |
| 58 | } |
| 59 | } |
| 60 |
| 61 | impl From<rusqlite::Error> for Problem { |
| 62 | fn from(e: rusqlite::Error) -> Problem { |
| 63 | problem(500, "failed", e.to_string()) |
| 64 | } |
| 65 | } |
| 66 |
| 67 | impl From<vcs_core::Error> for Problem { |
| 68 | fn from(e: vcs_core::Error) -> Problem { |
| 69 | problem(500, "failed", e.to_string()) |
| 70 | } |
| 71 | } |
| 72 |
| 73 | pub type Res<T> = Result<T, Problem>; |
| 74 |
| 75 | pub fn token_hash(token: &str) -> String { |
| 76 | let digest = Sha256::digest(token.as_bytes()); |
| 77 | digest.iter().map(|b| format!("{b:02x}")).collect() |
| 78 | } |
| 79 |
| 80 | fn now() -> i64 { |
| 81 | std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0) |
| 82 | } |
| 83 |
| 84 | pub struct Access { |
| 85 | pub user: Option<Me>, |
| 86 | pub can: Can, |
| 87 | } |
| 88 |
| 89 | impl State { |
| 90 | pub fn open(data: &Path) -> Result<State> { |
| 91 | std::fs::create_dir_all(data)?; |
| 92 | let conn = rusqlite::Connection::open(data.join("server.db"))?; |
| 93 | let db = Db::setup(conn)?; |
| 94 | db.conn.execute_batch(SCHEMA)?; |
| 95 | Ok(State { db, store: Store::open(&data.join("objects"))? }) |
| 96 | } |
| 97 |
| 98 | // Accounts. |
| 99 |
| 100 | pub fn add_user(&self, handle: &str, name: &str, email: &str) -> Result<String> { |
| 101 | self.db.conn.execute( |
| 102 | "INSERT OR REPLACE INTO s_users (handle, name, email, created) VALUES (?1, ?2, ?3, ?4)", |
| 103 | params![handle, name, email, now()], |
| 104 | )?; |
| 105 | let token = format!("vcs_{}", (0..40).map(|_| b"abcdefghijklmnopqrstuvwxyz0123456789"[rand::random_range(0..36)] as char).collect::<String>()); |
| 106 | self.db.conn.execute("INSERT INTO s_tokens (hash, handle, created) VALUES (?1, ?2, ?3)", params![token_hash(&token), handle, now()])?; |
| 107 | Ok(token) |
| 108 | } |
| 109 |
| 110 | pub fn add_project(&self, key: &str, owner: &str, public: bool) -> Result<()> { |
| 111 | if key.split('/').count() != 2 || key.split('/').any(|p| p.is_empty()) { |
| 112 | return Err(anyhow!("projects are OWNER/NAME")); |
| 113 | } |
| 114 | self.db.conn.execute("INSERT OR REPLACE INTO s_projects (key, public, created) VALUES (?1, ?2, ?3)", params![key, public as i64, now()])?; |
| 115 | self.add_member(key, owner, "owner") |
| 116 | } |
| 117 |
| 118 | /// A namespace is yours if it's your handle, or you claimed it first. |
| 119 | pub fn may_create_under(&self, owner: &str, handle: &str) -> Res<bool> { |
| 120 | if owner == handle { |
| 121 | return Ok(true); |
| 122 | } |
| 123 | let claimed: Option<String> = self.db.conn.query_row("SELECT handle FROM s_namespaces WHERE name = ?1", [owner], |r| r.get(0)).optional()?; |
| 124 | match claimed { |
| 125 | Some(h) => Ok(h == handle), |
| 126 | None => { |
| 127 | let taken = self.db.conn.query_row("SELECT 1 FROM s_users WHERE handle = ?1", [owner], |_| Ok(())).optional()?.is_some(); |
| 128 | if taken { |
| 129 | return Ok(false); |
| 130 | } |
| 131 | self.db.conn.execute("INSERT INTO s_namespaces (name, handle) VALUES (?1, ?2)", params![owner, handle])?; |
| 132 | Ok(true) |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 |
| 137 | pub fn add_member(&self, key: &str, handle: &str, role: &str) -> Result<()> { |
| 138 | self.db.conn.execute("INSERT OR REPLACE INTO s_members (project, handle, role) VALUES (?1, ?2, ?3)", params![key, handle, role])?; |
| 139 | Ok(()) |
| 140 | } |
| 141 |
| 142 | pub fn user_for_token(&self, token: &str) -> Res<Option<Me>> { |
| 143 | let handle: Option<String> = |
| 144 | self.db.conn.query_row("SELECT handle FROM s_tokens WHERE hash = ?1", [token_hash(token)], |r| r.get(0)).optional()?; |
| 145 | let Some(handle) = handle else { return Ok(None) }; |
| 146 | Ok(self |
| 147 | .db |
| 148 | .conn |
| 149 | .query_row("SELECT handle, name, email FROM s_users WHERE handle = ?1", [&handle], |r| { |
| 150 | Ok(Me { handle: r.get(0)?, name: r.get(1)?, email: r.get(2)? }) |
| 151 | }) |
| 152 | .optional()?) |
| 153 | } |
| 154 |
| 155 | pub fn project_exists(&self, key: &str) -> Res<Option<bool>> { |
| 156 | Ok(self.db.conn.query_row("SELECT public FROM s_projects WHERE key = ?1", [key], |r| r.get::<_, i64>(0)).optional()?.map(|p| p != 0)) |
| 157 | } |
| 158 |
| 159 | pub fn access(&self, key: &str, user: Option<Me>) -> Res<Access> { |
| 160 | let public = self.project_exists(key)?.ok_or_else(|| problem(404, "not_found", format!("no project {key}")))?; |
| 161 | let role: Option<String> = match &user { |
| 162 | Some(u) => self |
| 163 | .db |
| 164 | .conn |
| 165 | .query_row("SELECT role FROM s_members WHERE project = ?1 AND handle = ?2", params![key, u.handle], |r| r.get(0)) |
| 166 | .optional()?, |
| 167 | None => None, |
| 168 | }; |
| 169 | let can = Can { |
| 170 | read: public || role.is_some(), |
| 171 | land: matches!(role.as_deref(), Some("owner") | Some("member")), |
| 172 | admin: role.as_deref() == Some("owner"), |
| 173 | }; |
| 174 | if !can.read { |
| 175 | // Private projects look like missing ones to outsiders. |
| 176 | return Err(problem(404, "not_found", format!("no project {key}"))); |
| 177 | } |
| 178 | Ok(Access { user, can }) |
| 179 | } |
| 180 |
| 181 | pub fn public(&self, key: &str) -> Res<bool> { |
| 182 | Ok(self.project_exists(key)?.unwrap_or(false)) |
| 183 | } |
| 184 |
| 185 | pub fn landers(&self, key: &str) -> Res<Vec<String>> { |
| 186 | let mut stmt = self.db.conn.prepare("SELECT handle FROM s_members WHERE project = ?1 AND role IN ('owner', 'member') ORDER BY handle")?; |
| 187 | let rows = stmt.query_map([key], |r| r.get::<_, String>(0))?; |
| 188 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 189 | } |
| 190 |
| 191 | // Private paths. |
| 192 |
| 193 | /// Paths `handle` can't see in the project (none for owners). |
| 194 | pub fn hidden_for(&self, key: &str, handle: Option<&str>) -> Res<Vec<String>> { |
| 195 | let rules = self.rules(key)?; |
| 196 | if rules.is_empty() { |
| 197 | return Ok(Vec::new()); |
| 198 | } |
| 199 | let role: Option<String> = match handle { |
| 200 | Some(h) => self.db.conn.query_row("SELECT role FROM s_members WHERE project = ?1 AND handle = ?2", params![key, h], |r| r.get(0)).optional()?, |
| 201 | None => None, |
| 202 | }; |
| 203 | if role.as_deref() == Some("owner") { |
| 204 | return Ok(Vec::new()); |
| 205 | } |
| 206 | let mut hidden = Vec::new(); |
| 207 | for rule in rules { |
| 208 | let allowed = rule.who.iter().any(|w| self.matches(key, w, handle, role.is_some())); |
| 209 | if !allowed { |
| 210 | hidden.push(rule.path); |
| 211 | } |
| 212 | } |
| 213 | Ok(hidden) |
| 214 | } |
| 215 |
| 216 | pub fn audience(hidden: &[String]) -> String { |
| 217 | if hidden.is_empty() { |
| 218 | return String::new(); |
| 219 | } |
| 220 | let mut sorted = hidden.to_vec(); |
| 221 | sorted.sort(); |
| 222 | token_hash(&sorted.join("\n")) |
| 223 | } |
| 224 |
| 225 | /// The tree someone with these hidden paths sees for `full`. |
| 226 | pub fn to_visible(&self, key: &str, full: &Id, hidden: &[String]) -> Res<Id> { |
| 227 | if hidden.is_empty() { |
| 228 | return Ok(*full); |
| 229 | } |
| 230 | let audience = Self::audience(hidden); |
| 231 | let known: Option<String> = self |
| 232 | .db |
| 233 | .conn |
| 234 | .query_row("SELECT visible FROM s_visible WHERE project = ?1 AND key = ?2 AND full = ?3", params![key, audience, full.hex()], |r| r.get(0)) |
| 235 | .optional()?; |
| 236 | if let Some(v) = known.and_then(|t| Id::parse(&t)) { |
| 237 | return Ok(v); |
| 238 | } |
| 239 | let (visible, objects) = vcs_core::filter::filter(&self.store, full, hidden)?; |
| 240 | for o in &objects { |
| 241 | self.store.put(o)?; |
| 242 | } |
| 243 | self.remember(key, &audience, &visible, full)?; |
| 244 | Ok(visible) |
| 245 | } |
| 246 |
| 247 | fn remember(&self, key: &str, audience: &str, visible: &Id, full: &Id) -> Res<()> { |
| 248 | self.db.conn.execute( |
| 249 | "INSERT OR REPLACE INTO s_visible (project, key, visible, full) VALUES (?1, ?2, ?3, ?4)", |
| 250 | params![key, audience, visible.hex(), full.hex()], |
| 251 | )?; |
| 252 | Ok(()) |
| 253 | } |
| 254 |
| 255 | fn to_full(&self, key: &str, audience: &str, visible: &Id) -> Res<Option<Id>> { |
| 256 | let full: Option<String> = self |
| 257 | .db |
| 258 | .conn |
| 259 | .query_row("SELECT full FROM s_visible WHERE project = ?1 AND key = ?2 AND visible = ?3", params![key, audience, visible.hex()], |r| r.get(0)) |
| 260 | .optional()?; |
| 261 | Ok(full.and_then(|t| Id::parse(&t))) |
| 262 | } |
| 263 |
| 264 | fn is_version_tree(&self, key: &str, tree: &Id) -> Res<bool> { |
| 265 | Ok(self |
| 266 | .db |
| 267 | .conn |
| 268 | .query_row("SELECT 1 FROM s_roots WHERE project = ?1 AND tree = ?2 AND change = ''", params![key, tree.hex()], |_| Ok(())) |
| 269 | .optional()? |
| 270 | .is_some()) |
| 271 | } |
| 272 |
| 273 | // Main. |
| 274 |
| 275 | pub fn main(&self, key: &str) -> Res<Option<Version>> { |
| 276 | Ok(self.db.latest_version(key)?) |
| 277 | } |
| 278 |
| 279 | /// Main as `access` sees it: private paths left out, and versions that |
| 280 | /// only touched them shown as "a private change". |
| 281 | pub fn main_for(&self, key: &str, access: &Access) -> Res<Option<Version>> { |
| 282 | let Some(v) = self.main(key)? else { return Ok(None) }; |
| 283 | Ok(self.versions_for(key, access, vec![v])?.pop()) |
| 284 | } |
| 285 |
| 286 | pub fn versions_for(&self, key: &str, access: &Access, versions: Vec<Version>) -> Res<Vec<Version>> { |
| 287 | let hidden = self.hidden_for(key, access.user.as_ref().map(|u| u.handle.as_str()))?; |
| 288 | if hidden.is_empty() { |
| 289 | return Ok(versions); |
| 290 | } |
| 291 | let mut out = Vec::with_capacity(versions.len()); |
| 292 | for mut v in versions { |
| 293 | let full = v.tree; |
| 294 | v.tree = self.to_visible(key, &full, &hidden)?; |
| 295 | if v.n > 1 |
| 296 | && let Some(prev) = self.db.version(key, v.n - 1)? |
| 297 | && self.to_visible(key, &prev.tree, &hidden)? == v.tree |
| 298 | && prev.tree != full |
| 299 | { |
| 300 | v.title = "a private change".into(); |
| 301 | v.body = String::new(); |
| 302 | v.change = String::new(); |
| 303 | } |
| 304 | out.push(v); |
| 305 | } |
| 306 | Ok(out) |
| 307 | } |
| 308 |
| 309 | pub fn versions_since(&self, key: &str, since: u64, limit: i64) -> Res<Vec<Version>> { |
| 310 | let mut stmt = self.db.conn.prepare( |
| 311 | "SELECT n, tree, prev, change, author, time, title, body, git FROM versions WHERE project = ?1 AND n > ?2 ORDER BY n LIMIT ?3", |
| 312 | )?; |
| 313 | let rows = stmt.query_map(params![key, since as i64, limit], |row| { |
| 314 | let id = |i: usize| -> rusqlite::Result<Option<Id>> { Ok(row.get::<_, Option<String>>(i)?.and_then(|t| Id::parse(&t))) }; |
| 315 | Ok(Version { |
| 316 | n: row.get::<_, i64>(0)? as u64, |
| 317 | tree: id(1)?.unwrap_or(Id::ZERO), |
| 318 | prev: id(2)?, |
| 319 | change: row.get(3)?, |
| 320 | author: row.get(4)?, |
| 321 | time: row.get(5)?, |
| 322 | title: row.get(6)?, |
| 323 | body: row.get(7)?, |
| 324 | git: row.get(8)?, |
| 325 | }) |
| 326 | })?; |
| 327 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 328 | } |
| 329 |
| 330 | // Objects. |
| 331 |
| 332 | pub fn missing(&self, ids: &[Id]) -> Vec<Id> { |
| 333 | ids.iter().filter(|i| !self.store.has(i)).copied().collect() |
| 334 | } |
| 335 |
| 336 | fn add_root(&self, key: &str, tree: &Id, change: &str) -> Res<()> { |
| 337 | self.db.conn.execute("INSERT OR IGNORE INTO s_roots (project, tree, change) VALUES (?1, ?2, ?3)", params![key, tree.hex(), change])?; |
| 338 | Ok(()) |
| 339 | } |
| 340 |
| 341 | /// Whether `user` may read the objects under `tree`: it's a version's |
| 342 | /// tree, or a save of a change they can see. |
| 343 | pub fn may_read_tree(&self, key: &str, access: &Access, tree: &Id) -> Res<bool> { |
| 344 | let hidden = self.hidden_for(key, access.user.as_ref().map(|u| u.handle.as_str()))?; |
| 345 | if !hidden.is_empty() { |
| 346 | // Only trees made for this audience, or this person's own work. |
| 347 | let audience = Self::audience(&hidden); |
| 348 | if self.to_full(key, &audience, tree)?.is_some() { |
| 349 | return Ok(true); |
| 350 | } |
| 351 | let handle = access.user.as_ref().map(|u| u.handle.clone()).unwrap_or_default(); |
| 352 | let mut stmt = self.db.conn.prepare("SELECT r.change FROM s_roots r JOIN s_changes c ON c.project = r.project AND c.id = r.change WHERE r.project = ?1 AND r.tree = ?2 AND c.owner = ?3")?; |
| 353 | let own = stmt.query_map(params![key, tree.hex(), handle], |r| r.get::<_, String>(0))?.next().is_some(); |
| 354 | return Ok(own || tree == &tree::empty_id()); |
| 355 | } |
| 356 | let mut stmt = self.db.conn.prepare("SELECT change FROM s_roots WHERE project = ?1 AND tree = ?2")?; |
| 357 | let changes: Vec<String> = stmt.query_map(params![key, tree.hex()], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 358 | if changes.iter().any(|c| c.is_empty()) { |
| 359 | return Ok(true); |
| 360 | } |
| 361 | for c in changes { |
| 362 | if let Some((record, _)) = self.change_row(key, &c)? |
| 363 | && self.visible(key, access, &record)? |
| 364 | { |
| 365 | return Ok(true); |
| 366 | } |
| 367 | } |
| 368 | Ok(tree == &tree::empty_id()) |
| 369 | } |
| 370 |
| 371 | /// Every object under `tree` that `have` doesn't share, as a bundle. |
| 372 | pub fn tree_bundle(&self, tree: &Id, have: Option<&Id>) -> Res<Vec<u8>> { |
| 373 | let mut ids = Vec::new(); |
| 374 | tree::new_since(&self.store, have, tree, &mut ids)?; |
| 375 | let mut all = Vec::with_capacity(ids.len()); |
| 376 | for id in ids { |
| 377 | all.extend(self.store.file_parts(&id)?); |
| 378 | } |
| 379 | Ok(self.store.bundle(&all)?) |
| 380 | } |
| 381 |
| 382 | // Changes. |
| 383 |
| 384 | fn change_row(&self, key: &str, id: &str) -> Res<Option<(ChangeRecord, Option<String>)>> { |
| 385 | let row: Option<(String, String, Option<String>, Option<String>)> = self |
| 386 | .db |
| 387 | .conn |
| 388 | .query_row("SELECT record, owner, holder, holder_label FROM s_changes WHERE project = ?1 AND id = ?2", params![key, id], |r| { |
| 389 | Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)) |
| 390 | }) |
| 391 | .optional()?; |
| 392 | Ok(row.map(|(record, owner, holder, label)| { |
| 393 | let mut c: ChangeRecord = serde_json::from_str(&record).unwrap_or_else(|_| empty_record(id)); |
| 394 | c.owner = owner; |
| 395 | c.holder = label; |
| 396 | (c, holder) |
| 397 | })) |
| 398 | } |
| 399 |
| 400 | pub fn visible(&self, key: &str, access: &Access, c: &ChangeRecord) -> Res<bool> { |
| 401 | let Some(user) = &access.user else { return Ok(false) }; |
| 402 | if c.owner == user.handle || access.can.admin { |
| 403 | return Ok(true); |
| 404 | } |
| 405 | if c.state == "waiting" && access.can.land { |
| 406 | return Ok(true); |
| 407 | } |
| 408 | let member = access.can.land || self.is_member(key, &user.handle)?; |
| 409 | Ok(c.shared.iter().any(|s| self.matches(key, &s.who, Some(&user.handle), member))) |
| 410 | } |
| 411 |
| 412 | /// Whether `who` (from a rule or a share) takes in `handle`: themselves, |
| 413 | /// a group they're in, `team` or `everyone`. |
| 414 | fn matches(&self, key: &str, who: &str, handle: Option<&str>, member: bool) -> bool { |
| 415 | match who { |
| 416 | "everyone" => true, |
| 417 | "team" => member, |
| 418 | other => { |
| 419 | let Some(h) = handle else { return false }; |
| 420 | let name = other.trim_start_matches('@'); |
| 421 | name == h || self.group(key, name).is_some_and(|people| people.iter().any(|p| p == h)) |
| 422 | } |
| 423 | } |
| 424 | } |
| 425 |
| 426 | fn group(&self, key: &str, name: &str) -> Option<Vec<String>> { |
| 427 | let text: Option<String> = self.db.conn.query_row("SELECT members FROM s_groups WHERE project = ?1 AND name = ?2", params![key, name], |r| r.get(0)).optional().ok()?; |
| 428 | text.and_then(|t| serde_json::from_str(&t).ok()) |
| 429 | } |
| 430 |
| 431 | pub fn groups(&self, key: &str) -> Res<std::collections::BTreeMap<String, Vec<String>>> { |
| 432 | let mut stmt = self.db.conn.prepare("SELECT name, members FROM s_groups WHERE project = ?1 ORDER BY name")?; |
| 433 | let rows = stmt.query_map([key], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; |
| 434 | let mut out = std::collections::BTreeMap::new(); |
| 435 | for row in rows { |
| 436 | let (name, members) = row?; |
| 437 | out.insert(name, serde_json::from_str(&members).unwrap_or_default()); |
| 438 | } |
| 439 | Ok(out) |
| 440 | } |
| 441 |
| 442 | /// Sets a group's people (owners only); no people removes it. |
| 443 | pub fn set_group(&self, key: &str, access: &Access, name: &str, members: &[String]) -> Res<std::collections::BTreeMap<String, Vec<String>>> { |
| 444 | if !access.can.admin { |
| 445 | return Err(problem(403, "not_allowed", "only the project's owners can change groups")); |
| 446 | } |
| 447 | let mut people: Vec<String> = members.iter().map(|m| m.trim_start_matches('@').to_string()).collect(); |
| 448 | people.dedup(); |
| 449 | if people.is_empty() { |
| 450 | self.db.conn.execute("DELETE FROM s_groups WHERE project = ?1 AND name = ?2", params![key, name])?; |
| 451 | } else { |
| 452 | self.db.conn.execute("INSERT OR REPLACE INTO s_groups (project, name, members) VALUES (?1, ?2, ?3)", params![key, name, serde_json::to_string(&people).unwrap()])?; |
| 453 | } |
| 454 | self.groups(key) |
| 455 | } |
| 456 |
| 457 | /// Private paths, and folders holding them, look missing to people who |
| 458 | /// can't see them. |
| 459 | fn no_private(&self, key: &str, access: &Access, path: &str) -> Res<()> { |
| 460 | let hidden = self.hidden_for(key, access.user.as_ref().map(|u| u.handle.as_str()))?; |
| 461 | if hidden.iter().any(|h| tree::under(path, h) || tree::under(h, path)) { |
| 462 | return Err(problem(404, "not_found", format!("there's no {path} here"))); |
| 463 | } |
| 464 | Ok(()) |
| 465 | } |
| 466 |
| 467 | /// `vcs log <path>`: the versions that changed it, newest first. |
| 468 | pub fn history(&self, key: &str, access: &Access, path: &str, limit: usize) -> Res<serde_json::Value> { |
| 469 | let path = path.trim_matches('/'); |
| 470 | self.no_private(key, access, path)?; |
| 471 | let (changes, more) = vcs_cli::history::changes(&self.store, &self.db, key, path, limit)?; |
| 472 | let mut picked: Vec<Version> = Vec::with_capacity(changes.len()); |
| 473 | for (n, ..) in &changes { |
| 474 | picked.extend(self.db.version(key, *n)?); |
| 475 | } |
| 476 | let shown = self.versions_for(key, access, picked)?; |
| 477 | let kinds = changes.iter().map(|(_, k, _)| match k { |
| 478 | vcs_core::history::Kind::Added => "added", |
| 479 | vcs_core::history::Kind::Modified => "modified", |
| 480 | vcs_core::history::Kind::Removed => "removed", |
| 481 | }); |
| 482 | let list: Vec<serde_json::Value> = shown |
| 483 | .iter() |
| 484 | .zip(kinds) |
| 485 | .map(|(v, kind)| { |
| 486 | let mut x = serde_json::to_value(v).unwrap_or_default(); |
| 487 | x["kind"] = kind.into(); |
| 488 | x |
| 489 | }) |
| 490 | .collect(); |
| 491 | Ok(serde_json::json!({ "path": path, "versions": list, "more": more })) |
| 492 | } |
| 493 |
| 494 | /// A file at a version (the latest when None), as the caller sees it, |
| 495 | /// for reading without a workspace (up to 1 MB). |
| 496 | pub fn read_path(&self, key: &str, access: &Access, version: Option<u64>, path: &str) -> Res<serde_json::Value> { |
| 497 | use base64::Engine; |
| 498 | let path = path.trim_matches('/'); |
| 499 | let v = match version { |
| 500 | Some(n) => self.db.version(key, n)?, |
| 501 | None => self.db.latest_version(key)?, |
| 502 | } |
| 503 | .ok_or_else(|| problem(404, "not_found", "there's no such version"))?; |
| 504 | let n = v.n; |
| 505 | let shown = self.versions_for(key, access, vec![v])?.pop().ok_or_else(|| problem(404, "not_found", "there's no such version"))?; |
| 506 | let entry = match tree::lookup(&self.store, &shown.tree, path)? { |
| 507 | Some(e) if e.kind != tree::EntryKind::Tree => e, |
| 508 | _ => return Err(problem(404, "not_found", format!("there's no file {path} in version {n}"))), |
| 509 | }; |
| 510 | if entry.kind == tree::EntryKind::Gitlink { |
| 511 | return Ok(serde_json::json!({ "version": n, "path": path, "kind": entry.kind.name() })); |
| 512 | } |
| 513 | let content = vcs_core::chunk::read_file(&self.store, &entry.id)?; |
| 514 | if content.len() > 1 << 20 { |
| 515 | return Ok(serde_json::json!({ "version": n, "path": path, "kind": entry.kind.name(), "too_big": content.len() })); |
| 516 | } |
| 517 | Ok(serde_json::json!({ "version": n, "path": path, "kind": entry.kind.name(), "base64": base64::engine::general_purpose::STANDARD.encode(content) })) |
| 518 | } |
| 519 |
| 520 | /// `vcs blame <file>`: the version that last changed each line. |
| 521 | pub fn blame(&self, key: &str, access: &Access, path: &str) -> Res<serde_json::Value> { |
| 522 | use base64::Engine; |
| 523 | let path = path.trim_matches('/'); |
| 524 | self.no_private(key, access, path)?; |
| 525 | let Some((owners, content)) = vcs_cli::history::blame(&self.store, &self.db, key, path)? else { |
| 526 | return Err(problem(404, "not_found", format!("there's no file {path} in main"))); |
| 527 | }; |
| 528 | if content.len() > 1 << 20 { |
| 529 | return Err(problem(413, "too_big", format!("{path} is over 1 MB; blame reads files up to 1 MB"))); |
| 530 | } |
| 531 | let mut picked: Vec<Version> = Vec::new(); |
| 532 | for (n, _) in &owners { |
| 533 | if !picked.iter().any(|v| v.n == *n) { |
| 534 | picked.extend(self.db.version(key, *n)?); |
| 535 | } |
| 536 | } |
| 537 | let shown = self.versions_for(key, access, picked)?; |
| 538 | let info: serde_json::Map<String, serde_json::Value> = |
| 539 | shown.iter().map(|v| (v.n.to_string(), serde_json::json!({ "title": v.title, "author": v.author, "time": v.time }))).collect(); |
| 540 | Ok(serde_json::json!({ "path": path, "owners": owners, "versions": info, "base64": base64::engine::general_purpose::STANDARD.encode(content) })) |
| 541 | } |
| 542 |
| 543 | /// Checks a project: each version follows the one before it (its `prev` |
| 544 | /// is that version's ID), and everything main needs is stored. |
| 545 | pub fn check(&self, key: &str, access: &Access) -> Res<serde_json::Value> { |
| 546 | if !access.can.admin { |
| 547 | return Err(problem(403, "not_allowed", "only the project's owners can check it")); |
| 548 | } |
| 549 | let all = self.db.versions(key, i64::MAX)?; |
| 550 | let mut chain = None; |
| 551 | let mut prev: Option<Id> = None; |
| 552 | for (i, v) in all.iter().rev().enumerate() { |
| 553 | if v.n != i as u64 + 1 { |
| 554 | chain = Some(format!("version {} is missing", i + 1)); |
| 555 | break; |
| 556 | } |
| 557 | if v.prev != prev { |
| 558 | chain = Some(format!("version {} doesn't follow version {i}", v.n)); |
| 559 | break; |
| 560 | } |
| 561 | prev = Some(v.id(key)); |
| 562 | } |
| 563 | let (mut files, mut folders, mut missing) = (0, std::collections::HashSet::<String>::new(), Vec::new()); |
| 564 | if let Some(main) = all.first() { |
| 565 | match tree::flatten(&self.store, &main.tree) { |
| 566 | Err(e) => missing.push(format!("a folder of main ({e})")), |
| 567 | Ok(flat) => { |
| 568 | for (path, e) in &flat { |
| 569 | files += 1; |
| 570 | let mut at = 0; |
| 571 | while let Some(i) = path[at..].find('/') { |
| 572 | folders.insert(path[..at + i].to_string()); |
| 573 | at += i + 1; |
| 574 | } |
| 575 | if e.kind == tree::EntryKind::Gitlink { |
| 576 | continue; |
| 577 | } |
| 578 | let whole = match self.store.read(&e.id)? { |
| 579 | None => false, |
| 580 | Some(o) if o.kind == vcs_core::Kind::Chunks => vcs_core::object::decode_chunks(&o.data)?.iter().all(|(c, _)| self.store.has(c)), |
| 581 | Some(_) => true, |
| 582 | }; |
| 583 | if !whole { |
| 584 | missing.push(path.clone()); |
| 585 | } |
| 586 | } |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 | missing.truncate(100); |
| 591 | Ok(serde_json::json!({ "versions": all.len(), "chain": chain, "folders": folders.len(), "files": files, "missing": missing })) |
| 592 | } |
| 593 |
| 594 | pub fn approvals_required(&self, key: &str) -> Res<u32> { |
| 595 | let v: Option<String> = self.db.conn.query_row("SELECT value FROM s_settings WHERE project = ?1 AND key = 'approvals'", [key], |r| r.get(0)).optional()?; |
| 596 | Ok(v.and_then(|v| v.parse().ok()).unwrap_or(0)) |
| 597 | } |
| 598 |
| 599 | pub fn set_approvals(&self, key: &str, access: &Access, n: u32) -> Res<u32> { |
| 600 | if !access.can.admin { |
| 601 | return Err(problem(403, "not_allowed", "only the project's owners can change settings")); |
| 602 | } |
| 603 | if n > 10 { |
| 604 | return Err(problem(400, "bad_usage", "approvals is a number from 0 to 10")); |
| 605 | } |
| 606 | self.db.conn.execute("INSERT OR REPLACE INTO s_settings (project, key, value) VALUES (?1, 'approvals', ?2)", params![key, n.to_string()])?; |
| 607 | Ok(n) |
| 608 | } |
| 609 |
| 610 | /// Approvals of a change for exactly `tree`, from people other than its owner. |
| 611 | fn approvals_for(&self, key: &str, change: &str, tree: &Id, owner: &str) -> Res<Vec<String>> { |
| 612 | let mut stmt = self.db.conn.prepare("SELECT handle FROM s_approvals WHERE project = ?1 AND change = ?2 AND tree = ?3 AND handle != ?4 ORDER BY at")?; |
| 613 | let rows = stmt.query_map(params![key, change, tree.hex(), owner], |r| r.get::<_, String>(0))?; |
| 614 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 615 | } |
| 616 |
| 617 | /// Approves someone else's change as it is now; the last approval the |
| 618 | /// project needs lands it. |
| 619 | pub fn approve(&self, key: &str, access: &Access, id: &str) -> Res<serde_json::Value> { |
| 620 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 621 | if !access.can.land { |
| 622 | return Err(problem(403, "not_allowed", "only people who can land can approve")); |
| 623 | } |
| 624 | let (c, _) = self.change_row(key, id)?.filter(|(c, _)| self.visible(key, access, c).unwrap_or(false)).ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 625 | if c.owner == user.handle { |
| 626 | return Err(problem(403, "not_allowed", "someone else has to approve your change")); |
| 627 | } |
| 628 | if c.state != "open" && c.state != "waiting" { |
| 629 | return Err(problem(400, "bad_usage", format!("change {id} is {}", c.state))); |
| 630 | } |
| 631 | let tree = c.head_tree.unwrap_or(c.base_tree); |
| 632 | self.db.conn.execute( |
| 633 | "INSERT OR REPLACE INTO s_approvals (project, change, handle, tree, at) VALUES (?1, ?2, ?3, ?4, ?5)", |
| 634 | params![key, id, user.handle, tree.hex(), now()], |
| 635 | )?; |
| 636 | let required = self.approvals_required(key)?; |
| 637 | let approvals = self.approvals_for(key, id, &tree, &c.owner)?; |
| 638 | if c.state == "waiting" && approvals.len() as u32 >= required { |
| 639 | let request = LandRequest { change: c.id.clone(), base_tree: c.base_tree, tree, title: c.title.clone(), body: c.body.clone(), author: c.author.clone(), allow_secrets: true, record: None }; |
| 640 | return Ok(serde_json::to_value(self.land(key, access, &request)?).unwrap_or_default()); |
| 641 | } |
| 642 | Ok(serde_json::json!({ "outcome": "approved", "approvals": approvals, "required": required })) |
| 643 | } |
| 644 |
| 645 | fn is_member(&self, key: &str, handle: &str) -> Res<bool> { |
| 646 | Ok(self |
| 647 | .db |
| 648 | .conn |
| 649 | .query_row("SELECT 1 FROM s_members WHERE project = ?1 AND handle = ?2", params![key, handle], |_| Ok(())) |
| 650 | .optional()? |
| 651 | .is_some()) |
| 652 | } |
| 653 |
| 654 | fn may_edit(&self, key: &str, access: &Access, c: &ChangeRecord) -> bool { |
| 655 | let Some(user) = &access.user else { return false }; |
| 656 | let member = access.can.land || self.is_member(key, &user.handle).unwrap_or(false); |
| 657 | c.owner == user.handle || c.shared.iter().any(|s| s.edit && self.matches(key, &s.who, Some(&user.handle), member)) |
| 658 | } |
| 659 |
| 660 | /// A change as a viewer sees it: trees made for their audience when the |
| 661 | /// change belongs to someone who sees more. |
| 662 | fn for_viewer(&self, key: &str, access: &Access, mut c: ChangeRecord) -> Res<ChangeRecord> { |
| 663 | let viewer = access.user.as_ref().map(|u| u.handle.as_str()); |
| 664 | if viewer == Some(c.owner.as_str()) { |
| 665 | return Ok(c); |
| 666 | } |
| 667 | let hidden = self.hidden_for(key, viewer)?; |
| 668 | if hidden.is_empty() { |
| 669 | return Ok(c); |
| 670 | } |
| 671 | c.base_tree = self.to_visible(key, &c.base_tree, &hidden)?; |
| 672 | if let Some(h) = c.head_tree { |
| 673 | c.head_tree = Some(self.to_visible(key, &h, &hidden)?); |
| 674 | } |
| 675 | Ok(c) |
| 676 | } |
| 677 |
| 678 | pub fn changes(&self, key: &str, access: &Access) -> Res<Vec<ChangeRecord>> { |
| 679 | let mut stmt = self.db.conn.prepare("SELECT id FROM s_changes WHERE project = ?1 AND state IN ('open', 'waiting') ORDER BY updated DESC LIMIT 500")?; |
| 680 | let ids: Vec<String> = stmt.query_map([key], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 681 | let mut out = Vec::new(); |
| 682 | for id in ids { |
| 683 | if let Some((c, _)) = self.change_row(key, &id)? |
| 684 | && self.visible(key, access, &c)? |
| 685 | { |
| 686 | out.push(self.for_viewer(key, access, c)?); |
| 687 | } |
| 688 | } |
| 689 | Ok(out) |
| 690 | } |
| 691 |
| 692 | pub fn find_change(&self, key: &str, access: &Access, prefix: &str) -> Res<(ChangeRecord, Vec<SaveRecord>)> { |
| 693 | let mut stmt = self.db.conn.prepare("SELECT id FROM s_changes WHERE project = ?1 AND id LIKE ?2 || '%' LIMIT 10")?; |
| 694 | let ids: Vec<String> = stmt.query_map(params![key, prefix], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 695 | let mut found = Vec::new(); |
| 696 | for id in ids { |
| 697 | if let Some((c, _)) = self.change_row(key, &id)? |
| 698 | && self.visible(key, access, &c)? |
| 699 | { |
| 700 | found.push(c); |
| 701 | } |
| 702 | } |
| 703 | match found.len() { |
| 704 | 0 => Err(problem(404, "not_found", format!("no change {prefix}"))), |
| 705 | 1 => { |
| 706 | let c = found.remove(0); |
| 707 | let saves = self.saves(key, &c.id)?; |
| 708 | Ok((self.for_viewer(key, access, c)?, saves)) |
| 709 | } |
| 710 | _ => Err(problem(400, "bad_usage", format!("{prefix} matches several changes"))), |
| 711 | } |
| 712 | } |
| 713 |
| 714 | fn saves(&self, key: &str, change: &str) -> Res<Vec<SaveRecord>> { |
| 715 | let mut stmt = self.db.conn.prepare("SELECT n, tree, base_tree, at FROM s_saves WHERE project = ?1 AND change = ?2 ORDER BY n")?; |
| 716 | let rows = stmt.query_map(params![key, change], |r| { |
| 717 | let tree: String = r.get(1)?; |
| 718 | let base: String = r.get(2)?; |
| 719 | Ok(SaveRecord { n: r.get(0)?, tree: Id::parse(&tree).unwrap_or(Id::ZERO), base_tree: Id::parse(&base).unwrap_or(Id::ZERO), at: r.get(3)?, workspace: String::new() }) |
| 720 | })?; |
| 721 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 722 | } |
| 723 |
| 724 | /// Someone who can't see a path may only put trees without it in their |
| 725 | /// changes. Otherwise naming a full tree's ID in a change of their own |
| 726 | /// would let them read what's hidden. |
| 727 | fn claim(&self, key: &str, access: &Access, trees: &[Option<Id>]) -> Res<()> { |
| 728 | let hidden = self.hidden_for(key, access.user.as_ref().map(|u| u.handle.as_str()))?; |
| 729 | if hidden.is_empty() { |
| 730 | return Ok(()); |
| 731 | } |
| 732 | for t in trees.iter().flatten() { |
| 733 | if self.may_read_tree(key, access, t)? || !self.store.has(t) { |
| 734 | continue; |
| 735 | } |
| 736 | if let Some(path) = vcs_core::filter::holds_hidden(&self.store, t, &hidden)? { |
| 737 | return Err(problem(403, "not_allowed", format!("you can't change {path}: it's private"))); |
| 738 | } |
| 739 | } |
| 740 | Ok(()) |
| 741 | } |
| 742 |
| 743 | fn held_elsewhere(holder: &Option<String>, workspace: &str, label: Option<String>) -> Res<()> { |
| 744 | if let Some(h) = holder |
| 745 | && h != workspace |
| 746 | { |
| 747 | return Err(Problem { status: 409, code: "held_elsewhere", message: "another workspace took this change over".into(), holder: label }); |
| 748 | } |
| 749 | Ok(()) |
| 750 | } |
| 751 |
| 752 | pub fn put_change(&self, key: &str, access: &Access, mut record: ChangeRecord, workspace: &str, label: &str) -> Res<ChangeRecord> { |
| 753 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 754 | self.claim(key, access, &[Some(record.base_tree), record.head_tree])?; |
| 755 | let existing = self.change_row(key, &record.id)?; |
| 756 | match &existing { |
| 757 | Some((old, holder)) => { |
| 758 | if !self.may_edit(key, access, old) { |
| 759 | // Landers may move a waiting change to landed; nobody else may write. |
| 760 | return Err(problem(403, "not_allowed", "you can't change someone else's change")); |
| 761 | } |
| 762 | Self::held_elsewhere(holder, workspace, old.holder.clone())?; |
| 763 | record.owner = old.owner.clone(); |
| 764 | record.shared = old.shared.clone(); |
| 765 | if old.state == "landed" { |
| 766 | record.state = "landed".into(); |
| 767 | record.version = old.version; |
| 768 | } |
| 769 | } |
| 770 | None => { |
| 771 | record.owner = user.handle.clone(); |
| 772 | record.shared = Vec::new(); |
| 773 | } |
| 774 | } |
| 775 | record.updated = now(); |
| 776 | let holder = match &existing { |
| 777 | Some((_, Some(h))) => Some(h.clone()), |
| 778 | _ => Some(workspace.to_string()), |
| 779 | }; |
| 780 | let label = match &existing { |
| 781 | Some((old, Some(_))) => old.holder.clone().unwrap_or_default(), |
| 782 | _ => label.to_string(), |
| 783 | }; |
| 784 | self.db.conn.execute( |
| 785 | "INSERT OR REPLACE INTO s_changes (project, id, owner, record, holder, holder_label, state, updated) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", |
| 786 | params![key, record.id, record.owner, serde_json::to_string(&record).unwrap(), holder, label, record.state, record.updated], |
| 787 | )?; |
| 788 | if let Some(t) = record.head_tree { |
| 789 | self.add_root(key, &t, &record.id)?; |
| 790 | } |
| 791 | self.add_root(key, &record.base_tree, &record.id)?; |
| 792 | record.holder = Some(label); |
| 793 | Ok(record) |
| 794 | } |
| 795 |
| 796 | pub fn hold(&self, key: &str, access: &Access, id: &str, workspace: &str, label: &str) -> Res<Option<String>> { |
| 797 | let (c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 798 | if !self.may_edit(key, access, &c) { |
| 799 | return Err(problem(403, "not_allowed", "you can't work on someone else's change unless they share it with --edit")); |
| 800 | } |
| 801 | let previous = if holder.as_deref() == Some(workspace) { None } else { c.holder.clone() }; |
| 802 | self.db.conn.execute( |
| 803 | "UPDATE s_changes SET holder = ?3, holder_label = ?4, updated = ?5 WHERE project = ?1 AND id = ?2", |
| 804 | params![key, id, workspace, label, now()], |
| 805 | )?; |
| 806 | Ok(previous) |
| 807 | } |
| 808 |
| 809 | pub fn add_save(&self, key: &str, access: &Access, id: &str, save: &SaveRecord) -> Res<()> { |
| 810 | let (c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 811 | if !self.may_edit(key, access, &c) { |
| 812 | return Err(problem(403, "not_allowed", "not your change")); |
| 813 | } |
| 814 | Self::held_elsewhere(&holder, &save.workspace, c.holder.clone())?; |
| 815 | if !self.store.has(&save.tree) { |
| 816 | return Err(problem(400, "bad_usage", "upload the save's objects first")); |
| 817 | } |
| 818 | self.claim(key, access, &[Some(save.tree)])?; |
| 819 | self.db.conn.execute( |
| 820 | "INSERT OR REPLACE INTO s_saves (project, change, n, tree, base_tree, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 821 | params![key, id, save.n, save.tree.hex(), save.base_tree.hex(), save.at], |
| 822 | )?; |
| 823 | self.add_root(key, &save.tree, id)?; |
| 824 | Ok(()) |
| 825 | } |
| 826 |
| 827 | pub fn share(&self, key: &str, access: &Access, id: &str, who: &[String], edit: bool) -> Res<Vec<Share>> { |
| 828 | let (mut c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 829 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 830 | if c.owner != user.handle { |
| 831 | return Err(problem(403, "not_allowed", "only the change's owner can share it")); |
| 832 | } |
| 833 | if who.len() == 1 && who[0] == "me" { |
| 834 | c.shared.clear(); |
| 835 | } else { |
| 836 | for w in who { |
| 837 | c.shared.retain(|s| &s.who != w); |
| 838 | c.shared.push(Share { who: w.clone(), edit }); |
| 839 | } |
| 840 | } |
| 841 | let shared = c.shared.clone(); |
| 842 | self.db.conn.execute( |
| 843 | "UPDATE s_changes SET record = ?3 WHERE project = ?1 AND id = ?2", |
| 844 | params![key, id, serde_json::to_string(&c).unwrap()], |
| 845 | )?; |
| 846 | let _ = holder; |
| 847 | Ok(shared) |
| 848 | } |
| 849 |
| 850 | // Landing. |
| 851 |
| 852 | pub fn land(&self, key: &str, access: &Access, request: &LandRequest) -> Res<Landed> { |
| 853 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 854 | if !self.store.has(&request.tree) || !self.store.has(&request.base_tree) { |
| 855 | return Err(problem(400, "bad_usage", "upload the change's objects first")); |
| 856 | } |
| 857 | let existing = self.change_row(key, &request.change)?; |
| 858 | if !access.can.land { |
| 859 | // Ask the people who can. |
| 860 | let mut record = existing.map(|(c, _)| c).unwrap_or_else(|| empty_record(&request.change)); |
| 861 | if record.owner.is_empty() { |
| 862 | record.owner = user.handle.clone(); |
| 863 | } |
| 864 | if record.owner != user.handle { |
| 865 | return Err(problem(403, "not_allowed", "you can't land someone else's change")); |
| 866 | } |
| 867 | self.claim(key, access, &[Some(request.tree), Some(request.base_tree)])?; |
| 868 | record.title = request.title.clone(); |
| 869 | record.body = request.body.clone(); |
| 870 | record.base_tree = request.base_tree; |
| 871 | record.head_tree = Some(request.tree); |
| 872 | record.author = request.author.clone(); |
| 873 | record.state = "waiting".into(); |
| 874 | record.updated = now(); |
| 875 | self.db.conn.execute( |
| 876 | "INSERT INTO s_changes (project, id, owner, record, holder, holder_label, state, updated) VALUES (?1, ?2, ?3, ?4, NULL, '', 'waiting', ?5) |
| 877 | ON CONFLICT(project, id) DO UPDATE SET record = excluded.record, state = 'waiting', updated = excluded.updated", |
| 878 | params![key, record.id, record.owner, serde_json::to_string(&record).unwrap(), record.updated], |
| 879 | )?; |
| 880 | self.add_root(key, &request.tree, &request.change)?; |
| 881 | self.add_root(key, &request.base_tree, &request.change)?; |
| 882 | return Ok(Landed::Waiting { asked: self.landers(key)?.into_iter().map(|h| format!("@{h}")).collect(), reason: "needs someone with landing rights to land it".into() }); |
| 883 | } |
| 884 | if let Some((c, _)) = &existing |
| 885 | && c.owner != user.handle |
| 886 | && !self.visible(key, access, c)? |
| 887 | { |
| 888 | return Err(problem(403, "not_allowed", "you can't land a change you can't see")); |
| 889 | } |
| 890 | // A project that requires approvals lands a change once enough people |
| 891 | // other than its owner approved exactly what lands. |
| 892 | let required = self.approvals_required(key)?; |
| 893 | if required > 0 { |
| 894 | let owner = existing.as_ref().map(|(c, _)| c.owner.clone()).unwrap_or_else(|| user.handle.clone()); |
| 895 | let tree = if owner == user.handle { request.tree } else { existing.as_ref().and_then(|(c, _)| c.head_tree).unwrap_or(request.tree) }; |
| 896 | let approvals = self.approvals_for(key, &request.change, &tree, &owner)?; |
| 897 | if (approvals.len() as u32) < required { |
| 898 | if let Some((mut c, _)) = existing.clone() { |
| 899 | if owner == user.handle { |
| 900 | c.title = request.title.clone(); |
| 901 | c.body = request.body.clone(); |
| 902 | c.base_tree = request.base_tree; |
| 903 | c.head_tree = Some(request.tree); |
| 904 | } |
| 905 | c.state = "waiting".into(); |
| 906 | c.updated = now(); |
| 907 | self.db.conn.execute( |
| 908 | "UPDATE s_changes SET record = ?3, state = 'waiting', updated = ?4 WHERE project = ?1 AND id = ?2", |
| 909 | params![key, c.id, serde_json::to_string(&c).unwrap(), c.updated], |
| 910 | )?; |
| 911 | self.add_root(key, &tree, &c.id)?; |
| 912 | } |
| 913 | let asked: Vec<String> = self.landers(key)?.into_iter().filter(|h| *h != owner).map(|h| format!("@{h}")).collect(); |
| 914 | return Ok(Landed::Waiting { |
| 915 | asked, |
| 916 | reason: format!("needs {required} {} (has {}): someone else runs vcs approve {}", if required == 1 { "approval" } else { "approvals" }, approvals.len(), &request.change[..4.min(request.change.len())]), |
| 917 | }); |
| 918 | } |
| 919 | } |
| 920 | // Someone else's change lands as its owner made it, in the owner's view. |
| 921 | let (owner, base, tree) = match &existing { |
| 922 | Some((c, _)) if c.owner != user.handle => (c.owner.clone(), c.base_tree, c.head_tree.unwrap_or(c.base_tree)), |
| 923 | _ => (user.handle.clone(), request.base_tree, request.tree), |
| 924 | }; |
| 925 | if let Some(bad) = tree::unsafe_path(&self.store, &base, &tree)? { |
| 926 | return Err(problem(400, "bad_usage", format!("{bad} can't be in a project: it's vcs's or git's own folder, or not a safe path"))); |
| 927 | } |
| 928 | let hidden = self.hidden_for(key, Some(&owner))?; |
| 929 | let mut full = request.clone(); |
| 930 | full.base_tree = base; |
| 931 | full.tree = tree; |
| 932 | if !hidden.is_empty() { |
| 933 | let audience = Self::audience(&hidden); |
| 934 | let full_base = match self.to_full(key, &audience, &base)? { |
| 935 | Some(f) => f, |
| 936 | None if self.is_version_tree(key, &base)? => base, |
| 937 | None => { |
| 938 | return Err(problem(409, "conflict", "this change started from something the host can't place; vcs sync, then land again")); |
| 939 | } |
| 940 | }; |
| 941 | match vcs_core::filter::graft(&self.store, &tree, &full_base, &hidden)? { |
| 942 | Ok((t, objects)) => { |
| 943 | for o in &objects { |
| 944 | self.store.put(o)?; |
| 945 | } |
| 946 | self.remember(key, &audience, &tree, &t)?; |
| 947 | full.base_tree = full_base; |
| 948 | full.tree = t; |
| 949 | } |
| 950 | Err(path) => return Err(problem(403, "not_allowed", format!("you can't change {path}: it's private"))), |
| 951 | } |
| 952 | } |
| 953 | let outcome = vcs_cli::host::Local.land_on(&self.db, &self.store, key, &full)?; |
| 954 | if let Landed::Landed { version } = &outcome { |
| 955 | self.add_root(key, &version.tree, "")?; |
| 956 | if let Some((mut c, holder)) = existing { |
| 957 | c.state = "landed".into(); |
| 958 | c.version = Some(version.n); |
| 959 | c.updated = now(); |
| 960 | self.db.conn.execute( |
| 961 | "UPDATE s_changes SET record = ?3, state = 'landed', updated = ?4 WHERE project = ?1 AND id = ?2", |
| 962 | params![key, c.id, serde_json::to_string(&c).unwrap(), c.updated], |
| 963 | )?; |
| 964 | let _ = holder; |
| 965 | } |
| 966 | } |
| 967 | Ok(outcome) |
| 968 | } |
| 969 |
| 970 | /// Lands file edits without a workspace (see the hosted service's |
| 971 | /// landEdits): a new change of the caller's on version `base`. |
| 972 | pub fn land_edits(&self, key: &str, access: &Access, base: Option<u64>, put: Vec<tree::Put>, delete: Vec<String>, title: &str, body: &str, allow_secrets: bool) -> Res<(String, Landed)> { |
| 973 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 974 | let main = self.main(key)?; |
| 975 | let n = base.unwrap_or_else(|| main.as_ref().map(|v| v.n).unwrap_or(0)); |
| 976 | if n > main.as_ref().map(|v| v.n).unwrap_or(0) { |
| 977 | return Err(problem(400, "bad_usage", format!("there's no version {n}"))); |
| 978 | } |
| 979 | let base_tree = match n { |
| 980 | 0 => tree::empty_id(), |
| 981 | _ => { |
| 982 | let v = self.db.version(key, n)?.ok_or_else(|| problem(400, "bad_usage", format!("there's no version {n}")))?; |
| 983 | self.versions_for(key, access, vec![v])?.pop().map(|v| v.tree).unwrap_or_else(tree::empty_id) |
| 984 | } |
| 985 | }; |
| 986 | let (tree_id, objects) = match tree::edit(&self.store, &base_tree, &put, &delete)? { |
| 987 | Ok(done) => done, |
| 988 | Err(path) => return Err(problem(400, "bad_usage", format!("{path:?} isn't a path"))), |
| 989 | }; |
| 990 | if tree_id == base_tree { |
| 991 | return Err(problem(400, "empty_change", "these edits change nothing")); |
| 992 | } |
| 993 | self.store.put(&tree::empty())?; |
| 994 | for o in &objects { |
| 995 | self.store.put(o)?; |
| 996 | } |
| 997 | if !allow_secrets && let Some(hit) = vcs_core::secrets::scan(&self.store, &base_tree, &tree_id)?.first() { |
| 998 | return Err(problem(422, "secret", format!("{} line {} looks like a {}; remove it, or send allow_secrets", hit.path, hit.line, hit.kind))); |
| 999 | } |
| 1000 | let id = vcs_cli::ids::new_change_id(); |
| 1001 | let author = if user.email.is_empty() { user.name.clone() } else { format!("{} <{}>", user.name, user.email) }; |
| 1002 | let mut record = empty_record(&id); |
| 1003 | record.title = title.to_string(); |
| 1004 | record.body = body.to_string(); |
| 1005 | record.base_tree = base_tree; |
| 1006 | record.base_version = (n > 0).then_some(n); |
| 1007 | record.head_tree = Some(tree_id); |
| 1008 | record.author = author.clone(); |
| 1009 | self.put_change(key, access, record, "api", "the API")?; |
| 1010 | let request = LandRequest { change: id.clone(), base_tree, tree: tree_id, title: title.to_string(), body: body.to_string(), author, allow_secrets: true, record: None }; |
| 1011 | Ok((id, self.land(key, access, &request)?)) |
| 1012 | } |
| 1013 |
| 1014 | /// Takes a published project's history (only into an empty project). |
| 1015 | pub fn import(&self, key: &str, access: &Access, versions: Vec<Version>) -> Res<Option<u64>> { |
| 1016 | if !access.can.admin { |
| 1017 | return Err(problem(403, "not_allowed", "only the project's owners can import history")); |
| 1018 | } |
| 1019 | if self.main(key)?.is_some() { |
| 1020 | return Err(problem(409, "exists", "this project already has versions")); |
| 1021 | } |
| 1022 | for v in &versions { |
| 1023 | if !self.store.has(&v.tree) { |
| 1024 | return Err(problem(400, "bad_usage", format!("upload version {}'s objects first", v.n))); |
| 1025 | } |
| 1026 | } |
| 1027 | let tx = self.db.conn.unchecked_transaction()?; |
| 1028 | let mut prev = None; |
| 1029 | let mut last = None; |
| 1030 | for (i, v) in versions.into_iter().enumerate() { |
| 1031 | let v = Version { n: i as u64 + 1, prev, ..v }; |
| 1032 | self.db.put_version(key, &v)?; |
| 1033 | self.add_root(key, &v.tree, "")?; |
| 1034 | prev = Some(v.id(key)); |
| 1035 | last = Some(v.n); |
| 1036 | } |
| 1037 | tx.commit()?; |
| 1038 | Ok(last) |
| 1039 | } |
| 1040 |
| 1041 | // Rules and mine. |
| 1042 |
| 1043 | pub fn rules(&self, key: &str) -> Res<Vec<Rule>> { |
| 1044 | let mut stmt = self.db.conn.prepare("SELECT path, who FROM s_rules WHERE project = ?1 ORDER BY path")?; |
| 1045 | let rows = stmt.query_map([key], |r| { |
| 1046 | let who: String = r.get(1)?; |
| 1047 | Ok(Rule { path: r.get(0)?, who: serde_json::from_str(&who).unwrap_or_default() }) |
| 1048 | })?; |
| 1049 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 1050 | } |
| 1051 |
| 1052 | pub fn set_rule(&self, key: &str, access: &Access, rule: &Rule) -> Res<Vec<Rule>> { |
| 1053 | if !access.can.admin { |
| 1054 | return Err(problem(403, "not_allowed", "only the project's owners can set who sees a path")); |
| 1055 | } |
| 1056 | let path = rule.path.trim_matches('/'); |
| 1057 | if rule.who.is_empty() || (rule.who.len() == 1 && rule.who[0] == "team") { |
| 1058 | self.db.conn.execute("DELETE FROM s_rules WHERE project = ?1 AND path = ?2", params![key, path])?; |
| 1059 | } else { |
| 1060 | self.db.conn.execute( |
| 1061 | "INSERT OR REPLACE INTO s_rules (project, path, who) VALUES (?1, ?2, ?3)", |
| 1062 | params![key, path, serde_json::to_string(&rule.who).unwrap()], |
| 1063 | )?; |
| 1064 | } |
| 1065 | self.rules(key) |
| 1066 | } |
| 1067 |
| 1068 | pub fn mine(&self, key: &str, handle: &str) -> Res<Vec<MineFile>> { |
| 1069 | let text: Option<String> = |
| 1070 | self.db.conn.query_row("SELECT files FROM s_mine WHERE project = ?1 AND handle = ?2", params![key, handle], |r| r.get(0)).optional()?; |
| 1071 | Ok(text.and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()) |
| 1072 | } |
| 1073 |
| 1074 | pub fn set_mine(&self, key: &str, handle: &str, files: &[MineFile]) -> Res<()> { |
| 1075 | for f in files { |
| 1076 | if !self.store.has(&f.file) { |
| 1077 | return Err(problem(400, "bad_usage", format!("upload {} first", f.path))); |
| 1078 | } |
| 1079 | } |
| 1080 | self.db.conn.execute( |
| 1081 | "INSERT OR REPLACE INTO s_mine (project, handle, files) VALUES (?1, ?2, ?3)", |
| 1082 | params![key, handle, serde_json::to_string(files).unwrap()], |
| 1083 | )?; |
| 1084 | Ok(()) |
| 1085 | } |
| 1086 | } |
| 1087 |
| 1088 | fn empty_record(id: &str) -> ChangeRecord { |
| 1089 | ChangeRecord { |
| 1090 | id: id.to_string(), |
| 1091 | title: String::new(), |
| 1092 | body: String::new(), |
| 1093 | base_tree: tree::empty_id(), |
| 1094 | base_version: None, |
| 1095 | on_change: None, |
| 1096 | after_change: None, |
| 1097 | head_tree: None, |
| 1098 | saves: 0, |
| 1099 | state: "open".into(), |
| 1100 | version: None, |
| 1101 | author: String::new(), |
| 1102 | owner: String::new(), |
| 1103 | shared: Vec::new(), |
| 1104 | holder: None, |
| 1105 | updated: 0, |
| 1106 | } |
| 1107 | } |
| 1108 |