7 Commits

9 changed files with 436 additions and 4 deletions
+4 -1
View File
@@ -16,4 +16,7 @@ pub use organization::{Organization, OrganizationId, OrganizationMembership, Org
pub use rich_text::{Inline, RichText};
pub use tree::{DocumentTree, TreeError};
pub use user::{User, UserId};
pub use workspace::{Workspace, WorkspaceId};
pub use workspace::{
Workspace, WorkspaceAccess, WorkspaceAccessError, WorkspaceId, WorkspaceInvitation,
WorkspaceMembership, WorkspaceRole,
};
+15
View File
@@ -2,6 +2,7 @@ use super::contextualize::Contextualize;
use super::{
id::{IdError, validate_id},
user::UserId,
workspace::{Workspace, WorkspaceAccess, WorkspaceAccessError, WorkspaceId},
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
@@ -42,6 +43,20 @@ pub struct OrganizationMembership {
pub role: OrganizationRole,
}
impl Organization {
pub fn create_workspace(&self, id: WorkspaceId, name: impl Into<String>) -> Workspace {
Workspace::owned_by(id, name, self.id.clone())
}
pub fn set_workspace_access(
&self,
workspace: &mut Workspace,
access: WorkspaceAccess,
) -> Result<(), WorkspaceAccessError> {
workspace.set_organization_access(&self.id, access)
}
}
impl Contextualize for Organization {
fn render_context(&self) -> String {
format!("Organization: {}", self.name)
+184 -3
View File
@@ -1,7 +1,12 @@
use thiserror::Error;
use super::contextualize::Contextualize;
use super::{
Document,
id::{IdError, validate_id},
organization::OrganizationId,
organization::{OrganizationId, OrganizationMembership},
tree::{DocumentTree, TreeError},
user::UserId,
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
@@ -21,12 +26,188 @@ impl WorkspaceId {
}
}
/// A workspace belongs to one organization and contains documents.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkspaceRole {
Owner,
Admin,
Editor,
Viewer,
}
/// Controls which roles can be granted to people outside the owning organization.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum WorkspaceAccess {
#[default]
MembersOnly,
ExternalViewers,
ExternalEditors,
}
impl WorkspaceAccess {
fn allows_external(self, role: WorkspaceRole) -> bool {
matches!(
(self, role),
(
Self::ExternalViewers | Self::ExternalEditors,
WorkspaceRole::Viewer
) | (Self::ExternalEditors, WorkspaceRole::Editor)
)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct OrganizationWorkspace {
id: OrganizationId,
access: WorkspaceAccess,
}
/// A workspace contains documents and may be owned by an organization.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Workspace {
pub id: WorkspaceId,
pub organization_id: OrganizationId,
pub name: String,
organization: Option<OrganizationWorkspace>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceInvitation {
workspace_id: WorkspaceId,
invitee: UserId,
role: WorkspaceRole,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceMembership {
pub workspace_id: WorkspaceId,
pub user_id: UserId,
pub role: WorkspaceRole,
}
#[derive(Debug, Error, Eq, PartialEq)]
pub enum WorkspaceAccessError {
#[error("the workspace does not belong to this organization")]
OrganizationMismatch,
#[error("the workspace access policy does not allow this role for the invitee")]
RoleNotAllowed,
#[error("the invitation is for a different workspace or user")]
InvitationMismatch,
}
impl Workspace {
pub fn independent(id: WorkspaceId, name: impl Into<String>) -> Self {
Self {
id,
name: name.into(),
organization: None,
}
}
pub(super) fn owned_by(
id: WorkspaceId,
name: impl Into<String>,
organization_id: OrganizationId,
) -> Self {
Self {
id,
name: name.into(),
organization: Some(OrganizationWorkspace {
id: organization_id,
access: WorkspaceAccess::default(),
}),
}
}
pub fn organization_id(&self) -> Option<&OrganizationId> {
self.organization
.as_ref()
.map(|organization| &organization.id)
}
pub fn organization_access(&self) -> Option<WorkspaceAccess> {
self.organization
.as_ref()
.map(|organization| organization.access)
}
pub(super) fn set_organization_access(
&mut self,
organization_id: &OrganizationId,
access: WorkspaceAccess,
) -> Result<(), WorkspaceAccessError> {
let organization = self
.organization
.as_mut()
.filter(|organization| &organization.id == organization_id)
.ok_or(WorkspaceAccessError::OrganizationMismatch)?;
organization.access = access;
Ok(())
}
/// Evaluates the invitee against the current policy. The caller supplies the
/// invitee's current membership in the owning organization, if any.
pub fn invite(
&self,
invitee: UserId,
role: WorkspaceRole,
organization_membership: Option<&OrganizationMembership>,
) -> Result<WorkspaceInvitation, WorkspaceAccessError> {
self.check_access(&invitee, role, organization_membership)?;
Ok(WorkspaceInvitation {
workspace_id: self.id.clone(),
invitee,
role,
})
}
/// Rechecks policy and membership so a pending invitation cannot preserve
/// privileges after either has changed.
pub fn accept_invitation(
&self,
user: &UserId,
invitation: &WorkspaceInvitation,
organization_membership: Option<&OrganizationMembership>,
) -> Result<WorkspaceMembership, WorkspaceAccessError> {
if invitation.workspace_id != self.id || &invitation.invitee != user {
return Err(WorkspaceAccessError::InvitationMismatch);
}
self.check_access(user, invitation.role, organization_membership)?;
Ok(WorkspaceMembership {
workspace_id: self.id.clone(),
user_id: user.clone(),
role: invitation.role,
})
}
/// Assembles an ordered tree of document nodes in this workspace.
pub fn document_tree(
&self,
root: Document,
descendants: impl IntoIterator<Item = Document>,
) -> Result<DocumentTree, TreeError> {
if root.key.workspace != self.id {
return Err(TreeError::WorkspaceMismatch);
}
DocumentTree::new(root, descendants)
}
fn check_access(
&self,
user: &UserId,
role: WorkspaceRole,
membership: Option<&OrganizationMembership>,
) -> Result<(), WorkspaceAccessError> {
let Some(organization) = &self.organization else {
return Ok(());
};
let internal = membership.is_some_and(|membership| {
membership.organization_id == organization.id && &membership.user_id == user
});
if internal || organization.access.allows_external(role) {
Ok(())
} else {
Err(WorkspaceAccessError::RoleNotAllowed)
}
}
}
impl Contextualize for Workspace {
+174
View File
@@ -0,0 +1,174 @@
use documents::{
Document, DocumentContent, DocumentId, DocumentKey, Organization, OrganizationId,
OrganizationMembership, OrganizationRole, TreeError, UserId, Workspace, WorkspaceAccess,
WorkspaceAccessError, WorkspaceId, WorkspaceRole,
};
fn organization(id: &str) -> Organization {
Organization {
id: OrganizationId::new(id).unwrap(),
name: id.into(),
}
}
fn member(organization: &Organization, user: &UserId) -> OrganizationMembership {
OrganizationMembership {
organization_id: organization.id.clone(),
user_id: user.clone(),
role: OrganizationRole::Member,
}
}
fn workspace_id(value: &str) -> WorkspaceId {
WorkspaceId::new(value).unwrap()
}
#[test]
fn organization_controls_the_roles_available_to_external_users() {
use WorkspaceAccess::{ExternalEditors, ExternalViewers, MembersOnly};
use WorkspaceRole::{Admin, Editor, Owner, Viewer};
let organization = organization("org");
let mut workspace = organization.create_workspace(workspace_id("workspace"), "Workspace");
let outside = UserId::new("outside").unwrap();
let inside = UserId::new("inside").unwrap();
let membership = member(&organization, &inside);
assert_eq!(workspace.organization_id(), Some(&organization.id));
assert_eq!(workspace.organization_access(), Some(MembersOnly));
for (policy, allowed) in [
(MembersOnly, &[][..]),
(ExternalViewers, &[Viewer][..]),
(ExternalEditors, &[Viewer, Editor][..]),
] {
organization
.set_workspace_access(&mut workspace, policy)
.unwrap();
for role in [Owner, Admin, Editor, Viewer] {
let invitation = workspace.invite(outside.clone(), role, None);
if allowed.contains(&role) {
let membership = workspace
.accept_invitation(&outside, &invitation.unwrap(), None)
.unwrap();
assert_eq!(membership.user_id, outside);
assert_eq!(membership.workspace_id, workspace.id);
assert_eq!(membership.role, role);
} else {
assert_eq!(invitation, Err(WorkspaceAccessError::RoleNotAllowed));
}
assert!(
workspace
.invite(inside.clone(), role, Some(&membership))
.is_ok()
);
}
}
}
#[test]
fn acceptance_checks_the_invite_target_and_current_policy() {
let owner = organization("owner");
let other = organization("other");
let mut workspace = owner.create_workspace(workspace_id("workspace"), "Workspace");
let independent = Workspace::independent(workspace_id("personal"), "Personal");
let outsider = UserId::new("outside").unwrap();
let insider = UserId::new("inside").unwrap();
let inside_membership = member(&owner, &insider);
let other_membership = member(&other, &outsider);
for membership in [&inside_membership, &other_membership] {
assert_eq!(
workspace.invite(outsider.clone(), WorkspaceRole::Admin, Some(membership)),
Err(WorkspaceAccessError::RoleNotAllowed)
);
}
let invitation = workspace
.invite(
insider.clone(),
WorkspaceRole::Admin,
Some(&inside_membership),
)
.unwrap();
assert_eq!(
workspace.accept_invitation(&insider, &invitation, None),
Err(WorkspaceAccessError::RoleNotAllowed)
);
assert_eq!(
independent.accept_invitation(&insider, &invitation, Some(&inside_membership)),
Err(WorkspaceAccessError::InvitationMismatch)
);
assert_eq!(
workspace.accept_invitation(&outsider, &invitation, None),
Err(WorkspaceAccessError::InvitationMismatch)
);
assert_eq!(independent.organization_id(), None);
assert!(
independent
.invite(outsider.clone(), WorkspaceRole::Editor, None)
.is_ok()
);
assert_eq!(
other.set_workspace_access(&mut workspace, WorkspaceAccess::ExternalEditors),
Err(WorkspaceAccessError::OrganizationMismatch)
);
owner
.set_workspace_access(&mut workspace, WorkspaceAccess::ExternalEditors)
.unwrap();
let external = workspace
.invite(outsider.clone(), WorkspaceRole::Editor, None)
.unwrap();
owner
.set_workspace_access(&mut workspace, WorkspaceAccess::ExternalViewers)
.unwrap();
assert_eq!(
workspace.accept_invitation(&outsider, &external, None),
Err(WorkspaceAccessError::RoleNotAllowed)
);
}
#[test]
fn workspace_contains_nested_documents_of_different_kinds() {
let workspace = Workspace::independent(workspace_id("workspace"), "Workspace");
let key = |id: &str| DocumentKey {
workspace: workspace.id.clone(),
document: DocumentId::new(id).unwrap(),
};
let page = Document::new(
key("page"),
DocumentContent::Page {
title: "Page".into(),
},
);
let mut child_page = Document::new(
key("subpage"),
DocumentContent::Page {
title: "Nested".into(),
},
);
child_page.parent_id = Some(page.key.document.clone());
let mut code = Document::new(
key("code"),
DocumentContent::Code {
language: "rust".into(),
source: "fn main() {}".into(),
},
);
code.parent_id = Some(child_page.key.document.clone());
let tree = workspace
.document_tree(page.clone(), [code, child_page])
.unwrap();
assert_eq!(
tree.nodes()
.map(|(depth, document)| (depth, document.key.document.as_str()))
.collect::<Vec<_>>(),
[(0, "page"), (1, "subpage"), (2, "code")]
);
let other = Workspace::independent(workspace_id("other"), "Other");
assert!(matches!(
other.document_tree(page, []),
Err(TreeError::WorkspaceMismatch)
));
}
View File
View File
+59
View File
@@ -0,0 +1,59 @@
# Bedrock Kubernetes 部署路线
建集群、构建 Bedrock 镜像、编写部署清单可以并行。集群内 PostgreSQL 的清单在目标集群和命名空间就绪后提交。数据库可连接、Bedrock 镜像和运行配置就绪后,再初始化 Bedrock 存储。
```mermaid
flowchart TD
start["准备首次部署"]
subgraph infra ["准备 Kubernetes 集群"]
mode{"如何建集群"}
servers["自建:开云服务器,安装容器运行时和 Kubernetes 组件"]
controlPlane["kubeadm init 初始化控制平面"]
workers["kubeadm join 加入工作节点,安装 Pod 网络插件"]
managed["托管:创建 Kubernetes 集群和节点池"]
nodesReady["取得部署用 kubeconfig,确认节点 Ready"]
mode -->|"自建"| servers --> controlPlane --> workers --> nodesReady
mode -->|"托管"| managed --> nodesReady
end
subgraph image ["构建并发布镜像"]
compile["构建 runner 检出代码,编译 Rust 发布版"]
package["把 Bedrock 二进制打包进运行时镜像"]
push["用 Git SHA 标记镜像并推送到镜像仓库"]
compile --> package --> push
end
subgraph config ["准备部署清单和运行配置"]
database{"PostgreSQL 在哪里运行"}
inCluster["集群内:编写 PostgreSQL 部署清单,声明工作负载、持久卷和 Service"]
external["集群外:取得数据库端点并配置网络访问"]
app["编写 Bedrock Deployment、Service 和运行配置"]
secrets["准备数据库 Secret,私有镜像仓库按需配置拉取权限"]
database -->|"集群内"| inCluster --> app
database -->|"集群外"| external --> app
app --> secrets
end
start --> mode
start --> compile
start --> database
nodesReady --> target["确认目标集群和命名空间"]
target -->|"集群内 PostgreSQL"| applyDatabase["kubectl apply 提交 PostgreSQL 清单"]
inCluster -->|"清单已写好"| applyDatabase
applyDatabase --> dbReady["从目标集群确认 PostgreSQL 可连接"]
target -->|"集群外 PostgreSQL"| dbReady
external -->|"端点已配置"| dbReady
push --> appReady["确认 Bedrock 镜像版本和运行配置"]
secrets --> appReady
dbReady --> init["首次部署时运行 Bedrock 存储初始化"]
appReady --> init
init --> apply["kubectl apply 将 Bedrock 清单提交给 API Server"]
apply --> schedule["集群调度 Pod,工作节点拉取镜像并启动 Bedrock"]
schedule --> verify["检查 rollout、Pod 就绪状态和接口连通性"]
```
- **现有构建入口**。[Gitea 发布构建脚本](../../deploy/gitea/build-release.sh) 在构建容器里编译 Rust,并产出 `target/bedrock-release/bedrock`。上图的镜像打包、镜像推送和 Kubernetes 发布是迁移时要接上的步骤。
- **数据库清单**。编写 YAML 可以与建集群并行。提交清单前先拿到 kubeconfig,确认目标集群、命名空间和节点均已就绪。
- **首次初始化**。可以用同一份 Bedrock 镜像运行一次性 Kubernetes Job,等它成功完成再启动应用。集群内的数据库通过 Service 地址连接,集群外的数据库通过其端点连接。
- **日常发布**。沿用已有集群,在 runner 编译并推送新镜像,更新 Deployment 的镜像引用,提交清单并检查滚动发布结果。
View File
View File