package clientv3

import pb "github.com/coreos/etcd/etcdserver/etcdserverpb"

type opType int

const (
    // A default Op has opType 0, which is invalid.
    tRange opType = iota + 1
    tPut
    tDeleteRange
)

var (
    noPrefixEnd = []byte{0}
)

// Op represents an Operation that kv can execute.
type Op struct {
    t   opType
    key []byte
    end []byte

    // for range
    limit        int64
    sort         *SortOption
    serializable bool
    keysOnly     bool
    countOnly    bool
    minModRev    int64
    maxModRev    int64
    minCreateRev int64
    maxCreateRev int64

    // for range, watch
    rev int64

    // for watch, put, delete
    prevKV bool

    // progressNotify is for progress updates.
    progressNotify bool
    // createdNotify is for created event
    createdNotify bool
    // filters for watchers
    filterPut    bool
    filterDelete bool

    // for put
    val     []byte
    leaseID LeaseID
}

func (op Op) toRangeRequest() *pb.RangeRequest {
    if op.t != tRange {
        panic("op.t != tRange")
    }
    r := &pb.RangeRequest{
        Key:               op.key,
        RangeEnd:          op.end,
        Limit:             op.limit,
        Revision:          op.rev,
        Serializable:      op.serializable,
        KeysOnly:          op.keysOnly,
        CountOnly:         op.countOnly,
        MinModRevision:    op.minModRev,
        MaxModRevision:    op.maxModRev,
        MinCreateRevision: op.minCreateRev,
        MaxCreateRevision: op.maxCreateRev,
    }
    if op.sort != nil {
        r.SortOrder = pb.RangeRequest_SortOrder(op.sort.Order)
        r.SortTarget = pb.RangeRequest_SortTarget(op.sort.Target)
    }
    return r
}

func (op Op) toRequestOp() *pb.RequestOp {
    switch op.t {
    case tRange:
        return &pb.RequestOp{Request: &pb.RequestOp_RequestRange{RequestRange: op.toRangeRequest()}}
    case tPut:
        r := &pb.PutRequest{Key: op.key, Value: op.val, Lease: int64(op.leaseID), PrevKv: op.prevKV}
        return &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: r}}
    case tDeleteRange:
        r := &pb.DeleteRangeRequest{Key: op.key, RangeEnd: op.end, PrevKv: op.prevKV}
        return &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{RequestDeleteRange: r}}
    default:
        panic("Unknown Op")
    }
}

func (op Op) isWrite() bool {
    return op.t != tRange
}

func OpGet(key string, opts ...OpOption) Op {
    ret := Op{t: tRange, key: []byte(key)}
    ret.applyOpts(opts)
    return ret
}

func OpDelete(key string, opts ...OpOption) Op {
    ret := Op{t: tDeleteRange, key: []byte(key)}
    ret.applyOpts(opts)
    switch {
    case ret.leaseID != 0:
        panic("unexpected lease in delete")
    case ret.limit != 0:
        panic("unexpected limit in delete")
    case ret.rev != 0:
        panic("unexpected revision in delete")
    case ret.sort != nil:
        panic("unexpected sort in delete")
    case ret.serializable:
        panic("unexpected serializable in delete")
    case ret.countOnly:
        panic("unexpected countOnly in delete")
    case ret.minModRev != 0, ret.maxModRev != 0:
        panic("unexpected mod revision filter in delete")
    case ret.minCreateRev != 0, ret.maxCreateRev != 0:
        panic("unexpected create revision filter in delete")
    case ret.filterDelete, ret.filterPut:
        panic("unexpected filter in delete")
    case ret.createdNotify:
        panic("unexpected createdNotify in delete")
    }
    return ret
}

func OpPut(key, val string, opts ...OpOption) Op {
    ret := Op{t: tPut, key: []byte(key), val: []byte(val)}
    ret.applyOpts(opts)
    switch {
    case ret.end != nil:
        panic("unexpected range in put")
    case ret.limit != 0:
        panic("unexpected limit in put")
    case ret.rev != 0:
        panic("unexpected revision in put")
    case ret.sort != nil:
        panic("unexpected sort in put")
    case ret.serializable:
        panic("unexpected serializable in put")
    case ret.countOnly:
        panic("unexpected countOnly in put")
    case ret.minModRev != 0, ret.maxModRev != 0:
        panic("unexpected mod revision filter in put")
    case ret.minCreateRev != 0, ret.maxCreateRev != 0:
        panic("unexpected create revision filter in put")
    case ret.filterDelete, ret.filterPut:
        panic("unexpected filter in put")
    case ret.createdNotify:
        panic("unexpected createdNotify in put")
    }
    return ret
}

