2019-02-01 14:22:00 +03:00
|
|
|
package identity
|
|
|
|
|
2019-08-11 15:08:03 +03:00
|
|
|
import (
|
2021-04-04 14:28:21 +03:00
|
|
|
"sync"
|
|
|
|
|
2019-08-11 15:08:03 +03:00
|
|
|
"github.com/MichaelMure/git-bug/entity"
|
|
|
|
"github.com/MichaelMure/git-bug/repository"
|
|
|
|
)
|
2019-02-01 14:22:00 +03:00
|
|
|
|
|
|
|
// Resolver define the interface of an Identity resolver, able to load
|
|
|
|
// an identity from, for example, a repo or a cache.
|
|
|
|
type Resolver interface {
|
2019-08-11 15:08:03 +03:00
|
|
|
ResolveIdentity(id entity.Id) (Interface, error)
|
2019-02-01 14:22:00 +03:00
|
|
|
}
|
|
|
|
|
2020-09-16 17:22:02 +03:00
|
|
|
// SimpleResolver is a Resolver loading Identities directly from a Repo
|
2019-02-01 14:22:00 +03:00
|
|
|
type SimpleResolver struct {
|
|
|
|
repo repository.Repo
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSimpleResolver(repo repository.Repo) *SimpleResolver {
|
|
|
|
return &SimpleResolver{repo: repo}
|
|
|
|
}
|
|
|
|
|
2019-08-11 15:08:03 +03:00
|
|
|
func (r *SimpleResolver) ResolveIdentity(id entity.Id) (Interface, error) {
|
2019-02-03 21:55:35 +03:00
|
|
|
return ReadLocal(r.repo, id)
|
2019-02-01 14:22:00 +03:00
|
|
|
}
|
2020-09-16 17:22:02 +03:00
|
|
|
|
|
|
|
// StubResolver is a Resolver that doesn't load anything, only returning IdentityStub instances
|
|
|
|
type StubResolver struct{}
|
|
|
|
|
|
|
|
func NewStubResolver() *StubResolver {
|
|
|
|
return &StubResolver{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StubResolver) ResolveIdentity(id entity.Id) (Interface, error) {
|
|
|
|
return &IdentityStub{id: id}, nil
|
|
|
|
}
|
2021-04-04 14:28:21 +03:00
|
|
|
|
|
|
|
// CachedResolver is a resolver ensuring that loading is done only once through another Resolver.
|
|
|
|
type CachedResolver struct {
|
|
|
|
mu sync.RWMutex
|
|
|
|
resolver Resolver
|
|
|
|
identities map[entity.Id]Interface
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCachedResolver(resolver Resolver) *CachedResolver {
|
|
|
|
return &CachedResolver{
|
|
|
|
resolver: resolver,
|
|
|
|
identities: make(map[entity.Id]Interface),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *CachedResolver) ResolveIdentity(id entity.Id) (Interface, error) {
|
|
|
|
c.mu.RLock()
|
|
|
|
if i, ok := c.identities[id]; ok {
|
|
|
|
c.mu.RUnlock()
|
|
|
|
return i, nil
|
|
|
|
}
|
|
|
|
c.mu.RUnlock()
|
|
|
|
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
i, err := c.resolver.ResolveIdentity(id)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
c.identities[id] = i
|
|
|
|
return i, nil
|
|
|
|
}
|