go.etcd.io/etcd@v3.3.27+incompatible/clientv3/namespace/lease.go (about)

     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  
    15  package namespace
    16  
    17  import (
    18  	"bytes"
    19  	"context"
    20  
    21  	"github.com/coreos/etcd/clientv3"
    22  )
    23  
    24  type leasePrefix struct {
    25  	clientv3.Lease
    26  	pfx []byte
    27  }
    28  
    29  // NewLease wraps a Lease interface to filter for only keys with a prefix
    30  // and remove that prefix when fetching attached keys through TimeToLive.
    31  func NewLease(l clientv3.Lease, prefix string) clientv3.Lease {
    32  	return &leasePrefix{l, []byte(prefix)}
    33  }
    34  
    35  func (l *leasePrefix) TimeToLive(ctx context.Context, id clientv3.LeaseID, opts ...clientv3.LeaseOption) (*clientv3.LeaseTimeToLiveResponse, error) {
    36  	resp, err := l.Lease.TimeToLive(ctx, id, opts...)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  	if len(resp.Keys) > 0 {
    41  		var outKeys [][]byte
    42  		for i := range resp.Keys {
    43  			if len(resp.Keys[i]) < len(l.pfx) {
    44  				// too short
    45  				continue
    46  			}
    47  			if !bytes.Equal(resp.Keys[i][:len(l.pfx)], l.pfx) {
    48  				// doesn't match prefix
    49  				continue
    50  			}
    51  			// strip prefix
    52  			outKeys = append(outKeys, resp.Keys[i][len(l.pfx):])
    53  		}
    54  		resp.Keys = outKeys
    55  	}
    56  	return resp, nil
    57  }