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_namespaces (name TEXT PRIMARY KEY, handle TEXT NOT NULL); |
| 30 | CREATE TABLE IF NOT EXISTS s_mine (project TEXT NOT NULL, handle TEXT NOT NULL, files TEXT NOT NULL, PRIMARY KEY (project, handle)); |
| 31 | "#; |
| 32 |
| 33 | pub struct State { |
| 34 | pub db: Db, |
| 35 | pub store: Store, |
| 36 | } |
| 37 |
| 38 | #[derive(Debug)] |
| 39 | pub struct Problem { |
| 40 | pub status: u16, |
| 41 | pub code: &'static str, |
| 42 | pub message: String, |
| 43 | pub holder: Option<String>, |
| 44 | } |
| 45 |
| 46 | pub fn problem(status: u16, code: &'static str, message: impl Into<String>) -> Problem { |
| 47 | Problem { status, code, message: message.into(), holder: None } |
| 48 | } |
| 49 |
| 50 | impl From<anyhow::Error> for Problem { |
| 51 | fn from(e: anyhow::Error) -> Problem { |
| 52 | problem(500, "failed", format!("{e:#}")) |
| 53 | } |
| 54 | } |
| 55 |
| 56 | impl From<rusqlite::Error> for Problem { |
| 57 | fn from(e: rusqlite::Error) -> Problem { |
| 58 | problem(500, "failed", e.to_string()) |
| 59 | } |
| 60 | } |
| 61 |
| 62 | impl From<vcs_core::Error> for Problem { |
| 63 | fn from(e: vcs_core::Error) -> Problem { |
| 64 | problem(500, "failed", e.to_string()) |
| 65 | } |
| 66 | } |
| 67 |
| 68 | pub type Res<T> = Result<T, Problem>; |
| 69 |
| 70 | pub fn token_hash(token: &str) -> String { |
| 71 | let digest = Sha256::digest(token.as_bytes()); |
| 72 | digest.iter().map(|b| format!("{b:02x}")).collect() |
| 73 | } |
| 74 |
| 75 | fn now() -> i64 { |
| 76 | std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0) |
| 77 | } |
| 78 |
| 79 | pub struct Access { |
| 80 | pub user: Option<Me>, |
| 81 | pub can: Can, |
| 82 | } |
| 83 |
| 84 | impl State { |
| 85 | pub fn open(data: &Path) -> Result<State> { |
| 86 | std::fs::create_dir_all(data)?; |
| 87 | let conn = rusqlite::Connection::open(data.join("server.db"))?; |
| 88 | let db = Db::setup(conn)?; |
| 89 | db.conn.execute_batch(SCHEMA)?; |
| 90 | Ok(State { db, store: Store::open(&data.join("objects"))? }) |
| 91 | } |
| 92 |
| 93 | // Accounts. |
| 94 |
| 95 | pub fn add_user(&self, handle: &str, name: &str, email: &str) -> Result<String> { |
| 96 | self.db.conn.execute( |
| 97 | "INSERT OR REPLACE INTO s_users (handle, name, email, created) VALUES (?1, ?2, ?3, ?4)", |
| 98 | params![handle, name, email, now()], |
| 99 | )?; |
| 100 | let token = format!("vcs_{}", (0..40).map(|_| b"abcdefghijklmnopqrstuvwxyz0123456789"[rand::random_range(0..36)] as char).collect::<String>()); |
| 101 | self.db.conn.execute("INSERT INTO s_tokens (hash, handle, created) VALUES (?1, ?2, ?3)", params![token_hash(&token), handle, now()])?; |
| 102 | Ok(token) |
| 103 | } |
| 104 |
| 105 | pub fn add_project(&self, key: &str, owner: &str, public: bool) -> Result<()> { |
| 106 | if key.split('/').count() != 2 || key.split('/').any(|p| p.is_empty()) { |
| 107 | return Err(anyhow!("projects are OWNER/NAME")); |
| 108 | } |
| 109 | self.db.conn.execute("INSERT OR REPLACE INTO s_projects (key, public, created) VALUES (?1, ?2, ?3)", params![key, public as i64, now()])?; |
| 110 | self.add_member(key, owner, "owner") |
| 111 | } |
| 112 |
| 113 | /// A namespace is yours if it's your handle, or you claimed it first. |
| 114 | pub fn may_create_under(&self, owner: &str, handle: &str) -> Res<bool> { |
| 115 | if owner == handle { |
| 116 | return Ok(true); |
| 117 | } |
| 118 | let claimed: Option<String> = self.db.conn.query_row("SELECT handle FROM s_namespaces WHERE name = ?1", [owner], |r| r.get(0)).optional()?; |
| 119 | match claimed { |
| 120 | Some(h) => Ok(h == handle), |
| 121 | None => { |
| 122 | let taken = self.db.conn.query_row("SELECT 1 FROM s_users WHERE handle = ?1", [owner], |_| Ok(())).optional()?.is_some(); |
| 123 | if taken { |
| 124 | return Ok(false); |
| 125 | } |
| 126 | self.db.conn.execute("INSERT INTO s_namespaces (name, handle) VALUES (?1, ?2)", params![owner, handle])?; |
| 127 | Ok(true) |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 |
| 132 | pub fn add_member(&self, key: &str, handle: &str, role: &str) -> Result<()> { |
| 133 | self.db.conn.execute("INSERT OR REPLACE INTO s_members (project, handle, role) VALUES (?1, ?2, ?3)", params![key, handle, role])?; |
| 134 | Ok(()) |
| 135 | } |
| 136 |
| 137 | pub fn user_for_token(&self, token: &str) -> Res<Option<Me>> { |
| 138 | let handle: Option<String> = |
| 139 | self.db.conn.query_row("SELECT handle FROM s_tokens WHERE hash = ?1", [token_hash(token)], |r| r.get(0)).optional()?; |
| 140 | let Some(handle) = handle else { return Ok(None) }; |
| 141 | Ok(self |
| 142 | .db |
| 143 | .conn |
| 144 | .query_row("SELECT handle, name, email FROM s_users WHERE handle = ?1", [&handle], |r| { |
| 145 | Ok(Me { handle: r.get(0)?, name: r.get(1)?, email: r.get(2)? }) |
| 146 | }) |
| 147 | .optional()?) |
| 148 | } |
| 149 |
| 150 | pub fn project_exists(&self, key: &str) -> Res<Option<bool>> { |
| 151 | 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)) |
| 152 | } |
| 153 |
| 154 | pub fn access(&self, key: &str, user: Option<Me>) -> Res<Access> { |
| 155 | let public = self.project_exists(key)?.ok_or_else(|| problem(404, "not_found", format!("no project {key}")))?; |
| 156 | let role: Option<String> = match &user { |
| 157 | Some(u) => self |
| 158 | .db |
| 159 | .conn |
| 160 | .query_row("SELECT role FROM s_members WHERE project = ?1 AND handle = ?2", params![key, u.handle], |r| r.get(0)) |
| 161 | .optional()?, |
| 162 | None => None, |
| 163 | }; |
| 164 | let can = Can { |
| 165 | read: public || role.is_some(), |
| 166 | land: matches!(role.as_deref(), Some("owner") | Some("member")), |
| 167 | admin: role.as_deref() == Some("owner"), |
| 168 | }; |
| 169 | if !can.read { |
| 170 | // Private projects look like missing ones to outsiders. |
| 171 | return Err(problem(404, "not_found", format!("no project {key}"))); |
| 172 | } |
| 173 | Ok(Access { user, can }) |
| 174 | } |
| 175 |
| 176 | pub fn public(&self, key: &str) -> Res<bool> { |
| 177 | Ok(self.project_exists(key)?.unwrap_or(false)) |
| 178 | } |
| 179 |
| 180 | pub fn landers(&self, key: &str) -> Res<Vec<String>> { |
| 181 | let mut stmt = self.db.conn.prepare("SELECT handle FROM s_members WHERE project = ?1 AND role IN ('owner', 'member') ORDER BY handle")?; |
| 182 | let rows = stmt.query_map([key], |r| r.get::<_, String>(0))?; |
| 183 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 184 | } |
| 185 |
| 186 | // Main. |
| 187 |
| 188 | pub fn main(&self, key: &str) -> Res<Option<Version>> { |
| 189 | Ok(self.db.latest_version(key)?) |
| 190 | } |
| 191 |
| 192 | pub fn versions_since(&self, key: &str, since: u64, limit: i64) -> Res<Vec<Version>> { |
| 193 | let mut stmt = self.db.conn.prepare( |
| 194 | "SELECT n, tree, prev, change, author, time, title, body, git FROM versions WHERE project = ?1 AND n > ?2 ORDER BY n LIMIT ?3", |
| 195 | )?; |
| 196 | let rows = stmt.query_map(params![key, since as i64, limit], |row| { |
| 197 | let id = |i: usize| -> rusqlite::Result<Option<Id>> { Ok(row.get::<_, Option<String>>(i)?.and_then(|t| Id::parse(&t))) }; |
| 198 | Ok(Version { |
| 199 | n: row.get::<_, i64>(0)? as u64, |
| 200 | tree: id(1)?.unwrap_or(Id::ZERO), |
| 201 | prev: id(2)?, |
| 202 | change: row.get(3)?, |
| 203 | author: row.get(4)?, |
| 204 | time: row.get(5)?, |
| 205 | title: row.get(6)?, |
| 206 | body: row.get(7)?, |
| 207 | git: row.get(8)?, |
| 208 | }) |
| 209 | })?; |
| 210 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 211 | } |
| 212 |
| 213 | // Objects. |
| 214 |
| 215 | pub fn missing(&self, ids: &[Id]) -> Vec<Id> { |
| 216 | ids.iter().filter(|i| !self.store.has(i)).copied().collect() |
| 217 | } |
| 218 |
| 219 | fn add_root(&self, key: &str, tree: &Id, change: &str) -> Res<()> { |
| 220 | self.db.conn.execute("INSERT OR IGNORE INTO s_roots (project, tree, change) VALUES (?1, ?2, ?3)", params![key, tree.hex(), change])?; |
| 221 | Ok(()) |
| 222 | } |
| 223 |
| 224 | /// Whether `user` may read the objects under `tree`: it's a version's |
| 225 | /// tree, or a save of a change they can see. |
| 226 | pub fn may_read_tree(&self, key: &str, access: &Access, tree: &Id) -> Res<bool> { |
| 227 | let mut stmt = self.db.conn.prepare("SELECT change FROM s_roots WHERE project = ?1 AND tree = ?2")?; |
| 228 | let changes: Vec<String> = stmt.query_map(params![key, tree.hex()], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 229 | if changes.iter().any(|c| c.is_empty()) { |
| 230 | return Ok(true); |
| 231 | } |
| 232 | for c in changes { |
| 233 | if let Some((record, _)) = self.change_row(key, &c)? |
| 234 | && self.visible(key, access, &record)? |
| 235 | { |
| 236 | return Ok(true); |
| 237 | } |
| 238 | } |
| 239 | Ok(tree == &tree::empty_id()) |
| 240 | } |
| 241 |
| 242 | /// Every object under `tree` that `have` doesn't share, as a bundle. |
| 243 | pub fn tree_bundle(&self, tree: &Id, have: Option<&Id>) -> Res<Vec<u8>> { |
| 244 | let mut ids = Vec::new(); |
| 245 | tree::new_since(&self.store, have, tree, &mut ids)?; |
| 246 | let mut all = Vec::with_capacity(ids.len()); |
| 247 | for id in ids { |
| 248 | all.extend(self.store.file_parts(&id)?); |
| 249 | } |
| 250 | Ok(self.store.bundle(&all)?) |
| 251 | } |
| 252 |
| 253 | // Changes. |
| 254 |
| 255 | fn change_row(&self, key: &str, id: &str) -> Res<Option<(ChangeRecord, Option<String>)>> { |
| 256 | let row: Option<(String, String, Option<String>, Option<String>)> = self |
| 257 | .db |
| 258 | .conn |
| 259 | .query_row("SELECT record, owner, holder, holder_label FROM s_changes WHERE project = ?1 AND id = ?2", params![key, id], |r| { |
| 260 | Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)) |
| 261 | }) |
| 262 | .optional()?; |
| 263 | Ok(row.map(|(record, owner, holder, label)| { |
| 264 | let mut c: ChangeRecord = serde_json::from_str(&record).unwrap_or_else(|_| empty_record(id)); |
| 265 | c.owner = owner; |
| 266 | c.holder = label; |
| 267 | (c, holder) |
| 268 | })) |
| 269 | } |
| 270 |
| 271 | pub fn visible(&self, key: &str, access: &Access, c: &ChangeRecord) -> Res<bool> { |
| 272 | let Some(user) = &access.user else { return Ok(false) }; |
| 273 | if c.owner == user.handle || access.can.admin { |
| 274 | return Ok(true); |
| 275 | } |
| 276 | if c.state == "waiting" && access.can.land { |
| 277 | return Ok(true); |
| 278 | } |
| 279 | let member = access.can.land || self.is_member(key, &user.handle)?; |
| 280 | Ok(c.shared.iter().any(|s| s.who == format!("@{}", user.handle) || s.who == user.handle || (s.who == "team" && member))) |
| 281 | } |
| 282 |
| 283 | fn is_member(&self, key: &str, handle: &str) -> Res<bool> { |
| 284 | Ok(self |
| 285 | .db |
| 286 | .conn |
| 287 | .query_row("SELECT 1 FROM s_members WHERE project = ?1 AND handle = ?2", params![key, handle], |_| Ok(())) |
| 288 | .optional()? |
| 289 | .is_some()) |
| 290 | } |
| 291 |
| 292 | fn may_edit(&self, access: &Access, c: &ChangeRecord) -> bool { |
| 293 | let Some(user) = &access.user else { return false }; |
| 294 | c.owner == user.handle || c.shared.iter().any(|s| s.edit && (s.who == format!("@{}", user.handle) || s.who == user.handle || s.who == "team")) |
| 295 | } |
| 296 |
| 297 | pub fn changes(&self, key: &str, access: &Access) -> Res<Vec<ChangeRecord>> { |
| 298 | 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")?; |
| 299 | let ids: Vec<String> = stmt.query_map([key], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 300 | let mut out = Vec::new(); |
| 301 | for id in ids { |
| 302 | if let Some((c, _)) = self.change_row(key, &id)? |
| 303 | && self.visible(key, access, &c)? |
| 304 | { |
| 305 | out.push(c); |
| 306 | } |
| 307 | } |
| 308 | Ok(out) |
| 309 | } |
| 310 |
| 311 | pub fn find_change(&self, key: &str, access: &Access, prefix: &str) -> Res<(ChangeRecord, Vec<SaveRecord>)> { |
| 312 | let mut stmt = self.db.conn.prepare("SELECT id FROM s_changes WHERE project = ?1 AND id LIKE ?2 || '%' LIMIT 10")?; |
| 313 | let ids: Vec<String> = stmt.query_map(params![key, prefix], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 314 | let mut found = Vec::new(); |
| 315 | for id in ids { |
| 316 | if let Some((c, _)) = self.change_row(key, &id)? |
| 317 | && self.visible(key, access, &c)? |
| 318 | { |
| 319 | found.push(c); |
| 320 | } |
| 321 | } |
| 322 | match found.len() { |
| 323 | 0 => Err(problem(404, "not_found", format!("no change {prefix}"))), |
| 324 | 1 => { |
| 325 | let c = found.remove(0); |
| 326 | let saves = self.saves(key, &c.id)?; |
| 327 | Ok((c, saves)) |
| 328 | } |
| 329 | _ => Err(problem(400, "bad_usage", format!("{prefix} matches several changes"))), |
| 330 | } |
| 331 | } |
| 332 |
| 333 | fn saves(&self, key: &str, change: &str) -> Res<Vec<SaveRecord>> { |
| 334 | 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")?; |
| 335 | let rows = stmt.query_map(params![key, change], |r| { |
| 336 | let tree: String = r.get(1)?; |
| 337 | let base: String = r.get(2)?; |
| 338 | 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() }) |
| 339 | })?; |
| 340 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 341 | } |
| 342 |
| 343 | fn held_elsewhere(holder: &Option<String>, workspace: &str, label: Option<String>) -> Res<()> { |
| 344 | if let Some(h) = holder |
| 345 | && h != workspace |
| 346 | { |
| 347 | return Err(Problem { status: 409, code: "held_elsewhere", message: "another workspace took this change over".into(), holder: label }); |
| 348 | } |
| 349 | Ok(()) |
| 350 | } |
| 351 |
| 352 | pub fn put_change(&self, key: &str, access: &Access, mut record: ChangeRecord, workspace: &str, label: &str) -> Res<ChangeRecord> { |
| 353 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 354 | let existing = self.change_row(key, &record.id)?; |
| 355 | match &existing { |
| 356 | Some((old, holder)) => { |
| 357 | if !self.may_edit(access, old) { |
| 358 | // Landers may move a waiting change to landed; nobody else may write. |
| 359 | return Err(problem(403, "not_allowed", "you can't change someone else's change")); |
| 360 | } |
| 361 | Self::held_elsewhere(holder, workspace, old.holder.clone())?; |
| 362 | record.owner = old.owner.clone(); |
| 363 | record.shared = old.shared.clone(); |
| 364 | if old.state == "landed" { |
| 365 | record.state = "landed".into(); |
| 366 | record.version = old.version; |
| 367 | } |
| 368 | } |
| 369 | None => { |
| 370 | record.owner = user.handle.clone(); |
| 371 | record.shared = Vec::new(); |
| 372 | } |
| 373 | } |
| 374 | record.updated = now(); |
| 375 | let holder = match &existing { |
| 376 | Some((_, Some(h))) => Some(h.clone()), |
| 377 | _ => Some(workspace.to_string()), |
| 378 | }; |
| 379 | let label = match &existing { |
| 380 | Some((old, Some(_))) => old.holder.clone().unwrap_or_default(), |
| 381 | _ => label.to_string(), |
| 382 | }; |
| 383 | self.db.conn.execute( |
| 384 | "INSERT OR REPLACE INTO s_changes (project, id, owner, record, holder, holder_label, state, updated) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", |
| 385 | params![key, record.id, record.owner, serde_json::to_string(&record).unwrap(), holder, label, record.state, record.updated], |
| 386 | )?; |
| 387 | if let Some(t) = record.head_tree { |
| 388 | self.add_root(key, &t, &record.id)?; |
| 389 | } |
| 390 | self.add_root(key, &record.base_tree, &record.id)?; |
| 391 | record.holder = Some(label); |
| 392 | Ok(record) |
| 393 | } |
| 394 |
| 395 | pub fn hold(&self, key: &str, access: &Access, id: &str, workspace: &str, label: &str) -> Res<Option<String>> { |
| 396 | let (c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 397 | if !self.may_edit(access, &c) { |
| 398 | return Err(problem(403, "not_allowed", "you can't work on someone else's change unless they share it with --edit")); |
| 399 | } |
| 400 | let previous = if holder.as_deref() == Some(workspace) { None } else { c.holder.clone() }; |
| 401 | self.db.conn.execute( |
| 402 | "UPDATE s_changes SET holder = ?3, holder_label = ?4, updated = ?5 WHERE project = ?1 AND id = ?2", |
| 403 | params![key, id, workspace, label, now()], |
| 404 | )?; |
| 405 | Ok(previous) |
| 406 | } |
| 407 |
| 408 | pub fn add_save(&self, key: &str, access: &Access, id: &str, save: &SaveRecord) -> Res<()> { |
| 409 | let (c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 410 | if !self.may_edit(access, &c) { |
| 411 | return Err(problem(403, "not_allowed", "not your change")); |
| 412 | } |
| 413 | Self::held_elsewhere(&holder, &save.workspace, c.holder.clone())?; |
| 414 | if !self.store.has(&save.tree) { |
| 415 | return Err(problem(400, "bad_usage", "upload the save's objects first")); |
| 416 | } |
| 417 | self.db.conn.execute( |
| 418 | "INSERT OR REPLACE INTO s_saves (project, change, n, tree, base_tree, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 419 | params![key, id, save.n, save.tree.hex(), save.base_tree.hex(), save.at], |
| 420 | )?; |
| 421 | self.add_root(key, &save.tree, id)?; |
| 422 | Ok(()) |
| 423 | } |
| 424 |
| 425 | pub fn share(&self, key: &str, access: &Access, id: &str, who: &[String], edit: bool) -> Res<Vec<Share>> { |
| 426 | let (mut c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 427 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 428 | if c.owner != user.handle { |
| 429 | return Err(problem(403, "not_allowed", "only the change's owner can share it")); |
| 430 | } |
| 431 | if who.len() == 1 && who[0] == "me" { |
| 432 | c.shared.clear(); |
| 433 | } else { |
| 434 | for w in who { |
| 435 | c.shared.retain(|s| &s.who != w); |
| 436 | c.shared.push(Share { who: w.clone(), edit }); |
| 437 | } |
| 438 | } |
| 439 | let shared = c.shared.clone(); |
| 440 | self.db.conn.execute( |
| 441 | "UPDATE s_changes SET record = ?3 WHERE project = ?1 AND id = ?2", |
| 442 | params![key, id, serde_json::to_string(&c).unwrap()], |
| 443 | )?; |
| 444 | let _ = holder; |
| 445 | Ok(shared) |
| 446 | } |
| 447 |
| 448 | // Landing. |
| 449 |
| 450 | pub fn land(&self, key: &str, access: &Access, request: &LandRequest) -> Res<Landed> { |
| 451 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 452 | if !self.store.has(&request.tree) || !self.store.has(&request.base_tree) { |
| 453 | return Err(problem(400, "bad_usage", "upload the change's objects first")); |
| 454 | } |
| 455 | let existing = self.change_row(key, &request.change)?; |
| 456 | if !access.can.land { |
| 457 | // Ask the people who can. |
| 458 | let mut record = existing.map(|(c, _)| c).unwrap_or_else(|| empty_record(&request.change)); |
| 459 | if record.owner.is_empty() { |
| 460 | record.owner = user.handle.clone(); |
| 461 | } |
| 462 | if record.owner != user.handle { |
| 463 | return Err(problem(403, "not_allowed", "you can't land someone else's change")); |
| 464 | } |
| 465 | record.title = request.title.clone(); |
| 466 | record.body = request.body.clone(); |
| 467 | record.base_tree = request.base_tree; |
| 468 | record.head_tree = Some(request.tree); |
| 469 | record.author = request.author.clone(); |
| 470 | record.state = "waiting".into(); |
| 471 | record.updated = now(); |
| 472 | self.db.conn.execute( |
| 473 | "INSERT INTO s_changes (project, id, owner, record, holder, holder_label, state, updated) VALUES (?1, ?2, ?3, ?4, NULL, '', 'waiting', ?5) |
| 474 | ON CONFLICT(project, id) DO UPDATE SET record = excluded.record, state = 'waiting', updated = excluded.updated", |
| 475 | params![key, record.id, record.owner, serde_json::to_string(&record).unwrap(), record.updated], |
| 476 | )?; |
| 477 | self.add_root(key, &request.tree, &request.change)?; |
| 478 | self.add_root(key, &request.base_tree, &request.change)?; |
| 479 | 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() }); |
| 480 | } |
| 481 | if let Some((c, _)) = &existing |
| 482 | && c.owner != user.handle |
| 483 | && !self.visible(key, access, c)? |
| 484 | { |
| 485 | return Err(problem(403, "not_allowed", "you can't land a change you can't see")); |
| 486 | } |
| 487 | let outcome = vcs_cli::host::Local.land_on(&self.db, &self.store, key, request)?; |
| 488 | if let Landed::Landed { version } = &outcome { |
| 489 | self.add_root(key, &version.tree, "")?; |
| 490 | if let Some((mut c, holder)) = existing { |
| 491 | c.state = "landed".into(); |
| 492 | c.version = Some(version.n); |
| 493 | c.updated = now(); |
| 494 | self.db.conn.execute( |
| 495 | "UPDATE s_changes SET record = ?3, state = 'landed', updated = ?4 WHERE project = ?1 AND id = ?2", |
| 496 | params![key, c.id, serde_json::to_string(&c).unwrap(), c.updated], |
| 497 | )?; |
| 498 | let _ = holder; |
| 499 | } |
| 500 | } |
| 501 | Ok(outcome) |
| 502 | } |
| 503 |
| 504 | /// Takes a published project's history (only into an empty project). |
| 505 | pub fn import(&self, key: &str, access: &Access, versions: Vec<Version>) -> Res<Option<u64>> { |
| 506 | if !access.can.admin { |
| 507 | return Err(problem(403, "not_allowed", "only the project's owners can import history")); |
| 508 | } |
| 509 | if self.main(key)?.is_some() { |
| 510 | return Err(problem(409, "exists", "this project already has versions")); |
| 511 | } |
| 512 | for v in &versions { |
| 513 | if !self.store.has(&v.tree) { |
| 514 | return Err(problem(400, "bad_usage", format!("upload version {}'s objects first", v.n))); |
| 515 | } |
| 516 | } |
| 517 | let tx = self.db.conn.unchecked_transaction()?; |
| 518 | let mut prev = None; |
| 519 | let mut last = None; |
| 520 | for (i, v) in versions.into_iter().enumerate() { |
| 521 | let v = Version { n: i as u64 + 1, prev, ..v }; |
| 522 | self.db.put_version(key, &v)?; |
| 523 | self.add_root(key, &v.tree, "")?; |
| 524 | prev = Some(v.id(key)); |
| 525 | last = Some(v.n); |
| 526 | } |
| 527 | tx.commit()?; |
| 528 | Ok(last) |
| 529 | } |
| 530 |
| 531 | // Rules and mine. |
| 532 |
| 533 | pub fn rules(&self, key: &str) -> Res<Vec<Rule>> { |
| 534 | let mut stmt = self.db.conn.prepare("SELECT path, who FROM s_rules WHERE project = ?1 ORDER BY path")?; |
| 535 | let rows = stmt.query_map([key], |r| { |
| 536 | let who: String = r.get(1)?; |
| 537 | Ok(Rule { path: r.get(0)?, who: serde_json::from_str(&who).unwrap_or_default() }) |
| 538 | })?; |
| 539 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 540 | } |
| 541 |
| 542 | pub fn set_rule(&self, key: &str, access: &Access, rule: &Rule) -> Res<Vec<Rule>> { |
| 543 | if !access.can.admin { |
| 544 | return Err(problem(403, "not_allowed", "only the project's owners can set who sees a path")); |
| 545 | } |
| 546 | let path = rule.path.trim_matches('/'); |
| 547 | if rule.who.is_empty() || (rule.who.len() == 1 && rule.who[0] == "team") { |
| 548 | self.db.conn.execute("DELETE FROM s_rules WHERE project = ?1 AND path = ?2", params![key, path])?; |
| 549 | } else { |
| 550 | self.db.conn.execute( |
| 551 | "INSERT OR REPLACE INTO s_rules (project, path, who) VALUES (?1, ?2, ?3)", |
| 552 | params![key, path, serde_json::to_string(&rule.who).unwrap()], |
| 553 | )?; |
| 554 | } |
| 555 | self.rules(key) |
| 556 | } |
| 557 |
| 558 | pub fn mine(&self, key: &str, handle: &str) -> Res<Vec<MineFile>> { |
| 559 | let text: Option<String> = |
| 560 | self.db.conn.query_row("SELECT files FROM s_mine WHERE project = ?1 AND handle = ?2", params![key, handle], |r| r.get(0)).optional()?; |
| 561 | Ok(text.and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()) |
| 562 | } |
| 563 |
| 564 | pub fn set_mine(&self, key: &str, handle: &str, files: &[MineFile]) -> Res<()> { |
| 565 | for f in files { |
| 566 | if !self.store.has(&f.file) { |
| 567 | return Err(problem(400, "bad_usage", format!("upload {} first", f.path))); |
| 568 | } |
| 569 | } |
| 570 | self.db.conn.execute( |
| 571 | "INSERT OR REPLACE INTO s_mine (project, handle, files) VALUES (?1, ?2, ?3)", |
| 572 | params![key, handle, serde_json::to_string(files).unwrap()], |
| 573 | )?; |
| 574 | Ok(()) |
| 575 | } |
| 576 | } |
| 577 |
| 578 | fn empty_record(id: &str) -> ChangeRecord { |
| 579 | ChangeRecord { |
| 580 | id: id.to_string(), |
| 581 | title: String::new(), |
| 582 | body: String::new(), |
| 583 | base_tree: tree::empty_id(), |
| 584 | base_version: None, |
| 585 | on_change: None, |
| 586 | after_change: None, |
| 587 | head_tree: None, |
| 588 | saves: 0, |
| 589 | state: "open".into(), |
| 590 | version: None, |
| 591 | author: String::new(), |
| 592 | owner: String::new(), |
| 593 | shared: Vec::new(), |
| 594 | holder: None, |
| 595 | updated: 0, |
| 596 | } |
| 597 | } |
| 598 |