3 Commits

Author SHA1 Message Date
GW_MC
9c07fce607 feat(proxy): add proxy service module with configuration handling
- Introduced a new `proxy` module in the service layer.
- Created `ProxyServiceTrait` for managing proxy configurations.
- Implemented various configuration types including access rules, cache zones, limit rules, and more.
- Added rendering logic for Nginx configuration components.
- Developed a repository implementation for fetching and merging proxy configurations from the database.
- Enhanced error handling with `ProxyServiceError` for better clarity on configuration issues.
2026-06-21 11:07:13 +00:00
GW_MC
2dbab85c87 feat: add new database entities and migration for proxy configuration
- Introduced `log_setting`, `proxy_config`, `proxy_setting`, `rewrite_rule`, `server_block`, `ssl_certificate`, and `upstream` entities with their respective fields and relationships.
- Updated `mod.rs` and `prelude.rs` to include new entities.
- Created migration script to set up new tables and relationships in the database.
- Altered existing `agents` table to include a foreign key reference to `agent_group`.
2026-06-21 11:06:20 +00:00
be1d2e3fa9 Merge pull request 'feature/nginx-handler' (#6) from feature/nginx-handler into master
Some checks failed
Test / get-ci-image (push) Successful in 6s
Test / lint-frontend (push) Successful in 13s
Test / test-frontend (push) Successful in 23s
Test / frontend-build (push) Successful in 15s
Verify / get-ci-image (push) Successful in 5s
Test / test-crates (push) Failing after 1m27s
Test / lint-crates (push) Failing after 1m25s
Verify / verify-generated-db-entities (push) Successful in 1m53s
Reviewed-on: #6
2026-06-19 19:13:15 +08:00
38 changed files with 2912 additions and 1 deletions

View File

@@ -0,0 +1,61 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "access_rule")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub server_id: Option<Uuid>,
pub location_id: Option<Uuid>,
pub r#type: String,
pub ip_cidr: String,
pub description: Option<String>,
pub priority: i32,
pub is_deleted: bool,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
#[sea_orm(
belongs_to = "super::location_block::Entity",
from = "Column::LocationId",
to = "super::location_block::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
LocationBlock,
#[sea_orm(
belongs_to = "super::server_block::Entity",
from = "Column::ServerId",
to = "super::server_block::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
ServerBlock,
}
impl Related<super::location_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::LocationBlock.def()
}
}
impl Related<super::server_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::ServerBlock.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,64 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "agent_config_binding")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub agent_id: Option<Uuid>,
pub group_id: Option<Uuid>,
pub config_id: Uuid,
pub is_active: bool,
pub applied_at: DateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::agent_group::Entity",
from = "Column::GroupId",
to = "super::agent_group::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
AgentGroup,
#[sea_orm(
belongs_to = "super::agents::Entity",
from = "Column::AgentId",
to = "super::agents::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
Agents,
#[sea_orm(
belongs_to = "super::proxy_config::Entity",
from = "Column::ConfigId",
to = "super::proxy_config::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
ProxyConfig,
}
impl Related<super::agent_group::Entity> for Entity {
fn to() -> RelationDef {
Relation::AgentGroup.def()
}
}
impl Related<super::agents::Entity> for Entity {
fn to() -> RelationDef {
Relation::Agents.def()
}
}
impl Related<super::proxy_config::Entity> for Entity {
fn to() -> RelationDef {
Relation::ProxyConfig.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,35 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "agent_group")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub description: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::agent_config_binding::Entity")]
AgentConfigBinding,
#[sea_orm(has_many = "super::agents::Entity")]
Agents,
}
impl Related<super::agent_config_binding::Entity> for Entity {
fn to() -> RelationDef {
Relation::AgentConfigBinding.def()
}
}
impl Related<super::agents::Entity> for Entity {
fn to() -> RelationDef {
Relation::Agents.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -19,9 +19,33 @@ pub struct Model {
pub labels: Option<Json>,
pub created_at: DateTimeWithTimeZone,
pub updated_at: DateTimeWithTimeZone,
pub group_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
pub enum Relation {
#[sea_orm(has_many = "super::agent_config_binding::Entity")]
AgentConfigBinding,
#[sea_orm(
belongs_to = "super::agent_group::Entity",
from = "Column::GroupId",
to = "super::agent_group::Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
AgentGroup,
}
impl Related<super::agent_config_binding::Entity> for Entity {
fn to() -> RelationDef {
Relation::AgentConfigBinding.def()
}
}
impl Related<super::agent_group::Entity> for Entity {
fn to() -> RelationDef {
Relation::AgentGroup.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,37 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "cache_zone")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub path: String,
pub size_limit: String,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
#[sea_orm(has_many = "super::proxy_setting::Entity")]
ProxySetting,
}
impl Related<super::proxy_setting::Entity> for Entity {
fn to() -> RelationDef {
Relation::ProxySetting.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,37 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "config_inheritance")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub child_config_id: Uuid,
pub parent_config_id: Uuid,
pub priority: Option<i32>,
pub applied_at: DateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::proxy_config::Entity",
from = "Column::ChildConfigId",
to = "super::proxy_config::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
ProxyConfig2,
#[sea_orm(
belongs_to = "super::proxy_config::Entity",
from = "Column::ParentConfigId",
to = "super::proxy_config::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
ProxyConfig1,
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,59 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "limit_rule")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub location_id: Uuid,
pub zone_id: Uuid,
pub burst: Option<i32>,
pub nodelay: Option<bool>,
pub is_deleted: bool,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
#[sea_orm(
belongs_to = "super::limit_zone::Entity",
from = "Column::ZoneId",
to = "super::limit_zone::Column::Id",
on_update = "NoAction",
on_delete = "Cascade"
)]
LimitZone,
#[sea_orm(
belongs_to = "super::location_block::Entity",
from = "Column::LocationId",
to = "super::location_block::Column::Id",
on_update = "NoAction",
on_delete = "Cascade"
)]
LocationBlock,
}
impl Related<super::limit_zone::Entity> for Entity {
fn to() -> RelationDef {
Relation::LimitZone.def()
}
}
impl Related<super::location_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::LocationBlock.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,37 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "limit_zone")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub key: String,
pub rate: String,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::limit_rule::Entity")]
LimitRule,
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
}
impl Related<super::limit_rule::Entity> for Entity {
fn to() -> RelationDef {
Relation::LimitRule.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,91 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "location_block")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub server_id: Uuid,
pub path_pattern: String,
pub proxy_pass_upstream_id: Option<Uuid>,
#[sea_orm(column_type = "JsonBinary", nullable)]
pub metadata: Option<Json>,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::access_rule::Entity")]
AccessRule,
#[sea_orm(has_many = "super::limit_rule::Entity")]
LimitRule,
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
#[sea_orm(has_many = "super::proxy_setting::Entity")]
ProxySetting,
#[sea_orm(has_many = "super::rewrite_rule::Entity")]
RewriteRule,
#[sea_orm(
belongs_to = "super::server_block::Entity",
from = "Column::ServerId",
to = "super::server_block::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
ServerBlock,
#[sea_orm(
belongs_to = "super::upstream::Entity",
from = "Column::ProxyPassUpstreamId",
to = "super::upstream::Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
Upstream,
}
impl Related<super::access_rule::Entity> for Entity {
fn to() -> RelationDef {
Relation::AccessRule.def()
}
}
impl Related<super::limit_rule::Entity> for Entity {
fn to() -> RelationDef {
Relation::LimitRule.def()
}
}
impl Related<super::proxy_setting::Entity> for Entity {
fn to() -> RelationDef {
Relation::ProxySetting.def()
}
}
impl Related<super::rewrite_rule::Entity> for Entity {
fn to() -> RelationDef {
Relation::RewriteRule.def()
}
}
impl Related<super::server_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::ServerBlock.def()
}
}
impl Related<super::upstream::Entity> for Entity {
fn to() -> RelationDef {
Relation::Upstream.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,44 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "log_setting")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub server_id: Uuid,
pub access_log_path: Option<String>,
pub error_log_path: Option<String>,
pub log_level: Option<String>,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
#[sea_orm(
belongs_to = "super::server_block::Entity",
from = "Column::ServerId",
to = "super::server_block::Column::Id",
on_update = "NoAction",
on_delete = "Cascade"
)]
ServerBlock,
}
impl Related<super::server_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::ServerBlock.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -2,5 +2,20 @@
pub mod prelude;
pub mod access_rule;
pub mod agent_config_binding;
pub mod agent_group;
pub mod agents;
pub mod cache_zone;
pub mod config_inheritance;
pub mod limit_rule;
pub mod limit_zone;
pub mod location_block;
pub mod log_setting;
pub mod proxy_config;
pub mod proxy_setting;
pub mod public_key_revocations;
pub mod rewrite_rule;
pub mod server_block;
pub mod ssl_certificate;
pub mod upstream;