func opWatch(key string, opts ...OpOption) Op {
    ret := Op{t: tRange, key: []byte(key)}
    ret.applyOpts(opts)
    switch {
    case ret.leaseID != 0:
        panic("unexpected lease in watch")
    case ret.limit != 0:
        panic("unexpected limit in watch")
    case ret.sort != nil:
        panic("unexpected sort in watch")
    case ret.serializable:
        panic("unexpected serializable in watch")
    case ret.countOnly:
        panic("unexpected countOnly in watch")
    case ret.minModRev != 0, ret.maxModRev != 0:
        panic("unexpected mod revision filter in watch")
    case ret.minCreateRev != 0, ret.maxCreateRev != 0:
        panic("unexpected create revision filter in watch")
    }
    return ret
}

func (op *Op) applyOpts(opts []OpOption) {
    for _, opt := range opts {
        opt(op)
    }
}

// OpOption configures Operations like Get, Put, Delete.
type OpOption func(*Op)

// WithLease attaches a lease ID to a key in 'Put' request.
func WithLease(leaseID LeaseID) OpOption {
    return func(op *Op) { op.leaseID = leaseID }
}

// WithLimit limits the number of results to return from 'Get' request.
func WithLimit(n int64) OpOption { return func(op *Op) { op.limit = n } }

// WithRev specifies the store revision for 'Get' request.
// Or the start revision of 'Watch' request.
func WithRev(rev int64) OpOption { return func(op *Op) { op.rev = rev } }

// WithSort specifies the ordering in 'Get' request. It requires
// 'WithRange' and/or 'WithPrefix' to be specified too.
// 'target' specifies the target to sort by: key, version, revisions, value.
// 'order' can be either 'SortNone', 'SortAscend', 'SortDescend'.
func WithSort(target SortTarget, order SortOrder) OpOption {
    return func(op *Op) {
        if target == SortByKey && order == SortAscend {
            // If order != SortNone, server fetches the entire key-space,
            // and then applies the sort and limit, if provided.
            // Since current mvcc.Range implementation returns results
            // sorted by keys in lexicographically ascending order,
            // client should ignore SortOrder if the target is SortByKey.
            order = SortNone
        }
        op.sort = &SortOption{target, order}
    }
}

// GetPrefixRangeEnd gets the range end of the prefix.
// 'Get(foo, WithPrefix())' is equal to 'Get(foo, WithRange(GetPrefixRangeEnd(foo))'.
func GetPrefixRangeEnd(prefix string) string {
    return string(getPrefix([]byte(prefix)))
}

func getPrefix(key []byte) []byte {
    end := make([]byte, len(key))
    copy(end, key)
    for i := len(end) - 1; i >= 0; i-- {
        if end[i] < 0xff {
            end[i] = end[i] + 1
            end = end[:i+1]
            return end
        }
    }
    // next prefix does not exist (e.g., 0xffff);
    // default to WithFromKey policy
    return noPrefixEnd
}

// WithPrefix enables 'Get', 'Delete', or 'Watch' requests to operate
// on the keys with matching prefix. For example, 'Get(foo, WithPrefix())'
// can return 'foo1', 'foo2', and so on.
func WithPrefix() OpOption {
    return func(op *Op) {
        op.end = getPrefix(op.key)
    }
}

// WithRange specifies the range of 'Get', 'Delete', 'Watch' requests.
// For example, 'Get' requests with 'WithRange(end)' returns
// the keys in the range [key, end).
// endKey must be lexicographically greater than start key.
func WithRange(endKey string) OpOption {
    return func(op *Op) { op.end = []byte(endKey) }
}

// WithFromKey specifies the range of 'Get', 'Delete', 'Watch' requests
// to be equal or greater than the key in the argument.
func WithFromKey() OpOption { return WithRange("\x00") }

// WithSerializable makes 'Get' request serializable. By default,
// it's linearizable. Serializable requests are better for lower latency
// requirement.
func WithSerializable() OpOption {
    return func(op *Op) { op.serializable = true }
}

// WithKeysOnly makes the 'Get' request return only the keys and the corresponding
// values will be omitted.
func WithKeysOnly() OpOption {
    return func(op *Op) { op.keysOnly = true }
}

// WithCountOnly makes the 'Get' request return only the count of keys.
func WithCountOnly() OpOption {
    return func(op *Op) { op.countOnly = true }
}

// WithMinModRev filters out keys for Get with modification revisions less than the given revision.
func WithMinModRev(rev int64) OpOption { return func(op *Op) { op.minModRev = rev } }

