2023-12-22 12:13:44 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2024-05-23 17:21:19 +00:00
|
|
|
"context"
|
|
|
|
"errors"
|
2023-12-22 12:13:44 +00:00
|
|
|
"git.myservermanager.com/varakh/upda/util"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
|
|
|
type lockMemService struct {
|
|
|
|
registry *util.InMemoryLockRegistry
|
|
|
|
}
|
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
var (
|
|
|
|
errLockMemNotReleased = newServiceError(Conflict, errors.New("lock service: could not release lock"))
|
|
|
|
)
|
2023-12-22 12:13:44 +00:00
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
func newLockMemService() lockService {
|
2023-12-22 12:13:44 +00:00
|
|
|
zap.L().Info("Initialized in-memory locking service")
|
2024-05-23 17:21:19 +00:00
|
|
|
return &lockMemService{registry: util.NewInMemoryLockRegistry()}
|
2023-12-22 12:13:44 +00:00
|
|
|
}
|
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
func (s *lockMemService) lock(ctx context.Context, resource string) (appLock, error) {
|
2023-12-22 12:13:44 +00:00
|
|
|
if resource == "" {
|
2024-05-23 17:21:19 +00:00
|
|
|
return nil, errorValidationNotBlank
|
2023-12-22 12:13:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
zap.L().Sugar().Debugf("Trying to lock '%s'", resource)
|
2024-05-23 17:21:19 +00:00
|
|
|
|
2023-12-22 12:13:44 +00:00
|
|
|
s.registry.Lock(resource)
|
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
zap.L().Sugar().Debugf("Locked '%s'", resource)
|
2023-12-22 12:13:44 +00:00
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
l := &inMemoryLock{
|
|
|
|
registry: s.registry,
|
|
|
|
resource: resource,
|
2023-12-22 12:13:44 +00:00
|
|
|
}
|
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
return l, nil
|
|
|
|
}
|
2023-12-22 12:13:44 +00:00
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
func (s *lockMemService) lockWithOptions(ctx context.Context, resource string, options ...appLockOption) (appLock, error) {
|
|
|
|
// ignores any options
|
|
|
|
return s.lock(ctx, resource)
|
2023-12-22 12:13:44 +00:00
|
|
|
}
|
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
var _ appLock = (*inMemoryLock)(nil)
|
|
|
|
|
|
|
|
type inMemoryLock struct {
|
|
|
|
registry *util.InMemoryLockRegistry
|
|
|
|
resource string
|
2023-12-22 12:13:44 +00:00
|
|
|
}
|
|
|
|
|
2024-05-23 17:21:19 +00:00
|
|
|
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
|
2023-12-22 12:13:44 +00:00
|
|
|
}
|