View File

@@ -1,4 +1,19 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
pub use super::access_rule::Entity as AccessRule;
pub use super::agent_config_binding::Entity as AgentConfigBinding;
pub use super::agent_group::Entity as AgentGroup;
pub use super::agents::Entity as Agents;
pub use super::cache_zone::Entity as CacheZone;
pub use super::config_inheritance::Entity as ConfigInheritance;
pub use super::limit_rule::Entity as LimitRule;
pub use super::limit_zone::Entity as LimitZone;
pub use super::location_block::Entity as LocationBlock;
pub use super::log_setting::Entity as LogSetting;
pub use super::proxy_config::Entity as ProxyConfig;
pub use super::proxy_setting::Entity as ProxySetting;
pub use super::public_key_revocations::Entity as PublicKeyRevocations;
pub use super::rewrite_rule::Entity as RewriteRule;
pub use super::server_block::Entity as ServerBlock;
pub use super::ssl_certificate::Entity as SslCertificate;
pub use super::upstream::Entity as Upstream;

View File

@@ -0,0 +1,46 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "proxy_config")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub description: Option<String>,
pub is_template: bool,
pub created_at: DateTime,
pub updated_at: DateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::agent_config_binding::Entity")]
AgentConfigBinding,
#[sea_orm(has_many = "super::server_block::Entity")]
ServerBlock,
#[sea_orm(has_many = "super::upstream::Entity")]
Upstream,
}
impl Related<super::agent_config_binding::Entity> for Entity {
fn to() -> RelationDef {
Relation::AgentConfigBinding.def()
}
}
impl Related<super::server_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::ServerBlock.def()
}
}
impl Related<super::upstream::Entity> for Entity {
fn to() -> RelationDef {
Relation::Upstream.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,60 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "proxy_setting")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub location_id: Uuid,
pub read_timeout: Option<i32>,
pub connect_timeout: Option<i32>,
pub buffer_size: Option<i32>,
pub cache_enabled: Option<bool>,
pub cache_zone: Option<Uuid>,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::cache_zone::Entity",
from = "Column::CacheZone",
to = "super::cache_zone::Column::Id",
on_update = "NoAction",
on_delete = "SetNull"
)]
CacheZone,
#[sea_orm(
belongs_to = "super::location_block::Entity",
from = "Column::LocationId",
to = "super::location_block::Column::Id",
on_update = "NoAction",
on_delete = "Cascade"
)]
LocationBlock,
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
}
impl Related<super::cache_zone::Entity> for Entity {
fn to() -> RelationDef {
Relation::CacheZone.def()
}
}
impl Related<super::location_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::LocationBlock.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,46 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "rewrite_rule")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub location_id: Uuid,
pub pattern: String,
pub replacement: String,
pub flag: Option<String>,
pub priority: i32,
pub is_deleted: bool,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::location_block::Entity",
from = "Column::LocationId",
to = "super::location_block::Column::Id",
on_update = "NoAction",
on_delete = "Cascade"
)]
LocationBlock,
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
}
impl Related<super::location_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::LocationBlock.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,83 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "server_block")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub config_id: Uuid,
pub server_name: Option<Vec<String>>,
pub listen_port: i32,
pub ssl_enabled: Option<bool>,
pub ssl_cert_id: Option<Uuid>,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::access_rule::Entity")]
AccessRule,
#[sea_orm(has_many = "super::location_block::Entity")]
LocationBlock,
#[sea_orm(has_many = "super::log_setting::Entity")]
LogSetting,
#[sea_orm(
belongs_to = "super::proxy_config::Entity",
from = "Column::ConfigId",
to = "super::proxy_config::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
ProxyConfig,
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
#[sea_orm(
belongs_to = "super::ssl_certificate::Entity",
from = "Column::SslCertId",
to = "super::ssl_certificate::Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SslCertificate,
}
impl Related<super::access_rule::Entity> for Entity {
fn to() -> RelationDef {
Relation::AccessRule.def()
}
}
impl Related<super::location_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::LocationBlock.def()
}
}
impl Related<super::log_setting::Entity> for Entity {
fn to() -> RelationDef {
Relation::LogSetting.def()
}
}
impl Related<super::proxy_config::Entity> for Entity {
fn to() -> RelationDef {
Relation::ProxyConfig.def()
}
}
impl Related<super::ssl_certificate::Entity> for Entity {
fn to() -> RelationDef {
Relation::SslCertificate.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,29 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "ssl_certificate")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub cert_path: String,
pub key_path: String,
pub expiry_date: DateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::server_block::Entity")]
ServerBlock,
}
impl Related<super::server_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::ServerBlock.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,54 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 2.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "upstream")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub config_id: Uuid,
pub name: String,
pub target_host: String,
pub target_port: i32,
#[sea_orm(column_type = "JsonBinary", nullable)]
pub metadata: Option<Json>,
pub override_of_id: Option<Uuid>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::location_block::Entity")]
LocationBlock,
#[sea_orm(
belongs_to = "super::proxy_config::Entity",
from = "Column::ConfigId",
to = "super::proxy_config::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
ProxyConfig,
#[sea_orm(
belongs_to = "Entity",
from = "Column::OverrideOfId",
to = "Column::Id",
on_update = "Cascade",
on_delete = "SetNull"
)]
SelfRef,
}
impl Related<super::location_block::Entity> for Entity {
fn to() -> RelationDef {
Relation::LocationBlock.def()
}
}
impl Related<super::proxy_config::Entity> for Entity {
fn to() -> RelationDef {
Relation::ProxyConfig.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -6,6 +6,7 @@ use crate::{connector::agent::AgentConnectorTrait, service::certificate::Certifi
pub mod agent;
pub mod certificate;
pub mod proxy;
pub async fn start_master_server(
settings: crate::config::settings::Settings,

View File

@@ -0,0 +1,12 @@
use crate::service::proxy::types::{ProxyConfig, ProxyServiceResult};
pub(crate) mod nginx;
pub(crate) mod repo;
pub mod service;
pub mod types;
#[async_trait::async_trait]
pub trait ProxyServiceTrait: Send + Sync + 'static {
async fn get_proxy_config(&self, proxy_id: uuid::Uuid) -> ProxyServiceResult<ProxyConfig>;
}

View File

@@ -0,0 +1,7 @@
use crate::db::entities::access_rule::Model as AccessRule;
impl std::fmt::Display for AccessRule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {};", self.r#type.clone(), self.ip_cidr.clone())
}
}

View File

@@ -0,0 +1,11 @@
use crate::db::entities::cache_zone::Model as CacheZone;
impl std::fmt::Display for CacheZone {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"proxy_cache_path {} levels=1:2 keys_zone={}:{};",
self.path, self.name, self.size_limit
)
}
}

View File

@@ -0,0 +1,19 @@
use crate::db::entities::limit_rule::Model as LimitRule;
pub struct LimitRuleRender {
pub rule: LimitRule,
pub zone_name: String,
}
impl std::fmt::Display for LimitRuleRender {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "limit_req zone={}", self.zone_name)?;
if let Some(burst) = self.rule.burst {
write!(f, " burst={}", burst)?;
}
if self.rule.nodelay.unwrap_or(false) {
write!(f, " nodelay")?;
}
write!(f, ";")
}
}

View File

@@ -0,0 +1,11 @@
use crate::db::entities::limit_zone::Model as LimitZone;
impl std::fmt::Display for LimitZone {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"limit_req_zone {} zone={}:{};",
self.key, self.name, self.rate
)
}
}

View File

