package clientv3

import (
    "sync"

    pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
)

// Txn is the interface that wraps mini-transactions.
//
//     Tx.If(
//      Compare(Value(k1), ">", v1),
//      Compare(Version(k1), "=", 2)
//     ).Then(
//      OpPut(k2,v2), OpPut(k3,v3)
//     ).Else(
//      OpPut(k4,v4), OpPut(k5,v5)
//     ).Commit()
//
type Txn interface {
    // If takes a list of comparison. If all comparisons passed in succeed,
    // the operations passed into Then() will be executed. Or the operations
    // passed into Else() will be executed.
    If(cs ...Cmp) Txn

    // Then takes a list of operations. The Ops list will be executed, if the
    // comparisons passed in If() succeed.
    Then(ops ...Op) Txn

    // Else takes a list of operations. The Ops list will be executed, if the
    // comparisons passed in If() fail.
    Else(ops ...Op) Txn

    // Commit tries to commit the transaction.
    Commit() (*TxnResponse, error)

    // TODO: add a Do for shortcut the txn without any condition?
}

type txn struct {
    kv  *kv
    ctx context.Context

    mu    sync.Mutex
    cif   bool
    cthen bool
    celse bool

    isWrite bool

    cmps []*pb.Compare

    sus []*pb.RequestOp
    fas []*pb.RequestOp
}

func (txn *txn) If(cs ...Cmp) Txn {
    txn.mu.Lock()
    defer txn.mu.Unlock()

    if txn.cif {
        panic("cannot call If twice!")
    }

    if txn.cthen {
        panic("cannot call If after Then!")
    }

    if txn.celse {
        panic("cannot call If after Else!")
    }

    txn.cif = true

    for i := range cs {
        txn.cmps = append(txn.cmps, (*pb.Compare)(&cs[i]))
    }

    return txn
}

func (txn *txn) Then(ops ...Op) Txn {
    txn.mu.Lock()
    defer txn.mu.Unlock()

    if txn.cthen {
        panic("cannot call Then twice!")
    }
    if txn.celse {
        panic("cannot call Then after Else!")
    }

    txn.cthen = true

    for _, op := range ops {
        txn.isWrite = txn.isWrite || op.isWrite()
        txn.sus = append(txn.sus, op.toRequestOp())
    }

    return txn
}

func (txn *txn) Else(ops ...Op) Txn {
    txn.mu.Lock()
    defer txn.mu.Unlock()

    if txn.celse {
        panic("cannot call Else twice!")
    }

    txn.celse = true

    for _, op := range ops {
        txn.isWrite = txn.isWrite || op.isWrite()
        txn.fas = append(txn.fas, op.toRequestOp())
    }

    return txn
}

func (txn *txn) Commit() (*TxnResponse, error) {
    txn.mu.Lock()
    defer txn.mu.Unlock()
    for {
        resp, err := txn.commit()
        if err == nil {
            return resp, err
        }
        if isHaltErr(txn.ctx, err) {
            return nil, toErr(txn.ctx, err)
        }
        if txn.isWrite {
            return nil, toErr(txn.ctx, err)
        }
    }
}

func (txn *txn) commit() (*TxnResponse, error) {
    r := &pb.TxnRequest{Compare: txn.cmps, Success: txn.sus, Failure: txn.fas}

    var opts []grpc.CallOption
    if !txn.isWrite {
        opts = []grpc.CallOption{grpc.FailFast(false)}
    }
    resp, err := txn.kv.remote.Txn(txn.ctx, r, opts...)
    if err != nil {
        return nil, err
    }
    return (*TxnResponse)(resp), nil
}

