Unlock releases the lock if the calling instance is the lock holder (based on the value). The operation is atomic, ensuring only the holder of the lock can release it. Parameters: - ctx: The context for managing the unlock request lifecycle. Returns an error if the unlock operation fails, either bec
(ctx context.Context)
| 105 | // Returns an error if the unlock operation fails, either because the lock expired or |
| 106 | // the caller is not the lock holder. |
| 107 | func (l *Locker) Unlock(ctx context.Context) error { |
| 108 | // Lua script ensures atomicity: checks the value and deletes the key if the value matches. |
| 109 | script := "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end" |
| 110 | result, err := l.client.Eval(ctx, script, []string{l.key}, l.value).Result() |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | if result == int64(0) { |
| 115 | return fmt.Errorf("unlock failed, either lock expired or you're not the lock holder for key %s", l.key) |
| 116 | } |
| 117 | return nil |
| 118 | } |
| 119 | |
| 120 | // ExtendLock extends the TTL of the lock if the calling instance is the lock holder. |
| 121 | // This method ensures that the lock is renewed only by the lock holder. |
no outgoing calls