@@ -0,0 +1,44 @@
use crate::db::entities::location_block::Model as LocationBlock;
pub struct LocationBlockRender {
pub block: LocationBlock,
pub upstream_name: Option<String>,
pub access_rules: Vec<String>,
pub rewrite_rules: Vec<String>,
pub proxy_setting: Option<String>,
pub limit_rules: Vec<String>,
}
impl std::fmt::Display for LocationBlockRender {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, " location {} {{", self.block.path_pattern)?;
if let Some(ref upstream) = self.upstream_name {
writeln!(f, " proxy_pass http://{};", upstream)?;
writeln!(f, " proxy_set_header Host $host;")?;
writeln!(f, " proxy_set_header X-Real-IP $remote_addr;")?;
}
if let Some(ref settings) = self.proxy_setting {
for line in settings.lines() {
if !line.is_empty() {
writeln!(f, "{}", line)?;
}
}
}
for rule in &self.access_rules {
writeln!(f, " {}", rule)?;
}
for rule in &self.rewrite_rules {
writeln!(f, " {}", rule)?;
}
for rule in &self.limit_rules {
writeln!(f, " {}", rule)?;
}
writeln!(f, " }}")
}
}

View File

@@ -0,0 +1,21 @@
use crate::db::entities::log_setting::Model as LogSetting;
impl std::fmt::Display for LogSetting {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(ref path) = self.access_log_path {
if let Some(ref level) = self.log_level {
writeln!(f, " access_log {} {};", path, level)?;
} else {
writeln!(f, " access_log {};", path)?;
}
}
if let Some(ref path) = self.error_log_path {
if let Some(ref level) = self.log_level {
writeln!(f, " error_log {} {};", path, level)?;
} else {
writeln!(f, " error_log {};", path)?;
}
}
Ok(())
}
}

View File

@@ -0,0 +1,11 @@
mod access_rule;
mod cache_zone;
mod limit_rule;
mod limit_zone;
mod location_block;
mod log_setting;
mod proxy_setting;
mod rewrite_rule;
mod server_block;
mod ssl_certificate;
mod upstream;

View File

@@ -0,0 +1,35 @@
use crate::db::entities::proxy_setting::Model as ProxySetting;
pub struct ProxySettingRender {
pub setting: ProxySetting,
pub cache_zone_name: Option<String>,
}
impl ProxySettingRender {
fn render_timeout(value: Option<i32>, directive: &str) -> Option<String> {
value.map(|v| format!(" {} {}s;", directive, v))
}
}
impl std::fmt::Display for ProxySettingRender {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(line) = Self::render_timeout(self.setting.read_timeout, "proxy_read_timeout")
{
writeln!(f, "{}", line)?;
}
if let Some(line) =
Self::render_timeout(self.setting.connect_timeout, "proxy_connect_timeout")
{
writeln!(f, "{}", line)?;
}
if let Some(buffer) = self.setting.buffer_size {
writeln!(f, " proxy_buffer_size {};", buffer)?;
}
if self.setting.cache_enabled.unwrap_or(false) {
if let Some(ref zone_name) = self.cache_zone_name {
writeln!(f, " proxy_cache {};", zone_name)?;
}
}
Ok(())
}
}

View File

@@ -0,0 +1,11 @@
use crate::db::entities::rewrite_rule::Model as RewriteRule;
impl std::fmt::Display for RewriteRule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "rewrite {} {}", self.pattern, self.replacement)?;
if let Some(ref flag) = self.flag {
write!(f, " {}", flag)?;
}
write!(f, ";")
}
}

View File

@@ -0,0 +1,49 @@
use crate::db::entities::server_block::Model as ServerBlock;
pub struct ServerBlockRender {
pub block: ServerBlock,
pub ssl_cert: Option<String>,
pub locations: Vec<String>,
pub access_rules: Vec<String>,
pub log_setting: Option<String>,
}
impl std::fmt::Display for ServerBlockRender {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "server {{")?;
if self.block.ssl_enabled.unwrap_or(false) {
writeln!(f, " listen {} ssl;", self.block.listen_port)?;
} else {
writeln!(f, " listen {};", self.block.listen_port)?;
}
if let Some(ref names) = self.block.server_name {
if !names.is_empty() {
writeln!(f, " server_name {};", names.join(" "))?;
}
}
if let Some(ref cert) = self.ssl_cert {
writeln!(f, "{}", cert)?;
}
if let Some(ref log) = self.log_setting {
for line in log.lines() {
if !line.is_empty() {
writeln!(f, "{}", line)?;
}
}
}
for rule in &self.access_rules {
writeln!(f, " {}", rule)?;
}
for loc in &self.locations {
writeln!(f, "{}", loc)?;
}
write!(f, "}}")
}
}

View File

@@ -0,0 +1,8 @@
use crate::db::entities::ssl_certificate::Model as SslCertificate;
impl std::fmt::Display for SslCertificate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, " ssl_certificate {};", self.cert_path)?;
writeln!(f, " ssl_certificate_key {};", self.key_path)
}
}

View File

@@ -0,0 +1,7 @@
use crate::db::entities::upstream::Model as Upstream;
impl std::fmt::Display for Upstream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, " server {}:{};", self.target_host, self.target_port)
}
}

View File

@@ -0,0 +1 @@
pub mod config;

View File