// WithMaxModRev filters out keys for Get with modification revisions greater than the given revision.
func WithMaxModRev(rev int64) OpOption { return func(op *Op) { op.maxModRev = rev } }

// WithMinCreateRev filters out keys for Get with creation revisions less than the given revision.
func WithMinCreateRev(rev int64) OpOption { return func(op *Op) { op.minCreateRev = rev } }

// WithMaxCreateRev filters out keys for Get with creation revisions greater than the given revision.
func WithMaxCreateRev(rev int64) OpOption { return func(op *Op) { op.maxCreateRev = rev } }

// WithFirstCreate gets the key with the oldest creation revision in the request range.
func WithFirstCreate() []OpOption { return withTop(SortByCreateRevision, SortAscend) }

// WithLastCreate gets the key with the latest creation revision in the request range.
func WithLastCreate() []OpOption { return withTop(SortByCreateRevision, SortDescend) }

// WithFirstKey gets the lexically first key in the request range.
func WithFirstKey() []OpOption { return withTop(SortByKey, SortAscend) }

// WithLastKey gets the lexically last key in the request range.
func WithLastKey() []OpOption { return withTop(SortByKey, SortDescend) }

// WithFirstRev gets the key with the oldest modification revision in the request range.
func WithFirstRev() []OpOption { return withTop(SortByModRevision, SortAscend) }

// WithLastRev gets the key with the latest modification revision in the request range.
func WithLastRev() []OpOption { return withTop(SortByModRevision, SortDescend) }

// withTop gets the first key over the get's prefix given a sort order
func withTop(target SortTarget, order SortOrder) []OpOption {
    return []OpOption{WithPrefix(), WithSort(target, order), WithLimit(1)}
}

// WithProgressNotify makes watch server send periodic progress updates
// every 10 minutes when there is no incoming events.
// Progress updates have zero events in WatchResponse.
func WithProgressNotify() OpOption {
    return func(op *Op) {
        op.progressNotify = true
    }
}

// WithCreatedNotify makes watch server sends the created event.
func WithCreatedNotify() OpOption {
    return func(op *Op) {
        op.createdNotify = true
    }
}

// WithFilterPut discards PUT events from the watcher.
func WithFilterPut() OpOption {
    return func(op *Op) { op.filterPut = true }
}

// WithFilterDelete discards DELETE events from the watcher.
func WithFilterDelete() OpOption {
    return func(op *Op) { op.filterDelete = true }
}

// WithPrevKV gets the previous key-value pair before the event happens. If the previous KV is already compacted,
// nothing will be returned.
func WithPrevKV() OpOption {
    return func(op *Op) {
        op.prevKV = true
    }
}

// LeaseOp represents an Operation that lease can execute.
type LeaseOp struct {
    id LeaseID

    // for TimeToLive
    attachedKeys bool
}

// LeaseOption configures lease operations.
type LeaseOption func(*LeaseOp)

func (op *LeaseOp) applyOpts(opts []LeaseOption) {
    for _, opt := range opts {
        opt(op)
    }
}

// WithAttachedKeys requests lease timetolive API to return
// attached keys of given lease ID.
func WithAttachedKeys() LeaseOption {
    return func(op *LeaseOp) { op.attachedKeys = true }
}

func toLeaseTimeToLiveRequest(id LeaseID, opts ...LeaseOption) *pb.LeaseTimeToLiveRequest {
    ret := &LeaseOp{id: id}
    ret.applyOpts(opts)
    return &pb.LeaseTimeToLiveRequest{ID: int64(id), Keys: ret.attachedKeys}
}

