op.go

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}
}
				
时间: 2024-08-29 11:24:38

op.go的相关文章

ERROR&lt;53761&gt; - 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-Directory/6.3 B2008.0311.0224 (32-bit) starting up[04/May/2016:21:10:39 +0800] - Listening on all interfaces port 11111 for LDAP requests[04/May/2016:21:10

OP趋势系统

经过3年多时间的摸索,经历过熊市牛市的历练,终于完成坚持已久的OP趋势系统的实践,接下来,我将在股灾后,每天都分享OP趋势系统的信号,可以很负责任的说,经过10年历史数据的测试,加上3年的实盘,更加坚定我对这个OP趋势系统的信心,我们只需要等待,等待下一个行情,正如E大一样,等待价值回归,打折后买入一样,我们是等待OP趋势系统的信号,坚定执行,华丽丽完成人生下一次财富的积累. ————————————信号篇————————————OP趋势系统,从个股到指数ETF,正是其走向成熟的标志,之所以会公

互联网行业的那些缩写PM,RD,FE,UE,QA,OP,BRD,MRD,PRD,FSD

PM--product manager 这个是产品经理的意思.我一直以为是项目经理的缩写.太坑爹了,本人还写过一个屌丝文章,看来要贻笑大方了. RD--research and develop RD是研究与开发(研发).诸如PHP程序猿,Java程序猿,无论是爱疯的还是安卓的都是属于这一类别. FE -- front end development FE是前端研发.有点意思! UE--  user experience UE是用户体验 QA--quality assurance QA是测试 OP

如何从普通程序员晋升为架构师 面向过程编程OP和面向编程OO

引言 计算机科学是一门应用科学,它的知识体系是典型的倒三角结构,所用的基础知识并不多,只是随着应用领域和方向的不同,产生了很多的分支,所以说编程并不是一件很困难的事情,一个高中生经过特定的训练就可以做得到.但是,会编程和编好程绝对是两码事,同样的程序员,有的人几年之后成为了架构师,有的人却还在不停地coding,只不过ctrl-c.ctrl-v用得更加纯熟了.在中国,编程人员最终的归途无外乎两条:一是转向技术管理,它的终点是CTO:二是继续深入,它的终点是首席架构师,成为CEO的人毕竟是少数.如

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

没得事就爬一下我喜欢的海贼王上的图片 需要在d盘下建立一个imgcache文件夹 # -*- coding: utf-8 -*- import urllib import urllib2 import json from bs4 import BeautifulSoup import threadpool import thread class htmlpaser: def __init__(self): self.url='http://1.hzfans.sinaapp.com/process

完绘质勘Datamine.Studio.EM/OP.v2.1.170.0

完绘质勘Datamine.Studio.EM/OP.v2.1.170.0 Datamine Studio OP v2.1.2.0 Win64 1CD 主要特点和优点-整合-工作室EM可以与主机的现有的数据格式,包括动态链接到一个实时更新的钻孔数据库整合能力.图像支持容易进出查看地理参考图像从主机格式褶皱平面图像或适合现有地形数据.固体建模灵活的工具允许手动或自动线框实体或表面代表地质特征的创作.块建模利用笪塔敏锷著名的模块化建模工具快速创建准确的体积模型和进行基本的品位估计的力量.-通讯-以3D

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; op

服务介绍 VPN直译就是虚拟专用通道,是提供给企业之间或者个人与公司之间安全数据传输的隧道,OpenVPN无疑是Linux下开源VPN的先锋,提供了良好的性能和友好的用户GUI.它大量使用了OpenSSL加密库中的SSLv3/TLSv1协议函数库. 实验拓扑图 实验环境 xuegod 63 br0 IP :172.18.80.163  eth1:192.168.10.63  (vmnet1)       DG:192.168.10.64 备注使用vmnet1 模拟公网 xuegod 64 eth

PCI OP WiFi 測试(二):PCI对OP的要求

每次看PCI的文档.都一头雾水,本来就非常抽象.看英文就感觉更抽象.泛泛而谈的要求,看一次忘一次.仅仅好翻译成中文.没事就看看,知道指导思想. 例如以下,是翻译PCI的<Modular Derived Test Requirements>的OP部分,这样直接翻译不知道是不是有侵权的问题(⊙﹏⊙)b 正文開始: DTR 模块3: 开放协议的需求 F-发现与定义协议和接口 DTR F1:接口的定义 设备所用到的公开的协议和接口.应该清晰地写在<开放协议模块-协议声明表格>(原文摘录:O

ifconfig &nbsp; grep -op

[[email protected] ansible]#  ifconfig | grep eth -A 7eth0      Link encap:Ethernet  HWaddr 00:0C:29:D3:1E:A5            inet addr:10.4.104.86  Bcast:10.4.104.255  Mask:255.255.255.0          inet6 addr: fe80::20c:29ff:fed3:1ea5/64 Scope:Link        

数组进行多少次OP操作,才能有序

1 题目描述: 有一个数组:2,1,4,3.对于数组,有一种操作op(idx):将该index对应的数字移到首位.比如: op(3):  2 1 43 -> 3 2 1 4 op(1):  3 2 14 -> 2 3 1 4 op(2):  2 3 1 4 -> 1 2 3 4 问对于给定的数组,数组各个元素是任意的整数,可能有重复值,需要多少次OP操作,才能使得数组有序? 对于上面的例子,需要3次即可. 2. 问题解析: 最坏的情况需要 n 次就够了,第 i 次找到数组中倒数第 i 大