@@ -0,0 +1,444 @@
use std::collections::HashMap;
use sea_orm::{DatabaseConnection, prelude::*};
use crate::service::proxy::types::{
Mergeable, OverrideRef, ProxyConfig, ProxyServiceError, ProxyServiceResult, ProxyType,
};
#[async_trait::async_trait]
pub trait ProxyRepo: Send + Sync + 'static {
// get the raw config for the given proxy_id. This should return the config of the given proxy_id without merging it with its parent configs (if any).
async fn get_proxy_raw_config(&self, proxy_id: uuid::Uuid) -> ProxyServiceResult<ProxyConfig>;
// get the raw config for the given proxy_id. This should return the config of the given proxy_id and all its parent configs (if any) without merging them. The returned vector is ordered from the leaf (given proxy_id) down to the root config (most specific to least specific).
async fn get_proxy_raw_configs(
&self,
proxy_id: uuid::Uuid,
) -> ProxyServiceResult<Vec<ProxyConfig>>;
// get the merged config for the given proxy_id. This should merge the config of the given proxy_id with its parent configs (if any) and return the final merged config.
async fn get_merged_proxy_config(
&self,
proxy_id: uuid::Uuid,
) -> ProxyServiceResult<ProxyConfig>;
}
pub(crate) struct ProxyRepoImpl {
db: DatabaseConnection,
}
impl ProxyRepoImpl {
pub fn new(db: DatabaseConnection) -> Self {
Self { db }
}
}
#[async_trait::async_trait]
impl ProxyRepo for ProxyRepoImpl {
async fn get_proxy_raw_configs(
&self,
proxy_config_id: uuid::Uuid,
) -> ProxyServiceResult<Vec<ProxyConfig>> {
let mut proxy_config_id_frontier = vec![proxy_config_id];
let mut visited = std::collections::HashSet::new();
let mut configs: Vec<ProxyConfig> = Vec::new();
while let Some(current_id) = proxy_config_id_frontier.pop() {
if visited.contains(&current_id) {
continue;
}
visited.insert(current_id);
//
let config = self.get_proxy_raw_config(current_id).await?;
//
if let Some(parent_ids) = &config.parent_config_id {
proxy_config_id_frontier.extend(parent_ids);
}
configs.push(config);
}
Ok(configs)
}
async fn get_proxy_raw_config(&self, proxy_id: uuid::Uuid) -> ProxyServiceResult<ProxyConfig> {
let proxy_entity = crate::db::entities::proxy_config::Entity::find_by_id(proxy_id)
.one(&self.db)
.await?
.ok_or(ProxyServiceError::ConfigNotFound)?;
// Resolve parent configs from config_inheritance
let parent_config_id = {
let inheritance = crate::db::entities::config_inheritance::Entity::find()
.filter(crate::db::entities::config_inheritance::Column::ChildConfigId.eq(proxy_id))
.all(&self.db)
.await?;
if inheritance.is_empty() {
None
} else {
Some(
inheritance
.into_iter()
.map(|ci| ci.parent_config_id)
.collect(),
)
}
};
// Direct children of proxy_config
let server_blocks = crate::db::entities::server_block::Entity::find()
.filter(crate::db::entities::server_block::Column::ConfigId.eq(proxy_id))
.all(&self.db)
.await?;
let upstreams = crate::db::entities::upstream::Entity::find()
.filter(crate::db::entities::upstream::Column::ConfigId.eq(proxy_id))
.all(&self.db)
.await?;
// Children of server_blocks
let server_block_ids: Vec<uuid::Uuid> = server_blocks.iter().map(|sb| sb.id).collect();
let (location_blocks, log_settings, server_access_rules) = if server_block_ids.is_empty() {
(vec![], vec![], vec![])
} else {
(
crate::db::entities::location_block::Entity::find()
.filter(
crate::db::entities::location_block::Column::ServerId
.is_in(server_block_ids.clone()),
)
.all(&self.db)
.await?,
crate::db::entities::log_setting::Entity::find()
.filter(
crate::db::entities::log_setting::Column::ServerId
.is_in(server_block_ids.clone()),
)
.all(&self.db)
.await?,
crate::db::entities::access_rule::Entity::find()
.filter(
crate::db::entities::access_rule::Column::ServerId.is_in(server_block_ids),
)
.all(&self.db)
.await?,
)
};
// Children of location_blocks
let location_block_ids: Vec<uuid::Uuid> = location_blocks.iter().map(|lb| lb.id).collect();
let (location_access_rules, limit_rules, proxy_settings, rewrite_rules) =
if location_block_ids.is_empty() {
(vec![], vec![], vec![], vec![])
} else {
(
crate::db::entities::access_rule::Entity::find()
.filter(
crate::db::entities::access_rule::Column::LocationId
.is_in(location_block_ids.clone()),
)
.all(&self.db)
.await?,
crate::db::entities::limit_rule::Entity::find()
.filter(
crate::db::entities::limit_rule::Column::LocationId
.is_in(location_block_ids.clone()),
)
.all(&self.db)
.await?,
crate::db::entities::proxy_setting::Entity::find()
.filter(
crate::db::entities::proxy_setting::Column::LocationId
.is_in(location_block_ids.clone()),
)
.all(&self.db)
.await?,
crate::db::entities::rewrite_rule::Entity::find()
.filter(
crate::db::entities::rewrite_rule::Column::LocationId
.is_in(location_block_ids),
)
.all(&self.db)
.await?,
)
};
// Collect referenced IDs for zone and cert lookups
let limit_zone_ids: Vec<uuid::Uuid> = limit_rules.iter().map(|lr| lr.zone_id).collect();
let cache_zone_ids: Vec<uuid::Uuid> = proxy_settings
.iter()
.filter_map(|ps| ps.cache_zone)
.collect();
let ssl_cert_ids: Vec<uuid::Uuid> = server_blocks
.iter()
.filter_map(|sb| sb.ssl_cert_id)
.collect();
let limit_zones = if limit_zone_ids.is_empty() {
vec![]
} else {
crate::db::entities::limit_zone::Entity::find()
.filter(crate::db::entities::limit_zone::Column::Id.is_in(limit_zone_ids))
.all(&self.db)
.await?
};
let cache_zones = if cache_zone_ids.is_empty() {
vec![]
} else {
crate::db::entities::cache_zone::Entity::find()
.filter(crate::db::entities::cache_zone::Column::Id.is_in(cache_zone_ids))
.all(&self.db)
.await?
};
let ssl_certificates = if ssl_cert_ids.is_empty() {
vec![]
} else {
crate::db::entities::ssl_certificate::Entity::find()
.filter(crate::db::entities::ssl_certificate::Column::Id.is_in(ssl_cert_ids))
.all(&self.db)
.await?
};
// ── Group child IDs by parent ────────────────────────────────────────
// location_block IDs grouped by server_id
let loc_block_ids_by_server: HashMap<uuid::Uuid, Vec<OverrideRef>> = {
let mut map: HashMap<_, Vec<_>> = HashMap::new();
for lb in &location_blocks {
map.entry(lb.server_id).or_default().push(OverrideRef {
id: lb.id,
override_of_id: lb.override_of_id,
});
}
map
};
// log_setting IDs grouped by server_id
let log_setting_ids_by_server: HashMap<uuid::Uuid, Vec<OverrideRef>> = {
let mut map: HashMap<_, Vec<_>> = HashMap::new();
for ls in &log_settings {
map.entry(ls.server_id).or_default().push(OverrideRef {
id: ls.id,
override_of_id: ls.override_of_id,
});
}
map
};
// server-level access_rule IDs grouped by server_id
let server_ar_ids_by_server: HashMap<uuid::Uuid, Vec<OverrideRef>> = {
let mut map: HashMap<_, Vec<_>> = HashMap::new();
for ar in &server_access_rules {
if let Some(sid) = ar.server_id {
map.entry(sid).or_default().push(OverrideRef {
id: ar.id,
override_of_id: ar.override_of_id,
});
}
}
map
};
// location-level access_rule IDs grouped by location_id
let loc_ar_ids_by_location: HashMap<uuid::Uuid, Vec<OverrideRef>> = {
let mut map: HashMap<_, Vec<_>> = HashMap::new();
for ar in &location_access_rules {
if let Some(lid) = ar.location_id {
map.entry(lid).or_default().push(OverrideRef {
id: ar.id,
override_of_id: ar.override_of_id,
});
}
}
map
};
// limit_rule IDs grouped by location_id
let lr_ids_by_location: HashMap<uuid::Uuid, Vec<OverrideRef>> = {
let mut map: HashMap<_, Vec<_>> = HashMap::new();
for lr in &limit_rules {
map.entry(lr.location_id).or_default().push(OverrideRef {
id: lr.id,
override_of_id: lr.override_of_id,
});
}
map
};
// proxy_setting IDs grouped by location_id
let ps_ids_by_location: HashMap<uuid::Uuid, Vec<OverrideRef>> = {
let mut map: HashMap<_, Vec<_>> = HashMap::new();
for ps in &proxy_settings {
map.entry(ps.location_id).or_default().push(OverrideRef {
id: ps.id,
override_of_id: ps.override_of_id,
});
}
map
};
// rewrite_rule IDs grouped by location_id
let rr_ids_by_location: HashMap<uuid::Uuid, Vec<OverrideRef>> = {
let mut map: HashMap<_, Vec<_>> = HashMap::new();
for rr in &rewrite_rules {
map.entry(rr.location_id).or_default().push(OverrideRef {
id: rr.id,
override_of_id: rr.override_of_id,
});
}
map
};
// location_block IDs grouped by proxy_pass_upstream_id (reverse FK)
let loc_block_ids_by_upstream: HashMap<uuid::Uuid, Vec<OverrideRef>> = {
let mut map: HashMap<_, Vec<_>> = HashMap::new();
for lb in &location_blocks {
if let Some(up_id) = lb.proxy_pass_upstream_id {
map.entry(up_id).or_default().push(OverrideRef {
id: lb.id,
override_of_id: lb.override_of_id,
});
}
}
map
};
// ── Build child-ID tuples for each config type ───────────────────────
let location_block_tuples: Vec<(
crate::db::entities::location_block::Model,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
)> = location_blocks
.into_iter()
.map(|lb| {
let ar_ids = loc_ar_ids_by_location
.get(&lb.id)
.cloned()
.unwrap_or_default();
let lr_ids = lr_ids_by_location.get(&lb.id).cloned().unwrap_or_default();
let ps_ids = ps_ids_by_location.get(&lb.id).cloned().unwrap_or_default();
let rr_ids = rr_ids_by_location.get(&lb.id).cloned().unwrap_or_default();
(lb, ar_ids, lr_ids, ps_ids, rr_ids)
})
.collect();
let server_block_tuples: Vec<(
crate::db::entities::server_block::Model,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
)> = server_blocks
.into_iter()
.map(|sb| {
let ar_ids = server_ar_ids_by_server
.get(&sb.id)
.cloned()
.unwrap_or_default();
let lb_ids = loc_block_ids_by_server
.get(&sb.id)
.cloned()
.unwrap_or_default();
let ls_ids = log_setting_ids_by_server
.get(&sb.id)
.cloned()
.unwrap_or_default();
let sc_ids: Vec<OverrideRef> = sb
.ssl_cert_id
.into_iter()
.map(|id| OverrideRef {
id,
override_of_id: None,
})
.collect();
(sb, ar_ids, lb_ids, ls_ids, sc_ids)
})
.collect();
let upstream_tuples: Vec<(crate::db::entities::upstream::Model, Vec<OverrideRef>)> =
upstreams
.into_iter()
.map(|u| {
let lb_ids = loc_block_ids_by_upstream
.get(&u.id)
.cloned()
.unwrap_or_default();
(u, lb_ids)
})
.collect();
// Combine server-level and location-level access rules into one flat list
let all_access_rules: Vec<crate::db::entities::access_rule::Model> = {
let mut ars =
Vec::with_capacity(server_access_rules.len() + location_access_rules.len());
ars.extend(server_access_rules);
ars.extend(location_access_rules);
ars
};
Ok(ProxyConfig {
id: proxy_entity.id,
name: proxy_entity.name,
r#type: ProxyType::Nginx,
description: proxy_entity.description,
parent_config_id,
server_blocks: server_block_tuples
.into_iter()
.map(|m| (m.0.id, m.into()))
.collect(),
upstreams: upstream_tuples
.into_iter()
.map(|m| (m.0.id, m.into()))
.collect(),
location_blocks: location_block_tuples
.into_iter()
.map(|m| (m.0.id, m.into()))
.collect(),
access_rules: all_access_rules
.into_iter()
.map(|m| (m.id, m.into()))
.collect(),
cache_zones: cache_zones.into_iter().map(|m| (m.id, m.into())).collect(),
limit_rules: limit_rules.into_iter().map(|m| (m.id, m.into())).collect(),
limit_zones: limit_zones.into_iter().map(|m| (m.id, m.into())).collect(),
log_settings: log_settings.into_iter().map(|m| (m.id, m.into())).collect(),
proxy_settings: proxy_settings
.into_iter()
.map(|m| (m.id, m.into()))
.collect(),
rewrite_rules: rewrite_rules
.into_iter()
.map(|m| (m.id, m.into()))
.collect(),
ssl_certificates: ssl_certificates
.into_iter()
.map(|m| (m.id, m.into()))
.collect(),
})
}
async fn get_merged_proxy_config(
&self,
proxy_id: uuid::Uuid,
) -> ProxyServiceResult<ProxyConfig> {
let configs = self.get_proxy_raw_configs(proxy_id).await?;
// configs is ordered [leaf, ..., root] (most specific first)
// self.merge(other) means self overrides other
// So start with leaf and merge each ancestor into it
let mut iter = configs.into_iter();
let mut merged = iter.next().ok_or(ProxyServiceError::ConfigNotFound)?;
for config in iter {
merged.merge(config);
}
Ok(merged)
}
}

