mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-06 07:36:37 +08:00
migrate
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AcmeAccount OpenFlare ACME 账号实体。
|
||||
type AcmeAccount struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Email string `json:"email" gorm:"size:255"`
|
||||
URL string `json:"url" gorm:"size:255"`
|
||||
PrivateKey string `json:"-" gorm:"type:text;not null"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (AcmeAccount) TableName() string {
|
||||
return "of_acme_accounts"
|
||||
}
|
||||
|
||||
// GetAcmeAccountByID 按 ID 查询 ACME 账号。
|
||||
func GetAcmeAccountByID(ctx context.Context, id uint) (*AcmeAccount, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var account AcmeAccount
|
||||
if err := conn.First(&account, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
// GetDefaultAcmeAccount 获取默认 ACME 账号,不存在时创建占位记录。
|
||||
func GetDefaultAcmeAccount(ctx context.Context) (*AcmeAccount, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var account AcmeAccount
|
||||
err := conn.Order("id asc").First(&account).Error
|
||||
if err == nil {
|
||||
return &account, nil
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
account = AcmeAccount{
|
||||
Email: "admin@openflare.dev",
|
||||
}
|
||||
if err = conn.Create(&account).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &account, nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OpenFlareApplyLogQuery filters apply logs for list queries.
|
||||
type OpenFlareApplyLogQuery struct {
|
||||
NodeID string
|
||||
PageNo int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// OpenFlareApplyLog stores node configuration apply results.
|
||||
type OpenFlareApplyLog struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
Version string `json:"version" gorm:"size:32;not null"`
|
||||
Result string `json:"result" gorm:"size:32;not null"`
|
||||
Message string `json:"message" gorm:"type:text"`
|
||||
Checksum string `json:"checksum" gorm:"size:64;not null;default:''"`
|
||||
MainConfigChecksum string `json:"main_config_checksum" gorm:"size:64;not null;default:''"`
|
||||
RouteConfigChecksum string `json:"route_config_checksum" gorm:"size:64;not null;default:''"`
|
||||
SupportFileCount int `json:"support_file_count" gorm:"not null;default:0"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;index"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareApplyLog) TableName() string {
|
||||
return "of_apply_logs"
|
||||
}
|
||||
|
||||
// ListOpenFlareApplyLogs returns apply logs ordered by id desc with optional pagination.
|
||||
func ListOpenFlareApplyLogs(ctx context.Context, query OpenFlareApplyLogQuery) ([]*OpenFlareApplyLog, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
|
||||
dbQuery := conn.Model(&OpenFlareApplyLog{}).Order("id desc")
|
||||
if query.NodeID != "" {
|
||||
dbQuery = dbQuery.Where("node_id = ?", query.NodeID)
|
||||
}
|
||||
if query.PageSize > 0 {
|
||||
offset := 0
|
||||
if query.PageNo > 1 {
|
||||
offset = (query.PageNo - 1) * query.PageSize
|
||||
}
|
||||
dbQuery = dbQuery.Limit(query.PageSize).Offset(offset)
|
||||
}
|
||||
|
||||
var logs []*OpenFlareApplyLog
|
||||
if err := dbQuery.Find(&logs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
// CountOpenFlareApplyLogs returns total apply logs, optionally filtered by node_id.
|
||||
func CountOpenFlareApplyLogs(ctx context.Context, nodeID string) (int64, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return 0, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
|
||||
query := conn.Model(&OpenFlareApplyLog{})
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
// GetLatestOpenFlareApplyLogsByNodeIDs returns the latest apply log per node id.
|
||||
func GetLatestOpenFlareApplyLogsByNodeIDs(ctx context.Context, nodeIDs []string) (map[string]*OpenFlareApplyLog, error) {
|
||||
result := make(map[string]*OpenFlareApplyLog)
|
||||
if len(nodeIDs) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
|
||||
var logs []*OpenFlareApplyLog
|
||||
subQuery := conn.Model(&OpenFlareApplyLog{}).
|
||||
Select("MAX(id) AS id").
|
||||
Where("node_id IN ?", nodeIDs).
|
||||
Group("node_id")
|
||||
if err := conn.Where("id IN (?)", subQuery).Find(&logs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, log := range logs {
|
||||
result[log.NodeID] = log
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DeleteAllOpenFlareApplyLogs removes every apply log record.
|
||||
func DeleteAllOpenFlareApplyLogs(ctx context.Context) (int64, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return 0, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
|
||||
result := conn.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&OpenFlareApplyLog{})
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
// DeleteOpenFlareApplyLogsBefore removes apply logs created before the cutoff time.
|
||||
func DeleteOpenFlareApplyLogsBefore(ctx context.Context, before time.Time) (int64, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return 0, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
|
||||
result := conn.Where("created_at < ?", before).Delete(&OpenFlareApplyLog{})
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ConfigVersionSummary is the list view for config versions.
|
||||
type ConfigVersionSummary struct {
|
||||
ID uint `json:"id"`
|
||||
Version string `json:"version"`
|
||||
Checksum string `json:"checksum"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ConfigVersion stores a published OpenResty configuration snapshot.
|
||||
type ConfigVersion struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Version string `json:"version" gorm:"uniqueIndex;size:32;not null"`
|
||||
SnapshotJSON string `json:"snapshot_json" gorm:"type:text;not null"`
|
||||
MainConfig string `json:"main_config" gorm:"type:text;not null;default:''"`
|
||||
RenderedConfig string `json:"rendered_config" gorm:"type:text;not null"`
|
||||
SupportFilesJSON string `json:"support_files_json" gorm:"type:text;not null;default:'[]'"`
|
||||
Checksum string `json:"checksum" gorm:"size:64;not null"`
|
||||
IsActive bool `json:"is_active" gorm:"not null;default:false;index"`
|
||||
CreatedBy string `json:"created_by" gorm:"size:64;not null"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (ConfigVersion) TableName() string {
|
||||
return "of_config_versions"
|
||||
}
|
||||
|
||||
// ListConfigVersionSummaries returns config version summaries ordered by id desc.
|
||||
func ListConfigVersionSummaries(ctx context.Context) ([]*ConfigVersionSummary, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var versions []*ConfigVersionSummary
|
||||
err := conn.Model(&ConfigVersion{}).
|
||||
Select("id", "version", "checksum", "is_active", "created_by", "created_at").
|
||||
Order("id desc").
|
||||
Find(&versions).Error
|
||||
return versions, err
|
||||
}
|
||||
|
||||
// GetConfigVersionByID returns a config version by primary key.
|
||||
func GetConfigVersionByID(ctx context.Context, id uint) (*ConfigVersion, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var version ConfigVersion
|
||||
if err := conn.First(&version, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &version, nil
|
||||
}
|
||||
|
||||
// GetActiveConfigVersion returns the currently active config version.
|
||||
func GetActiveConfigVersion(ctx context.Context) (*ConfigVersion, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var version ConfigVersion
|
||||
if err := conn.Where("is_active = ?", true).Order("id desc").First(&version).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &version, nil
|
||||
}
|
||||
|
||||
// GetLatestConfigVersionByPrefix returns the latest version string matching a date prefix.
|
||||
func GetLatestConfigVersionByPrefix(ctx context.Context, prefix string) (string, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return "", errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var version ConfigVersion
|
||||
err := conn.Model(&ConfigVersion{}).
|
||||
Select("version").
|
||||
Where("version LIKE ?", prefix+"-%").
|
||||
Order("version desc").
|
||||
First(&version).Error
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return version.Version, nil
|
||||
}
|
||||
|
||||
// CreateConfigVersion inserts a new config version record.
|
||||
func CreateConfigVersion(ctx context.Context, version *ConfigVersion) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Create(version).Error
|
||||
}
|
||||
|
||||
// PublishConfigVersionTx deactivates all versions and creates a new active version.
|
||||
func PublishConfigVersionTx(ctx context.Context, version *ConfigVersion) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&ConfigVersion{}).Where("is_active = ?", true).Update("is_active", false).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(version).Error
|
||||
})
|
||||
}
|
||||
|
||||
// ActivateConfigVersionTx marks the given version active and deactivates others.
|
||||
func ActivateConfigVersionTx(ctx context.Context, id uint) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&ConfigVersion{}).Where("is_active = ?", true).Update("is_active", false).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&ConfigVersion{}).Where("id = ?", id).Update("is_active", true).Error
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteConfigVersionsByIDs removes config versions by ids.
|
||||
func DeleteConfigVersionsByIDs(ctx context.Context, ids []uint) (int64, error) {
|
||||
if len(ids) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return 0, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
result := conn.Where("id IN ?", ids).Delete(&ConfigVersion{})
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
// ListEnabledProxyRoutes returns enabled proxy routes ordered by id asc.
|
||||
func ListEnabledProxyRoutes(ctx context.Context) ([]*ProxyRoute, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var routes []*ProxyRoute
|
||||
if err := conn.Where("enabled = ?", true).Order("id asc").Find(&routes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return routes, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
)
|
||||
|
||||
// DNSAccount OpenFlare DNS 账号实体。
|
||||
type DNSAccount struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Name string `json:"name" gorm:"size:255;not null"`
|
||||
Type string `json:"type" gorm:"size:64;not null"`
|
||||
Authorization string `json:"-" gorm:"type:text;not null"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (DNSAccount) TableName() string {
|
||||
return "of_dns_accounts"
|
||||
}
|
||||
|
||||
// ListDNSAccounts 列出全部 DNS 账号(授权信息不通过 JSON 暴露)。
|
||||
func ListDNSAccounts(ctx context.Context) ([]DNSAccount, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var accounts []DNSAccount
|
||||
if err := conn.Order("id desc").Find(&accounts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
// GetDNSAccountByID 按 ID 查询 DNS 账号。
|
||||
func GetDNSAccountByID(ctx context.Context, id uint) (*DNSAccount, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var account DNSAccount
|
||||
if err := conn.First(&account, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
// CreateDNSAccountRecord 创建 DNS 账号。
|
||||
func CreateDNSAccountRecord(ctx context.Context, account *DNSAccount) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Create(account).Error
|
||||
}
|
||||
|
||||
// SaveDNSAccount 保存 DNS 账号。
|
||||
func SaveDNSAccount(ctx context.Context, account *DNSAccount) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Save(account).Error
|
||||
}
|
||||
|
||||
// DeleteDNSAccountRecord 删除 DNS 账号。
|
||||
func DeleteDNSAccountRecord(ctx context.Context, id uint) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Delete(&DNSAccount{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
)
|
||||
|
||||
// ManagedDomain OpenFlare 托管域名实体。
|
||||
type ManagedDomain struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Domain string `json:"domain" gorm:"uniqueIndex;size:255;not null"`
|
||||
CertID *uint `json:"cert_id"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (ManagedDomain) TableName() string {
|
||||
return "of_managed_domains"
|
||||
}
|
||||
|
||||
// ListManagedDomains 列出全部托管域名。
|
||||
func ListManagedDomains(ctx context.Context) ([]ManagedDomain, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var domains []ManagedDomain
|
||||
if err := conn.Order("id desc").Find(&domains).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return domains, nil
|
||||
}
|
||||
|
||||
// ListEnabledManagedDomainsWithCertificate 列出已启用且绑定证书的托管域名。
|
||||
func ListEnabledManagedDomainsWithCertificate(ctx context.Context) ([]ManagedDomain, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var domains []ManagedDomain
|
||||
if err := conn.Where("enabled = ? AND cert_id IS NOT NULL", true).Order("id desc").Find(&domains).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return domains, nil
|
||||
}
|
||||
|
||||
// GetManagedDomainByID 按 ID 查询托管域名。
|
||||
func GetManagedDomainByID(ctx context.Context, id uint) (*ManagedDomain, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var domain ManagedDomain
|
||||
if err := conn.First(&domain, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain, nil
|
||||
}
|
||||
|
||||
// CreateManagedDomainRecord 创建托管域名。
|
||||
func CreateManagedDomainRecord(ctx context.Context, domain *ManagedDomain) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Create(domain).Error
|
||||
}
|
||||
|
||||
// SaveManagedDomain 保存托管域名。
|
||||
func SaveManagedDomain(ctx context.Context, domain *ManagedDomain) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Save(domain).Error
|
||||
}
|
||||
|
||||
// DeleteManagedDomainRecord 删除托管域名。
|
||||
func DeleteManagedDomainRecord(ctx context.Context, id uint) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Delete(&ManagedDomain{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
)
|
||||
|
||||
// OpenFlareNode stores an edge, relay, or tunnel client node.
|
||||
type OpenFlareNode struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"uniqueIndex;size:64;not null"`
|
||||
Name string `json:"name" gorm:"size:128;not null"`
|
||||
IP string `json:"ip" gorm:"size:64;not null;default:''"`
|
||||
IPManualOverride bool `json:"ip_manual_override" gorm:"not null;default:false"`
|
||||
GeoName string `json:"geo_name" gorm:"size:128;not null;default:''"`
|
||||
GeoLatitude *float64 `json:"geo_latitude"`
|
||||
GeoLongitude *float64 `json:"geo_longitude"`
|
||||
GeoManualOverride bool `json:"geo_manual_override" gorm:"not null;default:false"`
|
||||
AccessToken string `json:"-" gorm:"column:access_token;size:128;index"`
|
||||
AutoUpdateEnabled bool `json:"auto_update_enabled" gorm:"not null;default:false"`
|
||||
UpdateRequested bool `json:"update_requested" gorm:"not null;default:false"`
|
||||
UpdateChannel string `json:"update_channel" gorm:"size:16;not null;default:'stable'"`
|
||||
UpdateTag string `json:"update_tag" gorm:"size:64;not null;default:''"`
|
||||
RestartOpenrestyRequested bool `json:"restart_openresty_requested" gorm:"not null;default:false"`
|
||||
Version string `json:"version" gorm:"size:64;not null;default:''"`
|
||||
ExtVersion string `json:"ext_version" gorm:"size:64;not null;default:''"`
|
||||
OpenrestyStatus string `json:"openresty_status" gorm:"size:16;not null;default:'unknown'"`
|
||||
OpenrestyMessage string `json:"openresty_message" gorm:"type:text"`
|
||||
Status string `json:"status" gorm:"size:16;not null;default:'offline'"`
|
||||
CurrentVersion string `json:"current_version" gorm:"size:32;not null;default:''"`
|
||||
LastSeenAt *time.Time `json:"last_seen_at"`
|
||||
LastError string `json:"last_error" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
NodeType string `json:"node_type" gorm:"size:32;not null;default:'edge_node'"`
|
||||
RelayBindPort int `json:"relay_bind_port" gorm:"not null;default:0"`
|
||||
RelayVhostHTTPPort int `json:"relay_vhost_http_port" gorm:"not null;default:0"`
|
||||
RelayAuthToken string `json:"-" gorm:"size:128;not null;default:''"`
|
||||
RelayAgentAccessAddr string `json:"relay_agent_access_addr" gorm:"size:255;not null;default:''"`
|
||||
RelayClientAccessAddr string `json:"relay_client_access_addr" gorm:"size:255;not null;default:''"`
|
||||
RelayClientProxyURL string `json:"relay_client_proxy_url" gorm:"size:512;not null;default:''"`
|
||||
CapabilitiesJSON string `json:"capabilities_json" gorm:"type:text;not null;default:'[]'"`
|
||||
RelayStatus string `json:"relay_status" gorm:"size:16;not null;default:'unknown'"`
|
||||
RelayWebServerEnabled bool `json:"relay_web_server_enabled" gorm:"not null;default:false"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareNode) TableName() string {
|
||||
return "of_nodes"
|
||||
}
|
||||
|
||||
// ListOpenFlareNodes returns all nodes ordered by id desc.
|
||||
func ListOpenFlareNodes(ctx context.Context) ([]OpenFlareNode, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var nodes []OpenFlareNode
|
||||
if err := conn.Order("id desc").Find(&nodes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareNodesByNodeIDs returns nodes matching the given node ids.
|
||||
func ListOpenFlareNodesByNodeIDs(ctx context.Context, nodeIDs []string) ([]OpenFlareNode, error) {
|
||||
if len(nodeIDs) == 0 {
|
||||
return []OpenFlareNode{}, nil
|
||||
}
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var nodes []OpenFlareNode
|
||||
if err := conn.Where("node_id IN ?", nodeIDs).Find(&nodes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// GetOpenFlareNodeByID returns a node by primary key.
|
||||
func GetOpenFlareNodeByID(ctx context.Context, id uint) (*OpenFlareNode, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var node OpenFlareNode
|
||||
if err := conn.First(&node, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &node, nil
|
||||
}
|
||||
|
||||
// GetOpenFlareNodeByNodeID returns a node by node_id.
|
||||
func GetOpenFlareNodeByNodeID(ctx context.Context, nodeID string) (*OpenFlareNode, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var node OpenFlareNode
|
||||
if err := conn.Where("node_id = ?", nodeID).First(&node).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &node, nil
|
||||
}
|
||||
|
||||
// GetOpenFlareNodeByAccessToken returns a node by access token.
|
||||
func GetOpenFlareNodeByAccessToken(ctx context.Context, token string) (*OpenFlareNode, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var node OpenFlareNode
|
||||
if err := conn.Where("access_token = ?", token).First(&node).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &node, nil
|
||||
}
|
||||
|
||||
// CreateOpenFlareNode inserts a new node.
|
||||
func CreateOpenFlareNode(ctx context.Context, node *OpenFlareNode) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Create(node).Error
|
||||
}
|
||||
|
||||
// SaveOpenFlareNode persists node changes.
|
||||
func SaveOpenFlareNode(ctx context.Context, node *OpenFlareNode) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Save(node).Error
|
||||
}
|
||||
|
||||
// UpdateOpenFlareNodeFields updates selected columns for a node.
|
||||
func UpdateOpenFlareNodeFields(ctx context.Context, node *OpenFlareNode, fields ...string) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
if len(fields) == 0 {
|
||||
return conn.Save(node).Error
|
||||
}
|
||||
return conn.Model(node).Select(fields).Updates(node).Error
|
||||
}
|
||||
|
||||
// DeleteOpenFlareNode removes a node by primary key.
|
||||
func DeleteOpenFlareNode(ctx context.Context, id uint) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Delete(&OpenFlareNode{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OpenFlareMetricSnapshot stores a node capacity snapshot (v1 single table, no sharding).
|
||||
type OpenFlareMetricSnapshot struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
CapturedAt time.Time `json:"captured_at" gorm:"index"`
|
||||
CPUUsagePercent float64 `json:"cpu_usage_percent"`
|
||||
MemoryUsedBytes int64 `json:"memory_used_bytes"`
|
||||
MemoryTotalBytes int64 `json:"memory_total_bytes"`
|
||||
StorageUsedBytes int64 `json:"storage_used_bytes"`
|
||||
StorageTotalBytes int64 `json:"storage_total_bytes"`
|
||||
DiskReadBytes int64 `json:"disk_read_bytes"`
|
||||
DiskWriteBytes int64 `json:"disk_write_bytes"`
|
||||
NetworkRxBytes int64 `json:"network_rx_bytes"`
|
||||
NetworkTxBytes int64 `json:"network_tx_bytes"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareMetricSnapshot) TableName() string {
|
||||
return "of_node_metric_snapshots"
|
||||
}
|
||||
|
||||
// OpenFlareRequestReport stores aggregated traffic windows per node.
|
||||
type OpenFlareRequestReport struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
WindowStartedAt time.Time `json:"window_started_at" gorm:"index"`
|
||||
WindowEndedAt time.Time `json:"window_ended_at" gorm:"index"`
|
||||
RequestCount int64 `json:"request_count"`
|
||||
ErrorCount int64 `json:"error_count"`
|
||||
UniqueVisitorCount int64 `json:"unique_visitor_count"`
|
||||
StatusCodesJSON string `json:"status_codes_json" gorm:"type:text"`
|
||||
TopDomainsJSON string `json:"top_domains_json" gorm:"type:text"`
|
||||
SourceCountriesJSON string `json:"source_countries_json" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareRequestReport) TableName() string {
|
||||
return "of_node_request_reports"
|
||||
}
|
||||
|
||||
// OpenFlareAccessLog stores a single access log row (v1 single table, no sharding).
|
||||
type OpenFlareAccessLog struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
LoggedAt time.Time `json:"logged_at" gorm:"index"`
|
||||
RemoteAddr string `json:"remote_addr" gorm:"index;size:128"`
|
||||
Region string `json:"region" gorm:"size:128"`
|
||||
Host string `json:"host" gorm:"index;size:255"`
|
||||
Path string `json:"path" gorm:"size:2048"`
|
||||
StatusCode int `json:"status_code" gorm:"index"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareAccessLog) TableName() string {
|
||||
return "of_node_access_logs"
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogRegionCount aggregates access log regions.
|
||||
type OpenFlareAccessLogRegionCount struct {
|
||||
Region string `json:"region"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// OpenFlareHealthEvent stores node health alert events.
|
||||
type OpenFlareHealthEvent struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
EventType string `json:"event_type" gorm:"index;size:64;not null"`
|
||||
Severity string `json:"severity" gorm:"size:16;not null"`
|
||||
Status string `json:"status" gorm:"index;size:16;not null"`
|
||||
Message string `json:"message" gorm:"type:text"`
|
||||
FirstTriggeredAt time.Time `json:"first_triggered_at" gorm:"index"`
|
||||
LastTriggeredAt time.Time `json:"last_triggered_at" gorm:"index"`
|
||||
ReportedAt time.Time `json:"reported_at" gorm:"index"`
|
||||
ResolvedAt *time.Time `json:"resolved_at" gorm:"index"`
|
||||
MetadataJSON string `json:"metadata_json" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareHealthEvent) TableName() string {
|
||||
return "of_node_health_events"
|
||||
}
|
||||
|
||||
// OpenFlareNodeSystemProfile stores the latest node system profile.
|
||||
type OpenFlareNodeSystemProfile struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"uniqueIndex;size:64;not null"`
|
||||
Hostname string `json:"hostname" gorm:"size:255"`
|
||||
OSName string `json:"os_name" gorm:"size:128"`
|
||||
OSVersion string `json:"os_version" gorm:"size:128"`
|
||||
KernelVersion string `json:"kernel_version" gorm:"size:128"`
|
||||
Architecture string `json:"architecture" gorm:"size:64"`
|
||||
CPUModel string `json:"cpu_model" gorm:"size:255"`
|
||||
CPUCores int `json:"cpu_cores"`
|
||||
TotalMemoryBytes int64 `json:"total_memory_bytes"`
|
||||
TotalDiskBytes int64 `json:"total_disk_bytes"`
|
||||
UptimeSeconds int64 `json:"uptime_seconds"`
|
||||
ReportedAt time.Time `json:"reported_at" gorm:"index"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareNodeSystemProfile) TableName() string {
|
||||
return "of_node_system_profiles"
|
||||
}
|
||||
|
||||
// OpenFlareNodeObservationOpenresty stores openresty network observations.
|
||||
type OpenFlareNodeObservationOpenresty struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
CapturedAt time.Time `json:"captured_at" gorm:"index"`
|
||||
OpenrestyRxBytes int64 `json:"openresty_rx_bytes"`
|
||||
OpenrestyTxBytes int64 `json:"openresty_tx_bytes"`
|
||||
OpenrestyConnections int64 `json:"openresty_connections"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareNodeObservationOpenresty) TableName() string {
|
||||
return "of_node_obs_openresty"
|
||||
}
|
||||
|
||||
// OpenFlareNodeObservationFrps stores tunnel relay frps observations.
|
||||
type OpenFlareNodeObservationFrps struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
NodeID string `json:"node_id" gorm:"index;size:64;not null"`
|
||||
CapturedAt time.Time `json:"captured_at" gorm:"index"`
|
||||
FrpsConnections int `json:"frps_connections"`
|
||||
FrpsProxyCount int `json:"frps_proxy_count"`
|
||||
FrpsClientCount int `json:"frps_client_count"`
|
||||
FrpsProxies string `json:"frps_proxies" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareNodeObservationFrps) TableName() string {
|
||||
return "of_node_obs_frps"
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogQuery filters access log list queries.
|
||||
type OpenFlareAccessLogQuery struct {
|
||||
NodeID string
|
||||
RemoteAddr string
|
||||
Host string
|
||||
Path string
|
||||
Since time.Time
|
||||
Until time.Time
|
||||
Page int
|
||||
PageSize int
|
||||
SortBy string
|
||||
SortOrder string
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogBucketQuery filters folded access log queries (v1 stub).
|
||||
type OpenFlareAccessLogBucketQuery struct {
|
||||
NodeID string
|
||||
RemoteAddr string
|
||||
Host string
|
||||
Path string
|
||||
Since time.Time
|
||||
Page int
|
||||
PageSize int
|
||||
SortBy string
|
||||
SortOrder string
|
||||
FoldMinutes int
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogBucketRow is a folded access log bucket row (v1 stub).
|
||||
type OpenFlareAccessLogBucketRow struct {
|
||||
BucketEpoch int64 `json:"bucket_epoch"`
|
||||
RequestCount int64 `json:"request_count"`
|
||||
UniqueIPCount int64 `json:"unique_ip_count"`
|
||||
UniqueHostCount int64 `json:"unique_host_count"`
|
||||
SuccessCount int64 `json:"success_count"`
|
||||
ClientErrorCount int64 `json:"client_error_count"`
|
||||
ServerErrorCount int64 `json:"server_error_count"`
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogBucketIPQuery filters folded IP summary queries (v1 stub).
|
||||
type OpenFlareAccessLogBucketIPQuery struct {
|
||||
NodeID string
|
||||
RemoteAddr string
|
||||
Host string
|
||||
Path string
|
||||
BucketStartedAt time.Time
|
||||
FoldMinutes int
|
||||
Page int
|
||||
PageSize int
|
||||
SortBy string
|
||||
SortOrder string
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogBucketIPRow is a folded IP row (v1 stub).
|
||||
type OpenFlareAccessLogBucketIPRow struct {
|
||||
RemoteAddr string `json:"remote_addr"`
|
||||
RequestCount int64 `json:"request_count"`
|
||||
SuccessCount int64 `json:"success_count"`
|
||||
ClientErrorCount int64 `json:"client_error_count"`
|
||||
ServerErrorCount int64 `json:"server_error_count"`
|
||||
LastSeenEpoch int64 `json:"last_seen_epoch"`
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogIPSummaryQuery filters IP summary list queries (v1 stub).
|
||||
type OpenFlareAccessLogIPSummaryQuery struct {
|
||||
NodeID string
|
||||
RemoteAddr string
|
||||
Host string
|
||||
Since time.Time
|
||||
Page int
|
||||
PageSize int
|
||||
SortBy string
|
||||
SortOrder string
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogIPSummaryRow is an IP summary row (v1 stub).
|
||||
type OpenFlareAccessLogIPSummaryRow struct {
|
||||
RemoteAddr string `json:"remote_addr"`
|
||||
TotalRequests int64 `json:"total_requests"`
|
||||
RecentRequests int64 `json:"recent_requests"`
|
||||
LastSeenEpoch int64 `json:"last_seen_epoch"`
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogIPTrendQuery filters IP trend queries (v1 stub).
|
||||
type OpenFlareAccessLogIPTrendQuery struct {
|
||||
NodeID string
|
||||
RemoteAddr string
|
||||
Host string
|
||||
Since time.Time
|
||||
BucketMinutes int
|
||||
}
|
||||
|
||||
// OpenFlareAccessLogIPTrendRow is an IP trend bucket row (v1 stub).
|
||||
type OpenFlareAccessLogIPTrendRow struct {
|
||||
BucketEpoch int64 `json:"bucket_epoch"`
|
||||
RequestCount int64 `json:"request_count"`
|
||||
}
|
||||
|
||||
func isMissingTableError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "no such table") ||
|
||||
strings.Contains(msg, "doesn't exist") ||
|
||||
strings.Contains(msg, "does not exist")
|
||||
}
|
||||
|
||||
// ListOpenFlareMetricSnapshotsSince returns metric snapshots since the given time.
|
||||
func ListOpenFlareMetricSnapshotsSince(ctx context.Context, nodeID string, since time.Time, limit int) ([]*OpenFlareMetricSnapshot, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
query := conn.Model(&OpenFlareMetricSnapshot{}).Order("captured_at desc, id desc")
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
if !since.IsZero() {
|
||||
query = query.Where("captured_at >= ?", since)
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
var rows []*OpenFlareMetricSnapshot
|
||||
if err := query.Find(&rows).Error; err != nil {
|
||||
if isMissingTableError(err) {
|
||||
return []*OpenFlareMetricSnapshot{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareRequestReportsSince returns request reports since the given time.
|
||||
func ListOpenFlareRequestReportsSince(ctx context.Context, nodeID string, since time.Time, limit int) ([]*OpenFlareRequestReport, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
query := conn.Model(&OpenFlareRequestReport{}).Order("window_ended_at desc, id desc")
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
if !since.IsZero() {
|
||||
query = query.Where("window_ended_at >= ?", since)
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
var rows []*OpenFlareRequestReport
|
||||
if err := query.Find(&rows).Error; err != nil {
|
||||
if isMissingTableError(err) {
|
||||
return []*OpenFlareRequestReport{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareAccessLogRegionCounts returns region counts for access logs (v1 stub).
|
||||
func ListOpenFlareAccessLogRegionCounts(_ context.Context, _ string, _ time.Time, _ int) ([]*OpenFlareAccessLogRegionCount, error) {
|
||||
return []*OpenFlareAccessLogRegionCount{}, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareActiveHealthEvents returns active health events across all nodes.
|
||||
func ListOpenFlareActiveHealthEvents(ctx context.Context) ([]*OpenFlareHealthEvent, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var rows []*OpenFlareHealthEvent
|
||||
if err := conn.Where("status = ?", "active").Order("last_triggered_at desc").Find(&rows).Error; err != nil {
|
||||
if isMissingTableError(err) {
|
||||
return []*OpenFlareHealthEvent{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareHealthEvents returns health events for a node.
|
||||
func ListOpenFlareHealthEvents(ctx context.Context, nodeID string, activeOnly bool, limit int) ([]*OpenFlareHealthEvent, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
query := conn.Model(&OpenFlareHealthEvent{}).Where("node_id = ?", nodeID).Order("last_triggered_at desc")
|
||||
if activeOnly {
|
||||
query = query.Where("status = ?", "active")
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
var rows []*OpenFlareHealthEvent
|
||||
if err := query.Find(&rows).Error; err != nil {
|
||||
if isMissingTableError(err) {
|
||||
return []*OpenFlareHealthEvent{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// DeleteOpenFlareHealthEventsByNodeID deletes all health events for a node.
|
||||
func DeleteOpenFlareHealthEventsByNodeID(ctx context.Context, nodeID string) (int64, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return 0, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
result := conn.Where("node_id = ?", nodeID).Delete(&OpenFlareHealthEvent{})
|
||||
if result.Error != nil {
|
||||
if isMissingTableError(result.Error) {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, result.Error
|
||||
}
|
||||
return result.RowsAffected, nil
|
||||
}
|
||||
|
||||
// GetOpenFlareNodeSystemProfile returns the system profile for a node.
|
||||
func GetOpenFlareNodeSystemProfile(ctx context.Context, nodeID string) (*OpenFlareNodeSystemProfile, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var profile OpenFlareNodeSystemProfile
|
||||
if err := conn.Where("node_id = ?", nodeID).First(&profile).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) || isMissingTableError(err) {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &profile, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareNodeObservationOpenresty returns openresty observations.
|
||||
func ListOpenFlareNodeObservationOpenresty(ctx context.Context, nodeID string, since time.Time, limit int) ([]*OpenFlareNodeObservationOpenresty, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
query := conn.Model(&OpenFlareNodeObservationOpenresty{}).Order("captured_at desc, id desc")
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
if !since.IsZero() {
|
||||
query = query.Where("captured_at >= ?", since)
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
var rows []*OpenFlareNodeObservationOpenresty
|
||||
if err := query.Find(&rows).Error; err != nil {
|
||||
if isMissingTableError(err) {
|
||||
return []*OpenFlareNodeObservationOpenresty{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareNodeObservationFrps returns frps observations.
|
||||
func ListOpenFlareNodeObservationFrps(ctx context.Context, nodeID string, since time.Time, limit int) ([]*OpenFlareNodeObservationFrps, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
query := conn.Model(&OpenFlareNodeObservationFrps{}).Order("captured_at desc, id desc")
|
||||
if nodeID != "" {
|
||||
query = query.Where("node_id = ?", nodeID)
|
||||
}
|
||||
if !since.IsZero() {
|
||||
query = query.Where("captured_at >= ?", since)
|
||||
}
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
var rows []*OpenFlareNodeObservationFrps
|
||||
if err := query.Find(&rows).Error; err != nil {
|
||||
if isMissingTableError(err) {
|
||||
return []*OpenFlareNodeObservationFrps{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareAccessLogs lists access logs (v1 stub returns empty until table is migrated).
|
||||
func ListOpenFlareAccessLogs(_ context.Context, _ OpenFlareAccessLogQuery) ([]*OpenFlareAccessLog, error) {
|
||||
return []*OpenFlareAccessLog{}, nil
|
||||
}
|
||||
|
||||
// CountOpenFlareAccessLogs counts access logs (v1 stub).
|
||||
func CountOpenFlareAccessLogs(_ context.Context, _ OpenFlareAccessLogQuery) (int64, int64, error) {
|
||||
return 0, 0, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareAccessLogBuckets lists folded access log buckets (v1 stub).
|
||||
func ListOpenFlareAccessLogBuckets(_ context.Context, _ OpenFlareAccessLogBucketQuery) ([]*OpenFlareAccessLogBucketRow, error) {
|
||||
return []*OpenFlareAccessLogBucketRow{}, nil
|
||||
}
|
||||
|
||||
// CountOpenFlareAccessLogBuckets counts folded access log buckets (v1 stub).
|
||||
func CountOpenFlareAccessLogBuckets(_ context.Context, _ OpenFlareAccessLogBucketQuery) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareAccessLogBucketIPs lists folded IP rows (v1 stub).
|
||||
func ListOpenFlareAccessLogBucketIPs(_ context.Context, _ OpenFlareAccessLogBucketIPQuery) ([]*OpenFlareAccessLogBucketIPRow, error) {
|
||||
return []*OpenFlareAccessLogBucketIPRow{}, nil
|
||||
}
|
||||
|
||||
// CountOpenFlareAccessLogBucketIPs counts folded IP rows (v1 stub).
|
||||
func CountOpenFlareAccessLogBucketIPs(_ context.Context, _ OpenFlareAccessLogBucketIPQuery) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareAccessLogIPSummaries lists IP summaries (v1 stub).
|
||||
func ListOpenFlareAccessLogIPSummaries(_ context.Context, _ OpenFlareAccessLogIPSummaryQuery, _ time.Time) ([]*OpenFlareAccessLogIPSummaryRow, error) {
|
||||
return []*OpenFlareAccessLogIPSummaryRow{}, nil
|
||||
}
|
||||
|
||||
// CountOpenFlareAccessLogIPSummaries counts IP summaries (v1 stub).
|
||||
func CountOpenFlareAccessLogIPSummaries(_ context.Context, _ OpenFlareAccessLogIPSummaryQuery) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareAccessLogIPTrend lists IP trend points (v1 stub).
|
||||
func ListOpenFlareAccessLogIPTrend(_ context.Context, _ OpenFlareAccessLogIPTrendQuery) ([]*OpenFlareAccessLogIPTrendRow, error) {
|
||||
return []*OpenFlareAccessLogIPTrendRow{}, nil
|
||||
}
|
||||
|
||||
// DeleteOpenFlareAccessLogsBefore deletes access logs before cutoff (v1 stub).
|
||||
func DeleteOpenFlareAccessLogsBefore(_ context.Context, _ time.Time) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OpenFlareOption stores a hot-reloadable OpenFlare system option.
|
||||
type OpenFlareOption struct {
|
||||
Key string `json:"key" gorm:"column:key;primaryKey;size:128;not null"`
|
||||
Value string `json:"value" gorm:"type:text;not null"`
|
||||
}
|
||||
|
||||
// TableName returns the OpenFlare options table name.
|
||||
func (OpenFlareOption) TableName() string {
|
||||
return "of_options"
|
||||
}
|
||||
|
||||
// OptionMap holds the in-memory option snapshot for fast reads and hot reload.
|
||||
var (
|
||||
OptionMap map[string]string
|
||||
OptionMapRWMutex sync.RWMutex
|
||||
|
||||
// StartTime records process start time (seconds) for legacy /api/status.
|
||||
StartTime = time.Now().Unix()
|
||||
|
||||
// Hot-reload mirrors for frequently read options (legacy OpenFlare keys).
|
||||
SystemName = "OpenFlare"
|
||||
ServerAddress = ""
|
||||
Footer = ""
|
||||
HomePageLink = ""
|
||||
PasswordLoginEnabled = true
|
||||
CapLoginEnabled = true
|
||||
PasswordRegisterEnabled = false
|
||||
EmailVerificationEnabled = false
|
||||
GitHubOAuthEnabled = false
|
||||
WeChatAuthEnabled = false
|
||||
GitHubClientId = ""
|
||||
GitHubClientSecret = ""
|
||||
WeChatServerAddress = ""
|
||||
WeChatServerToken = ""
|
||||
WeChatAccountQRCodeImageURL = ""
|
||||
SMTPServer = ""
|
||||
SMTPPort = 587
|
||||
SMTPAccount = ""
|
||||
SMTPToken = ""
|
||||
AgentDiscoveryToken = ""
|
||||
AgentHeartbeatInterval = 10000
|
||||
AgentWebsocketUpgradeEnabled = true
|
||||
NodeOfflineThreshold = 2 * time.Minute
|
||||
AgentUpdateRepo = "Rain-kl/OpenFlare"
|
||||
GeoIPProvider = "ipinfo"
|
||||
DatabaseAutoCleanupEnabled = false
|
||||
DatabaseAutoCleanupRetentionDays = 30
|
||||
UptimeKumaEnabled = false
|
||||
UptimeKumaUrl = ""
|
||||
UptimeKumaUsername = ""
|
||||
UptimeKumaPassword = ""
|
||||
UptimeKumaMonitorScope = "all"
|
||||
UptimeKumaSelectedSites = ""
|
||||
UptimeKumaSyncInterval = 5
|
||||
UptimeKumaInterval = 60
|
||||
UptimeKumaRetry = 0
|
||||
UptimeKumaRetryInterval = 60
|
||||
UptimeKumaTimeout = 48
|
||||
OpenRestyDefaultServerReturnStatus = 421
|
||||
OpenRestyWorkerProcesses = "auto"
|
||||
OpenRestyWorkerConnections = 4096
|
||||
OpenRestyWorkerRlimitNofile = 65535
|
||||
OpenRestyEventsUse = "epoll"
|
||||
OpenRestyEventsMultiAcceptEnabled = true
|
||||
OpenRestyKeepaliveTimeout = 20
|
||||
OpenRestyKeepaliveRequests = 1000
|
||||
OpenRestyClientHeaderTimeout = 15
|
||||
OpenRestyClientBodyTimeout = 15
|
||||
OpenRestyClientMaxBodySize = "64m"
|
||||
OpenRestyLargeClientHeaderBuffers = "4 16k"
|
||||
OpenRestySendTimeout = 30
|
||||
OpenRestyResolvers = ""
|
||||
OpenRestyProxyConnectTimeout = 3
|
||||
OpenRestyProxySendTimeout = 60
|
||||
OpenRestyProxyReadTimeout = 60
|
||||
OpenRestyWebsocketEnabled = true
|
||||
OpenRestyHTTP3Enabled = true
|
||||
OpenRestyProxyRequestBufferingEnabled = false
|
||||
OpenRestyProxyBufferingEnabled = true
|
||||
OpenRestyProxyBuffers = "16 16k"
|
||||
OpenRestyProxyBufferSize = "8k"
|
||||
OpenRestyProxyBusyBuffersSize = "64k"
|
||||
OpenRestyGzipEnabled = true
|
||||
OpenRestyGzipMinLength = 1024
|
||||
OpenRestyGzipCompLevel = 5
|
||||
OpenRestyCacheEnabled = false
|
||||
OpenRestyCachePath = ""
|
||||
OpenRestyCacheLevels = "1:2"
|
||||
OpenRestyCacheInactive = "30m"
|
||||
OpenRestyCacheMaxSize = "1g"
|
||||
OpenRestyCacheKeyTemplate = "$scheme$host$request_uri"
|
||||
OpenRestyCacheLockEnabled = true
|
||||
OpenRestyCacheLockTimeout = "5s"
|
||||
OpenRestyCacheUseStale = "error timeout updating http_500 http_502 http_503 http_504"
|
||||
OpenRestyMainConfigTemplate = defaultOpenRestyMainConfigTemplate
|
||||
GlobalApiRateLimitNum = 300
|
||||
GlobalApiRateLimitDuration int64 = 3 * 60
|
||||
GlobalWebRateLimitNum = 300
|
||||
GlobalWebRateLimitDuration int64 = 3 * 60
|
||||
CriticalRateLimitNum = 100
|
||||
CriticalRateLimitDuration int64 = 20 * 60
|
||||
)
|
||||
|
||||
const defaultOpenRestyMainConfigTemplate = `# This file is generated by OpenFlare. Do not edit manually.
|
||||
worker_processes {{OpenRestyWorkerProcesses}};
|
||||
worker_rlimit_nofile {{OpenRestyWorkerRlimitNofile}};
|
||||
pid logs/nginx.pid;
|
||||
error_log {{OpenRestyErrorLogPath}} warn;
|
||||
|
||||
events {
|
||||
worker_connections {{OpenRestyWorkerConnections}};
|
||||
{{OpenRestyEventsUseDirective}}{{OpenRestyEventsMultiAcceptDirective}}}
|
||||
|
||||
http {
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
{{OpenRestyConnectionUpgradeMap}}{{OpenRestyDefaultServerBlock}} log_format openflare_json escape=json '{"ts":"$time_iso8601","host":"$host","path":"$request_uri","remote_addr":"$remote_addr","status":$status,"request_time":$request_time,"bytes_sent":$body_bytes_sent,"request_length":$request_length}';
|
||||
access_log {{OpenRestyAccessLogPath}} openflare_json;
|
||||
sendfile on;
|
||||
tcp_nopush on;
|
||||
tcp_nodelay on;
|
||||
keepalive_timeout {{OpenRestyKeepaliveTimeout}};
|
||||
keepalive_requests {{OpenRestyKeepaliveRequests}};
|
||||
client_header_timeout {{OpenRestyClientHeaderTimeout}};
|
||||
client_body_timeout {{OpenRestyClientBodyTimeout}};
|
||||
client_max_body_size {{OpenRestyClientMaxBodySize}};
|
||||
large_client_header_buffers {{OpenRestyLargeClientHeaderBuffers}};
|
||||
send_timeout {{OpenRestySendTimeout}};
|
||||
proxy_connect_timeout {{OpenRestyProxyConnectTimeout}};
|
||||
proxy_send_timeout {{OpenRestyProxySendTimeout}};
|
||||
proxy_read_timeout {{OpenRestyProxyReadTimeout}};
|
||||
proxy_request_buffering {{OpenRestyProxyRequestBuffering}};
|
||||
proxy_buffering {{OpenRestyProxyBuffering}};
|
||||
proxy_buffers {{OpenRestyProxyBuffers}};
|
||||
proxy_buffer_size {{OpenRestyProxyBufferSize}};
|
||||
proxy_busy_buffers_size {{OpenRestyProxyBusyBuffersSize}};
|
||||
gzip {{OpenRestyGzip}};
|
||||
gzip_min_length {{OpenRestyGzipMinLength}};
|
||||
gzip_comp_level {{OpenRestyGzipCompLevel}};
|
||||
{{OpenRestyResolverDirective}}{{OpenRestyCacheBlock}} include {{OpenRestyRouteConfigInclude}};
|
||||
}
|
||||
`
|
||||
|
||||
// DefaultOpenFlareOptions returns built-in defaults keyed by legacy OpenFlare option names.
|
||||
func DefaultOpenFlareOptions() map[string]string {
|
||||
return map[string]string{
|
||||
"PasswordLoginEnabled": strconv.FormatBool(PasswordLoginEnabled),
|
||||
"CapLoginEnabled": strconv.FormatBool(CapLoginEnabled),
|
||||
"PasswordRegisterEnabled": strconv.FormatBool(PasswordRegisterEnabled),
|
||||
"EmailVerificationEnabled": strconv.FormatBool(EmailVerificationEnabled),
|
||||
"GitHubOAuthEnabled": strconv.FormatBool(GitHubOAuthEnabled),
|
||||
"WeChatAuthEnabled": strconv.FormatBool(WeChatAuthEnabled),
|
||||
"SMTPServer": "",
|
||||
"SMTPPort": strconv.Itoa(SMTPPort),
|
||||
"SMTPAccount": "",
|
||||
"SMTPToken": "",
|
||||
"Notice": "",
|
||||
"About": "",
|
||||
"Footer": Footer,
|
||||
"HomePageLink": HomePageLink,
|
||||
"SystemName": SystemName,
|
||||
"ServerAddress": "",
|
||||
"GitHubClientId": "",
|
||||
"GitHubClientSecret": "",
|
||||
"WeChatServerAddress": "",
|
||||
"WeChatServerToken": "",
|
||||
"WeChatAccountQRCodeImageURL": "",
|
||||
"AgentDiscoveryToken": "",
|
||||
"AgentHeartbeatInterval": strconv.Itoa(AgentHeartbeatInterval),
|
||||
"AgentWebsocketUpgradeEnabled": strconv.FormatBool(AgentWebsocketUpgradeEnabled),
|
||||
"NodeOfflineThreshold": strconv.Itoa(int(NodeOfflineThreshold.Milliseconds())),
|
||||
"AgentUpdateRepo": AgentUpdateRepo,
|
||||
"GeoIPProvider": GeoIPProvider,
|
||||
"DatabaseAutoCleanupEnabled": strconv.FormatBool(DatabaseAutoCleanupEnabled),
|
||||
"UptimeKumaEnabled": strconv.FormatBool(UptimeKumaEnabled),
|
||||
"UptimeKumaUrl": UptimeKumaUrl,
|
||||
"UptimeKumaUsername": UptimeKumaUsername,
|
||||
"UptimeKumaPassword": UptimeKumaPassword,
|
||||
"UptimeKumaMonitorScope": UptimeKumaMonitorScope,
|
||||
"UptimeKumaSelectedSites": UptimeKumaSelectedSites,
|
||||
"UptimeKumaSyncInterval": strconv.Itoa(UptimeKumaSyncInterval),
|
||||
"UptimeKumaInterval": strconv.Itoa(UptimeKumaInterval),
|
||||
"UptimeKumaRetry": strconv.Itoa(UptimeKumaRetry),
|
||||
"UptimeKumaRetryInterval": strconv.Itoa(UptimeKumaRetryInterval),
|
||||
"UptimeKumaTimeout": strconv.Itoa(UptimeKumaTimeout),
|
||||
"DatabaseAutoCleanupRetentionDays": strconv.Itoa(DatabaseAutoCleanupRetentionDays),
|
||||
"OpenRestyDefaultServerReturnStatus": strconv.Itoa(OpenRestyDefaultServerReturnStatus),
|
||||
"OpenRestyWorkerProcesses": OpenRestyWorkerProcesses,
|
||||
"OpenRestyWorkerConnections": strconv.Itoa(OpenRestyWorkerConnections),
|
||||
"OpenRestyWorkerRlimitNofile": strconv.Itoa(OpenRestyWorkerRlimitNofile),
|
||||
"OpenRestyEventsUse": OpenRestyEventsUse,
|
||||
"OpenRestyEventsMultiAcceptEnabled": strconv.FormatBool(OpenRestyEventsMultiAcceptEnabled),
|
||||
"OpenRestyKeepaliveTimeout": strconv.Itoa(OpenRestyKeepaliveTimeout),
|
||||
"OpenRestyKeepaliveRequests": strconv.Itoa(OpenRestyKeepaliveRequests),
|
||||
"OpenRestyClientHeaderTimeout": strconv.Itoa(OpenRestyClientHeaderTimeout),
|
||||
"OpenRestyClientBodyTimeout": strconv.Itoa(OpenRestyClientBodyTimeout),
|
||||
"OpenRestyClientMaxBodySize": OpenRestyClientMaxBodySize,
|
||||
"OpenRestyLargeClientHeaderBuffers": OpenRestyLargeClientHeaderBuffers,
|
||||
"OpenRestySendTimeout": strconv.Itoa(OpenRestySendTimeout),
|
||||
"OpenRestyProxyConnectTimeout": strconv.Itoa(OpenRestyProxyConnectTimeout),
|
||||
"OpenRestyProxySendTimeout": strconv.Itoa(OpenRestyProxySendTimeout),
|
||||
"OpenRestyProxyReadTimeout": strconv.Itoa(OpenRestyProxyReadTimeout),
|
||||
"OpenRestyWebsocketEnabled": strconv.FormatBool(OpenRestyWebsocketEnabled),
|
||||
"OpenRestyHTTP3Enabled": strconv.FormatBool(OpenRestyHTTP3Enabled),
|
||||
"OpenRestyProxyRequestBufferingEnabled": strconv.FormatBool(OpenRestyProxyRequestBufferingEnabled),
|
||||
"OpenRestyProxyBufferingEnabled": strconv.FormatBool(OpenRestyProxyBufferingEnabled),
|
||||
"OpenRestyProxyBuffers": OpenRestyProxyBuffers,
|
||||
"OpenRestyProxyBufferSize": OpenRestyProxyBufferSize,
|
||||
"OpenRestyProxyBusyBuffersSize": OpenRestyProxyBusyBuffersSize,
|
||||
"OpenRestyGzipEnabled": strconv.FormatBool(OpenRestyGzipEnabled),
|
||||
"OpenRestyGzipMinLength": strconv.Itoa(OpenRestyGzipMinLength),
|
||||
"OpenRestyGzipCompLevel": strconv.Itoa(OpenRestyGzipCompLevel),
|
||||
"OpenRestyCacheEnabled": strconv.FormatBool(OpenRestyCacheEnabled),
|
||||
"OpenRestyCachePath": OpenRestyCachePath,
|
||||
"OpenRestyCacheLevels": OpenRestyCacheLevels,
|
||||
"OpenRestyCacheInactive": OpenRestyCacheInactive,
|
||||
"OpenRestyCacheMaxSize": OpenRestyCacheMaxSize,
|
||||
"OpenRestyCacheKeyTemplate": OpenRestyCacheKeyTemplate,
|
||||
"OpenRestyCacheLockEnabled": strconv.FormatBool(OpenRestyCacheLockEnabled),
|
||||
"OpenRestyCacheLockTimeout": OpenRestyCacheLockTimeout,
|
||||
"OpenRestyCacheUseStale": OpenRestyCacheUseStale,
|
||||
"OpenRestyMainConfigTemplate": OpenRestyMainConfigTemplate,
|
||||
"GlobalApiRateLimitNum": strconv.Itoa(GlobalApiRateLimitNum),
|
||||
"GlobalApiRateLimitDuration": strconv.FormatInt(GlobalApiRateLimitDuration, 10),
|
||||
"GlobalWebRateLimitNum": strconv.Itoa(GlobalWebRateLimitNum),
|
||||
"GlobalWebRateLimitDuration": strconv.FormatInt(GlobalWebRateLimitDuration, 10),
|
||||
"CriticalRateLimitNum": strconv.Itoa(CriticalRateLimitNum),
|
||||
"CriticalRateLimitDuration": strconv.FormatInt(CriticalRateLimitDuration, 10),
|
||||
}
|
||||
}
|
||||
|
||||
// InitOptionMap seeds defaults and overlays persisted options from of_options.
|
||||
func InitOptionMap(ctx context.Context) error {
|
||||
OptionMapRWMutex.Lock()
|
||||
OptionMap = DefaultOpenFlareOptions()
|
||||
OptionMapRWMutex.Unlock()
|
||||
|
||||
options, err := ListOpenFlareOptions(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, option := range options {
|
||||
applyOptionMap(option.Key, option.Value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListOpenFlareOptions returns all persisted options.
|
||||
func ListOpenFlareOptions(ctx context.Context) ([]OpenFlareOption, error) {
|
||||
var options []OpenFlareOption
|
||||
if err := db.DB(ctx).Find(&options).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return options, nil
|
||||
}
|
||||
|
||||
// UpdateOpenFlareOption updates a single option in DB and memory.
|
||||
func UpdateOpenFlareOption(ctx context.Context, key, value string) error {
|
||||
return UpdateOpenFlareOptions(ctx, []OpenFlareOption{{Key: key, Value: value}})
|
||||
}
|
||||
|
||||
// UpdateOpenFlareOptions batch-updates options in a transaction and refreshes OptionMap.
|
||||
func UpdateOpenFlareOptions(ctx context.Context, options []OpenFlareOption) error {
|
||||
if len(options) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := db.DB(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for _, item := range options {
|
||||
if item.Key == "UptimeKumaPassword" && strings.TrimSpace(item.Value) == "" {
|
||||
continue
|
||||
}
|
||||
option := OpenFlareOption{Key: item.Key}
|
||||
if err := tx.FirstOrCreate(&option, OpenFlareOption{Key: item.Key}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
option.Value = item.Value
|
||||
if err := tx.Save(&option).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, item := range options {
|
||||
if item.Key == "UptimeKumaPassword" && strings.TrimSpace(item.Value) == "" {
|
||||
continue
|
||||
}
|
||||
applyOptionMap(item.Key, item.Value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// OptionValue returns a snapshot value from OptionMap.
|
||||
func OptionValue(key string) string {
|
||||
OptionMapRWMutex.RLock()
|
||||
defer OptionMapRWMutex.RUnlock()
|
||||
if OptionMap == nil {
|
||||
return ""
|
||||
}
|
||||
return OptionMap[key]
|
||||
}
|
||||
|
||||
// ResetOptionMapForTest clears in-memory option state for unit tests.
|
||||
func ResetOptionMapForTest() {
|
||||
OptionMapRWMutex.Lock()
|
||||
OptionMap = nil
|
||||
OptionMapRWMutex.Unlock()
|
||||
}
|
||||
|
||||
func applyOptionMap(key, value string) {
|
||||
OptionMapRWMutex.Lock()
|
||||
if OptionMap == nil {
|
||||
OptionMap = make(map[string]string)
|
||||
}
|
||||
OptionMap[key] = value
|
||||
if strings.HasSuffix(key, "Enabled") {
|
||||
boolValue := value == "true"
|
||||
switch key {
|
||||
case "PasswordRegisterEnabled":
|
||||
PasswordRegisterEnabled = boolValue
|
||||
case "PasswordLoginEnabled":
|
||||
PasswordLoginEnabled = boolValue
|
||||
case "CapLoginEnabled":
|
||||
CapLoginEnabled = boolValue
|
||||
case "EmailVerificationEnabled":
|
||||
EmailVerificationEnabled = boolValue
|
||||
case "GitHubOAuthEnabled":
|
||||
GitHubOAuthEnabled = boolValue
|
||||
case "WeChatAuthEnabled":
|
||||
WeChatAuthEnabled = boolValue
|
||||
}
|
||||
}
|
||||
switch key {
|
||||
case "SMTPServer":
|
||||
SMTPServer = value
|
||||
case "SMTPPort":
|
||||
if intValue, err := strconv.Atoi(value); err == nil {
|
||||
SMTPPort = intValue
|
||||
}
|
||||
case "SMTPAccount":
|
||||
SMTPAccount = value
|
||||
case "SMTPToken":
|
||||
SMTPToken = value
|
||||
case "ServerAddress":
|
||||
ServerAddress = value
|
||||
case "GitHubClientId":
|
||||
GitHubClientId = value
|
||||
case "GitHubClientSecret":
|
||||
GitHubClientSecret = value
|
||||
case "Footer":
|
||||
Footer = value
|
||||
case "HomePageLink":
|
||||
HomePageLink = value
|
||||
case "SystemName":
|
||||
SystemName = value
|
||||
case "WeChatServerAddress":
|
||||
WeChatServerAddress = value
|
||||
case "WeChatServerToken":
|
||||
WeChatServerToken = value
|
||||
case "WeChatAccountQRCodeImageURL":
|
||||
WeChatAccountQRCodeImageURL = value
|
||||
case "AgentDiscoveryToken":
|
||||
AgentDiscoveryToken = value
|
||||
case "AgentHeartbeatInterval":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
AgentHeartbeatInterval = v
|
||||
}
|
||||
case "AgentWebsocketUpgradeEnabled":
|
||||
AgentWebsocketUpgradeEnabled = value == "true"
|
||||
case "NodeOfflineThreshold":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
NodeOfflineThreshold = time.Duration(v) * time.Millisecond
|
||||
}
|
||||
case "AgentUpdateRepo":
|
||||
if value != "" {
|
||||
AgentUpdateRepo = value
|
||||
}
|
||||
case "GeoIPProvider":
|
||||
GeoIPProvider = value
|
||||
case "UptimeKumaEnabled":
|
||||
UptimeKumaEnabled = value == "true"
|
||||
case "UptimeKumaUrl":
|
||||
UptimeKumaUrl = value
|
||||
case "UptimeKumaUsername":
|
||||
UptimeKumaUsername = value
|
||||
case "UptimeKumaPassword":
|
||||
UptimeKumaPassword = value
|
||||
case "UptimeKumaMonitorScope":
|
||||
UptimeKumaMonitorScope = value
|
||||
case "UptimeKumaSelectedSites":
|
||||
UptimeKumaSelectedSites = value
|
||||
case "UptimeKumaSyncInterval":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
UptimeKumaSyncInterval = v
|
||||
}
|
||||
case "UptimeKumaInterval":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
UptimeKumaInterval = v
|
||||
}
|
||||
case "UptimeKumaRetry":
|
||||
if v, err := strconv.Atoi(value); err == nil && v >= 0 {
|
||||
UptimeKumaRetry = v
|
||||
}
|
||||
case "UptimeKumaRetryInterval":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
UptimeKumaRetryInterval = v
|
||||
}
|
||||
case "UptimeKumaTimeout":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
UptimeKumaTimeout = v
|
||||
}
|
||||
case "DatabaseAutoCleanupEnabled":
|
||||
DatabaseAutoCleanupEnabled = value == "true"
|
||||
case "DatabaseAutoCleanupRetentionDays":
|
||||
if v, err := strconv.Atoi(value); err == nil && v >= 1 {
|
||||
DatabaseAutoCleanupRetentionDays = v
|
||||
}
|
||||
case "GlobalApiRateLimitNum":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
GlobalApiRateLimitNum = v
|
||||
}
|
||||
case "GlobalApiRateLimitDuration":
|
||||
if v, err := strconv.ParseInt(value, 10, 64); err == nil && v > 0 {
|
||||
GlobalApiRateLimitDuration = v
|
||||
}
|
||||
case "GlobalWebRateLimitNum":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
GlobalWebRateLimitNum = v
|
||||
}
|
||||
case "GlobalWebRateLimitDuration":
|
||||
if v, err := strconv.ParseInt(value, 10, 64); err == nil && v > 0 {
|
||||
GlobalWebRateLimitDuration = v
|
||||
}
|
||||
case "CriticalRateLimitNum":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
CriticalRateLimitNum = v
|
||||
}
|
||||
case "CriticalRateLimitDuration":
|
||||
if v, err := strconv.ParseInt(value, 10, 64); err == nil && v > 0 {
|
||||
CriticalRateLimitDuration = v
|
||||
}
|
||||
}
|
||||
OptionMapRWMutex.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
)
|
||||
|
||||
// Origin OpenFlare 源站实体。
|
||||
type Origin struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Name string `json:"name" gorm:"size:255;not null"`
|
||||
Address string `json:"address" gorm:"uniqueIndex;size:255;not null"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (Origin) TableName() string {
|
||||
return "of_origins"
|
||||
}
|
||||
|
||||
// OriginRouteCount 源站关联的代理规则数量。
|
||||
type OriginRouteCount struct {
|
||||
OriginID uint `json:"origin_id"`
|
||||
RouteCount int64 `json:"route_count"`
|
||||
}
|
||||
|
||||
// OriginProxyRoute 源站模块查询代理规则时使用的最小字段集。
|
||||
type OriginProxyRoute struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
OriginID *uint `gorm:"column:origin_id"`
|
||||
Domain string `gorm:"column:domain"`
|
||||
OriginURL string `gorm:"column:origin_url"`
|
||||
Upstreams string `gorm:"column:upstreams"`
|
||||
Enabled bool `gorm:"column:enabled"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (OriginProxyRoute) TableName() string {
|
||||
return "of_proxy_routes"
|
||||
}
|
||||
|
||||
// HasProxyRoutesTable 判断代理规则表是否已迁移。
|
||||
func HasProxyRoutesTable(ctx context.Context) bool {
|
||||
return db.DB(ctx).Migrator().HasTable(&OriginProxyRoute{})
|
||||
}
|
||||
|
||||
// ListOrigins 列出全部源站。
|
||||
func ListOrigins(ctx context.Context) ([]Origin, error) {
|
||||
var origins []Origin
|
||||
if err := db.DB(ctx).Order("id desc").Find(&origins).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return origins, nil
|
||||
}
|
||||
|
||||
// GetOriginByID 按 ID 查询源站。
|
||||
func GetOriginByID(ctx context.Context, id uint) (*Origin, error) {
|
||||
var origin Origin
|
||||
if err := db.DB(ctx).First(&origin, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &origin, nil
|
||||
}
|
||||
|
||||
// GetOriginByAddress 按地址查询源站。
|
||||
func GetOriginByAddress(ctx context.Context, address string) (*Origin, error) {
|
||||
var origin Origin
|
||||
if err := db.DB(ctx).Where("address = ?", address).First(&origin).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &origin, nil
|
||||
}
|
||||
|
||||
// CreateOriginRecord 创建源站。
|
||||
func CreateOriginRecord(ctx context.Context, origin *Origin) error {
|
||||
return db.DB(ctx).Create(origin).Error
|
||||
}
|
||||
|
||||
// SaveOrigin 保存源站。
|
||||
func SaveOrigin(ctx context.Context, origin *Origin) error {
|
||||
return db.DB(ctx).Save(origin).Error
|
||||
}
|
||||
|
||||
// DeleteOriginRecord 删除源站。
|
||||
func DeleteOriginRecord(ctx context.Context, id uint) error {
|
||||
return db.DB(ctx).Delete(&Origin{}, id).Error
|
||||
}
|
||||
|
||||
// ListOriginRouteCounts 统计各源站关联的代理规则数量。
|
||||
func ListOriginRouteCounts(ctx context.Context) ([]OriginRouteCount, error) {
|
||||
if !HasProxyRoutesTable(ctx) {
|
||||
return nil, nil
|
||||
}
|
||||
result := make([]OriginRouteCount, 0)
|
||||
err := db.DB(ctx).Model(&OriginProxyRoute{}).
|
||||
Select("origin_id, COUNT(*) AS route_count").
|
||||
Where("origin_id IS NOT NULL").
|
||||
Group("origin_id").
|
||||
Scan(&result).Error
|
||||
return result, err
|
||||
}
|
||||
|
||||
// ListProxyRoutesByOriginID 列出源站关联的代理规则。
|
||||
func ListProxyRoutesByOriginID(ctx context.Context, originID uint) ([]OriginProxyRoute, error) {
|
||||
if !HasProxyRoutesTable(ctx) {
|
||||
return nil, nil
|
||||
}
|
||||
var routes []OriginProxyRoute
|
||||
if err := db.DB(ctx).Where("origin_id = ?", originID).Order("id desc").Find(&routes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return routes, nil
|
||||
}
|
||||
|
||||
// CountProxyRoutesByOriginID 统计源站关联的代理规则数量。
|
||||
func CountProxyRoutesByOriginID(ctx context.Context, originID uint) (int64, error) {
|
||||
if !HasProxyRoutesTable(ctx) {
|
||||
return 0, nil
|
||||
}
|
||||
var count int64
|
||||
if err := db.DB(ctx).Model(&OriginProxyRoute{}).Where("origin_id = ?", originID).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
)
|
||||
|
||||
const (
|
||||
PagesDeploymentStatusUploaded = "uploaded"
|
||||
PagesDeploymentStatusActive = "active"
|
||||
)
|
||||
|
||||
// PagesProject OpenFlare Pages 静态托管项目。
|
||||
type PagesProject struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Name string `json:"name" gorm:"size:255;not null"`
|
||||
Slug string `json:"slug" gorm:"uniqueIndex;size:128;not null"`
|
||||
Description string `json:"description" gorm:"type:text;not null;default:''"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
SPAFallbackEnabled bool `json:"spa_fallback_enabled" gorm:"not null;default:false"`
|
||||
SPAFallbackPath string `json:"spa_fallback_path" gorm:"size:512;not null;default:'/index.html'"`
|
||||
APIProxyEnabled bool `json:"api_proxy_enabled" gorm:"not null;default:false"`
|
||||
APIProxyPath string `json:"api_proxy_path" gorm:"size:255;not null;default:''"`
|
||||
APIProxyPass string `json:"api_proxy_pass" gorm:"size:2048;not null;default:''"`
|
||||
APIProxyRewrite string `json:"api_proxy_rewrite" gorm:"size:255;not null;default:''"`
|
||||
ActiveDeploymentID *uint `json:"active_deployment_id" gorm:"index"`
|
||||
RootDir string `json:"root_dir" gorm:"size:512;not null;default:''"`
|
||||
EntryFile string `json:"entry_file" gorm:"size:512;not null;default:'index.html'"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (PagesProject) TableName() string {
|
||||
return "of_pages_projects"
|
||||
}
|
||||
|
||||
// PagesDeployment OpenFlare Pages 不可变部署记录。
|
||||
type PagesDeployment struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
ProjectID uint `json:"project_id" gorm:"not null;index"`
|
||||
DeploymentNumber int `json:"deployment_number" gorm:"not null"`
|
||||
Checksum string `json:"checksum" gorm:"size:64;not null;index"`
|
||||
Status string `json:"status" gorm:"size:32;not null;default:'uploaded';index"`
|
||||
ArtifactPath string `json:"artifact_path" gorm:"size:2048;not null"`
|
||||
FileCount int `json:"file_count" gorm:"not null;default:0"`
|
||||
TotalSize int64 `json:"total_size" gorm:"not null;default:0"`
|
||||
CreatedBy string `json:"created_by" gorm:"size:64;not null;default:''"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
ActivatedAt *time.Time `json:"activated_at"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (PagesDeployment) TableName() string {
|
||||
return "of_pages_deployments"
|
||||
}
|
||||
|
||||
// PagesDeploymentFile OpenFlare Pages 部署文件清单。
|
||||
type PagesDeploymentFile struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
DeploymentID uint `json:"deployment_id" gorm:"not null;index"`
|
||||
Path string `json:"path" gorm:"size:2048;not null"`
|
||||
Size int64 `json:"size" gorm:"not null;default:0"`
|
||||
Checksum string `json:"checksum" gorm:"size:64;not null"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (PagesDeploymentFile) TableName() string {
|
||||
return "of_pages_deployment_files"
|
||||
}
|
||||
|
||||
// HasPagesProjectsTable 判断 Pages 项目表是否已迁移。
|
||||
func HasPagesProjectsTable(ctx context.Context) bool {
|
||||
return db.DB(ctx).Migrator().HasTable(&PagesProject{})
|
||||
}
|
||||
|
||||
// ListPagesProjects 列出全部 Pages 项目。
|
||||
func ListPagesProjects(ctx context.Context) ([]PagesProject, error) {
|
||||
var projects []PagesProject
|
||||
if err := db.DB(ctx).Order("id desc").Find(&projects).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return projects, nil
|
||||
}
|
||||
|
||||
// GetPagesProjectByID 按 ID 查询 Pages 项目。
|
||||
func GetPagesProjectByID(ctx context.Context, id uint) (*PagesProject, error) {
|
||||
var project PagesProject
|
||||
if err := db.DB(ctx).First(&project, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &project, nil
|
||||
}
|
||||
|
||||
// GetPagesProjectBySlug 按 slug 查询 Pages 项目。
|
||||
func GetPagesProjectBySlug(ctx context.Context, slug string) (*PagesProject, error) {
|
||||
var project PagesProject
|
||||
if err := db.DB(ctx).Where("slug = ?", slug).First(&project).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &project, nil
|
||||
}
|
||||
|
||||
// CreatePagesProjectRecord 创建 Pages 项目。
|
||||
func CreatePagesProjectRecord(ctx context.Context, project *PagesProject) error {
|
||||
return db.DB(ctx).Create(project).Error
|
||||
}
|
||||
|
||||
// ListPagesDeployments 列出项目的全部部署。
|
||||
func ListPagesDeployments(ctx context.Context, projectID uint) ([]PagesDeployment, error) {
|
||||
var deployments []PagesDeployment
|
||||
if err := db.DB(ctx).Where("project_id = ?", projectID).Order("id desc").Find(&deployments).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return deployments, nil
|
||||
}
|
||||
|
||||
// GetPagesDeploymentByID 按 ID 查询 Pages 部署。
|
||||
func GetPagesDeploymentByID(ctx context.Context, id uint) (*PagesDeployment, error) {
|
||||
var deployment PagesDeployment
|
||||
if err := db.DB(ctx).First(&deployment, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &deployment, nil
|
||||
}
|
||||
|
||||
// ListPagesDeploymentFiles 列出部署文件清单。
|
||||
func ListPagesDeploymentFiles(ctx context.Context, deploymentID uint) ([]PagesDeploymentFile, error) {
|
||||
var files []PagesDeploymentFile
|
||||
if err := db.DB(ctx).Where("deployment_id = ?", deploymentID).Order("path asc").Find(&files).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// CountPagesDeploymentsByProjectID 统计项目部署数量。
|
||||
func CountPagesDeploymentsByProjectID(ctx context.Context, projectID uint) (int64, error) {
|
||||
var count int64
|
||||
if err := db.DB(ctx).Model(&PagesDeployment{}).Where("project_id = ?", projectID).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// CountProxyRoutesByPagesProjectID 统计引用 Pages 项目的代理规则数量。
|
||||
func CountProxyRoutesByPagesProjectID(ctx context.Context, projectID uint) (int64, error) {
|
||||
if !HasProxyRoutesTable(ctx) {
|
||||
return 0, nil
|
||||
}
|
||||
var count int64
|
||||
if err := db.DB(ctx).Model(&ProxyRoute{}).Where("pages_project_id = ?", projectID).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
)
|
||||
|
||||
// ProxyRoute OpenFlare 代理规则实体。
|
||||
type ProxyRoute struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
SiteName string `json:"site_name" gorm:"size:255;not null;default:''"`
|
||||
Domain string `json:"domain" gorm:"uniqueIndex;size:255;not null"`
|
||||
Domains string `json:"domains" gorm:"type:text;not null;default:'[]'"`
|
||||
OriginID *uint `json:"origin_id" gorm:"index"`
|
||||
OriginURL string `json:"origin_url" gorm:"size:2048;not null"`
|
||||
OriginHost string `json:"origin_host" gorm:"size:255"`
|
||||
Upstreams string `json:"upstreams" gorm:"type:text;not null;default:'[]'"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
EnableHTTPS bool `json:"enable_https" gorm:"column:enable_https;not null;default:false"`
|
||||
CertID *uint `json:"cert_id"`
|
||||
CertIDs string `json:"cert_ids" gorm:"type:text;not null;default:'[]'"`
|
||||
DomainCertIDs string `json:"domain_cert_ids" gorm:"type:text;not null;default:'[]'"`
|
||||
RedirectHTTP bool `json:"redirect_http" gorm:"not null;default:false"`
|
||||
LimitConnPerServer int `json:"limit_conn_per_server" gorm:"not null;default:0"`
|
||||
LimitConnPerIP int `json:"limit_conn_per_ip" gorm:"not null;default:0"`
|
||||
LimitRate string `json:"limit_rate" gorm:"size:32;not null;default:''"`
|
||||
CacheEnabled bool `json:"cache_enabled" gorm:"not null;default:false"`
|
||||
CachePolicy string `json:"cache_policy" gorm:"size:32;not null;default:''"`
|
||||
CacheRules string `json:"cache_rules" gorm:"type:text;not null;default:'[]'"`
|
||||
CustomHeaders string `json:"custom_headers" gorm:"type:text;not null;default:'[]'"`
|
||||
BasicAuthEnabled bool `json:"basic_auth_enabled" gorm:"not null;default:false"`
|
||||
BasicAuthUsername string `json:"basic_auth_username" gorm:"size:255;not null;default:''"`
|
||||
BasicAuthPassword string `json:"basic_auth_password" gorm:"size:255;not null;default:''"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
UpstreamType string `json:"upstream_type" gorm:"size:32;not null;default:'direct'"`
|
||||
TunnelNodeID *uint `json:"tunnel_node_id" gorm:"index"`
|
||||
TunnelTargetAddr string `json:"tunnel_target_addr" gorm:"size:512"`
|
||||
TunnelTargetProtocol string `json:"tunnel_target_protocol" gorm:"size:16"`
|
||||
PagesProjectID *uint `json:"pages_project_id" gorm:"index"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (ProxyRoute) TableName() string {
|
||||
return "of_proxy_routes"
|
||||
}
|
||||
|
||||
// ListProxyRoutes 列出全部代理规则。
|
||||
func ListProxyRoutes(ctx context.Context) ([]*ProxyRoute, error) {
|
||||
var routes []*ProxyRoute
|
||||
if err := db.DB(ctx).Order("id desc").Find(&routes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return routes, nil
|
||||
}
|
||||
|
||||
// GetProxyRouteByID 按 ID 查询代理规则。
|
||||
func GetProxyRouteByID(ctx context.Context, id uint) (*ProxyRoute, error) {
|
||||
var route ProxyRoute
|
||||
if err := db.DB(ctx).First(&route, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &route, nil
|
||||
}
|
||||
|
||||
// CreateProxyRouteRecord 创建代理规则。
|
||||
func CreateProxyRouteRecord(ctx context.Context, route *ProxyRoute) error {
|
||||
return db.DB(ctx).Create(route).Error
|
||||
}
|
||||
|
||||
// UpdateProxyRouteRecord 更新代理规则。
|
||||
func UpdateProxyRouteRecord(ctx context.Context, route *ProxyRoute) error {
|
||||
return db.DB(ctx).Model(&ProxyRoute{}).Where("id = ?", route.ID).Updates(map[string]any{
|
||||
"site_name": route.SiteName,
|
||||
"domain": route.Domain,
|
||||
"domains": route.Domains,
|
||||
"origin_id": route.OriginID,
|
||||
"origin_url": route.OriginURL,
|
||||
"origin_host": route.OriginHost,
|
||||
"upstreams": route.Upstreams,
|
||||
"enabled": route.Enabled,
|
||||
"enable_https": route.EnableHTTPS,
|
||||
"cert_id": route.CertID,
|
||||
"cert_ids": route.CertIDs,
|
||||
"domain_cert_ids": route.DomainCertIDs,
|
||||
"redirect_http": route.RedirectHTTP,
|
||||
"limit_conn_per_server": route.LimitConnPerServer,
|
||||
"limit_conn_per_ip": route.LimitConnPerIP,
|
||||
"limit_rate": route.LimitRate,
|
||||
"cache_enabled": route.CacheEnabled,
|
||||
"cache_policy": route.CachePolicy,
|
||||
"cache_rules": route.CacheRules,
|
||||
"custom_headers": route.CustomHeaders,
|
||||
"basic_auth_enabled": route.BasicAuthEnabled,
|
||||
"basic_auth_username": route.BasicAuthUsername,
|
||||
"basic_auth_password": route.BasicAuthPassword,
|
||||
"remark": route.Remark,
|
||||
"upstream_type": route.UpstreamType,
|
||||
"tunnel_node_id": route.TunnelNodeID,
|
||||
"tunnel_target_addr": route.TunnelTargetAddr,
|
||||
"tunnel_target_protocol": route.TunnelTargetProtocol,
|
||||
"pages_project_id": route.PagesProjectID,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// DeleteProxyRouteRecord 删除代理规则。
|
||||
func DeleteProxyRouteRecord(ctx context.Context, id uint) error {
|
||||
return db.DB(ctx).Delete(&ProxyRoute{}, id).Error
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
)
|
||||
|
||||
// TLSCertificate OpenFlare TLS 证书实体。
|
||||
type TLSCertificate struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Name string `json:"name" gorm:"uniqueIndex;size:255;not null"`
|
||||
CertPEM string `json:"-" gorm:"type:text;not null"`
|
||||
KeyPEM string `json:"-" gorm:"type:text;not null"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
Provider string `json:"provider" gorm:"size:64;default:upload"`
|
||||
AcmeAccountID uint `json:"acme_account_id"`
|
||||
DnsAccountID uint `json:"dns_account_id"`
|
||||
KeyAlgorithm string `json:"key_algorithm" gorm:"size:32"`
|
||||
AutoRenew bool `json:"auto_renew"`
|
||||
PrimaryDomain string `json:"primary_domain" gorm:"size:255"`
|
||||
OtherDomains string `json:"other_domains" gorm:"type:text"`
|
||||
DisableCNAME bool `json:"disable_cname"`
|
||||
SkipDNS bool `json:"skip_dns"`
|
||||
DNS1 string `json:"dns1" gorm:"size:128"`
|
||||
DNS2 string `json:"dns2" gorm:"size:128"`
|
||||
ApplyStatus string `json:"apply_status" gorm:"size:64;default:ready"`
|
||||
ApplyMessage string `json:"apply_message" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (TLSCertificate) TableName() string {
|
||||
return "of_tls_certificates"
|
||||
}
|
||||
|
||||
// TLSProxyRouteRef 删除证书时检查代理规则引用的最小字段集。
|
||||
type TLSProxyRouteRef struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
CertID *uint `gorm:"column:cert_id"`
|
||||
CertIDs string `gorm:"column:cert_ids"`
|
||||
DomainCertIDs string `gorm:"column:domain_cert_ids"`
|
||||
}
|
||||
|
||||
// TableName 表名。
|
||||
func (TLSProxyRouteRef) TableName() string {
|
||||
return "of_proxy_routes"
|
||||
}
|
||||
|
||||
// HasTLSProxyRoutesTable 判断代理规则表是否已迁移。
|
||||
func HasTLSProxyRoutesTable(ctx context.Context) bool {
|
||||
return db.DB(ctx).Migrator().HasTable(&TLSProxyRouteRef{})
|
||||
}
|
||||
|
||||
// ListTLSCertificates 列出全部证书(不含 PEM 敏感字段的 JSON 暴露由 struct tag 控制)。
|
||||
func ListTLSCertificates(ctx context.Context) ([]TLSCertificate, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var certificates []TLSCertificate
|
||||
if err := conn.Order("id desc").Find(&certificates).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return certificates, nil
|
||||
}
|
||||
|
||||
// GetTLSCertificateByID 按 ID 查询证书。
|
||||
func GetTLSCertificateByID(ctx context.Context, id uint) (*TLSCertificate, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var certificate TLSCertificate
|
||||
if err := conn.First(&certificate, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &certificate, nil
|
||||
}
|
||||
|
||||
// CreateTLSCertificateRecord 创建证书记录。
|
||||
func CreateTLSCertificateRecord(ctx context.Context, certificate *TLSCertificate) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Create(certificate).Error
|
||||
}
|
||||
|
||||
// SaveTLSCertificate 保存证书记录。
|
||||
func SaveTLSCertificate(ctx context.Context, certificate *TLSCertificate) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Save(certificate).Error
|
||||
}
|
||||
|
||||
// DeleteTLSCertificateRecord 删除证书记录。
|
||||
func DeleteTLSCertificateRecord(ctx context.Context, id uint) error {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn.Delete(&TLSCertificate{}, id).Error
|
||||
}
|
||||
|
||||
// CountTLSCertificatesByDNSAccountID 统计引用指定 DNS 账号的证书数量。
|
||||
func CountTLSCertificatesByDNSAccountID(ctx context.Context, dnsAccountID uint) (int64, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return 0, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
var count int64
|
||||
if err := conn.Model(&TLSCertificate{}).Where("dns_account_id = ?", dnsAccountID).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// ListTLSProxyRouteRefs 列出代理规则证书引用字段。
|
||||
func ListTLSProxyRouteRefs(ctx context.Context) ([]TLSProxyRouteRef, error) {
|
||||
if !HasTLSProxyRoutesTable(ctx) {
|
||||
return nil, nil
|
||||
}
|
||||
var routes []TLSProxyRouteRef
|
||||
if err := db.DB(ctx).Order("id asc").Find(&routes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return routes, nil
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/db"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OpenFlareWAFRuleGroup stores a WAF rule group.
|
||||
type OpenFlareWAFRuleGroup struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Name string `json:"name" gorm:"size:255;not null"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
IsGlobal bool `json:"is_global" gorm:"not null;default:false;index"`
|
||||
BlockStatusCode int `json:"block_status_code" gorm:"not null;default:418"`
|
||||
BlockResponseBody string `json:"block_response_body" gorm:"type:text;not null;default:''"`
|
||||
IPWhitelist string `json:"ip_whitelist" gorm:"type:text;not null;default:'[]'"`
|
||||
IPBlacklist string `json:"ip_blacklist" gorm:"type:text;not null;default:'[]'"`
|
||||
IPWhitelistGroups string `json:"ip_whitelist_group_ids" gorm:"column:ip_whitelist_groups;type:text;not null;default:'[]'"`
|
||||
IPBlacklistGroups string `json:"ip_blacklist_group_ids" gorm:"column:ip_blacklist_groups;type:text;not null;default:'[]'"`
|
||||
CountryWhitelist string `json:"country_whitelist" gorm:"type:text;not null;default:'[]'"`
|
||||
CountryBlacklist string `json:"country_blacklist" gorm:"type:text;not null;default:'[]'"`
|
||||
RegionWhitelist string `json:"region_whitelist" gorm:"type:text;not null;default:'[]'"`
|
||||
RegionBlacklist string `json:"region_blacklist" gorm:"type:text;not null;default:'[]'"`
|
||||
PoWEnabled bool `json:"pow_enabled" gorm:"column:pow_enabled;not null;default:false"`
|
||||
PoWConfig string `json:"pow_config" gorm:"column:pow_config;type:text;not null;default:'{}'"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareWAFRuleGroup) TableName() string {
|
||||
return "of_waf_rule_groups"
|
||||
}
|
||||
|
||||
// OpenFlareWAFIPGroup stores a WAF IP group.
|
||||
type OpenFlareWAFIPGroup struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Name string `json:"name" gorm:"size:255;not null"`
|
||||
Type string `json:"type" gorm:"size:32;not null;index"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true"`
|
||||
IPList string `json:"ip_list" gorm:"type:text;not null;default:'[]'"`
|
||||
AutoConfig string `json:"auto_config" gorm:"type:text;not null;default:'{}'"`
|
||||
ExtIPs string `json:"ext_ips" gorm:"type:text;not null;default:'[]'"`
|
||||
SubscriptionURL string `json:"subscription_url" gorm:"size:2048;not null;default:''"`
|
||||
SubscriptionFormat string `json:"subscription_format" gorm:"size:32;not null;default:'text'"`
|
||||
SubscriptionMappingRule string `json:"subscription_mapping_rule" gorm:"size:255;not null;default:''"`
|
||||
SyncIntervalMinutes int `json:"sync_interval_minutes" gorm:"not null;default:1440"`
|
||||
LastSyncedAt *time.Time `json:"last_synced_at"`
|
||||
NextSyncAt *time.Time `json:"next_sync_at" gorm:"index"`
|
||||
LastSyncStatus string `json:"last_sync_status" gorm:"size:32;not null;default:''"`
|
||||
LastSyncMessage string `json:"last_sync_message" gorm:"type:text;not null;default:''"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareWAFIPGroup) TableName() string {
|
||||
return "of_waf_ip_groups"
|
||||
}
|
||||
|
||||
// OpenFlareWAFRuleGroupBinding binds a rule group to a proxy route.
|
||||
type OpenFlareWAFRuleGroupBinding struct {
|
||||
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
RuleGroupID uint `json:"rule_group_id" gorm:"not null;uniqueIndex:idx_of_waf_group_route"`
|
||||
ProxyRouteID uint `json:"proxy_route_id" gorm:"not null;uniqueIndex:idx_of_waf_group_route;index"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
// TableName returns the GORM table name.
|
||||
func (OpenFlareWAFRuleGroupBinding) TableName() string {
|
||||
return "of_waf_rule_group_bindings"
|
||||
}
|
||||
|
||||
func wafDB(ctx context.Context) (*gorm.DB, error) {
|
||||
conn := db.DB(ctx)
|
||||
if conn == nil {
|
||||
return nil, errors.New(errDatabaseNotInitialized)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareWAFRuleGroups returns all rule groups.
|
||||
func ListOpenFlareWAFRuleGroups(ctx context.Context) ([]*OpenFlareWAFRuleGroup, error) {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var groups []*OpenFlareWAFRuleGroup
|
||||
if err = conn.Order("is_global desc").Order("id asc").Find(&groups).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
// GetOpenFlareWAFRuleGroupByID returns a rule group by id.
|
||||
func GetOpenFlareWAFRuleGroupByID(ctx context.Context, id uint) (*OpenFlareWAFRuleGroup, error) {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var group OpenFlareWAFRuleGroup
|
||||
if err = conn.First(&group, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &group, nil
|
||||
}
|
||||
|
||||
// GetGlobalOpenFlareWAFRuleGroup returns the global rule group if present.
|
||||
func GetGlobalOpenFlareWAFRuleGroup(ctx context.Context) (*OpenFlareWAFRuleGroup, error) {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var group OpenFlareWAFRuleGroup
|
||||
if err = conn.Where("is_global = ?", true).Order("id asc").First(&group).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &group, nil
|
||||
}
|
||||
|
||||
// CreateOpenFlareWAFRuleGroup inserts a rule group.
|
||||
func CreateOpenFlareWAFRuleGroup(ctx context.Context, group *OpenFlareWAFRuleGroup) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Create(group).Error
|
||||
}
|
||||
|
||||
// UpdateOpenFlareWAFRuleGroup updates mutable rule group fields.
|
||||
func UpdateOpenFlareWAFRuleGroup(ctx context.Context, group *OpenFlareWAFRuleGroup) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Model(&OpenFlareWAFRuleGroup{}).Where("id = ?", group.ID).Updates(map[string]any{
|
||||
"name": group.Name,
|
||||
"enabled": group.Enabled,
|
||||
"is_global": group.IsGlobal,
|
||||
"block_status_code": group.BlockStatusCode,
|
||||
"block_response_body": group.BlockResponseBody,
|
||||
"ip_whitelist": group.IPWhitelist,
|
||||
"ip_blacklist": group.IPBlacklist,
|
||||
"ip_whitelist_groups": group.IPWhitelistGroups,
|
||||
"ip_blacklist_groups": group.IPBlacklistGroups,
|
||||
"country_whitelist": group.CountryWhitelist,
|
||||
"country_blacklist": group.CountryBlacklist,
|
||||
"region_whitelist": group.RegionWhitelist,
|
||||
"region_blacklist": group.RegionBlacklist,
|
||||
"pow_enabled": group.PoWEnabled,
|
||||
"pow_config": group.PoWConfig,
|
||||
"remark": group.Remark,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// DeleteOpenFlareWAFRuleGroup removes a rule group.
|
||||
func DeleteOpenFlareWAFRuleGroup(ctx context.Context, id uint) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Delete(&OpenFlareWAFRuleGroup{}, id).Error
|
||||
}
|
||||
|
||||
// ListOpenFlareWAFIPGroups returns all IP groups.
|
||||
func ListOpenFlareWAFIPGroups(ctx context.Context) ([]*OpenFlareWAFIPGroup, error) {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var groups []*OpenFlareWAFIPGroup
|
||||
if err = conn.Order("type asc").Order("id asc").Find(&groups).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
// GetOpenFlareWAFIPGroupByID returns an IP group by id.
|
||||
func GetOpenFlareWAFIPGroupByID(ctx context.Context, id uint) (*OpenFlareWAFIPGroup, error) {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var group OpenFlareWAFIPGroup
|
||||
if err = conn.First(&group, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &group, nil
|
||||
}
|
||||
|
||||
// CreateOpenFlareWAFIPGroup inserts an IP group.
|
||||
func CreateOpenFlareWAFIPGroup(ctx context.Context, group *OpenFlareWAFIPGroup) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Create(group).Error
|
||||
}
|
||||
|
||||
// UpdateOpenFlareWAFIPGroup updates mutable IP group fields.
|
||||
func UpdateOpenFlareWAFIPGroup(ctx context.Context, group *OpenFlareWAFIPGroup) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Model(&OpenFlareWAFIPGroup{}).Where("id = ?", group.ID).Updates(map[string]any{
|
||||
"name": group.Name,
|
||||
"type": group.Type,
|
||||
"enabled": group.Enabled,
|
||||
"ip_list": group.IPList,
|
||||
"auto_config": group.AutoConfig,
|
||||
"ext_ips": group.ExtIPs,
|
||||
"subscription_url": group.SubscriptionURL,
|
||||
"subscription_format": group.SubscriptionFormat,
|
||||
"subscription_mapping_rule": group.SubscriptionMappingRule,
|
||||
"sync_interval_minutes": group.SyncIntervalMinutes,
|
||||
"next_sync_at": group.NextSyncAt,
|
||||
"last_sync_status": group.LastSyncStatus,
|
||||
"last_sync_message": group.LastSyncMessage,
|
||||
"remark": group.Remark,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// DeleteOpenFlareWAFIPGroup removes an IP group.
|
||||
func DeleteOpenFlareWAFIPGroup(ctx context.Context, id uint) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Delete(&OpenFlareWAFIPGroup{}, id).Error
|
||||
}
|
||||
|
||||
// ListOpenFlareWAFRuleGroupBindings returns all bindings.
|
||||
func ListOpenFlareWAFRuleGroupBindings(ctx context.Context) ([]OpenFlareWAFRuleGroupBinding, error) {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var bindings []OpenFlareWAFRuleGroupBinding
|
||||
if err = conn.Order("rule_group_id asc").Order("proxy_route_id asc").Find(&bindings).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bindings, nil
|
||||
}
|
||||
|
||||
// ListOpenFlareWAFRuleGroupBindingsByRouteID returns bindings for a proxy route.
|
||||
func ListOpenFlareWAFRuleGroupBindingsByRouteID(ctx context.Context, routeID uint) ([]OpenFlareWAFRuleGroupBinding, error) {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var bindings []OpenFlareWAFRuleGroupBinding
|
||||
if err = conn.Where("proxy_route_id = ?", routeID).Order("rule_group_id asc").Find(&bindings).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bindings, nil
|
||||
}
|
||||
|
||||
// ReplaceOpenFlareWAFRuleGroupBindings replaces bindings for a rule group.
|
||||
func ReplaceOpenFlareWAFRuleGroupBindings(ctx context.Context, groupID uint, routeIDs []uint) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Transaction(func(tx *gorm.DB) error {
|
||||
if err = tx.Where("rule_group_id = ?", groupID).Delete(&OpenFlareWAFRuleGroupBinding{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, routeID := range routeIDs {
|
||||
binding := OpenFlareWAFRuleGroupBinding{RuleGroupID: groupID, ProxyRouteID: routeID}
|
||||
if err = tx.Create(&binding).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ReplaceOpenFlareWAFSiteRuleGroupBindings replaces bindings for a proxy route.
|
||||
func ReplaceOpenFlareWAFSiteRuleGroupBindings(ctx context.Context, routeID uint, groupIDs []uint) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Transaction(func(tx *gorm.DB) error {
|
||||
if err = tx.Where("proxy_route_id = ?", routeID).Delete(&OpenFlareWAFRuleGroupBinding{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, groupID := range groupIDs {
|
||||
binding := OpenFlareWAFRuleGroupBinding{RuleGroupID: groupID, ProxyRouteID: routeID}
|
||||
if err = tx.Create(&binding).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteOpenFlareWAFRuleGroupBindingsByGroupID removes bindings for a rule group.
|
||||
func DeleteOpenFlareWAFRuleGroupBindingsByGroupID(ctx context.Context, groupID uint) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Where("rule_group_id = ?", groupID).Delete(&OpenFlareWAFRuleGroupBinding{}).Error
|
||||
}
|
||||
|
||||
// DeleteOpenFlareWAFRuleGroupWithBindings removes a rule group and its bindings.
|
||||
func DeleteOpenFlareWAFRuleGroupWithBindings(ctx context.Context, groupID uint) error {
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return conn.Transaction(func(tx *gorm.DB) error {
|
||||
if err = tx.Where("rule_group_id = ?", groupID).Delete(&OpenFlareWAFRuleGroupBinding{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&OpenFlareWAFRuleGroup{}, groupID).Error
|
||||
})
|
||||
}
|
||||
|
||||
// GetOpenFlareProxyRouteByID returns a proxy route by id when the table exists.
|
||||
func GetOpenFlareProxyRouteByID(ctx context.Context, id uint) (*OriginProxyRoute, error) {
|
||||
if !HasProxyRoutesTable(ctx) {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
conn, err := wafDB(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var route OriginProxyRoute
|
||||
if err = conn.First(&route, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &route, nil
|
||||
}
|
||||
Reference in New Issue
Block a user