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 }