|
| 1 | +// Copyright 2024 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package globallock |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "sync" |
| 9 | +) |
| 10 | + |
| 11 | +var ( |
| 12 | + defaultLocker Locker |
| 13 | + initOnce sync.Once |
| 14 | + initFunc = func() { |
| 15 | + // TODO: read the setting and initialize the default locker. |
| 16 | + // Before implementing this, don't use it. |
| 17 | + } // define initFunc as a variable to make it possible to change it in tests |
| 18 | +) |
| 19 | + |
| 20 | +// DefaultLocker returns the default locker. |
| 21 | +func DefaultLocker() Locker { |
| 22 | + initOnce.Do(func() { |
| 23 | + initFunc() |
| 24 | + }) |
| 25 | + return defaultLocker |
| 26 | +} |
| 27 | + |
| 28 | +// Lock tries to acquire a lock for the given key, it uses the default locker. |
| 29 | +// Read the documentation of Locker.Lock for more information about the behavior. |
| 30 | +func Lock(ctx context.Context, key string) (context.Context, ReleaseFunc, error) { |
| 31 | + return DefaultLocker().Lock(ctx, key) |
| 32 | +} |
| 33 | + |
| 34 | +// TryLock tries to acquire a lock for the given key, it uses the default locker. |
| 35 | +// Read the documentation of Locker.TryLock for more information about the behavior. |
| 36 | +func TryLock(ctx context.Context, key string) (bool, context.Context, ReleaseFunc, error) { |
| 37 | + return DefaultLocker().TryLock(ctx, key) |
| 38 | +} |
| 39 | + |
| 40 | +// LockAndDo tries to acquire a lock for the given key and then calls the given function. |
| 41 | +// It uses the default locker. |
| 42 | +func LockAndDo(ctx context.Context, key string, f func(context.Context) error) error { |
| 43 | + ctx, release, err := Lock(ctx, key) |
| 44 | + if err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + defer release() |
| 48 | + |
| 49 | + return f(ctx) |
| 50 | +} |
| 51 | + |
| 52 | +// TryLockAndDo tries to acquire a lock for the given key and then calls the given function. |
| 53 | +// It uses the default locker, and it will return false if failed to acquire the lock. |
| 54 | +func TryLockAndDo(ctx context.Context, key string, f func(context.Context) error) (bool, error) { |
| 55 | + ok, ctx, release, err := TryLock(ctx, key) |
| 56 | + if err != nil { |
| 57 | + return false, err |
| 58 | + } |
| 59 | + defer release() |
| 60 | + |
| 61 | + if !ok { |
| 62 | + return false, nil |
| 63 | + } |
| 64 | + |
| 65 | + return true, f(ctx) |
| 66 | +} |
0 commit comments