View File

@@ -0,0 +1,478 @@
use std::collections::HashMap;
#[derive(Debug)]
pub enum ProxyServiceError {
ConfigNotFound,
InvalidConfig,
DatabaseError(sea_orm::DbErr),
}
impl From<sea_orm::DbErr> for ProxyServiceError {
fn from(err: sea_orm::DbErr) -> Self {
ProxyServiceError::DatabaseError(err)
}
}
pub type ProxyServiceResult<T> = Result<T, ProxyServiceError>;
pub enum ProxyType {
Nginx,
}
pub trait Mergeable<T> {
// merge with other, self overrides other
fn merge(&mut self, other: T);
}
#[derive(Debug, Clone)]
pub struct OverrideRef {
pub id: uuid::Uuid,
pub override_of_id: Option<uuid::Uuid>,
}
pub fn merge_override_vecs(
mut child: Vec<OverrideRef>,
parent: Vec<OverrideRef>,
) -> Vec<OverrideRef> {
let overridden_ids: std::collections::HashSet<uuid::Uuid> = child
.iter()
.filter_map(|r| r.override_of_id)
.collect();
for item in parent {
if !overridden_ids.contains(&item.id) {
child.push(item);
}
}
child
}
pub trait Overridable {
fn override_of_id(&self) -> Option<uuid::Uuid>;
}
pub struct ProxyConfig {
pub id: uuid::Uuid,
pub name: String,
pub r#type: ProxyType,
pub description: Option<String>,
pub parent_config_id: Option<Vec<uuid::Uuid>>,
//
pub server_blocks: HashMap<uuid::Uuid, ServerBlockConfig>,
pub upstreams: HashMap<uuid::Uuid, UpstreamConfig>,
pub access_rules: HashMap<uuid::Uuid, AccessRuleConfig>,
pub cache_zones: HashMap<uuid::Uuid, CacheZoneConfig>,
pub limit_rules: HashMap<uuid::Uuid, LimitRuleConfig>,
pub limit_zones: HashMap<uuid::Uuid, LimitZoneConfig>,
pub location_blocks: HashMap<uuid::Uuid, LocationBlockConfig>,
pub log_settings: HashMap<uuid::Uuid, LogSettingConfig>,
pub proxy_settings: HashMap<uuid::Uuid, ProxySettingConfig>,
pub rewrite_rules: HashMap<uuid::Uuid, RewriteRuleConfig>,
pub ssl_certificates: HashMap<uuid::Uuid, SslCertificateConfig>,
}
impl Mergeable<ProxyConfig> for ProxyConfig {
fn merge(&mut self, other: ProxyConfig) {
use std::collections::HashSet;
macro_rules! merge_overridable_field {
($field:ident) => {
let overridden: HashSet<uuid::Uuid> = self.$field
.values()
.filter_map(|v| v.override_of_id())
.collect();
for (id, value) in other.$field {
if !overridden.contains(&id) && !self.$field.contains_key(&id) {
self.$field.insert(id, value);
}
}
};
}
// server_blocks: merge matching entries (field-level), handle overrides
{
let overridden: HashSet<uuid::Uuid> = self.server_blocks
.values()
.filter_map(|sb| sb.override_of_id)
.collect();
for (id, block) in other.server_blocks {
if let Some(self_block) = self.server_blocks.get_mut(&id) {
self_block.merge(block);
} else if !overridden.contains(&id) {
self.server_blocks.insert(id, block);
}
}
}
merge_overridable_field!(upstreams);
merge_overridable_field!(access_rules);
merge_overridable_field!(cache_zones);
merge_overridable_field!(limit_rules);
merge_overridable_field!(limit_zones);
merge_overridable_field!(location_blocks);
merge_overridable_field!(log_settings);
merge_overridable_field!(proxy_settings);
merge_overridable_field!(rewrite_rules);
// ssl_certificates: simple merge (no override_of_id)
for (id, cert) in other.ssl_certificates {
self.ssl_certificates.entry(id).or_insert(cert);
}
}
}
pub struct ServerBlockConfig {
pub id: uuid::Uuid,
pub server_name: Option<Vec<String>>,
pub listen_port: i32,
pub ssl_enabled: Option<bool>,
pub override_of_id: Option<uuid::Uuid>,
//
pub access_rules: Vec<OverrideRef>,
pub location_blocks: Vec<OverrideRef>,
pub log_settings: Vec<OverrideRef>,
pub ssl_certificates: Vec<OverrideRef>,
}
impl
From<(
crate::db::entities::server_block::Model,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
)> for ServerBlockConfig
{
fn from(
(model, access_rules, location_blocks, log_settings, ssl_certificates): (
crate::db::entities::server_block::Model,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
),
) -> Self {
ServerBlockConfig {
id: model.id,
server_name: model.server_name,
listen_port: model.listen_port,
ssl_enabled: model.ssl_enabled,
override_of_id: model.override_of_id,
access_rules,
location_blocks,
log_settings,
ssl_certificates,
}
}
}
impl Mergeable<ServerBlockConfig> for ServerBlockConfig {
fn merge(&mut self, other: ServerBlockConfig) {
if let Some(server_name) = other.server_name {
self.server_name = Some(server_name);
}
self.listen_port = other.listen_port;
if let Some(ssl_enabled) = other.ssl_enabled {
self.ssl_enabled = Some(ssl_enabled);
}
self.override_of_id = other.override_of_id;
self.access_rules = merge_override_vecs(
std::mem::take(&mut self.access_rules),
other.access_rules,
);
self.location_blocks = merge_override_vecs(
std::mem::take(&mut self.location_blocks),
other.location_blocks,
);
self.log_settings = merge_override_vecs(
std::mem::take(&mut self.log_settings),
other.log_settings,
);
self.ssl_certificates = merge_override_vecs(
std::mem::take(&mut self.ssl_certificates),
other.ssl_certificates,
);
}
}
pub struct UpstreamConfig {
pub id: uuid::Uuid,
pub name: String,
pub target_host: String,
pub target_port: i32,
pub metadata: Option<serde_json::Value>,
pub override_of_id: Option<uuid::Uuid>,
//
pub location_blocks: Vec<OverrideRef>,
}
impl From<(crate::db::entities::upstream::Model, Vec<OverrideRef>)> for UpstreamConfig {
fn from(
(model, location_blocks): (crate::db::entities::upstream::Model, Vec<OverrideRef>),
) -> Self {
UpstreamConfig {
id: model.id,
name: model.name,
target_host: model.target_host,
target_port: model.target_port,
metadata: model.metadata,
override_of_id: model.override_of_id,
location_blocks,
}
}
}
pub struct AccessRuleConfig {
pub id: uuid::Uuid,
pub r#type: String,
pub ip_cidr: String,
pub description: Option<String>,
pub priority: i32,
pub override_of_id: Option<uuid::Uuid>,
}
impl From<crate::db::entities::access_rule::Model> for AccessRuleConfig {
fn from(model: crate::db::entities::access_rule::Model) -> Self {
AccessRuleConfig {
id: model.id,
r#type: model.r#type,
ip_cidr: model.ip_cidr,
description: model.description,
priority: model.priority,
override_of_id: model.override_of_id,
}
}
}
pub struct CacheZoneConfig {
pub id: uuid::Uuid,
pub name: String,
pub size: String,
pub override_of_id: Option<uuid::Uuid>,
}
impl From<crate::db::entities::cache_zone::Model> for CacheZoneConfig {
fn from(model: crate::db::entities::cache_zone::Model) -> Self {
CacheZoneConfig {
id: model.id,
name: model.name,
size: model.size_limit,
override_of_id: model.override_of_id,
}
}
}
pub struct LimitRuleConfig {
pub id: uuid::Uuid,
pub location_id: uuid::Uuid,
pub zone_id: uuid::Uuid,
pub burst: Option<i32>,
pub nodelay: Option<bool>,
pub is_deleted: bool,
pub override_of_id: Option<uuid::Uuid>,
}
impl From<crate::db::entities::limit_rule::Model> for LimitRuleConfig {
fn from(model: crate::db::entities::limit_rule::Model) -> Self {
LimitRuleConfig {
id: model.id,
location_id: model.location_id,
zone_id: model.zone_id,
burst: model.burst,
nodelay: model.nodelay,
is_deleted: model.is_deleted,
override_of_id: model.override_of_id,
}
}
}
pub struct LimitZoneConfig {
pub id: uuid::Uuid,
pub name: String,
pub key: String,
pub rate: String,
pub override_of_id: Option<uuid::Uuid>,
}
impl From<crate::db::entities::limit_zone::Model> for LimitZoneConfig {
fn from(model: crate::db::entities::limit_zone::Model) -> Self {
LimitZoneConfig {
id: model.id,
name: model.name,
key: model.key,
rate: model.rate,
override_of_id: model.override_of_id,
}
}
}
pub struct LocationBlockConfig {
pub id: uuid::Uuid,
pub server_id: uuid::Uuid,
pub path_pattern: String,
pub proxy_pass_upstream_id: Option<uuid::Uuid>,
pub metadata: Option<serde_json::Value>,
pub override_of_id: Option<uuid::Uuid>,
//
pub access_rules: Vec<OverrideRef>,
pub limit_rules: Vec<OverrideRef>,
pub proxy_settings: Vec<OverrideRef>,
pub rewrite_rules: Vec<OverrideRef>,
}
impl
From<(
crate::db::entities::location_block::Model,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
)> for LocationBlockConfig
{
fn from(
(model, access_rules, limit_rules, proxy_settings, rewrite_rules): (
crate::db::entities::location_block::Model,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
Vec<OverrideRef>,
),
) -> Self {
LocationBlockConfig {
id: model.id,
server_id: model.server_id,
path_pattern: model.path_pattern,
proxy_pass_upstream_id: model.proxy_pass_upstream_id,
metadata: model.metadata,
override_of_id: model.override_of_id,
access_rules,
limit_rules,
proxy_settings,
rewrite_rules,
}
}
}
pub struct LogSettingConfig {
pub id: uuid::Uuid,
pub access_log_path: Option<String>,
pub error_log_path: Option<String>,
pub log_level: Option<String>,
pub override_of_id: Option<uuid::Uuid>,
}
impl From<crate::db::entities::log_setting::Model> for LogSettingConfig {
fn from(model: crate::db::entities::log_setting::Model) -> Self {
LogSettingConfig {
id: model.id,
access_log_path: model.access_log_path,
error_log_path: model.error_log_path,
log_level: model.log_level,
override_of_id: model.override_of_id,
}
}
}
pub struct SslCertificateConfig {
pub id: uuid::Uuid,
pub name: String,
pub cert_path: String,
pub key_path: String,
pub expiry_date: chrono::DateTime<chrono::Utc>,
}
impl From<crate::db::entities::ssl_certificate::Model> for SslCertificateConfig {
fn from(model: crate::db::entities::ssl_certificate::Model) -> Self {
SslCertificateConfig {
id: model.id,
name: model.name,
cert_path: model.cert_path,
key_path: model.key_path,
expiry_date: model.expiry_date.and_utc(),
}
}
}
pub struct ProxySettingConfig {
pub id: uuid::Uuid,
pub location_id: uuid::Uuid,
pub read_timeout: Option<i32>,
pub connect_timeout: Option<i32>,
pub buffer_size: Option<i32>,
pub cache_enabled: Option<bool>,
pub cache_zone: Option<uuid::Uuid>,
pub override_of_id: Option<uuid::Uuid>,
}
impl From<crate::db::entities::proxy_setting::Model> for ProxySettingConfig {
fn from(model: crate::db::entities::proxy_setting::Model) -> Self {
ProxySettingConfig {
id: model.id,
location_id: model.location_id,
read_timeout: model.read_timeout,
connect_timeout: model.connect_timeout,
buffer_size: model.buffer_size,
cache_enabled: model.cache_enabled,
cache_zone: model.cache_zone,
override_of_id: model.override_of_id,
}
}
}
pub struct RewriteRuleConfig {
pub id: uuid::Uuid,
pub location_id: uuid::Uuid,
pub pattern: String,
pub replacement: String,
pub flag: Option<String>,
pub priority: i32,
pub override_of_id: Option<uuid::Uuid>,
}
impl From<crate::db::entities::rewrite_rule::Model> for RewriteRuleConfig {
fn from(model: crate::db::entities::rewrite_rule::Model) -> Self {
RewriteRuleConfig {
id: model.id,
location_id: model.location_id,
pattern: model.pattern,
replacement: model.replacement,
flag: model.flag,
priority: model.priority,
override_of_id: model.override_of_id,
}
}
}
// ── Overridable implementations ──
impl Overridable for ServerBlockConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for UpstreamConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for AccessRuleConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for CacheZoneConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for LimitRuleConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for LimitZoneConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for LocationBlockConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for LogSettingConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for ProxySettingConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}
impl Overridable for RewriteRuleConfig {
fn override_of_id(&self) -> Option<uuid::Uuid> { self.override_of_id }
}

