feat(tenant): 增加租户基础与域名解析
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
type Scope struct {
|
||||
TenantID uint64
|
||||
TenantCode string
|
||||
TenantName string
|
||||
TenantStatus string
|
||||
Host string
|
||||
DomainType string
|
||||
ProfileJSON datatypes.JSON
|
||||
FeaturesJSON datatypes.JSON
|
||||
}
|
||||
|
||||
func WithScope(ctx context.Context, scope Scope) context.Context {
|
||||
return context.WithValue(ctx, contextKey{}, scope)
|
||||
}
|
||||
|
||||
func FromContext(ctx context.Context) (Scope, bool) {
|
||||
scope, ok := ctx.Value(contextKey{}).(Scope)
|
||||
return scope, ok && scope.TenantID > 0
|
||||
}
|
||||
|
||||
func MustFromContext(ctx context.Context) Scope {
|
||||
scope, ok := FromContext(ctx)
|
||||
if !ok {
|
||||
panic("tenant scope missing from context")
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
func (s Scope) Profile() map[string]any {
|
||||
return decodeJSONMap(s.ProfileJSON)
|
||||
}
|
||||
|
||||
func (s Scope) Features() map[string]any {
|
||||
return decodeJSONMap(s.FeaturesJSON)
|
||||
}
|
||||
|
||||
func decodeJSONMap(raw datatypes.JSON) map[string]any {
|
||||
if len(raw) == 0 {
|
||||
return map[string]any{}
|
||||
}
|
||||
var value map[string]any
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type SiteContextDTO struct {
|
||||
Mode string `json:"mode"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TenantCode string `json:"tenant_code"`
|
||||
TenantName string `json:"tenant_name"`
|
||||
Host string `json:"host"`
|
||||
DomainType string `json:"domain_type"`
|
||||
Status string `json:"status"`
|
||||
Profile map[string]any `json:"profile"`
|
||||
Features map[string]any `json:"features"`
|
||||
}
|
||||
|
||||
type Handler struct{}
|
||||
|
||||
func NewHandler() *Handler {
|
||||
return &Handler{}
|
||||
}
|
||||
|
||||
func (h *Handler) SiteContext(c *gin.Context) {
|
||||
scope, ok := FromContext(c.Request.Context())
|
||||
if !ok {
|
||||
response.Error(c, http.StatusNotFound, "site_not_found", "当前域名未配置站点")
|
||||
return
|
||||
}
|
||||
response.OK(c, SiteContextDTO{
|
||||
Mode: "tenant",
|
||||
TenantID: scope.TenantID,
|
||||
TenantCode: scope.TenantCode,
|
||||
TenantName: scope.TenantName,
|
||||
Host: scope.Host,
|
||||
DomainType: scope.DomainType,
|
||||
Status: scope.TenantStatus,
|
||||
Profile: scope.Profile(),
|
||||
Features: scope.Features(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("tenancy dependency unavailable")
|
||||
ErrTenantNotFound = errors.New("tenant not found")
|
||||
ErrDomainConflict = errors.New("tenant domain belongs to another tenant")
|
||||
)
|
||||
|
||||
const domainCacheTTL = time.Minute
|
||||
|
||||
type domainCacheEntry struct {
|
||||
scope *Scope
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
mu sync.RWMutex
|
||||
cache map[string]domainCacheEntry
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db, cache: make(map[string]domainCacheEntry)}
|
||||
}
|
||||
|
||||
func (r *Repository) ResolveHost(ctx context.Context, rawHost string) (*Scope, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
host := sitecode.ExtractHost(rawHost)
|
||||
if host == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if cached, ok := r.cachedHost(host); ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
var row struct {
|
||||
TenantID uint64 `gorm:"column:tenant_id"`
|
||||
TenantCode string `gorm:"column:tenant_code"`
|
||||
TenantName string `gorm:"column:tenant_name"`
|
||||
TenantStatus string `gorm:"column:tenant_status"`
|
||||
Host string `gorm:"column:host"`
|
||||
DomainType string `gorm:"column:domain_type"`
|
||||
ProfileJSON []byte `gorm:"column:profile_json"`
|
||||
FeaturesJSON []byte `gorm:"column:features_json"`
|
||||
}
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("tenant_domains AS d").
|
||||
Select(`t.id AS tenant_id, t.code AS tenant_code, t.name AS tenant_name, t.status AS tenant_status,
|
||||
d.host, d.domain_type, t.profile_json, t.features_json`).
|
||||
Joins("JOIN tenants AS t ON t.id = d.tenant_id").
|
||||
Where("d.host = ? AND d.status = ? AND t.status = ?", host, "active", "active").
|
||||
Take(&row).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
r.cacheHost(host, nil)
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
scope := &Scope{
|
||||
TenantID: row.TenantID,
|
||||
TenantCode: row.TenantCode,
|
||||
TenantName: row.TenantName,
|
||||
TenantStatus: row.TenantStatus,
|
||||
Host: row.Host,
|
||||
DomainType: row.DomainType,
|
||||
ProfileJSON: row.ProfileJSON,
|
||||
FeaturesJSON: row.FeaturesJSON,
|
||||
}
|
||||
r.cacheHost(host, scope)
|
||||
return scope, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ResolveCode(ctx context.Context, code string) (*Scope, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
code = strings.TrimSpace(strings.ToLower(code))
|
||||
if code == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var tenant model.Tenant
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("code = ? AND status = ?", code, "active").
|
||||
First(&tenant).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &Scope{
|
||||
TenantID: tenant.ID,
|
||||
TenantCode: tenant.Code,
|
||||
TenantName: tenant.Name,
|
||||
TenantStatus: tenant.Status,
|
||||
DomainType: "development",
|
||||
ProfileJSON: tenant.ProfileJSON,
|
||||
FeaturesJSON: tenant.FeaturesJSON,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) IsActiveDomain(ctx context.Context, rawHost string) (bool, error) {
|
||||
scope, err := r.ResolveHost(ctx, rawHost)
|
||||
return scope != nil, err
|
||||
}
|
||||
|
||||
func (r *Repository) Invalidate() {
|
||||
r.mu.Lock()
|
||||
r.cache = make(map[string]domainCacheEntry)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *Repository) cachedHost(host string) (*Scope, bool) {
|
||||
r.mu.RLock()
|
||||
entry, ok := r.cache[host]
|
||||
r.mu.RUnlock()
|
||||
if !ok || time.Now().After(entry.expiresAt) {
|
||||
return nil, false
|
||||
}
|
||||
if entry.scope == nil {
|
||||
return nil, true
|
||||
}
|
||||
copied := *entry.scope
|
||||
return &copied, true
|
||||
}
|
||||
|
||||
func (r *Repository) cacheHost(host string, scope *Scope) {
|
||||
r.mu.Lock()
|
||||
r.cache[host] = domainCacheEntry{scope: scope, expiresAt: time.Now().Add(domainCacheTTL)}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
type BootstrapConfig struct {
|
||||
PrimaryDomain string
|
||||
JieyouDomain string
|
||||
}
|
||||
|
||||
func BootstrapDomains(ctx context.Context, db *gorm.DB, cfg BootstrapConfig) error {
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
primary := sitecode.ExtractHost(cfg.PrimaryDomain)
|
||||
jieyou := sitecode.ExtractHost(cfg.JieyouDomain)
|
||||
|
||||
if primary != "" {
|
||||
if err := repo.UpsertDomain(ctx, "dachui", primary, "storefront"); err != nil {
|
||||
return err
|
||||
}
|
||||
h5 := "h5." + primary
|
||||
if err := repo.UpsertDomain(ctx, "dachui", h5, "storefront_alias"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if jieyou != "" && jieyou != primary {
|
||||
if err := repo.UpsertDomain(ctx, "jieyou", jieyou, "storefront"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) UpsertDomain(ctx context.Context, tenantCode, rawHost, domainType string) error {
|
||||
if r == nil || r.db == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
host := sitecode.ExtractHost(rawHost)
|
||||
if host == "" {
|
||||
return nil
|
||||
}
|
||||
var tenant model.Tenant
|
||||
if err := r.db.WithContext(ctx).Where("code = ?", tenantCode).First(&tenant).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrTenantNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var existing model.TenantDomain
|
||||
err := tx.Where("host = ?", host).First(&existing).Error
|
||||
if err == nil {
|
||||
if existing.TenantID != tenant.ID {
|
||||
return ErrDomainConflict
|
||||
}
|
||||
return tx.Model(&existing).Updates(map[string]any{
|
||||
"domain_type": domainType,
|
||||
"status": "active",
|
||||
}).Error
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model.TenantDomain{
|
||||
TenantID: tenant.ID,
|
||||
Host: host,
|
||||
DomainType: domainType,
|
||||
Status: "active",
|
||||
}).Error
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
r.Invalidate()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package tenancy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
func setupTenantRepoTest(t *testing.T) (*Repository, model.Tenant, model.Tenant) {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
dachui := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
|
||||
jieyou := model.Tenant{Code: "jieyou", Name: "解忧商行", Status: "active"}
|
||||
if err := db.Create(&dachui).Error; err != nil {
|
||||
t.Fatalf("create dachui tenant: %v", err)
|
||||
}
|
||||
if err := db.Create(&jieyou).Error; err != nil {
|
||||
t.Fatalf("create jieyou tenant: %v", err)
|
||||
}
|
||||
return NewRepository(db), dachui, jieyou
|
||||
}
|
||||
|
||||
func TestResolveHostNormalizesAndIgnoresInactiveDomains(t *testing.T) {
|
||||
repo, dachui, jieyou := setupTenantRepoTest(t)
|
||||
if err := repo.UpsertDomain(t.Context(), "dachui", "hao858.com", "storefront"); err != nil {
|
||||
t.Fatalf("upsert dachui domain: %v", err)
|
||||
}
|
||||
if err := repo.db.Create(&model.TenantDomain{
|
||||
TenantID: jieyou.ID,
|
||||
Host: "disabled.example.com",
|
||||
DomainType: "storefront",
|
||||
Status: "disabled",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create disabled domain: %v", err)
|
||||
}
|
||||
|
||||
scope, err := repo.ResolveHost(t.Context(), "HAO858.COM:443")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve host: %v", err)
|
||||
}
|
||||
if scope == nil || scope.TenantID != dachui.ID || scope.TenantCode != "dachui" {
|
||||
t.Fatalf("resolved scope = %#v, want dachui", scope)
|
||||
}
|
||||
|
||||
scope, err = repo.ResolveHost(t.Context(), "disabled.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve disabled host: %v", err)
|
||||
}
|
||||
if scope != nil {
|
||||
t.Fatalf("disabled domain resolved to %#v", scope)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapDomainsIsIdempotentAndRejectsHostConflict(t *testing.T) {
|
||||
repo, _, _ := setupTenantRepoTest(t)
|
||||
cfg := BootstrapConfig{PrimaryDomain: "hao858.com", JieyouDomain: "zuhaox.com"}
|
||||
if err := BootstrapDomains(t.Context(), repo.db, cfg); err != nil {
|
||||
t.Fatalf("bootstrap domains: %v", err)
|
||||
}
|
||||
if err := BootstrapDomains(t.Context(), repo.db, cfg); err != nil {
|
||||
t.Fatalf("bootstrap domains second run: %v", err)
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := repo.db.Model(&model.TenantDomain{}).Count(&count).Error; err != nil {
|
||||
t.Fatalf("count domains: %v", err)
|
||||
}
|
||||
if count != 3 {
|
||||
t.Fatalf("domain count = %d, want 3", count)
|
||||
}
|
||||
if err := repo.UpsertDomain(t.Context(), "jieyou", "hao858.com", "storefront"); !errors.Is(err, ErrDomainConflict) {
|
||||
t.Fatalf("conflicting domain error = %v, want ErrDomainConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveCode(t *testing.T) {
|
||||
repo, dachui, _ := setupTenantRepoTest(t)
|
||||
scope, err := repo.ResolveCode(t.Context(), " DAC HUI ")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve empty code: %v", err)
|
||||
}
|
||||
if scope != nil {
|
||||
t.Fatalf("invalid code resolved to %#v", scope)
|
||||
}
|
||||
scope, err = repo.ResolveCode(t.Context(), "DACHUI")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve code: %v", err)
|
||||
}
|
||||
if scope == nil || scope.TenantID != dachui.ID {
|
||||
t.Fatalf("resolved scope = %#v, want dachui", scope)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user