Files
appks/service/workspace/core.rs
T
zhenyi dca717be10 refactor(workspace): pass workspace object instead of id to service methods
- Replace workspace_id parameter with Workspace object reference in all workspace service methods
- Remove redundant find_workspace_by_id calls that were duplicated in each method
- Update all method signatures across approval, audit, billing, branding, core, settings and stats modules
- Modify SQL queries to bind ws.id instead of separate workspace_id parameter
- Add Workspace import to all affected modules
- Adjust method calls in API handlers to pass workspace object instead of id
- Consolidate workspace retrieval logic to single location per operation flow
2026-06-07 18:44:01 +08:00

613 lines
20 KiB
Rust

use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::{Role, Visibility};
use crate::models::workspaces::Workspace;
use crate::service::WorkspaceService;
use crate::session::Session;
use super::util::{clamp_limit_offset, ensure_affected, merge_optional_text, parse_enum};
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct CreateWorkspaceParams {
pub name: String,
pub description: Option<String>,
pub visibility: Option<String>,
}
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct UpdateWorkspaceParams {
pub name: Option<String>,
pub description: Option<String>,
pub visibility: Option<String>,
pub default_role: Option<String>,
}
impl WorkspaceService {
pub async fn workspace_list(
&self,
ctx: &Session,
limit: i64,
offset: i64,
) -> Result<Vec<Workspace>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let (limit, offset) = clamp_limit_offset(limit, offset);
sqlx::query_as::<_, Workspace>(
"SELECT id, owner_id, name, description, avatar_url, visibility, plan, status, \
default_role, is_personal, archived_at, created_at, updated_at, deleted_at \
FROM workspace WHERE deleted_at IS NULL AND (owner_id = $1 OR id IN \
(SELECT workspace_id FROM workspace_member WHERE user_id = $1 AND status = 'active') \
OR visibility = 'public') \
ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(user_uid)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)
}
pub async fn workspace_get(
&self,
ctx: &Session,
ws: &Workspace,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_readable(user_uid, &ws).await?;
Ok(ws.clone())
}
pub async fn workspace_create(
&self,
ctx: &Session,
params: CreateWorkspaceParams,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
let name = params.name.trim().to_string();
if name.is_empty() {
return Err(AppError::BadRequest("name is required".into()));
}
let visibility = match params.visibility {
Some(ref v) => parse_enum(
Some(v.clone()),
Visibility::Internal,
Visibility::Unknown,
"visibility",
)?,
None => Visibility::Internal,
};
let now = chrono::Utc::now();
let workspace_id = Uuid::now_v7();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query("SET LOCAL app.current_user_id = $1")
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let ws = sqlx::query_as::<_, Workspace>(
"INSERT INTO workspace (id, owner_id, name, description, visibility, plan, status, \
default_role, is_personal, created_at, updated_at) \
VALUES ($1, $2, $3, $4, $5, 'free', 'active', 'member', false, $6, $6) \
RETURNING id, owner_id, name, description, avatar_url, visibility, plan, status, \
default_role, is_personal, archived_at, created_at, updated_at, deleted_at",
)
.bind(workspace_id)
.bind(user_uid)
.bind(&name)
.bind(params.description.as_deref())
.bind(visibility)
.bind(now)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"INSERT INTO workspace_member (id, workspace_id, user_id, role, status, joined_at, created_at, updated_at) \
VALUES ($1, $2, $3, 'owner', 'active', $4, $4, $4)",
)
.bind(Uuid::now_v7())
.bind(workspace_id)
.bind(user_uid)
.bind(now)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"INSERT INTO workspace_settings (workspace_id, allow_public_repos, allow_member_invites, \
require_two_factor, default_repo_visibility, default_branch_name, \
issue_tracking_enabled, pull_requests_enabled, wiki_enabled, created_at, updated_at) \
VALUES ($1, true, true, false, 'private', 'main', true, true, true, $2, $2)",
)
.bind(workspace_id)
.bind(now)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"INSERT INTO workspace_stats (workspace_id, members_count, repos_count, issues_count, \
pull_requests_count, storage_bytes, bandwidth_bytes, build_minutes_used, updated_at) \
VALUES ($1, 1, 0, 0, 0, 0, 0, 0, $2)",
)
.bind(workspace_id)
.bind(now)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"INSERT INTO workspace_billing (workspace_id, plan, status, seats, created_at, updated_at) \
VALUES ($1, 'free', 'active', 1, $2, $2)",
)
.bind(workspace_id)
.bind(now)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"INSERT INTO workspace_custom_branding (workspace_id, enabled, created_at, updated_at) \
VALUES ($1, false, $2, $2)",
)
.bind(workspace_id)
.bind(now)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(ws)
}
pub async fn workspace_update(
&self,
ctx: &Session,
ws: &Workspace,
params: UpdateWorkspaceParams,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let name =
merge_optional_text(params.name, Some(ws.name.clone())).unwrap_or(ws.name.clone());
let description = merge_optional_text(params.description, ws.description.clone());
let visibility = parse_enum(
params.visibility,
ws.visibility,
Visibility::Unknown,
"visibility",
)?;
let default_role = match params.default_role {
Some(ref v) => parse_enum(
Some(v.clone()),
ws.default_role.parse().unwrap_or(Role::Member),
Role::Unknown,
"default_role",
)?,
None => ws.default_role.parse().unwrap_or(Role::Member),
};
match default_role {
Role::Member | Role::Contributor | Role::Viewer | Role::Guest => {}
_ => {
return Err(AppError::BadRequest(
"default_role must be one of: member, contributor, viewer, guest".into(),
));
}
}
let now = chrono::Utc::now();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query("SET LOCAL app.current_user_id = $1")
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let result = sqlx::query_as::<_, Workspace>(
"UPDATE workspace SET name = $1, description = $2, visibility = $3, default_role = $4, \
updated_at = $5 WHERE id = $6 AND deleted_at IS NULL \
RETURNING id, owner_id, name, description, avatar_url, visibility, plan, status, \
default_role, is_personal, archived_at, created_at, updated_at, deleted_at",
)
.bind(&name)
.bind(&description)
.bind(visibility)
.bind(default_role.to_string())
.bind(now)
.bind(ws.id)
.fetch_optional(&mut *txn)
.await
.map_err(AppError::Database)?
.ok_or(AppError::NotFound("workspace not found".into()))?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(result)
}
pub async fn workspace_archive(&self, ctx: &Session, ws: &Workspace) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
let now = chrono::Utc::now();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query("SET LOCAL app.current_user_id = $1")
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let result = sqlx::query(
"UPDATE workspace SET status = 'archived', archived_at = $1, updated_at = $1 \
WHERE id = $2 AND deleted_at IS NULL AND status <> 'archived'",
)
.bind(now)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
ensure_affected(
result.rows_affected(),
"workspace not found or already archived",
)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(())
}
pub async fn workspace_unarchive(&self, ctx: &Session, ws: &Workspace) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
let now = chrono::Utc::now();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query("SET LOCAL app.current_user_id = $1")
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let result = sqlx::query(
"UPDATE workspace SET status = 'active', archived_at = NULL, updated_at = $1 \
WHERE id = $2 AND deleted_at IS NULL AND status = 'archived'",
)
.bind(now)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
ensure_affected(
result.rows_affected(),
"workspace not found or not archived",
)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(())
}
pub async fn workspace_delete(&self, ctx: &Session, ws: &Workspace) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
let now = chrono::Utc::now();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query("SET LOCAL app.current_user_id = $1")
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let result = sqlx::query(
"UPDATE workspace SET deleted_at = $1, status = 'deleted', updated_at = $1 \
WHERE id = $2 AND deleted_at IS NULL",
)
.bind(now)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
ensure_affected(result.rows_affected(), "workspace not found")?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(())
}
pub async fn workspace_transfer_owner(
&self,
ctx: &Session,
ws: &Workspace,
new_owner_id: Uuid,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner)
.await?;
if new_owner_id == ws.owner_id {
return Err(AppError::BadRequest(
"new owner must be different from current owner".into(),
));
}
let is_member = sqlx::query_scalar::<_, bool>(
"SELECT EXISTS(SELECT 1 FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active')",
)
.bind(ws.id)
.bind(new_owner_id)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
if !is_member {
return Err(AppError::BadRequest(
"new owner must be an active member".into(),
));
}
let now = chrono::Utc::now();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query("SET LOCAL app.current_user_id = $1")
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"UPDATE workspace_member SET role = 'owner', updated_at = $1 \
WHERE workspace_id = $2 AND user_id = $3",
)
.bind(now)
.bind(ws.id)
.bind(new_owner_id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
sqlx::query(
"UPDATE workspace_member SET role = 'admin', updated_at = $1 \
WHERE workspace_id = $2 AND user_id = $3",
)
.bind(now)
.bind(ws.id)
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let result = sqlx::query_as::<_, Workspace>(
"UPDATE workspace SET owner_id = $1, updated_at = $2 WHERE id = $3 AND deleted_at IS NULL \
RETURNING id, owner_id, name, description, avatar_url, visibility, plan, status, \
default_role, is_personal, archived_at, created_at, updated_at, deleted_at",
)
.bind(new_owner_id)
.bind(now)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(result)
}
pub async fn workspace_upload_avatar(
&self,
ctx: &Session,
ws: &Workspace,
data: Vec<u8>,
content_type: Option<String>,
file_name: Option<String>,
) -> Result<Workspace, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
.await?;
let ext =
crate::service::util::avatar_extension(content_type.as_deref(), file_name.as_deref())?;
crate::service::util::validate_avatar_size(data.len(), 5 * 1024 * 1024)?;
let old_avatar_url = ws.avatar_url.clone();
let storage_key = format!("workspaces/{}/avatar/{}.{}", ws.id, Uuid::now_v7(), ext);
self.ctx.storage.put(&storage_key, data).await?;
let avatar_url = self.ctx.storage.public_url(&storage_key).ok_or_else(|| {
AppError::Config("APP_S3_PUBLIC_URL is required for avatar upload".into())
})?;
let now = chrono::Utc::now();
let mut txn = self
.ctx
.db
.writer()
.begin()
.await
.map_err(|_| AppError::TxnError)?;
sqlx::query("SET LOCAL app.current_user_id = $1")
.bind(user_uid)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
let result = sqlx::query_as::<_, Workspace>(
"UPDATE workspace SET avatar_url = $1, updated_at = $2 \
WHERE id = $3 AND deleted_at IS NULL \
RETURNING id, owner_id, name, description, avatar_url, visibility, plan, status, \
default_role, is_personal, archived_at, created_at, updated_at, deleted_at",
)
.bind(&avatar_url)
.bind(now)
.bind(ws.id)
.fetch_optional(&mut *txn)
.await
.map_err(AppError::Database)?;
if let Some(updated) = result {
txn.commit().await.map_err(|_| AppError::TxnError)?;
if let Some(old_url) = old_avatar_url
&& let Some(old_key) = extract_storage_key_from_url(&old_url)
{
let _ = self.ctx.storage.delete(&old_key).await;
}
Ok(updated)
} else {
let _ = self.ctx.storage.delete(&storage_key).await;
Err(AppError::NotFound("workspace not found".into()))
}
}
pub(crate) async fn find_workspace_by_id(
&self,
workspace_id: Uuid,
) -> Result<Workspace, AppError> {
sqlx::query_as::<_, Workspace>(
"SELECT id, owner_id, name, description, avatar_url, visibility, plan, status, \
default_role, is_personal, archived_at, created_at, updated_at, deleted_at \
FROM workspace WHERE id = $1 AND deleted_at IS NULL",
)
.bind(workspace_id)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
.ok_or(AppError::NotFound("workspace not found".into()))
}
pub(crate) async fn find_workspace_by_name(&self, name: &str) -> Result<Workspace, AppError> {
sqlx::query_as::<_, Workspace>(
"SELECT id, owner_id, name, description, avatar_url, visibility, plan, status, \
default_role, is_personal, archived_at, created_at, updated_at, deleted_at \
FROM workspace WHERE lower(name) = lower($1) AND deleted_at IS NULL",
)
.bind(name)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
.ok_or(AppError::NotFound("workspace not found".into()))
}
pub async fn workspace_user_role(
&self,
user_uid: Uuid,
ws: &Workspace,
) -> Result<Option<Role>, AppError> {
let role_str: Option<String> = sqlx::query_scalar(
"SELECT role FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active'",
)
.bind(ws.id)
.bind(user_uid)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
match role_str {
Some(r) => Ok(Some(r.parse().unwrap_or(Role::Unknown))),
None => {
if ws.owner_id == user_uid {
return Ok(Some(Role::Owner));
}
Ok(None)
}
}
}
pub async fn ensure_workspace_readable(
&self,
user_uid: Uuid,
ws: &Workspace,
) -> Result<(), AppError> {
if ws.owner_id == user_uid {
return Ok(());
}
let is_member = sqlx::query_scalar::<_, bool>(
"SELECT EXISTS(SELECT 1 FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active')",
)
.bind(ws.id)
.bind(user_uid)
.fetch_one(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
if is_member {
return Ok(());
}
match ws.visibility {
Visibility::Public | Visibility::Internal => Ok(()),
_ => Err(AppError::Unauthorized),
}
}
pub async fn ensure_workspace_role_at_least(
&self,
user_uid: Uuid,
ws: &Workspace,
min_role: Role,
) -> Result<Role, AppError> {
if ws.owner_id == user_uid {
return Ok(Role::Owner);
}
let role_str: Option<String> = sqlx::query_scalar(
"SELECT role FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active'",
)
.bind(ws.id)
.bind(user_uid)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?;
let role = role_str
.and_then(|r| r.parse::<Role>().ok())
.unwrap_or(Role::Unknown);
if super::util::role_level(role) < super::util::role_level(min_role) {
return Err(AppError::Unauthorized);
}
Ok(role)
}
}
use crate::service::util::extract_storage_key_from_url;