Skip to content

Instantly share code, notes, and snippets.

@chancez
Last active September 16, 2015 00:16
Show Gist options
  • Save chancez/dd11e958af08829ceb17 to your computer and use it in GitHub Desktop.
Save chancez/dd11e958af08829ceb17 to your computer and use it in GitHub Desktop.
package clientv3
import "github.com/coreos/etcd/storage/storagepb"
// A KV executes etcd key-value operations
type KV interface {
Execute(KvOp) (*Response, error)
}
// A Txn executes multiple etcd operations atomically
type Txn interface {
// If all comparisons in Compare suceed, then the operations in Success
// will be executed, otherwise the operations in Fail with be executed
Execute(MultiOp) (*TxnResponse, error)
}
type Manager interface {
// Compact compacts etcd KV history before the given rev.
Compact(rev int64) error
NewTxn() Txn
NewKV() KV
}
type MultiOp struct {
Compare CompareList
Success, Fail KvOpList
}
type CompareList []CompareOp
func (l CompareList) Add(ops ...CompareOp) {
l = append(l, ops...)
}
// Todo implement these
func CompareValue(key, value []byte) CompareOp {}
func CompareVersion(key []byte, version int64) CompareOp {}
func CompareModifiedRevision(key []byte, modifiedRevision int64) CompareOp {}
func CompareCreatedRevision(key []byte, createdRevision int64) CompareOp {}
type KvOpList []KvOp
func (l KvOpList) Add(ops ...KvOp) {
l = append(l, ops...)
}
type CompareOp interface {
Compare() (pb.Compare, error)
}
type KvOp interface {
// What to call this method?
Operation() (pb.Request, error)
}
// Todo implement these
func KvPut(key, val []byte) KvOp {}
func KvRange(key, end []byte, limit, rev int64) KvOp {}
func KvDeleteRange(key, end []byte) KvOp {}
type Response struct {
Rev int64
KVs []storagepb.KeyValue
More bool
}
type TxnResponse struct {
Success bool
Rev int64
Resps []*Response
}
func main() {
manager := NewManager()
kv := manager.NewKv()
resp, err := kv.Execute(KvPut([]byte("fiz"), []byte("buz")))
if err != nil {
panic(err)
}
fmt.Println(resp.Rev)
// Transactions
tx := manager.NewTxn()
ops := MultiOp{}
ops.Compare = CompareList{CompareValue([]byte("foo"), []byte("bar")), CompareVersion([]byte("baz"), 50)}
// on success delete all keys between 0 and 1000
ops.Success = KvOpList{KvDeleteRange([]byte("0"), []byte("1000"))}
for i := 0; i < 1000; i++ {
// then set all values between 0 and 1000 to 100
ops.Success.Add(KvPut([]byte(strconv.Itoa(i)), []byte("100")))
}
// Builder pattern (supports var args)
ops.Fail.Add(KvDeleteRange([]byte("0"), []byte("1000")), KvDeleteRange([]byte("2000"), []byte("3000")))
txResp, err := tx.Execute(ops)
if err != nil {
panic(err)
}
// Do something with resp
fmt.Println(txResp.Success)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment