Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions crates/copper-cloud/migrations/0015_sync_doc_revisions.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- Recoverable sync docs (copper-cloud 0.12.0). The server cannot read a doc, so its guard is
-- keeping what a write replaced: every accepted overwrite of a sync_docs row first copies the
-- old row here, sealed bytes as they were (same AAD "<user_id>:<domain>"). The last 20 per
-- (user, domain) are kept; a restore writes one back as a new version.
--
-- client_build: the optional X-Copper-Build header of the write (NULL for older clients).

ALTER TABLE sync_docs
ADD COLUMN client_build text CHECK (client_build IS NULL OR length(client_build) <= 64);

CREATE TABLE sync_doc_revisions (
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
domain text NOT NULL CHECK (length(domain) BETWEEN 1 AND 64),
version bigint NOT NULL CHECK (version > 0),
device_id uuid,
client_build text CHECK (client_build IS NULL OR length(client_build) <= 64),
-- When this version was written; replaced_at = when a newer write archived it.
updated_at timestamptz NOT NULL,
replaced_at timestamptz NOT NULL DEFAULT now(),
payload bytea NOT NULL,
payload_bytes integer NOT NULL CHECK (payload_bytes >= 0),
PRIMARY KEY (user_id, domain, version)
);
79 changes: 63 additions & 16 deletions crates/copper-cloud/src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use uuid::Uuid;
use copper_cloud_core::intelligence;

use crate::cli::{
AdminCommand, HistoryCommand, HistoryDeleteArgs, IntegrationCommand, IntelligenceCommand,
SsoCommand,
AdminCommand, DocsCommand, HistoryCommand, HistoryDeleteArgs, IntegrationCommand,
IntelligenceCommand, SsoCommand,
};
use copper_cloud_core::{agents, sso};

Expand Down Expand Up @@ -277,23 +277,56 @@ async fn dispatch(cfg: &Config, pool: &sqlx::PgPool, cmd: AdminCommand) -> anyho
println!("deleted {entries} of {email}");
}
}
AdminCommand::Docs(cmd) => docs_command(pool, cmd).await?,
AdminCommand::Addons(cmd) => crate::admin_addons_cli::dispatch(cfg, pool, cmd).await?,
}
Ok(())
}