View File

@@ -2,6 +2,7 @@ pub use sea_orm_migration::prelude::*;
mod m20260301_000001_create_agents;
mod m20260301_000002_create_public_key_revokaction;
mod m20260620_111325_create_proxy_tables;
pub struct Migrator;
@@ -11,6 +12,7 @@ impl MigratorTrait for Migrator {
vec![
Box::new(m20260301_000001_create_agents::Migration),
Box::new(m20260301_000002_create_public_key_revokaction::Migration),
Box::new(m20260620_111325_create_proxy_tables::Migration),
]
}
}

View File

@@ -0,0 +1,902 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(AgentGroup::Table)
.if_not_exists()
.col(
ColumnDef::new(AgentGroup::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(AgentGroup::Name).string().not_null())
.col(ColumnDef::new(AgentGroup::Description).string())
.to_owned(),
)
.await?;
manager
.alter_table(
Table::alter()
.table(Agents::Table)
.add_column(ColumnDef::new(Agents::GroupId).uuid().null())
.add_foreign_key(
TableForeignKey::new()
.name("fk_agents_group_id")
.from_tbl(Agents::Table)
.to_tbl(AgentGroup::Table)
.from_col(Agents::GroupId)
.to_col(AgentGroup::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(ProxyConfig::Table)
.if_not_exists()
.col(
ColumnDef::new(ProxyConfig::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(ProxyConfig::Name).string().not_null())
.col(ColumnDef::new(ProxyConfig::Description).string())
.col(ColumnDef::new(ProxyConfig::IsTemplate).boolean().not_null())
.col(
ColumnDef::new(ProxyConfig::CreatedAt)
.timestamp()
.not_null(),
)
.col(
ColumnDef::new(ProxyConfig::UpdatedAt)
.timestamp()
.not_null(),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(SSLCertificate::Table)
.if_not_exists()
.col(
ColumnDef::new(SSLCertificate::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(SSLCertificate::Name).string().not_null())
.col(ColumnDef::new(SSLCertificate::CertPath).string().not_null())
.col(ColumnDef::new(SSLCertificate::KeyPath).string().not_null())
.col(
ColumnDef::new(SSLCertificate::ExpiryDate)
.timestamp()
.not_null(),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(CacheZone::Table)
.if_not_exists()
.col(
ColumnDef::new(CacheZone::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(CacheZone::Name).string().not_null())
.col(ColumnDef::new(CacheZone::Path).string().not_null())
.col(ColumnDef::new(CacheZone::SizeLimit).string().not_null())
.col(ColumnDef::new(CacheZone::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_cache_zone_override_of")
.from_tbl(CacheZone::Table)
.to_tbl(CacheZone::Table)
.from_col(CacheZone::OverrideOfId)
.to_col(CacheZone::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(LimitZone::Table)
.if_not_exists()
.col(
ColumnDef::new(LimitZone::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(LimitZone::Name).string().not_null())
.col(ColumnDef::new(LimitZone::Key).string().not_null())
.col(ColumnDef::new(LimitZone::Rate).string().not_null())
.col(ColumnDef::new(LimitZone::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_limit_zone_override_of")
.from_tbl(LimitZone::Table)
.to_tbl(LimitZone::Table)
.from_col(LimitZone::OverrideOfId)
.to_col(LimitZone::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(AgentConfigBinding::Table)
.if_not_exists()
.col(
ColumnDef::new(AgentConfigBinding::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(AgentConfigBinding::AgentId).uuid())
.col(ColumnDef::new(AgentConfigBinding::GroupId).uuid())
.col(
ColumnDef::new(AgentConfigBinding::ConfigId)
.uuid()
.not_null(),
)
.col(
ColumnDef::new(AgentConfigBinding::IsActive)
.boolean()
.not_null(),
)
.col(
ColumnDef::new(AgentConfigBinding::AppliedAt)
.timestamp()
.not_null(),
)
.foreign_key(
ForeignKey::create()
.name("fk_agent_config_binding_agent")
.from_tbl(AgentConfigBinding::Table)
.to_tbl(Agents::Table)
.from_col(AgentConfigBinding::AgentId)
.to_col(Agents::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_agent_config_binding_group")
.from_tbl(AgentConfigBinding::Table)
.to_tbl(AgentGroup::Table)
.from_col(AgentConfigBinding::GroupId)
.to_col(AgentGroup::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_agent_config_binding_config")
.from_tbl(AgentConfigBinding::Table)
.to_tbl(ProxyConfig::Table)
.from_col(AgentConfigBinding::ConfigId)
.to_col(ProxyConfig::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(ConfigInheritance::Table)
.if_not_exists()
.col(
ColumnDef::new(ConfigInheritance::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(
ColumnDef::new(ConfigInheritance::ChildConfigId)
.uuid()
.not_null(),
)
.col(
ColumnDef::new(ConfigInheritance::ParentConfigId)
.uuid()
.not_null(),
)
.col(ColumnDef::new(ConfigInheritance::Priority).integer())
.col(
ColumnDef::new(ConfigInheritance::AppliedAt)
.timestamp()
.not_null(),
)
.foreign_key(
ForeignKey::create()
.name("fk_config_inheritance_child")
.from_tbl(ConfigInheritance::Table)
.to_tbl(ProxyConfig::Table)
.from_col(ConfigInheritance::ChildConfigId)
.to_col(ProxyConfig::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_config_inheritance_parent")
.from_tbl(ConfigInheritance::Table)
.to_tbl(ProxyConfig::Table)
.from_col(ConfigInheritance::ParentConfigId)
.to_col(ProxyConfig::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(Upstream::Table)
.if_not_exists()
.col(ColumnDef::new(Upstream::Id).uuid().not_null().primary_key())
.col(ColumnDef::new(Upstream::ConfigId).uuid().not_null())
.col(ColumnDef::new(Upstream::Name).string().not_null())
.col(ColumnDef::new(Upstream::TargetHost).string().not_null())
.col(ColumnDef::new(Upstream::TargetPort).integer().not_null())
.col(ColumnDef::new(Upstream::Metadata).json_binary())
.col(ColumnDef::new(Upstream::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_upstream_config")
.from_tbl(Upstream::Table)
.to_tbl(ProxyConfig::Table)
.from_col(Upstream::ConfigId)
.to_col(ProxyConfig::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_upstream_override_of")
.from_tbl(Upstream::Table)
.to_tbl(Upstream::Table)
.from_col(Upstream::OverrideOfId)
.to_col(Upstream::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(ServerBlock::Table)
.if_not_exists()
.col(
ColumnDef::new(ServerBlock::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(ServerBlock::ConfigId).uuid().not_null())
.col(
ColumnDef::new(ServerBlock::ServerName)
.array(ColumnType::String(StringLen::None)),
)
.col(ColumnDef::new(ServerBlock::ListenPort).integer().not_null())
.col(ColumnDef::new(ServerBlock::SslEnabled).boolean())
.col(ColumnDef::new(ServerBlock::SslCertId).uuid())
.col(ColumnDef::new(ServerBlock::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_server_block_config")
.from_tbl(ServerBlock::Table)
.to_tbl(ProxyConfig::Table)
.from_col(ServerBlock::ConfigId)
.to_col(ProxyConfig::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_server_block_ssl_cert")
.from_tbl(ServerBlock::Table)
.to_tbl(SSLCertificate::Table)
.from_col(ServerBlock::SslCertId)
.to_col(SSLCertificate::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_server_block_override_of")
.from_tbl(ServerBlock::Table)
.to_tbl(ServerBlock::Table)
.from_col(ServerBlock::OverrideOfId)
.to_col(ServerBlock::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(LocationBlock::Table)
.if_not_exists()
.col(
ColumnDef::new(LocationBlock::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(LocationBlock::ServerId).uuid().not_null())
.col(
ColumnDef::new(LocationBlock::PathPattern)
.string()
.not_null(),
)
.col(ColumnDef::new(LocationBlock::ProxyPassUpstreamId).uuid())
.col(ColumnDef::new(LocationBlock::Metadata).json_binary())
.col(ColumnDef::new(LocationBlock::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_location_block_server")
.from_tbl(LocationBlock::Table)
.to_tbl(ServerBlock::Table)
.from_col(LocationBlock::ServerId)
.to_col(ServerBlock::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_location_block_upstream")
.from_tbl(LocationBlock::Table)
.to_tbl(Upstream::Table)
.from_col(LocationBlock::ProxyPassUpstreamId)
.to_col(Upstream::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_location_block_override_of")
.from_tbl(LocationBlock::Table)
.to_tbl(LocationBlock::Table)
.from_col(LocationBlock::OverrideOfId)
.to_col(LocationBlock::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(AccessRule::Table)
.if_not_exists()
.col(
ColumnDef::new(AccessRule::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(AccessRule::ServerId).uuid())
.col(ColumnDef::new(AccessRule::LocationId).uuid())
.col(
ColumnDef::new(AccessRule::Type)
.string()
.not_null()
.comment("allow or deny"),
)
.col(
ColumnDef::new(AccessRule::IpCidr)
.string()
.not_null()
.comment("IP address or CIDR range. 0.0.0.0/0 means all IPs"),
)
.col(ColumnDef::new(AccessRule::Description).string())
.col(
ColumnDef::new(AccessRule::Priority)
.integer()
.not_null()
.comment(
"Priority of the access rule. Lower number means higher priority.",
),
)
.col(ColumnDef::new(AccessRule::IsDeleted).boolean().not_null())
.col(ColumnDef::new(AccessRule::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_access_rule_server")
.from_tbl(AccessRule::Table)
.to_tbl(ServerBlock::Table)
.from_col(AccessRule::ServerId)
.to_col(ServerBlock::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_access_rule_location")
.from_tbl(AccessRule::Table)
.to_tbl(LocationBlock::Table)
.from_col(AccessRule::LocationId)
.to_col(LocationBlock::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_access_rule_override_of")
.from_tbl(AccessRule::Table)
.to_tbl(AccessRule::Table)
.from_col(AccessRule::OverrideOfId)
.to_col(AccessRule::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(RewriteRule::Table)
.if_not_exists()
.col(
ColumnDef::new(RewriteRule::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(RewriteRule::LocationId).uuid().not_null())
.col(ColumnDef::new(RewriteRule::Pattern).string().not_null())
.col(ColumnDef::new(RewriteRule::Replacement).string().not_null())
.col(ColumnDef::new(RewriteRule::Flag).string())
.col(ColumnDef::new(RewriteRule::Priority).integer().not_null())
.col(ColumnDef::new(RewriteRule::IsDeleted).boolean().not_null())
.col(ColumnDef::new(RewriteRule::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_rewrite_rule_location")
.from_tbl(RewriteRule::Table)
.to_tbl(LocationBlock::Table)
.from_col(RewriteRule::LocationId)
.to_col(LocationBlock::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_rewrite_rule_override_of")
.from_tbl(RewriteRule::Table)
.to_tbl(RewriteRule::Table)
.from_col(RewriteRule::OverrideOfId)
.to_col(RewriteRule::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(ProxySetting::Table)
.if_not_exists()
.col(
ColumnDef::new(ProxySetting::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(ProxySetting::LocationId).uuid().not_null())
.col(ColumnDef::new(ProxySetting::ReadTimeout).integer())
.col(ColumnDef::new(ProxySetting::ConnectTimeout).integer())
.col(ColumnDef::new(ProxySetting::BufferSize).integer())
.col(ColumnDef::new(ProxySetting::CacheEnabled).boolean())
.col(ColumnDef::new(ProxySetting::CacheZone).uuid())
.col(ColumnDef::new(ProxySetting::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_proxy_setting_location")
.from_tbl(ProxySetting::Table)
.to_tbl(LocationBlock::Table)
.from_col(ProxySetting::LocationId)
.to_col(LocationBlock::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_proxy_setting_cache_zone")
.from_tbl(ProxySetting::Table)
.to_tbl(CacheZone::Table)
.from_col(ProxySetting::CacheZone)
.to_col(CacheZone::Id)
.on_delete(ForeignKeyAction::SetNull),
)
.foreign_key(
ForeignKey::create()
.name("fk_proxy_setting_override_of")
.from_tbl(ProxySetting::Table)
.to_tbl(ProxySetting::Table)
.from_col(ProxySetting::OverrideOfId)
.to_col(ProxySetting::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(LimitRule::Table)
.if_not_exists()
.col(
ColumnDef::new(LimitRule::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(LimitRule::LocationId).uuid().not_null())
.col(ColumnDef::new(LimitRule::ZoneId).uuid().not_null())
.col(ColumnDef::new(LimitRule::Burst).integer())
.col(ColumnDef::new(LimitRule::Nodelay).boolean())
.col(ColumnDef::new(LimitRule::IsDeleted).boolean().not_null())
.col(ColumnDef::new(LimitRule::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_limit_rule_location")
.from_tbl(LimitRule::Table)
.to_tbl(LocationBlock::Table)
.from_col(LimitRule::LocationId)
.to_col(LocationBlock::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_limit_rule_zone")
.from_tbl(LimitRule::Table)
.to_tbl(LimitZone::Table)
.from_col(LimitRule::ZoneId)
.to_col(LimitZone::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_limit_rule_override_of")
.from_tbl(LimitRule::Table)
.to_tbl(LimitRule::Table)
.from_col(LimitRule::OverrideOfId)
.to_col(LimitRule::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(LogSetting::Table)
.if_not_exists()
.col(
ColumnDef::new(LogSetting::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(LogSetting::ServerId).uuid().not_null())
.col(ColumnDef::new(LogSetting::AccessLogPath).string())
.col(ColumnDef::new(LogSetting::ErrorLogPath).string())
.col(ColumnDef::new(LogSetting::LogLevel).string())
.col(ColumnDef::new(LogSetting::OverrideOfId).uuid())
.foreign_key(
ForeignKey::create()
.name("fk_log_setting_server")
.from_tbl(LogSetting::Table)
.to_tbl(ServerBlock::Table)
.from_col(LogSetting::ServerId)
.to_col(ServerBlock::Id)
.on_delete(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name("fk_log_setting_override_of")
.from_tbl(LogSetting::Table)
.to_tbl(LogSetting::Table)
.from_col(LogSetting::OverrideOfId)
.to_col(LogSetting::Id)
.on_delete(ForeignKeyAction::SetNull)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(LogSetting::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(LimitRule::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(ProxySetting::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(RewriteRule::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(AccessRule::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(LocationBlock::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(ServerBlock::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(Upstream::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(ConfigInheritance::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(AgentConfigBinding::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(LimitZone::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(CacheZone::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(SSLCertificate::Table).to_owned())
.await?;
manager
.drop_table(Table::drop().table(ProxyConfig::Table).to_owned())
.await?;
manager
.alter_table(
Table::alter()
.table(Agents::Table)
.drop_foreign_key(Alias::new("fk_agents_group_id"))
.to_owned(),
)
.await?;
manager
.alter_table(
Table::alter()
.table(Agents::Table)
.drop_column(Agents::GroupId)
.to_owned(),
)
.await?;
manager
.drop_table(Table::drop().table(AgentGroup::Table).to_owned())
.await?;
Ok(())
}
}
#[derive(DeriveIden)]
enum Agents {
Table,
Id,
GroupId,
}
#[derive(DeriveIden)]
enum AgentGroup {
Table,
Id,
Name,
Description,
}
#[derive(DeriveIden)]
enum AgentConfigBinding {
Table,
Id,
AgentId,
GroupId,
ConfigId,
IsActive,
AppliedAt,
}
#[derive(DeriveIden)]
enum ProxyConfig {
Table,
Id,
Name,
Description,
IsTemplate,
CreatedAt,
UpdatedAt,
}
#[derive(DeriveIden)]
enum ConfigInheritance {
Table,
Id,
ChildConfigId,
ParentConfigId,
Priority,
AppliedAt,
}
#[derive(DeriveIden)]
enum SSLCertificate {
Table,
Id,
Name,
CertPath,
KeyPath,
ExpiryDate,
}
#[derive(DeriveIden)]
enum CacheZone {
Table,
Id,
Name,
Path,
SizeLimit,
OverrideOfId,
}
#[derive(DeriveIden)]
enum LimitZone {
Table,
Id,
Name,
Key,
Rate,
OverrideOfId,
}
#[derive(DeriveIden)]
enum Upstream {
Table,
Id,
ConfigId,
Name,
TargetHost,
TargetPort,
Metadata,
OverrideOfId,
}
#[derive(DeriveIden)]
enum ServerBlock {
Table,
Id,
ConfigId,
ServerName,
ListenPort,
SslEnabled,
SslCertId,
OverrideOfId,
}
#[derive(DeriveIden)]
enum LocationBlock {
Table,
Id,
ServerId,
PathPattern,
ProxyPassUpstreamId,
Metadata,
OverrideOfId,
}
#[derive(DeriveIden)]
enum AccessRule {
Table,
Id,
ServerId,
LocationId,
Type,
IpCidr,
Priority,
Description,
IsDeleted,
OverrideOfId,
}
#[derive(DeriveIden)]
enum RewriteRule {
Table,
Id,
LocationId,
Pattern,
Replacement,
Flag,
Priority,
IsDeleted,
OverrideOfId,
}
#[derive(DeriveIden)]
enum ProxySetting {
Table,
Id,
LocationId,
ReadTimeout,
ConnectTimeout,
BufferSize,
CacheEnabled,
CacheZone,
OverrideOfId,
}
#[derive(DeriveIden)]
enum LimitRule {
Table,
Id,
LocationId,
ZoneId,
Burst,
Nodelay,
IsDeleted,
OverrideOfId,
}
#[derive(DeriveIden)]
enum LogSetting {
Table,
Id,
ServerId,
AccessLogPath,
ErrorLogPath,
LogLevel,
OverrideOfId,
}