upda/server/service_lock_mem.go
Varakh 77e7a08c4d
All checks were successful
/ build (pull_request) Successful in 3m6s
feature(locking): add proper locking and overhaul existing locking service
2024-05-23 18:43:01 +02:00

61 lines
1.3 KiB
Go

package server
import (
"context"
"errors"
"git.myservermanager.com/varakh/upda/util"
"go.uber.org/zap"
)
type lockMemService struct {
registry *util.InMemoryLockRegistry
}
var (
errLockMemNotReleased = newServiceError(Conflict, errors.New("lock service: could not release lock"))
)
func newLockMemService() lockService {
zap.L().Info("Initialized in-memory locking service")
return &lockMemService{registry: util.NewInMemoryLockRegistry()}
}
func (s *lockMemService) lock(ctx context.Context, resource string) (appLock, error) {
if resource == "" {
return nil, errorValidationNotBlank
}
zap.L().Sugar().Debugf("Trying to lock '%s'", resource)
s.registry.Lock(resource)
zap.L().Sugar().Debugf("Locked '%s'", resource)
l := &inMemoryLock{
registry: s.registry,
resource: resource,
}
return l, nil
}
func (s *lockMemService) lockWithOptions(ctx context.Context, resource string, options ...appLockOption) (appLock, error) {
// ignores any options
return s.lock(ctx, resource)
}
var _ appLock = (*inMemoryLock)(nil)
type inMemoryLock struct {
registry *util.InMemoryLockRegistry
resource string
}
func (r inMemoryLock) unlock(ctx context.Context) error {
zap.L().Sugar().Debugf("Unlocking '%s'", r.resource)
if err := r.registry.Unlock(r.resource); err != nil {
return errLockMemNotReleased
}
return nil
}