/// `admin history delete`: resolves `--user` (email or id) and deletes or, with `--dry-run`,
/// counts their history rows matching the metadata filter (`--since` / `--until` /
/// `--device`; none = everything). Wholesale only: no payload is opened and no data key is
/// unwrapped. Returns the user's email and the count. Running servers do not learn about it
/// (no `history_deleted` event); Coppers see fewer rows on their next pull.
pub async fn history_delete(
pool: &sqlx::PgPool,
args: &HistoryDeleteArgs,
) -> anyhow::Result<(String, u64)> {
use copper_cloud_core::sync::{HistoryFilter, HistorySelection};
let filter = HistoryFilter::new(args.since, args.until, args.device).map_err(api)?;
let row: Option<(Uuid, String)> = match Uuid::parse_str(args.user.trim()) {
/// `admin docs …`: kept revisions of a user's sync doc (see `sync_doc_revisions`).
pub async fn docs_command(pool: &sqlx::PgPool, cmd: DocsCommand) -> anyhow::Result<()> {
use copper_cloud_core::sync::{self, Domain};
match cmd {
DocsCommand::Revisions { user, domain } => {
let (user_id, email) = resolve_user(pool, &user).await?;
let domain = Domain::parse(&domain).map_err(api)?.as_str();
let revs = sync::list_revisions(pool, user_id, &domain)
.await
.map_err(api)?;
if revs.is_empty() {
println!("no kept revisions of {domain} for {email}");
}
for r in revs {
println!(
"v{}\twritten {}\treplaced {}\t{} bytes\tdevice {}\tbuild {}",
r.version,
fmt_time(r.updated_at),
fmt_time(r.replaced_at),
r.bytes,
r.device_id.map_or_else(|| "-".into(), |d| d.to_string()),
r.client_build.as_deref().unwrap_or("-"),
);
}
}
DocsCommand::Restore {
user,
domain,
version,
} => {
let (user_id, email) = resolve_user(pool, &user).await?;
let domain = Domain::parse(&domain).map_err(api)?.as_str();
let (new, _) = sync::restore_revision(pool, user_id, &domain, version, None)
.await
.map_err(|e| anyhow::anyhow!("restoring v{version} of {domain}: {e}"))?;
println!("restored {domain} v{version} of {email} as v{new}");
}
}
Ok(())
}

/// `--user`: a user id or an email (case-insensitive) → (id, email).
async fn resolve_user(pool: &sqlx::PgPool, user: &str) -> anyhow::Result<(Uuid, String)> {
let row: Option<(Uuid, String)> = match Uuid::parse_str(user.trim()) {
Ok(id) => {
sqlx::query_as("SELECT id, email FROM users WHERE id = $1")
.bind(id)
Expand All @@ -302,12 +335,26 @@ pub async fn history_delete(
}
Err(_) => {
sqlx::query_as("SELECT id, email FROM users WHERE lower(email) = lower($1)")
.bind(args.user.trim())
.bind(user.trim())
.fetch_optional(pool)
.await?
}
};
let (user_id, email) = row.with_context(|| format!("no user {}", args.user))?;
row.with_context(|| format!("no user {user}"))
}

/// `admin history delete`: resolves `--user` (email or id) and deletes or, with `--dry-run`,
/// counts their history rows matching the metadata filter (`--since` / `--until` /
/// `--device`; none = everything). Wholesale only: no payload is opened and no data key is
/// unwrapped. Returns the user's email and the count. Running servers do not learn about it
/// (no `history_deleted` event); Coppers see fewer rows on their next pull.
pub async fn history_delete(
pool: &sqlx::PgPool,
args: &HistoryDeleteArgs,
) -> anyhow::Result<(String, u64)> {
use copper_cloud_core::sync::{HistoryFilter, HistorySelection};
let filter = HistoryFilter::new(args.since, args.until, args.device).map_err(api)?;
let (user_id, email) = resolve_user(pool, &args.user).await?;
let n = copper_cloud_core::sync::delete_history(
pool,
user_id,
Expand Down
6 changes: 5 additions & 1 deletion crates/copper-cloud/src/admin_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1165,11 +1165,15 @@ async fn delete_device(
if users.is_empty() {
return Err(ApiError::NotFound);
}
sqlx::query("DELETE FROM sync_docs WHERE domain = $1 AND user_id = ANY($2)")
for table in ["sync_docs", "sync_doc_revisions"] {
sqlx::query(&format!(
"DELETE FROM {table} WHERE domain = $1 AND user_id = ANY($2)"
))
.bind(copper_cloud_core::sync::tabs_domain(id))
.bind(&users)
.execute(&mut *tx)
.await?;
}
let detail = if let [user] = users.as_slice() {
json!({ "user_id": user })
} else {
Expand Down
27 changes: 27 additions & 0 deletions crates/copper-cloud/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,9 @@ pub enum AdminCommand {
/// A user's synced browsing history.
#[command(subcommand)]
History(HistoryCommand),
/// A user's synced docs (spaces, settings, bookmarks, tabs:<device>): kept revisions.
#[command(subcommand)]
Docs(DocsCommand),
/// Company single sign-on (Google or OIDC) for Coppers.
#[command(subcommand)]
Sso(SsoCommand),
Expand Down Expand Up @@ -449,6 +452,30 @@ pub enum HistoryCommand {
Delete(HistoryDeleteArgs),
}

#[derive(Subcommand, Debug)]
pub enum DocsCommand {
/// List the kept revisions of one doc, newest first (metadata only; never opens a doc).
Revisions {
/// The user: email or user id.
#[arg(long, value_name = "EMAIL|UUID")]
user: String,
/// spaces, settings, bookmarks or tabs:<device_id>.
#[arg(long)]
domain: String,
},
/// Write a kept revision back as the doc's new version. Running servers send no event;
/// Coppers pick it up on their next pull.
Restore {
#[arg(long, value_name = "EMAIL|UUID")]
user: String,
#[arg(long)]
domain: String,
/// The revision's version (from `admin docs revisions`).
#[arg(long)]
version: i64,
},
}

#[derive(Args, Debug, Clone)]
pub struct HistoryDeleteArgs {
/// The user: email or user id.
Expand Down
Loading
Loading