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 | "#; |
| 34 |
| 35 | pub struct State { |
| 36 | pub db: Db, |
| 37 | pub store: Store, |
| 38 | } |
| 39 |
| 40 | #[derive(Debug)] |
| 41 | pub struct Problem { |
| 42 | pub status: u16, |
| 43 | pub code: &'static str, |
| 44 | pub message: String, |
| 45 | pub holder: Option<String>, |
| 46 | } |
| 47 |
| 48 | pub fn problem(status: u16, code: &'static str, message: impl Into<String>) -> Problem { |
| 49 | Problem { status, code, message: message.into(), holder: None } |
| 50 | } |
| 51 |
| 52 | impl From<anyhow::Error> for Problem { |
| 53 | fn from(e: anyhow::Error) -> Problem { |
| 54 | problem(500, "failed", format!("{e:#}")) |
| 55 | } |
| 56 | } |
| 57 |
| 58 | impl From<rusqlite::Error> for Problem { |
| 59 | fn from(e: rusqlite::Error) -> Problem { |
| 60 | problem(500, "failed", e.to_string()) |
| 61 | } |
| 62 | } |
| 63 |
| 64 | impl From<vcs_core::Error> for Problem { |
| 65 | fn from(e: vcs_core::Error) -> Problem { |
| 66 | problem(500, "failed", e.to_string()) |
| 67 | } |
| 68 | } |
| 69 |
| 70 | pub type Res<T> = Result<T, Problem>; |
| 71 |
| 72 | pub fn token_hash(token: &str) -> String { |
| 73 | let digest = Sha256::digest(token.as_bytes()); |
| 74 | digest.iter().map(|b| format!("{b:02x}")).collect() |
| 75 | } |
| 76 |
| 77 | fn now() -> i64 { |
| 78 | std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0) |
| 79 | } |
| 80 |
| 81 | pub struct Access { |
| 82 | pub user: Option<Me>, |
| 83 | pub can: Can, |
| 84 | } |
| 85 |
| 86 | impl State { |
| 87 | pub fn open(data: &Path) -> Result<State> { |
| 88 | std::fs::create_dir_all(data)?; |
| 89 | let conn = rusqlite::Connection::open(data.join("server.db"))?; |
| 90 | let db = Db::setup(conn)?; |
| 91 | db.conn.execute_batch(SCHEMA)?; |
| 92 | Ok(State { db, store: Store::open(&data.join("objects"))? }) |
| 93 | } |
| 94 |
| 95 | // Accounts. |
| 96 |
| 97 | pub fn add_user(&self, handle: &str, name: &str, email: &str) -> Result<String> { |
| 98 | self.db.conn.execute( |
| 99 | "INSERT OR REPLACE INTO s_users (handle, name, email, created) VALUES (?1, ?2, ?3, ?4)", |
| 100 | params![handle, name, email, now()], |
| 101 | )?; |
| 102 | let token = format!("vcs_{}", (0..40).map(|_| b"abcdefghijklmnopqrstuvwxyz0123456789"[rand::random_range(0..36)] as char).collect::<String>()); |
| 103 | self.db.conn.execute("INSERT INTO s_tokens (hash, handle, created) VALUES (?1, ?2, ?3)", params![token_hash(&token), handle, now()])?; |
| 104 | Ok(token) |
| 105 | } |
| 106 |
| 107 | pub fn add_project(&self, key: &str, owner: &str, public: bool) -> Result<()> { |
| 108 | if key.split('/').count() != 2 || key.split('/').any(|p| p.is_empty()) { |
| 109 | return Err(anyhow!("projects are OWNER/NAME")); |
| 110 | } |
| 111 | self.db.conn.execute("INSERT OR REPLACE INTO s_projects (key, public, created) VALUES (?1, ?2, ?3)", params![key, public as i64, now()])?; |
| 112 | self.add_member(key, owner, "owner") |
| 113 | } |
| 114 |
| 115 | /// A namespace is yours if it's your handle, or you claimed it first. |
| 116 | pub fn may_create_under(&self, owner: &str, handle: &str) -> Res<bool> { |
| 117 | if owner == handle { |
| 118 | return Ok(true); |
| 119 | } |
| 120 | let claimed: Option<String> = self.db.conn.query_row("SELECT handle FROM s_namespaces WHERE name = ?1", [owner], |r| r.get(0)).optional()?; |
| 121 | match claimed { |
| 122 | Some(h) => Ok(h == handle), |
| 123 | None => { |
| 124 | let taken = self.db.conn.query_row("SELECT 1 FROM s_users WHERE handle = ?1", [owner], |_| Ok(())).optional()?.is_some(); |
| 125 | if taken { |
| 126 | return Ok(false); |
| 127 | } |
| 128 | self.db.conn.execute("INSERT INTO s_namespaces (name, handle) VALUES (?1, ?2)", params![owner, handle])?; |
| 129 | Ok(true) |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 |
| 134 | pub fn add_member(&self, key: &str, handle: &str, role: &str) -> Result<()> { |
| 135 | self.db.conn.execute("INSERT OR REPLACE INTO s_members (project, handle, role) VALUES (?1, ?2, ?3)", params![key, handle, role])?; |
| 136 | Ok(()) |
| 137 | } |
| 138 |
| 139 | pub fn user_for_token(&self, token: &str) -> Res<Option<Me>> { |
| 140 | let handle: Option<String> = |
| 141 | self.db.conn.query_row("SELECT handle FROM s_tokens WHERE hash = ?1", [token_hash(token)], |r| r.get(0)).optional()?; |
| 142 | let Some(handle) = handle else { return Ok(None) }; |
| 143 | Ok(self |
| 144 | .db |
| 145 | .conn |
| 146 | .query_row("SELECT handle, name, email FROM s_users WHERE handle = ?1", [&handle], |r| { |
| 147 | Ok(Me { handle: r.get(0)?, name: r.get(1)?, email: r.get(2)? }) |
| 148 | }) |
| 149 | .optional()?) |
| 150 | } |
| 151 |
| 152 | pub fn project_exists(&self, key: &str) -> Res<Option<bool>> { |
| 153 | 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)) |
| 154 | } |
| 155 |
| 156 | pub fn access(&self, key: &str, user: Option<Me>) -> Res<Access> { |
| 157 | let public = self.project_exists(key)?.ok_or_else(|| problem(404, "not_found", format!("no project {key}")))?; |
| 158 | let role: Option<String> = match &user { |
| 159 | Some(u) => self |
| 160 | .db |
| 161 | .conn |
| 162 | .query_row("SELECT role FROM s_members WHERE project = ?1 AND handle = ?2", params![key, u.handle], |r| r.get(0)) |
| 163 | .optional()?, |
| 164 | None => None, |
| 165 | }; |
| 166 | let can = Can { |
| 167 | read: public || role.is_some(), |
| 168 | land: matches!(role.as_deref(), Some("owner") | Some("member")), |
| 169 | admin: role.as_deref() == Some("owner"), |
| 170 | }; |
| 171 | if !can.read { |
| 172 | // Private projects look like missing ones to outsiders. |
| 173 | return Err(problem(404, "not_found", format!("no project {key}"))); |
| 174 | } |
| 175 | Ok(Access { user, can }) |
| 176 | } |
| 177 |
| 178 | pub fn public(&self, key: &str) -> Res<bool> { |
| 179 | Ok(self.project_exists(key)?.unwrap_or(false)) |
| 180 | } |
| 181 |
| 182 | pub fn landers(&self, key: &str) -> Res<Vec<String>> { |
| 183 | let mut stmt = self.db.conn.prepare("SELECT handle FROM s_members WHERE project = ?1 AND role IN ('owner', 'member') ORDER BY handle")?; |
| 184 | let rows = stmt.query_map([key], |r| r.get::<_, String>(0))?; |
| 185 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 186 | } |
| 187 |
| 188 | // Private paths. |
| 189 |
| 190 | /// Paths `handle` can't see in the project (none for owners). |
| 191 | pub fn hidden_for(&self, key: &str, handle: Option<&str>) -> Res<Vec<String>> { |
| 192 | let rules = self.rules(key)?; |
| 193 | if rules.is_empty() { |
| 194 | return Ok(Vec::new()); |
| 195 | } |
| 196 | let role: Option<String> = match handle { |
| 197 | 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()?, |
| 198 | None => None, |
| 199 | }; |
| 200 | if role.as_deref() == Some("owner") { |
| 201 | return Ok(Vec::new()); |
| 202 | } |
| 203 | let mut hidden = Vec::new(); |
| 204 | for rule in rules { |
| 205 | let allowed = rule.who.iter().any(|w| match w.as_str() { |
| 206 | "everyone" => true, |
| 207 | "team" => role.is_some(), |
| 208 | other => handle.is_some_and(|h| other.trim_start_matches('@') == h), |
| 209 | }); |
| 210 | if !allowed { |
| 211 | hidden.push(rule.path); |
| 212 | } |
| 213 | } |
| 214 | Ok(hidden) |
| 215 | } |
| 216 |
| 217 | pub fn audience(hidden: &[String]) -> String { |
| 218 | if hidden.is_empty() { |
| 219 | return String::new(); |
| 220 | } |
| 221 | let mut sorted = hidden.to_vec(); |
| 222 | sorted.sort(); |
| 223 | token_hash(&sorted.join("\n")) |
| 224 | } |
| 225 |
| 226 | /// The tree someone with these hidden paths sees for `full`. |
| 227 | pub fn to_visible(&self, key: &str, full: &Id, hidden: &[String]) -> Res<Id> { |
| 228 | if hidden.is_empty() { |
| 229 | return Ok(*full); |
| 230 | } |
| 231 | let audience = Self::audience(hidden); |
| 232 | let known: Option<String> = self |
| 233 | .db |
| 234 | .conn |
| 235 | .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)) |
| 236 | .optional()?; |
| 237 | if let Some(v) = known.and_then(|t| Id::parse(&t)) { |
| 238 | return Ok(v); |
| 239 | } |
| 240 | let (visible, objects) = vcs_core::filter::filter(&self.store, full, hidden)?; |
| 241 | for o in &objects { |
| 242 | self.store.put(o)?; |
| 243 | } |
| 244 | self.remember(key, &audience, &visible, full)?; |
| 245 | Ok(visible) |
| 246 | } |
| 247 |
| 248 | fn remember(&self, key: &str, audience: &str, visible: &Id, full: &Id) -> Res<()> { |
| 249 | self.db.conn.execute( |
| 250 | "INSERT OR REPLACE INTO s_visible (project, key, visible, full) VALUES (?1, ?2, ?3, ?4)", |
| 251 | params![key, audience, visible.hex(), full.hex()], |
| 252 | )?; |
| 253 | Ok(()) |
| 254 | } |
| 255 |
| 256 | fn to_full(&self, key: &str, audience: &str, visible: &Id) -> Res<Option<Id>> { |
| 257 | let full: Option<String> = self |
| 258 | .db |
| 259 | .conn |
| 260 | .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)) |
| 261 | .optional()?; |
| 262 | Ok(full.and_then(|t| Id::parse(&t))) |
| 263 | } |
| 264 |
| 265 | fn is_version_tree(&self, key: &str, tree: &Id) -> Res<bool> { |
| 266 | Ok(self |
| 267 | .db |
| 268 | .conn |
| 269 | .query_row("SELECT 1 FROM s_roots WHERE project = ?1 AND tree = ?2 AND change = ''", params![key, tree.hex()], |_| Ok(())) |
| 270 | .optional()? |
| 271 | .is_some()) |
| 272 | } |
| 273 |
| 274 | // Main. |
| 275 |
| 276 | pub fn main(&self, key: &str) -> Res<Option<Version>> { |
| 277 | Ok(self.db.latest_version(key)?) |
| 278 | } |
| 279 |
| 280 | /// Main as `access` sees it: private paths left out, and versions that |
| 281 | /// only touched them shown as "a private change". |
| 282 | pub fn main_for(&self, key: &str, access: &Access) -> Res<Option<Version>> { |
| 283 | let Some(v) = self.main(key)? else { return Ok(None) }; |
| 284 | Ok(self.versions_for(key, access, vec![v])?.pop()) |
| 285 | } |
| 286 |
| 287 | pub fn versions_for(&self, key: &str, access: &Access, versions: Vec<Version>) -> Res<Vec<Version>> { |
| 288 | let hidden = self.hidden_for(key, access.user.as_ref().map(|u| u.handle.as_str()))?; |
| 289 | if hidden.is_empty() { |
| 290 | return Ok(versions); |
| 291 | } |
| 292 | let mut out = Vec::with_capacity(versions.len()); |
| 293 | for mut v in versions { |
| 294 | let full = v.tree; |
| 295 | v.tree = self.to_visible(key, &full, &hidden)?; |
| 296 | if v.n > 1 |
| 297 | && let Some(prev) = self.db.version(key, v.n - 1)? |
| 298 | && self.to_visible(key, &prev.tree, &hidden)? == v.tree |
| 299 | && prev.tree != full |
| 300 | { |
| 301 | v.title = "a private change".into(); |
| 302 | v.body = String::new(); |
| 303 | v.change = String::new(); |
| 304 | } |
| 305 | out.push(v); |
| 306 | } |
| 307 | Ok(out) |
| 308 | } |
| 309 |
| 310 | pub fn versions_since(&self, key: &str, since: u64, limit: i64) -> Res<Vec<Version>> { |
| 311 | let mut stmt = self.db.conn.prepare( |
| 312 | "SELECT n, tree, prev, change, author, time, title, body, git FROM versions WHERE project = ?1 AND n > ?2 ORDER BY n LIMIT ?3", |
| 313 | )?; |
| 314 | let rows = stmt.query_map(params![key, since as i64, limit], |row| { |
| 315 | let id = |i: usize| -> rusqlite::Result<Option<Id>> { Ok(row.get::<_, Option<String>>(i)?.and_then(|t| Id::parse(&t))) }; |
| 316 | Ok(Version { |
| 317 | n: row.get::<_, i64>(0)? as u64, |
| 318 | tree: id(1)?.unwrap_or(Id::ZERO), |
| 319 | prev: id(2)?, |
| 320 | change: row.get(3)?, |
| 321 | author: row.get(4)?, |
| 322 | time: row.get(5)?, |
| 323 | title: row.get(6)?, |
| 324 | body: row.get(7)?, |
| 325 | git: row.get(8)?, |
| 326 | }) |
| 327 | })?; |
| 328 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 329 | } |
| 330 |
| 331 | // Objects. |
| 332 |
| 333 | pub fn missing(&self, ids: &[Id]) -> Vec<Id> { |
| 334 | ids.iter().filter(|i| !self.store.has(i)).copied().collect() |
| 335 | } |
| 336 |
| 337 | fn add_root(&self, key: &str, tree: &Id, change: &str) -> Res<()> { |
| 338 | self.db.conn.execute("INSERT OR IGNORE INTO s_roots (project, tree, change) VALUES (?1, ?2, ?3)", params![key, tree.hex(), change])?; |
| 339 | Ok(()) |
| 340 | } |
| 341 |
| 342 | /// Whether `user` may read the objects under `tree`: it's a version's |
| 343 | /// tree, or a save of a change they can see. |
| 344 | pub fn may_read_tree(&self, key: &str, access: &Access, tree: &Id) -> Res<bool> { |
| 345 | let hidden = self.hidden_for(key, access.user.as_ref().map(|u| u.handle.as_str()))?; |
| 346 | if !hidden.is_empty() { |
| 347 | // Only trees made for this audience, or this person's own work. |
| 348 | let audience = Self::audience(&hidden); |
| 349 | if self.to_full(key, &audience, tree)?.is_some() { |
| 350 | return Ok(true); |
| 351 | } |
| 352 | let handle = access.user.as_ref().map(|u| u.handle.clone()).unwrap_or_default(); |
| 353 | 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")?; |
| 354 | let own = stmt.query_map(params![key, tree.hex(), handle], |r| r.get::<_, String>(0))?.next().is_some(); |
| 355 | return Ok(own || tree == &tree::empty_id()); |
| 356 | } |
| 357 | let mut stmt = self.db.conn.prepare("SELECT change FROM s_roots WHERE project = ?1 AND tree = ?2")?; |
| 358 | let changes: Vec<String> = stmt.query_map(params![key, tree.hex()], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 359 | if changes.iter().any(|c| c.is_empty()) { |
| 360 | return Ok(true); |
| 361 | } |
| 362 | for c in changes { |
| 363 | if let Some((record, _)) = self.change_row(key, &c)? |
| 364 | && self.visible(key, access, &record)? |
| 365 | { |
| 366 | return Ok(true); |
| 367 | } |
| 368 | } |
| 369 | Ok(tree == &tree::empty_id()) |
| 370 | } |
| 371 |
| 372 | /// Every object under `tree` that `have` doesn't share, as a bundle. |
| 373 | pub fn tree_bundle(&self, tree: &Id, have: Option<&Id>) -> Res<Vec<u8>> { |
| 374 | let mut ids = Vec::new(); |
| 375 | tree::new_since(&self.store, have, tree, &mut ids)?; |
| 376 | let mut all = Vec::with_capacity(ids.len()); |
| 377 | for id in ids { |
| 378 | all.extend(self.store.file_parts(&id)?); |
| 379 | } |
| 380 | Ok(self.store.bundle(&all)?) |
| 381 | } |
| 382 |
| 383 | // Changes. |
| 384 |
| 385 | fn change_row(&self, key: &str, id: &str) -> Res<Option<(ChangeRecord, Option<String>)>> { |
| 386 | let row: Option<(String, String, Option<String>, Option<String>)> = self |
| 387 | .db |
| 388 | .conn |
| 389 | .query_row("SELECT record, owner, holder, holder_label FROM s_changes WHERE project = ?1 AND id = ?2", params![key, id], |r| { |
| 390 | Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)) |
| 391 | }) |
| 392 | .optional()?; |
| 393 | Ok(row.map(|(record, owner, holder, label)| { |
| 394 | let mut c: ChangeRecord = serde_json::from_str(&record).unwrap_or_else(|_| empty_record(id)); |
| 395 | c.owner = owner; |
| 396 | c.holder = label; |
| 397 | (c, holder) |
| 398 | })) |
| 399 | } |
| 400 |
| 401 | pub fn visible(&self, key: &str, access: &Access, c: &ChangeRecord) -> Res<bool> { |
| 402 | let Some(user) = &access.user else { return Ok(false) }; |
| 403 | if c.owner == user.handle || access.can.admin { |
| 404 | return Ok(true); |
| 405 | } |
| 406 | if c.state == "waiting" && access.can.land { |
| 407 | return Ok(true); |
| 408 | } |
| 409 | let member = access.can.land || self.is_member(key, &user.handle)?; |
| 410 | Ok(c.shared.iter().any(|s| s.who == format!("@{}", user.handle) || s.who == user.handle || (s.who == "team" && member))) |
| 411 | } |
| 412 |
| 413 | fn is_member(&self, key: &str, handle: &str) -> Res<bool> { |
| 414 | Ok(self |
| 415 | .db |
| 416 | .conn |
| 417 | .query_row("SELECT 1 FROM s_members WHERE project = ?1 AND handle = ?2", params![key, handle], |_| Ok(())) |
| 418 | .optional()? |
| 419 | .is_some()) |
| 420 | } |
| 421 |
| 422 | fn may_edit(&self, access: &Access, c: &ChangeRecord) -> bool { |
| 423 | let Some(user) = &access.user else { return false }; |
| 424 | c.owner == user.handle || c.shared.iter().any(|s| s.edit && (s.who == format!("@{}", user.handle) || s.who == user.handle || s.who == "team")) |
| 425 | } |
| 426 |
| 427 | /// A change as a viewer sees it: trees made for their audience when the |
| 428 | /// change belongs to someone who sees more. |
| 429 | fn for_viewer(&self, key: &str, access: &Access, mut c: ChangeRecord) -> Res<ChangeRecord> { |
| 430 | let viewer = access.user.as_ref().map(|u| u.handle.as_str()); |
| 431 | if viewer == Some(c.owner.as_str()) { |
| 432 | return Ok(c); |
| 433 | } |
| 434 | let hidden = self.hidden_for(key, viewer)?; |
| 435 | if hidden.is_empty() { |
| 436 | return Ok(c); |
| 437 | } |
| 438 | c.base_tree = self.to_visible(key, &c.base_tree, &hidden)?; |
| 439 | if let Some(h) = c.head_tree { |
| 440 | c.head_tree = Some(self.to_visible(key, &h, &hidden)?); |
| 441 | } |
| 442 | Ok(c) |
| 443 | } |
| 444 |
| 445 | pub fn changes(&self, key: &str, access: &Access) -> Res<Vec<ChangeRecord>> { |
| 446 | 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")?; |
| 447 | let ids: Vec<String> = stmt.query_map([key], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 448 | let mut out = Vec::new(); |
| 449 | for id in ids { |
| 450 | if let Some((c, _)) = self.change_row(key, &id)? |
| 451 | && self.visible(key, access, &c)? |
| 452 | { |
| 453 | out.push(self.for_viewer(key, access, c)?); |
| 454 | } |
| 455 | } |
| 456 | Ok(out) |
| 457 | } |
| 458 |
| 459 | pub fn find_change(&self, key: &str, access: &Access, prefix: &str) -> Res<(ChangeRecord, Vec<SaveRecord>)> { |
| 460 | let mut stmt = self.db.conn.prepare("SELECT id FROM s_changes WHERE project = ?1 AND id LIKE ?2 || '%' LIMIT 10")?; |
| 461 | let ids: Vec<String> = stmt.query_map(params![key, prefix], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?; |
| 462 | let mut found = Vec::new(); |
| 463 | for id in ids { |
| 464 | if let Some((c, _)) = self.change_row(key, &id)? |
| 465 | && self.visible(key, access, &c)? |
| 466 | { |
| 467 | found.push(c); |
| 468 | } |
| 469 | } |
| 470 | match found.len() { |
| 471 | 0 => Err(problem(404, "not_found", format!("no change {prefix}"))), |
| 472 | 1 => { |
| 473 | let c = found.remove(0); |
| 474 | let saves = self.saves(key, &c.id)?; |
| 475 | Ok((self.for_viewer(key, access, c)?, saves)) |
| 476 | } |
| 477 | _ => Err(problem(400, "bad_usage", format!("{prefix} matches several changes"))), |
| 478 | } |
| 479 | } |
| 480 |
| 481 | fn saves(&self, key: &str, change: &str) -> Res<Vec<SaveRecord>> { |
| 482 | 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")?; |
| 483 | let rows = stmt.query_map(params![key, change], |r| { |
| 484 | let tree: String = r.get(1)?; |
| 485 | let base: String = r.get(2)?; |
| 486 | 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() }) |
| 487 | })?; |
| 488 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 489 | } |
| 490 |
| 491 | fn held_elsewhere(holder: &Option<String>, workspace: &str, label: Option<String>) -> Res<()> { |
| 492 | if let Some(h) = holder |
| 493 | && h != workspace |
| 494 | { |
| 495 | return Err(Problem { status: 409, code: "held_elsewhere", message: "another workspace took this change over".into(), holder: label }); |
| 496 | } |
| 497 | Ok(()) |
| 498 | } |
| 499 |
| 500 | pub fn put_change(&self, key: &str, access: &Access, mut record: ChangeRecord, workspace: &str, label: &str) -> Res<ChangeRecord> { |
| 501 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 502 | let existing = self.change_row(key, &record.id)?; |
| 503 | match &existing { |
| 504 | Some((old, holder)) => { |
| 505 | if !self.may_edit(access, old) { |
| 506 | // Landers may move a waiting change to landed; nobody else may write. |
| 507 | return Err(problem(403, "not_allowed", "you can't change someone else's change")); |
| 508 | } |
| 509 | Self::held_elsewhere(holder, workspace, old.holder.clone())?; |
| 510 | record.owner = old.owner.clone(); |
| 511 | record.shared = old.shared.clone(); |
| 512 | if old.state == "landed" { |
| 513 | record.state = "landed".into(); |
| 514 | record.version = old.version; |
| 515 | } |
| 516 | } |
| 517 | None => { |
| 518 | record.owner = user.handle.clone(); |
| 519 | record.shared = Vec::new(); |
| 520 | } |
| 521 | } |
| 522 | record.updated = now(); |
| 523 | let holder = match &existing { |
| 524 | Some((_, Some(h))) => Some(h.clone()), |
| 525 | _ => Some(workspace.to_string()), |
| 526 | }; |
| 527 | let label = match &existing { |
| 528 | Some((old, Some(_))) => old.holder.clone().unwrap_or_default(), |
| 529 | _ => label.to_string(), |
| 530 | }; |
| 531 | self.db.conn.execute( |
| 532 | "INSERT OR REPLACE INTO s_changes (project, id, owner, record, holder, holder_label, state, updated) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", |
| 533 | params![key, record.id, record.owner, serde_json::to_string(&record).unwrap(), holder, label, record.state, record.updated], |
| 534 | )?; |
| 535 | if let Some(t) = record.head_tree { |
| 536 | self.add_root(key, &t, &record.id)?; |
| 537 | } |
| 538 | self.add_root(key, &record.base_tree, &record.id)?; |
| 539 | record.holder = Some(label); |
| 540 | Ok(record) |
| 541 | } |
| 542 |
| 543 | pub fn hold(&self, key: &str, access: &Access, id: &str, workspace: &str, label: &str) -> Res<Option<String>> { |
| 544 | let (c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 545 | if !self.may_edit(access, &c) { |
| 546 | return Err(problem(403, "not_allowed", "you can't work on someone else's change unless they share it with --edit")); |
| 547 | } |
| 548 | let previous = if holder.as_deref() == Some(workspace) { None } else { c.holder.clone() }; |
| 549 | self.db.conn.execute( |
| 550 | "UPDATE s_changes SET holder = ?3, holder_label = ?4, updated = ?5 WHERE project = ?1 AND id = ?2", |
| 551 | params![key, id, workspace, label, now()], |
| 552 | )?; |
| 553 | Ok(previous) |
| 554 | } |
| 555 |
| 556 | pub fn add_save(&self, key: &str, access: &Access, id: &str, save: &SaveRecord) -> Res<()> { |
| 557 | let (c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 558 | if !self.may_edit(access, &c) { |
| 559 | return Err(problem(403, "not_allowed", "not your change")); |
| 560 | } |
| 561 | Self::held_elsewhere(&holder, &save.workspace, c.holder.clone())?; |
| 562 | if !self.store.has(&save.tree) { |
| 563 | return Err(problem(400, "bad_usage", "upload the save's objects first")); |
| 564 | } |
| 565 | self.db.conn.execute( |
| 566 | "INSERT OR REPLACE INTO s_saves (project, change, n, tree, base_tree, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 567 | params![key, id, save.n, save.tree.hex(), save.base_tree.hex(), save.at], |
| 568 | )?; |
| 569 | self.add_root(key, &save.tree, id)?; |
| 570 | Ok(()) |
| 571 | } |
| 572 |
| 573 | pub fn share(&self, key: &str, access: &Access, id: &str, who: &[String], edit: bool) -> Res<Vec<Share>> { |
| 574 | let (mut c, holder) = self.change_row(key, id)?.ok_or_else(|| problem(404, "not_found", format!("no change {id}")))?; |
| 575 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 576 | if c.owner != user.handle { |
| 577 | return Err(problem(403, "not_allowed", "only the change's owner can share it")); |
| 578 | } |
| 579 | if who.len() == 1 && who[0] == "me" { |
| 580 | c.shared.clear(); |
| 581 | } else { |
| 582 | for w in who { |
| 583 | c.shared.retain(|s| &s.who != w); |
| 584 | c.shared.push(Share { who: w.clone(), edit }); |
| 585 | } |
| 586 | } |
| 587 | let shared = c.shared.clone(); |
| 588 | self.db.conn.execute( |
| 589 | "UPDATE s_changes SET record = ?3 WHERE project = ?1 AND id = ?2", |
| 590 | params![key, id, serde_json::to_string(&c).unwrap()], |
| 591 | )?; |
| 592 | let _ = holder; |
| 593 | Ok(shared) |
| 594 | } |
| 595 |
| 596 | // Landing. |
| 597 |
| 598 | pub fn land(&self, key: &str, access: &Access, request: &LandRequest) -> Res<Landed> { |
| 599 | let user = access.user.as_ref().ok_or_else(|| problem(401, "not_logged_in", "sign in first"))?; |
| 600 | if !self.store.has(&request.tree) || !self.store.has(&request.base_tree) { |
| 601 | return Err(problem(400, "bad_usage", "upload the change's objects first")); |
| 602 | } |
| 603 | let existing = self.change_row(key, &request.change)?; |
| 604 | if !access.can.land { |
| 605 | // Ask the people who can. |
| 606 | let mut record = existing.map(|(c, _)| c).unwrap_or_else(|| empty_record(&request.change)); |
| 607 | if record.owner.is_empty() { |
| 608 | record.owner = user.handle.clone(); |
| 609 | } |
| 610 | if record.owner != user.handle { |
| 611 | return Err(problem(403, "not_allowed", "you can't land someone else's change")); |
| 612 | } |
| 613 | record.title = request.title.clone(); |
| 614 | record.body = request.body.clone(); |
| 615 | record.base_tree = request.base_tree; |
| 616 | record.head_tree = Some(request.tree); |
| 617 | record.author = request.author.clone(); |
| 618 | record.state = "waiting".into(); |
| 619 | record.updated = now(); |
| 620 | self.db.conn.execute( |
| 621 | "INSERT INTO s_changes (project, id, owner, record, holder, holder_label, state, updated) VALUES (?1, ?2, ?3, ?4, NULL, '', 'waiting', ?5) |
| 622 | ON CONFLICT(project, id) DO UPDATE SET record = excluded.record, state = 'waiting', updated = excluded.updated", |
| 623 | params![key, record.id, record.owner, serde_json::to_string(&record).unwrap(), record.updated], |
| 624 | )?; |
| 625 | self.add_root(key, &request.tree, &request.change)?; |
| 626 | self.add_root(key, &request.base_tree, &request.change)?; |
| 627 | 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() }); |
| 628 | } |
| 629 | if let Some((c, _)) = &existing |
| 630 | && c.owner != user.handle |
| 631 | && !self.visible(key, access, c)? |
| 632 | { |
| 633 | return Err(problem(403, "not_allowed", "you can't land a change you can't see")); |
| 634 | } |
| 635 | // Someone else's change lands as its owner made it, in the owner's view. |
| 636 | let (owner, base, tree) = match &existing { |
| 637 | Some((c, _)) if c.owner != user.handle => (c.owner.clone(), c.base_tree, c.head_tree.unwrap_or(c.base_tree)), |
| 638 | _ => (user.handle.clone(), request.base_tree, request.tree), |
| 639 | }; |
| 640 | let hidden = self.hidden_for(key, Some(&owner))?; |
| 641 | let mut full = request.clone(); |
| 642 | full.base_tree = base; |
| 643 | full.tree = tree; |
| 644 | if !hidden.is_empty() { |
| 645 | let audience = Self::audience(&hidden); |
| 646 | let full_base = match self.to_full(key, &audience, &base)? { |
| 647 | Some(f) => f, |
| 648 | None if self.is_version_tree(key, &base)? => base, |
| 649 | None => { |
| 650 | return Err(problem(409, "conflict", "this change started from something the host can't place; vcs sync, then land again")); |
| 651 | } |
| 652 | }; |
| 653 | match vcs_core::filter::graft(&self.store, &tree, &full_base, &hidden)? { |
| 654 | Ok((t, objects)) => { |
| 655 | for o in &objects { |
| 656 | self.store.put(o)?; |
| 657 | } |
| 658 | self.remember(key, &audience, &tree, &t)?; |
| 659 | full.base_tree = full_base; |
| 660 | full.tree = t; |
| 661 | } |
| 662 | Err(path) => return Err(problem(403, "not_allowed", format!("you can't change {path}: it's private"))), |
| 663 | } |
| 664 | } |
| 665 | let outcome = vcs_cli::host::Local.land_on(&self.db, &self.store, key, &full)?; |
| 666 | if let Landed::Landed { version } = &outcome { |
| 667 | self.add_root(key, &version.tree, "")?; |
| 668 | if let Some((mut c, holder)) = existing { |
| 669 | c.state = "landed".into(); |
| 670 | c.version = Some(version.n); |
| 671 | c.updated = now(); |
| 672 | self.db.conn.execute( |
| 673 | "UPDATE s_changes SET record = ?3, state = 'landed', updated = ?4 WHERE project = ?1 AND id = ?2", |
| 674 | params![key, c.id, serde_json::to_string(&c).unwrap(), c.updated], |
| 675 | )?; |
| 676 | let _ = holder; |
| 677 | } |
| 678 | } |
| 679 | Ok(outcome) |
| 680 | } |
| 681 |
| 682 | /// Takes a published project's history (only into an empty project). |
| 683 | pub fn import(&self, key: &str, access: &Access, versions: Vec<Version>) -> Res<Option<u64>> { |
| 684 | if !access.can.admin { |
| 685 | return Err(problem(403, "not_allowed", "only the project's owners can import history")); |
| 686 | } |
| 687 | if self.main(key)?.is_some() { |
| 688 | return Err(problem(409, "exists", "this project already has versions")); |
| 689 | } |
| 690 | for v in &versions { |
| 691 | if !self.store.has(&v.tree) { |
| 692 | return Err(problem(400, "bad_usage", format!("upload version {}'s objects first", v.n))); |
| 693 | } |
| 694 | } |
| 695 | let tx = self.db.conn.unchecked_transaction()?; |
| 696 | let mut prev = None; |
| 697 | let mut last = None; |
| 698 | for (i, v) in versions.into_iter().enumerate() { |
| 699 | let v = Version { n: i as u64 + 1, prev, ..v }; |
| 700 | self.db.put_version(key, &v)?; |
| 701 | self.add_root(key, &v.tree, "")?; |
| 702 | prev = Some(v.id(key)); |
| 703 | last = Some(v.n); |
| 704 | } |
| 705 | tx.commit()?; |
| 706 | Ok(last) |
| 707 | } |
| 708 |
| 709 | // Rules and mine. |
| 710 |
| 711 | pub fn rules(&self, key: &str) -> Res<Vec<Rule>> { |
| 712 | let mut stmt = self.db.conn.prepare("SELECT path, who FROM s_rules WHERE project = ?1 ORDER BY path")?; |
| 713 | let rows = stmt.query_map([key], |r| { |
| 714 | let who: String = r.get(1)?; |
| 715 | Ok(Rule { path: r.get(0)?, who: serde_json::from_str(&who).unwrap_or_default() }) |
| 716 | })?; |
| 717 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 718 | } |
| 719 |
| 720 | pub fn set_rule(&self, key: &str, access: &Access, rule: &Rule) -> Res<Vec<Rule>> { |
| 721 | if !access.can.admin { |
| 722 | return Err(problem(403, "not_allowed", "only the project's owners can set who sees a path")); |
| 723 | } |
| 724 | let path = rule.path.trim_matches('/'); |
| 725 | if rule.who.is_empty() || (rule.who.len() == 1 && rule.who[0] == "team") { |
| 726 | self.db.conn.execute("DELETE FROM s_rules WHERE project = ?1 AND path = ?2", params![key, path])?; |
| 727 | } else { |
| 728 | self.db.conn.execute( |
| 729 | "INSERT OR REPLACE INTO s_rules (project, path, who) VALUES (?1, ?2, ?3)", |
| 730 | params![key, path, serde_json::to_string(&rule.who).unwrap()], |
| 731 | )?; |
| 732 | } |
| 733 | self.rules(key) |
| 734 | } |
| 735 |
| 736 | pub fn mine(&self, key: &str, handle: &str) -> Res<Vec<MineFile>> { |
| 737 | let text: Option<String> = |
| 738 | self.db.conn.query_row("SELECT files FROM s_mine WHERE project = ?1 AND handle = ?2", params![key, handle], |r| r.get(0)).optional()?; |
| 739 | Ok(text.and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()) |
| 740 | } |
| 741 |
| 742 | pub fn set_mine(&self, key: &str, handle: &str, files: &[MineFile]) -> Res<()> { |
| 743 | for f in files { |
| 744 | if !self.store.has(&f.file) { |
| 745 | return Err(problem(400, "bad_usage", format!("upload {} first", f.path))); |
| 746 | } |
| 747 | } |
| 748 | self.db.conn.execute( |
| 749 | "INSERT OR REPLACE INTO s_mine (project, handle, files) VALUES (?1, ?2, ?3)", |
| 750 | params![key, handle, serde_json::to_string(files).unwrap()], |
| 751 | )?; |
| 752 | Ok(()) |
| 753 | } |
| 754 | } |
| 755 |
| 756 | fn empty_record(id: &str) -> ChangeRecord { |
| 757 | ChangeRecord { |
| 758 | id: id.to_string(), |
| 759 | title: String::new(), |
| 760 | body: String::new(), |
| 761 | base_tree: tree::empty_id(), |
| 762 | base_version: None, |
| 763 | on_change: None, |
| 764 | after_change: None, |
| 765 | head_tree: None, |
| 766 | saves: 0, |
| 767 | state: "open".into(), |
| 768 | version: None, |
| 769 | author: String::new(), |
| 770 | owner: String::new(), |
| 771 | shared: Vec::new(), |
| 772 | holder: None, |
| 773 | updated: 0, |
| 774 | } |
| 775 | } |
| 776 |