txn.go的更多相关文章

  1. Oracle EBS OPM update material txn

    --update_material_txn --created by jenrry DECLARE p_mmti_rec mtl_transactions_interface%ROWTYPE; p_m ...

  2. zookeeper源码分析之四服务端(单机)处理请求流程

    上文: zookeeper源码分析之一服务端启动过程 中,我们介绍了zookeeper服务器的启动过程,其中单机是ZookeeperServer启动,集群使用QuorumPeer启动,那么这次我们分析 ...

  3. zookeeper源码分析之一服务端启动过程

    zookeeper简介 zookeeper是为分布式应用提供分布式协作服务的开源软件.它提供了一组简单的原子操作,分布式应用可以基于这些原子操作来实现更高层次的同步服务,配置维护,组管理和命名.zoo ...

  4. PMON failed to acquire latch, see PMON dump

    前几天,一台Oracle数据库(Oracle Database 10g Release 10.2.0.4.0 - 64bit Production)监控出现"PMON failed to a ...

  5. Troubleshooting:重新安装Vertica建库后无法启动

    环境:RHEL6.5 + Vertica7.1.0-3 1.故障现象 2.重装集群 3.再次定位 4.解决问题 5.总结 1.故障现象 故障现象:Vertica集群安装成功,但是创建数据库后一直无法u ...

  6. Vertica删除历史分区数据

    假设test用户下创建的t_jingyu表 vsql -Utest -wtestpwd create table t_jingyu( col1 int, col2 varchar, col3 time ...

  7. ORA 各种oraclesql错误

    ORA-00001: 违反唯一约束条件 (.) ORA-00017: 请求会话以设置跟踪事件 ORA-00018: 超出最大会话数 ORA-00019: 超出最大会话许可数 ORA-00020: 超出 ...

  8. 【分布式】Zookeeper序列化及通信协议

    一.前言 前面介绍了Zookeeper的系统模型,下面进一步学习Zookeeper的底层序列化机制,Zookeeper的客户端与服务端之间会进行一系列的网络通信来实现数据传输,Zookeeper使用J ...

  9. java web学习总结(二十七) -------------------JSP标签介绍

    一.JSP标签介绍 JSP标签也称之为Jsp Action(JSP动作)元素,它用于在Jsp页面中提供业务逻辑功能,避免在JSP页面中直接编写java代码,造成jsp页面难以维护. 二.JSP常用标签 ...

随机推荐

  1. for循环嵌套讲解:

    1.for循环嵌套讲解: class ForForDemo {     public static void main(String[] args)     {         //大圈套小圈思想: ...

  2. Python的基本数据数字、字符串、布尔值及其魔法

    基本数据类型介绍 若要把Pyhton的基本数据类型:数字(int).字符串(str).布尔(bool).列表(list).元组(tuple).字典(dict)都分为一个个不同的角色 如:战士,魔法师, ...

  3. ansible常见模块

    模块的使用 查看模块帮助 ansible-doc -l 查看所有模块 ansible-doc -s MODULE_NAME 查看指定模块的详细帮助 ansible命令应用基础 语法: ansible ...

  4. 区块链共识机制(POW、POS、DPOS等)的优缺点

    一.POW:工作量证明机制 基本原理: 第一代共识机制,比特币的基础.理解起来,很简单,就是“按劳取酬”,你付出多少工作量,就会获得多少报酬(比特币等加密货币).在网络世界里,这里的劳动就是你为网络提 ...

  5. No plugin found for prefix 'tomcat' in the current project and in the plugin groups和java.net.BindException: Address already in use: JVM_Bind <null>:8080的错误解决

    错误报告:No plugin found for prefix 'tomcat' in the current project and in the plugin groups [org.apache ...

  6. jjava Date格式是 May 07 17:44:06 CST 2018,怎么插入数据库中的timestamp格式中

    首先 我来记录下错误 死在时间格式转换错误手里了 大致就是时间格式转化失败 java代码中的May 07 17:44:06 CST 2018  是这个格式转换为 数据库的 yyyy-MM-dd HH: ...

  7. JavaScript中push ,pop ,concat ,join方法

    push 方法 将新元素添加到一个数组中,并返回数组的新长度值. arrayObj.push([item1 [item2[. . . [itemN ]]]]) 说明 push 方法将以新元素出现的顺序 ...

  8. 搜索应用参考示例XXL-SEARCH

    <搜索应用参考示例XXL-SEARCH> 一.简介 1.1 概述 XXL-SEARCH 是以 "lucene/elasticsearch" 为核心的,Pragmatic ...

  9. Zookeeper + Dubbo + SpringMVC + dubbo-admin

    第一步:在CentOS/Windows上安装Zookeeper[前提] A:CentOS     Zookeeper作为Dubbo服务的注册中心,Dubbo原先基于数据库的注册中心,没采用Zookee ...

  10. Java学习导航

    由于最近在系统的重新学习Java,为了便于日后复习,给个人博客中Java内容做一个目录. Java基础:Java虚拟机(JVM) Java基础:内存模型 Java基础:JVM垃圾回收算法 Java基础 ...