Files
dobotai-platform/internal/directory/resolver.go
2026-07-23 10:55:25 +08:00

66 lines
2.1 KiB
Go

package directory
import (
"context"
"errors"
"strings"
"time"
)
type ProfileStore interface {
LookupDirectoryProfile(ctx context.Context, tenantKey, staffID string) (Profile, bool, error)
UpsertDirectoryProfiles(ctx context.Context, tenantKey string, profiles []Profile) error
}
type UserLookup interface {
LookupUser(ctx context.Context, staffID string) (Profile, error)
}
type Resolver struct {
store ProfileStore
lookup UserLookup
now func() time.Time
}
func NewResolver(store ProfileStore, lookup UserLookup) (*Resolver, error) {
if store == nil {
return nil, errors.New("directory profile store is required")
}
return &Resolver{store: store, lookup: lookup, now: time.Now}, nil
}
// ResolveUser always returns a safe callback-based fallback profile when the
// cache or on-demand lookup is unavailable. The diagnostic error is intentionally
// generic so identifiers and upstream payloads cannot leak into logs.
func (r *Resolver) ResolveUser(ctx context.Context, tenantKey, staffID, fallbackName string) (Profile, error) {
fallback := Profile{StaffID: strings.TrimSpace(staffID), Name: strings.TrimSpace(fallbackName)}
profile, found, err := r.store.LookupDirectoryProfile(ctx, tenantKey, fallback.StaffID)
if err != nil {
return fallback, errors.New("directory local lookup failed")
}
if found && strings.TrimSpace(profile.Name) != "" {
profile.Name = strings.TrimSpace(profile.Name)
return profile, nil
}
if r.lookup == nil {
return fallback, nil
}
profile, err = r.lookup.LookupUser(ctx, fallback.StaffID)
if err != nil {
return fallback, errors.New("directory on-demand lookup failed")
}
profile.StaffID = fallback.StaffID
profile.Name = strings.TrimSpace(profile.Name)
if profile.Name == "" {
return fallback, errors.New("directory on-demand lookup returned no name")
}
profile.Source = SourceOnDemand
if profile.SyncedAt.IsZero() {
profile.SyncedAt = r.now().UTC()
}
if err := r.store.UpsertDirectoryProfiles(ctx, tenantKey, []Profile{profile}); err != nil {
return profile, errors.New("directory on-demand cache write failed")
}
return profile, nil
}