feat(drive): start implementation of drive

- add storage.drives
    - prepare migration phase
    - add created_by and updated_by on storage.folders
This commit is contained in:
Edouard Vanbelle
2026-06-18 13:29:41 +02:00
parent 77545aee05
commit eab7a609b9
43 changed files with 2434 additions and 154 deletions
@@ -0,0 +1,173 @@
//! PostgreSQL implementation of [`DriveRepository`].
//!
//! The repo deals only with the `storage.drives` table itself. Drive
//! membership lives in `storage.role_grants` (`resource_type='drive'`)
//! and is queried through the engine's existing grant paths;
//! `list_for_subjects` below resolves `role_grants` → `storage.drives`
//! via a single join.
//!
//! See `migrations/20260802000000_drives_schema_additive.sql` for the
//! schema and `docs/plan/drive.md` §3 / §15 for the locked design.
use std::sync::Arc;
use sqlx::{PgPool, Row, types::Uuid};
use crate::domain::entities::drive::{Drive, DriveKind};
use crate::domain::repositories::drive_repository::{
CreatePersonalDriveInput, DriveRepository, DriveRepositoryError,
};
pub struct DrivePgRepository {
pool: Arc<PgPool>,
}
impl DrivePgRepository {
pub fn new(pool: Arc<PgPool>) -> Self {
Self { pool }
}
fn map_sqlx_err(context: &'static str, e: sqlx::Error) -> DriveRepositoryError {
if let sqlx::Error::Database(ref dberr) = e
&& let Some(code) = dberr.code()
&& code.as_ref() == "23505"
{
// unique_violation. With drives, the only relevant unique is
// the partial index `idx_drives_default_for_user_unique` —
// surface the typed variant so the lifecycle hook can detect
// idempotent re-runs (D0-9 calls create_personal during
// user provisioning).
return DriveRepositoryError::DefaultDriveAlreadyExists(dberr.to_string());
}
DriveRepositoryError::StorageError(format!("{context}: {e}"))
}
fn row_to_drive(row: &sqlx::postgres::PgRow) -> Result<Drive, DriveRepositoryError> {
let kind_str: String = row.get("kind");
let kind = DriveKind::from_sql(&kind_str)?;
Ok(Drive {
id: row.get("id"),
name: row.get("name"),
kind,
default_for_user: row.get("default_for_user"),
quota_bytes: row.get("quota_bytes"),
used_bytes: row.get("used_bytes"),
policies: row.get("policies"),
created_at: row.get("created_at"),
updated_at: row.get("updated_at"),
})
}
}
#[async_trait::async_trait]
impl DriveRepository for DrivePgRepository {
async fn create_personal(
&self,
input: CreatePersonalDriveInput,
) -> Result<Drive, DriveRepositoryError> {
let default_for_user = if input.is_default {
Some(input.owner_id)
} else {
None
};
let row = sqlx::query(
r#"
INSERT INTO storage.drives
(name, kind, default_for_user, quota_bytes, policies)
VALUES ($1, 'personal', $2, $3, '{}'::jsonb)
RETURNING id, name, kind, default_for_user, quota_bytes,
used_bytes, policies, created_at, updated_at
"#,
)
.bind(&input.name)
.bind(default_for_user)
.bind(input.quota_bytes)
.fetch_one(self.pool.as_ref())
.await
.map_err(|e| Self::map_sqlx_err("create_personal", e))?;
Self::row_to_drive(&row)
}
async fn get_by_id(&self, id: Uuid) -> Result<Drive, DriveRepositoryError> {
let row = sqlx::query(
r#"
SELECT id, name, kind, default_for_user, quota_bytes,
used_bytes, policies, created_at, updated_at
FROM storage.drives
WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| Self::map_sqlx_err("get_by_id", e))?
.ok_or_else(|| DriveRepositoryError::NotFound(id.to_string()))?;
Self::row_to_drive(&row)
}
async fn find_default_for_user(&self, user_id: Uuid) -> Result<Drive, DriveRepositoryError> {
let row = sqlx::query(
r#"
SELECT id, name, kind, default_for_user, quota_bytes,
used_bytes, policies, created_at, updated_at
FROM storage.drives
WHERE default_for_user = $1
"#,
)
.bind(user_id)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| Self::map_sqlx_err("find_default_for_user", e))?
.ok_or_else(|| DriveRepositoryError::NotFound(user_id.to_string()))?;
Self::row_to_drive(&row)
}
async fn list_for_subjects(
&self,
subject_types: &[&str],
subject_ids: &[Uuid],
) -> Result<Vec<Drive>, DriveRepositoryError> {
// Joining `role_grants` → `storage.drives` returns every drive
// the expanded subject set can read. ORDER BY puts default
// drives first (so the picker UI doesn't need a follow-up
// sort), then alphabetical by name. DISTINCT collapses the
// case where a caller has multiple role_grants on the same
// drive (e.g. direct + group-mediated); a GROUP BY on the
// drive id sidesteps PostgreSQL's "ORDER BY expression must
// appear in select list" rule that `SELECT DISTINCT` imposes.
let rows = sqlx::query(
r#"
SELECT d.id, d.name, d.kind, d.default_for_user,
d.quota_bytes, d.used_bytes, d.policies,
d.created_at, d.updated_at
FROM storage.drives d
JOIN storage.role_grants g
ON g.resource_type = 'drive'
AND g.resource_id = d.id
WHERE g.subject_type = ANY($1)
AND g.subject_id = ANY($2)
AND (g.expires_at IS NULL OR g.expires_at > NOW())
GROUP BY d.id, d.name, d.kind, d.default_for_user,
d.quota_bytes, d.used_bytes, d.policies,
d.created_at, d.updated_at
ORDER BY (d.default_for_user IS NULL) ASC,
LOWER(d.name) ASC
"#,
)
.bind(
subject_types
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>(),
)
.bind(subject_ids)
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| Self::map_sqlx_err("list_for_subjects", e))?;
rows.iter().map(Self::row_to_drive).collect()
}
}
@@ -27,6 +27,10 @@ use crate::infrastructure::services::dedup_service::DedupService;
pub struct FileBlobWriteRepository {
pool: Arc<PgPool>,
dedup: Arc<DedupService>,
/// Retained on the struct after D0-8 inlined parent-folder lookups
/// directly via SQL; kept for now so D0's diff stays scoped to drive_id
/// + provenance plumbing. Slated for removal in a follow-up cleanup.
#[allow(dead_code)]
folder_repo: Arc<FolderDbRepository>,
/// Shared handle to `FileBlobReadRepository`'s file_id → blob_hash
/// cache. Content swaps and hard deletes invalidate the mapping here
@@ -128,10 +132,27 @@ impl FileBlobWriteRepository {
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("entity: {e}")))
}
/// Derive user_id from the parent folder, or error if folder_id is None.
async fn resolve_user_id(&self, folder_id: Option<&str>) -> Result<Uuid, DomainError> {
/// Derive `(user_id, drive_id)` from the parent folder. Both are
/// needed during the D0 dual-write window: `user_id` for the legacy
/// column (dropped in D7) and `drive_id` for the new owning-drive
/// reference.
async fn resolve_owner_and_drive(
&self,
folder_id: Option<&str>,
) -> Result<(Uuid, Uuid), DomainError> {
match folder_id {
Some(fid) => self.folder_repo.get_folder_user_id(fid).await,
Some(fid) => {
let row: Option<(Uuid, Uuid)> = sqlx::query_as::<_, (Uuid, Uuid)>(
"SELECT user_id, drive_id FROM storage.folders WHERE id = $1::uuid",
)
.bind(fid)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::internal_error("FileBlobWrite", format!("parent lookup: {e}"))
})?;
row.ok_or_else(|| DomainError::not_found("Folder", fid))
}
None => Err(DomainError::internal_error(
"FileBlobWrite",
"folder_id is required to determine file owner",
@@ -168,7 +189,8 @@ impl FileBlobWriteRepository {
)
UPDATE storage.files f
SET blob_hash = $1, size = $2,
updated_at = COALESCE(to_timestamp($4), NOW())
updated_at = COALESCE(to_timestamp($4), NOW()),
updated_by = f.user_id
FROM old
WHERE f.id = old.id
RETURNING old.blob_hash, EXTRACT(EPOCH FROM f.updated_at)::bigint
@@ -263,11 +285,14 @@ impl FileBlobWriteRepository {
sqlx::query_as::<_, (String, Uuid, String, i64, i64)>(
r#"
WITH parent AS (
SELECT id, user_id, path FROM storage.folders WHERE id = $2::uuid
SELECT id, user_id, drive_id, path FROM storage.folders WHERE id = $2::uuid
)
INSERT INTO storage.files
(name, folder_id, user_id, blob_hash, size, mime_type, category_order)
SELECT $1, parent.id, parent.user_id, $3, $4, $5, $6 FROM parent
(name, folder_id, user_id, drive_id, blob_hash, size,
mime_type, category_order, created_by, updated_by)
SELECT $1, parent.id, parent.user_id, parent.drive_id, $3, $4,
$5, $6, parent.user_id, parent.user_id
FROM parent
RETURNING id::text,
user_id,
(SELECT path FROM parent),
@@ -363,12 +388,19 @@ impl FileWritePort for FileBlobWriteRepository {
// If moving to a different folder, get the new user_id (must be same user)
let row = sqlx::query_as::<_, (String, String, Option<String>, i64, String, i64, i64)>(
r#"
UPDATE storage.files
SET folder_id = $1::uuid, updated_at = NOW()
WHERE id = $2::uuid AND NOT is_trashed
RETURNING id::text, name, folder_id::text, size, mime_type,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint
WITH dest AS (
SELECT user_id, drive_id FROM storage.folders WHERE id = $1::uuid
)
UPDATE storage.files f
SET folder_id = $1::uuid,
user_id = COALESCE((SELECT user_id FROM dest), f.user_id),
drive_id = COALESCE((SELECT drive_id FROM dest), f.drive_id),
updated_at = NOW(),
updated_by = COALESCE((SELECT user_id FROM dest), f.user_id)
WHERE f.id = $2::uuid AND NOT f.is_trashed
RETURNING f.id::text, f.name, f.folder_id::text, f.size, f.mime_type,
EXTRACT(EPOCH FROM f.created_at)::bigint,
EXTRACT(EPOCH FROM f.updated_at)::bigint
"#,
)
.bind(&target_folder_id)
@@ -424,16 +456,33 @@ impl FileWritePort for FileBlobWriteRepository {
FROM storage.files
WHERE id = $1::uuid AND NOT is_trashed
),
-- The destination folder may differ from the source's
-- folder (when $2 is set); derive drive_id from the
-- DESTINATION so cross-drive copies land in the right
-- drive. Files in personal drives only copy within the
-- same drive today, but the join makes the migration
-- future-proof for D2's cross-drive copy story.
dest_folder AS (
SELECT id, user_id, drive_id
FROM storage.folders
WHERE id = COALESCE($2::uuid,
(SELECT folder_id FROM src))
),
new_file AS (
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type, category_order)
SELECT COALESCE($3::text, name),
COALESCE($2::uuid, folder_id),
user_id,
blob_hash,
size,
mime_type,
category_order
FROM src
INSERT INTO storage.files
(name, folder_id, user_id, drive_id, blob_hash, size,
mime_type, category_order, created_by, updated_by)
SELECT COALESCE($3::text, src.name),
dest_folder.id,
dest_folder.user_id,
dest_folder.drive_id,
src.blob_hash,
src.size,
src.mime_type,
src.category_order,
dest_folder.user_id,
dest_folder.user_id
FROM src, dest_folder
RETURNING id::text, name, folder_id::text, size, mime_type,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint,
@@ -497,7 +546,7 @@ impl FileWritePort for FileBlobWriteRepository {
let row = sqlx::query_as::<_, (String, String, Option<String>, i64, String, i64, i64)>(
r#"
UPDATE storage.files
SET name = $1, updated_at = NOW()
SET name = $1, updated_at = NOW(), updated_by = user_id
WHERE id = $2::uuid AND NOT is_trashed
RETURNING id::text, name, folder_id::text, size, mime_type,
EXTRACT(EPOCH FROM created_at)::bigint,
@@ -580,7 +629,7 @@ impl FileWritePort for FileBlobWriteRepository {
content_type: String,
size: u64,
) -> Result<(File, PathBuf), DomainError> {
let user_id = self.resolve_user_id(folder_id.as_deref()).await?;
let (user_id, drive_id) = self.resolve_owner_and_drive(folder_id.as_deref()).await?;
// For deferred registration we use a placeholder hash.
// The write-behind cache will call update_file_content later.
@@ -589,8 +638,10 @@ impl FileWritePort for FileBlobWriteRepository {
let row = retry_on_deadlock("files.insert_deferred", || {
sqlx::query_as::<_, (String, i64, i64)>(
r#"
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type, category_order)
VALUES ($1, $2::uuid, $3, $4, $5, $6, $7)
INSERT INTO storage.files
(name, folder_id, user_id, drive_id, blob_hash, size,
mime_type, category_order, created_by, updated_by)
VALUES ($1, $2::uuid, $3, $4, $5, $6, $7, $8, $3, $3)
RETURNING id::text,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint
@@ -599,6 +650,7 @@ impl FileWritePort for FileBlobWriteRepository {
.bind(&name)
.bind(&folder_id)
.bind(user_id)
.bind(drive_id)
.bind(placeholder_hash)
.bind(size as i64)
.bind(&content_type)
@@ -638,7 +690,8 @@ impl FileWritePort for FileBlobWriteRepository {
SET is_trashed = TRUE,
trashed_at = NOW(),
original_folder_id = folder_id,
updated_at = NOW()
updated_at = NOW(),
updated_by = user_id
WHERE id = $1::uuid AND NOT is_trashed
"#,
)
@@ -665,7 +718,8 @@ impl FileWritePort for FileBlobWriteRepository {
trashed_at = NULL,
folder_id = COALESCE(original_folder_id, folder_id),
original_folder_id = NULL,
updated_at = NOW()
updated_at = NOW(),
updated_by = user_id
WHERE id = $1::uuid AND is_trashed
"#,
)
@@ -148,18 +148,19 @@ impl FolderRepository for FolderDbRepository {
name: String,
parent_id: Option<String>,
) -> Result<Folder, DomainError> {
// Derive user_id from parent folder. Root-level folders require the
// caller to have set up the home folder beforehand (done during user
// registration).
let user_id: Uuid = if let Some(ref pid) = parent_id {
sqlx::query_scalar::<_, Uuid>("SELECT user_id FROM storage.folders WHERE id = $1::uuid")
.bind(pid)
.fetch_optional(self.pool())
.await
.map_err(|e| {
DomainError::internal_error("FolderDb", format!("parent lookup: {e}"))
})?
.ok_or_else(|| DomainError::not_found("Folder", pid))?
// Derive (user_id, drive_id) from parent folder in one round-trip.
// Root-level folders require the caller to have set up the home
// drive beforehand (done during user registration via the
// lifecycle hook).
let (user_id, drive_id): (Uuid, Uuid) = if let Some(ref pid) = parent_id {
sqlx::query_as::<_, (Uuid, Uuid)>(
"SELECT user_id, drive_id FROM storage.folders WHERE id = $1::uuid",
)
.bind(pid)
.fetch_optional(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("parent lookup: {e}")))?
.ok_or_else(|| DomainError::not_found("Folder", pid))?
} else {
return Err(DomainError::internal_error(
"FolderDb",
@@ -167,10 +168,17 @@ impl FolderRepository for FolderDbRepository {
));
};
// D0 dual-write: drive_id alongside user_id (drops in D7), plus
// provenance columns created_by/updated_by. The repo derives
// created_by from user_id because the parent's owner is the
// creator on personal drives (the only kind that exists in D0).
// D2 plumbs the real caller_id when shared drives let other
// members write into a drive they don't own.
let row = sqlx::query_as::<_, (String, String, i64, i64, i64)>(
r#"
INSERT INTO storage.folders (name, parent_id, user_id)
VALUES ($1, $2::uuid, $3)
INSERT INTO storage.folders
(name, parent_id, user_id, drive_id, created_by, updated_by)
VALUES ($1, $2::uuid, $3, $4, $3, $3)
RETURNING id::text,
path,
EXTRACT(EPOCH FROM created_at)::bigint,
@@ -181,6 +189,7 @@ impl FolderRepository for FolderDbRepository {
.bind(&name)
.bind(&parent_id)
.bind(user_id)
.bind(drive_id)
.fetch_one(self.pool())
.await
.map_err(|e| {
@@ -489,7 +498,7 @@ impl FolderRepository for FolderDbRepository {
sqlx::query_as::<_, FolderRow>(
r#"
UPDATE storage.folders
SET name = $1, updated_at = NOW()
SET name = $1, updated_at = NOW(), updated_by = user_id
WHERE id = $2::uuid AND NOT is_trashed
RETURNING id::text, name, path, parent_id::text, user_id,
EXTRACT(EPOCH FROM created_at)::bigint,
@@ -528,7 +537,7 @@ impl FolderRepository for FolderDbRepository {
sqlx::query_as::<_, FolderRow>(
r#"
UPDATE storage.folders
SET parent_id = $1::uuid, updated_at = NOW()
SET parent_id = $1::uuid, updated_at = NOW(), updated_by = user_id
WHERE id = $2::uuid AND NOT is_trashed
RETURNING id::text, name, path, parent_id::text, user_id,
EXTRACT(EPOCH FROM created_at)::bigint,
@@ -634,7 +643,8 @@ impl FolderRepository for FolderDbRepository {
SET is_trashed = TRUE,
trashed_at = NOW(),
original_parent_id = parent_id,
updated_at = NOW()
updated_at = NOW(),
updated_by = user_id
WHERE id = $1::uuid AND NOT is_trashed
RETURNING id, lpath
),
@@ -642,7 +652,8 @@ impl FolderRepository for FolderDbRepository {
UPDATE storage.folders f
SET is_trashed = TRUE,
trashed_at = NOW(),
updated_at = NOW()
updated_at = NOW(),
updated_by = f.user_id
FROM trash_root tr
WHERE f.lpath <@ tr.lpath
AND f.id != tr.id
@@ -653,7 +664,8 @@ impl FolderRepository for FolderDbRepository {
UPDATE storage.files fi
SET is_trashed = TRUE,
trashed_at = NOW(),
updated_at = NOW()
updated_at = NOW(),
updated_by = fi.user_id
FROM trash_root tr
JOIN storage.folders f ON f.lpath <@ tr.lpath
WHERE fi.folder_id = f.id
@@ -698,7 +710,8 @@ impl FolderRepository for FolderDbRepository {
trashed_at = NULL,
parent_id = COALESCE(original_parent_id, parent_id),
original_parent_id = NULL,
updated_at = NOW()
updated_at = NOW(),
updated_by = user_id
WHERE id = $1::uuid AND is_trashed
RETURNING id, lpath
),
@@ -706,7 +719,8 @@ impl FolderRepository for FolderDbRepository {
UPDATE storage.folders f
SET is_trashed = FALSE,
trashed_at = NULL,
updated_at = NOW()
updated_at = NOW(),
updated_by = f.user_id
FROM restore_root rr
WHERE f.lpath <@ rr.lpath
AND f.id != rr.id
@@ -718,7 +732,8 @@ impl FolderRepository for FolderDbRepository {
UPDATE storage.files fi
SET is_trashed = FALSE,
trashed_at = NULL,
updated_at = NOW()
updated_at = NOW(),
updated_by = fi.user_id
FROM restore_root rr
JOIN storage.folders f ON f.lpath <@ rr.lpath
WHERE fi.folder_id = f.id
@@ -775,11 +790,24 @@ impl FolderRepository for FolderDbRepository {
Ok(())
}
async fn create_home_folder(&self, user_id: Uuid, name: String) -> Result<Folder, DomainError> {
async fn create_home_folder(
&self,
user_id: Uuid,
drive_id: Uuid,
name: String,
) -> Result<Folder, DomainError> {
// D0-9 keeps the wrapper-folder convention through the dual-write
// window: the lifecycle hook creates the personal drive AND a
// root folder under it. Wrapper retirement (the `My Folder -
// <username>/` prefix and the wrapper row itself) lands in M2b
// alongside the path rewrite. drive_id is required (M3 NOT NULL);
// created_by/updated_by are stamped from user_id for D0
// provenance.
let row = sqlx::query_as::<_, (String, String, i64, i64, i64)>(
r#"
INSERT INTO storage.folders (name, parent_id, user_id)
VALUES ($1, NULL, $2)
INSERT INTO storage.folders
(name, parent_id, user_id, drive_id, created_by, updated_by)
VALUES ($1, NULL, $2, $3, $2, $2)
ON CONFLICT DO NOTHING
RETURNING id::text,
path,
@@ -790,6 +818,7 @@ impl FolderRepository for FolderDbRepository {
)
.bind(&name)
.bind(user_id)
.bind(drive_id)
.fetch_optional(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("home folder: {e}")))?;
@@ -6,6 +6,7 @@ mod contact_group_pg_repository;
mod contact_persistence_dto;
mod contact_pg_repository;
mod device_code_pg_repository;
mod drive_pg_repository;
mod face_pg_repository;
mod favorites_pg_repository;
pub mod file_metadata_repository;
@@ -34,6 +35,7 @@ pub use contact_group_pg_repository::ContactGroupPgRepository;
pub use contact_persistence_dto::*;
pub use contact_pg_repository::ContactPgRepository;
pub use device_code_pg_repository::DeviceCodePgRepository;
pub use drive_pg_repository::DrivePgRepository;
pub use face_pg_repository::FacePgRepository;
pub use favorites_pg_repository::FavoritesPgRepository;
pub use file_blob_read_repository::FileBlobReadRepository;