64 lines
1.5 KiB
Go
64 lines
1.5 KiB
Go
// Package store holds the repository implementations of the users module.
|
|
// inmem.go is the in-process one: state lives only in this process and
|
|
// disappears with it by design of the lab.
|
|
package store
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"messenger/internal/user"
|
|
)
|
|
|
|
type InMemUsers struct {
|
|
mu sync.RWMutex
|
|
byID map[uuid.UUID]user.User
|
|
byUsername map[string]struct{}
|
|
}
|
|
|
|
var _ user.Repository = (*InMemUsers)(nil)
|
|
|
|
func NewInMemUsers() *InMemUsers {
|
|
return &InMemUsers{
|
|
byID: make(map[uuid.UUID]user.User),
|
|
byUsername: make(map[string]struct{}),
|
|
}
|
|
}
|
|
|
|
// Create checks and inserts under the same write lock, so concurrent
|
|
// registrations of one username admit exactly one winner.
|
|
func (r *InMemUsers) Create(_ context.Context, u user.User) error {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
if _, taken := r.byUsername[u.Username]; taken {
|
|
return user.ErrUsernameTaken
|
|
}
|
|
r.byUsername[u.Username] = struct{}{}
|
|
r.byID[u.ID] = u
|
|
return nil
|
|
}
|
|
|
|
func (r *InMemUsers) GetByID(_ context.Context, id uuid.UUID) (user.User, error) {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
u, ok := r.byID[id]
|
|
if !ok {
|
|
return user.User{}, user.ErrNotFound
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
func (r *InMemUsers) ExistingIDs(_ context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
found := make([]uuid.UUID, 0, len(ids))
|
|
for _, id := range ids {
|
|
if _, ok := r.byID[id]; ok {
|
|
found = append(found, id)
|
|
}
|
|
}
|
|
return found, nil
|
|
}
|