-
Notifications
You must be signed in to change notification settings - Fork 0
/
memorylocker.go
72 lines (59 loc) · 1.98 KB
/
memorylocker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Package memorylocker provides an in-memory locking mechanism.
//
// When multiple processes are attempting to access an upload, whether it be
// by reading or writing, a synchronization mechanism is required to prevent
// data corruption, especially to ensure correct offset values and the proper
// order of chunks inside a single upload.
//
// MemoryLocker persists locks using memory and therefore allowing a simple and
// cheap mechanism. Locks will only exist as long as this object is kept in
// reference and will be erased if the program exits.
package memorylocker
import (
"github.com/jxo-me/plus-core/pkg/v2/tus"
"sync"
)
// MemoryLocker persists locks using memory and therefore allowing a simple and
// cheap mechanism. Locks will only exist as long as this object is kept in
// reference and will be erased if the program exits.
type MemoryLocker struct {
locks map[string]struct{}
mutex sync.Mutex
}
// New creates a new in-memory locker.
func New() *MemoryLocker {
return &MemoryLocker{
locks: make(map[string]struct{}),
}
}
// UseIn adds this locker to the passed composer.
func (locker *MemoryLocker) UseIn(composer *tus.StoreComposer) {
composer.UseLocker(locker)
}
func (locker *MemoryLocker) NewLock(id string) (tus.Lock, error) {
return memoryLock{locker, id}, nil
}
type memoryLock struct {
locker *MemoryLocker
id string
}
// Lock tries to obtain the exclusive lock.
func (lock memoryLock) Lock() error {
lock.locker.mutex.Lock()
defer lock.locker.mutex.Unlock()
// Ensure file is not locked
if _, ok := lock.locker.locks[lock.id]; ok {
return tus.ErrFileLocked
}
lock.locker.locks[lock.id] = struct{}{}
return nil
}
// Unlock releases a lock. If no such lock exists, no error will be returned.
func (lock memoryLock) Unlock() error {
lock.locker.mutex.Lock()
// Deleting a non-existing key does not end in unexpected errors or panic
// since this operation results in a no-op
delete(lock.locker.locks, lock.id)
lock.locker.mutex.Unlock()
return nil
}