op.go的更多相关文章

  1. IE、FF、Safari、OP不同浏览器兼容报告

    IE.FF.Safari.OP不同浏览器兼容报告 1         浏览器内核简介 Trident IE浏览器(GreenBrowser绿色浏览器, 遨游浏览器....都是IE) Geckos Fi ...

  2. ERROR<53761> - Plugins - conn=-1 op=-1 msgId=-1 - Connection Bind through PTA failed (91). Retrying...

    LDAP6.3在DSCC控制台启动实例完成,但是操作状态显示“意外错误”,查看日志如下: 04/May/2016:21:10:39 +0800] - Sun-Java(tm)-System-Direc ...

  3. 兼容ie6/ff/ch/op的div+css实现的圆角框

    <!DOCTYPE html> <html> <head> <title>青春不迷茫:寻梦时代的“蚁族”逆袭之旅- 职场管理专题-中国人力资源开发网-中 ...

  4. read op case $op in

     read op case $op in

  5. OP(Over-provisioning)预留空间

    SSD上的OP指的是用户不可操作的容量,大小为实际容量减去用户可用容量,OP区域一般被用于优化操作如:WL,GC和坏块映射等.       OP一般分三层(见下图).第一层容量固定为SSD标称容量的7 ...

  6. Python 实现的下载op海贼王网的图片(网络爬虫)

    没得事就爬一下我喜欢的海贼王上的图片 须要在d盘下建立一个imgcache目录 # -*- coding: utf-8 -*- import urllib import urllib2 import ...

  7. Microsoft Dynamics CRM 9.0 OP 版本 安装 的那些 雷

    天天讲安装过程好无聊了,还是搞点有营养的东西来,那么后面来说说刚出来的MSCRM OP 9.0 版本安装的那些雷: 雷1:操作系统要求Windows 2016 Server 这点还好,因为之前安装MS ...

  8. op 和 oo 的区别

    本是之前一位前辈留下的问题,因为我不是程序出身,略懂一些代码,后又查了很多人的博客,问了周围搞开发的朋友,得出以下结论: 有人这么形容OP和OO的不同:用面向过程的方法写出来的程序是一份蛋炒饭,而用面 ...

  9. tensorflow 升级到1.9-rc0,生成静态图frozen graph.pb本地测试正常, 在其他版本(eg1.4版本)或者android下运行出错NodeDef mentions attr 'dilations' not in Op<name=Conv2D; signature=input:T, filter:T -> output:T; attr=T:type,allowed=[DT_

    这时节点定义找不到NodeDef attr 'dilations' not in,说明执行版本的NodeDef不在节点定义上,两个不一致,分别是执行inference的代码和生成静态图节点不一致(当然 ...

随机推荐

  1. C#在PDF中如何以不同颜色高亮文本

    高亮的文本有助于阅读者快速有效地获取文章关键信息.在PDF文件中,对文章的不同文本,关键词.句等进行不同颜色的文本高亮操作,可以使阅读者在阅读过程中有效地区分不同高亮颜色文本的意义.在下面的示例中,我 ...

  2. 新型USB病毒BadUSB 即使U盘被格式化也无法根除

    这种病毒并不存在于USB设备中的存储文件中,而是根植于USB设备的固件里.这意味着,即使用户对U盘进行全面的格式化清理,仍不能"杀死"它.

  3. WebSocket 和 Golang 实现聊天功能

    http://www.open-open.com/lib/view/open1416379948711.html 这个示例应用程序展示了如何使用 WebSocket, Golang 和 jQuery  ...

  4. 使用Swashbuckle构建RESTful风格文档

    本次和大家分享的是Swagger to WebApi的nuget包Swashbuckle:因为项目需要统一api文档的风格,并要支持多种开发语言(C#,java,python),所以首先想到的是swa ...

  5. JavaScript函数节流和函数防抖之间的区别

    一.概念解释  函数节流和函数防抖,两者都是优化高频率执行js代码的一种手段.  大家大概都知道旧款电视机的工作原理,就是一行行得扫描出色彩到屏幕上,然后组成一张张图片.由于肉眼只能分辨出一定频率的变 ...

  6. Linux——浅析信号处理

    信号及其处理 信号处理是Unix和LInux系统为了响应某些状况而产生的事件,通常内核产生信号,进程收到信号后采取相应的动作. 例如当我们想强制结束一个程序的时候,我们通常会给它发送一个信号,然后该进 ...

  7. Eeffective C++ 读书笔记( 32-38)

    条款三十二:确定你的public继承塑模出is-a关系 1.所谓最佳设计,取决于系统希望做什么事,包括现在和未来. 2.好的接口可以防止无效的代码通过编译,因此你应该宁可采取“在编译期拒绝企鹅飞行”的 ...

  8. 花生日记_花生日记APP下载_花生日记邀请码

    花生日记 国内领先的社交电商导购分享平台. 独创社交电商3+模式,社交+电商+社群,上线1个月注册用户超百万.合作商家涵括各个类目以及平台.为数万宝妈提供月收入3000以上兼职收入. 微信扫描下方二维 ...

  9. MySQL varchar类型数据转tinyint类型

    在mysql数据库中性别字段以前存的是'男'和'女',使用varchar类型存储的,但是在我mongo库中这个字段使用的是'1'和'0'存储的,在两个库之间的数据转换就很不方便,于是想要统一存储类型, ...

  10. linux下c编程 基础

    1. 熟悉Linux系统下的开发环境 2. 熟悉vi的基本操作 3. 熟悉gcc编译器的基本原理 4. 熟练使用gcc编译器的常用选项 5 .熟练使用gdb调试技术 6. 熟悉makefile基本原理 ...