lease.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2017 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package namespace
  15. import (
  16. "bytes"
  17. "context"
  18. "github.com/coreos/etcd/clientv3"
  19. )
  20. type leasePrefix struct {
  21. clientv3.Lease
  22. pfx []byte
  23. }
  24. // NewLease wraps a Lease interface to filter for only keys with a prefix
  25. // and remove that prefix when fetching attached keys through TimeToLive.
  26. func NewLease(l clientv3.Lease, prefix string) clientv3.Lease {
  27. return &leasePrefix{l, []byte(prefix)}
  28. }
  29. func (l *leasePrefix) TimeToLive(ctx context.Context, id clientv3.LeaseID, opts ...clientv3.LeaseOption) (*clientv3.LeaseTimeToLiveResponse, error) {
  30. resp, err := l.Lease.TimeToLive(ctx, id, opts...)
  31. if err != nil {
  32. return nil, err
  33. }
  34. if len(resp.Keys) > 0 {
  35. var outKeys [][]byte
  36. for i := range resp.Keys {
  37. if len(resp.Keys[i]) < len(l.pfx) {
  38. // too short
  39. continue
  40. }
  41. if !bytes.Equal(resp.Keys[i][:len(l.pfx)], l.pfx) {
  42. // doesn't match prefix
  43. continue
  44. }
  45. // strip prefix
  46. outKeys = append(outKeys, resp.Keys[i][len(l.pfx):])
  47. }
  48. resp.Keys = outKeys
  49. }
  50. return resp, nil
  51. }