1 package endpoints 2 3 import ( 4 "context" 5 6 clientv3 "go.etcd.io/etcd/client/v3" 7 ) 8 9 // Endpoint represents a single address the connection can be established with. 10 // 11 // Inspired by: https://pkg.go.dev/google.golang.org/grpc/resolver#Address. 12 // Please document etcd version since which version each field is supported. 13 type Endpoint struct { 14 // Addr is the server address on which a connection will be established. 15 // Since etcd 3.1 16 Addr string 17 18 // Metadata is the information associated with Addr, which may be used 19 // to make load balancing decision. 20 // Since etcd 3.1 21 Metadata interface{} 22 } 23 24 type Operation uint8 25 26 const ( 27 // Add indicates an Endpoint is added. 28 Add Operation = iota 29 // Delete indicates an existing address is deleted. 30 Delete 31 ) 32 33 // Update describes a single edit action of an Endpoint. 34 type Update struct { 35 // Op - action Add or Delete. 36 Op Operation 37 Key string 38 Endpoint Endpoint 39 } 40 41 // WatchChannel is used to deliver notifications about endpoints updates. 42 type WatchChannel <-chan []*Update 43 44 // Key2EndpointMap maps etcd key into struct describing the endpoint. 45 type Key2EndpointMap map[string]Endpoint 46 47 // UpdateWithOpts describes endpoint update (add or delete) together 48 // with etcd options (e.g. to attach an endpoint to a lease). 49 type UpdateWithOpts struct { 50 Update 51 Opts []clientv3.OpOption 52 } 53 54 // NewAddUpdateOpts constructs UpdateWithOpts for endpoint registration. 55 func NewAddUpdateOpts(key string, endpoint Endpoint, opts ...clientv3.OpOption) *UpdateWithOpts { 56 return &UpdateWithOpts{Update: Update{Op: Add, Key: key, Endpoint: endpoint}, Opts: opts} 57 } 58 59 // NewDeleteUpdateOpts constructs UpdateWithOpts for endpoint deletion. 60 func NewDeleteUpdateOpts(key string, opts ...clientv3.OpOption) *UpdateWithOpts { 61 return &UpdateWithOpts{Update: Update{Op: Delete, Key: key}, Opts: opts} 62 } 63 64 // Manager can be used to add/remove & inspect endpoints stored in etcd for 65 // a particular target. 66 type Manager interface { 67 // Update allows to atomically add/remove a few endpoints from etcd. 68 Update(ctx context.Context, updates []*UpdateWithOpts) error 69 70 // AddEndpoint registers a single endpoint in etcd. 71 // For more advanced use-cases use the Update method. 72 AddEndpoint(ctx context.Context, key string, endpoint Endpoint, opts ...clientv3.OpOption) error 73 // DeleteEndpoint deletes a single endpoint stored in etcd. 74 // For more advanced use-cases use the Update method. 75 DeleteEndpoint(ctx context.Context, key string, opts ...clientv3.OpOption) error 76 77 // List returns all the endpoints for the current target as a map. 78 List(ctx context.Context) (Key2EndpointMap, error) 79 // NewWatchChannel creates a channel that populates or endpoint updates. 80 // Cancel the 'ctx' to close the watcher. 81 NewWatchChannel(ctx context.Context) (WatchChannel, error) 82 } 83