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. c# http请求ajax页面

    我们在用Http请求的时候,某些页面是ajax加载的,所以请求过来的页面数据不完整.也就是说ajax局部加载数据的地方,我们请求不到,这时候该怎么办呢? WebDriver+phantomjs 这两个 ...

  2. HDU-5705

    Clock Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others) Problem De ...

  3. nginx基本配置参数说明

    #运行用户 user nobody; #启动进程,通常设置成和cpu的数量相等 worker_processes 1; #全局错误日志及PID文件 #error_log logs/error.log; ...

  4. td默认文字超出后显示..,点击tr时td文字显示完整

    做项目时,产品提的需求,table表格里面,每一列限制文字超出宽度后显示省略号,等点击td时,文字显示完整,今天整理了一下代码,积累一下 备注:1.邮箱和网址,在td里面不会自动换行,需要增加word ...

  5. 想要薪资20-30K,Python程序员认真敲代码就够了!

    在这个年代,互联网的飞速壮大大家有目共睹,除了表露出的公共受益,其中计算机编程者也是做出了巨大的贡献,即使外国编程语言仍旧属于领导者,但是在互联网的壮大下,我们这是"地球村",国内 ...

  6. android获取手机机型、厂商、deviceID基本信息

    /** * 系统工具类 */ public class SystemUtil { /** * 获取当前手机系统语言. * * @return 返回当前系统语言.例如:当前设置的是"中文-中国 ...

  7. Django入门五之admin管理

    1. 准备工作 #settings.py #urls.py 2. 创建管理员账号 进入CMD 3. 运行服务器 登录后,发现没有数据的 4. 创建数据 在website/blog/ 新建一个admin ...

  8. mint-ui之picker爬坑记

    picker的数据来源为动态获取时,数据无法正常渲染!因为方法不对,所以坑大了!深刻地体会到'业不精,我之过',谨以此文,深刻地记录一下踩坑及爬坑的整个过程,以便日后不再入坑,也给后来者提供一下参考 ...

  9. Codeforces Round #483 (Div. 2) D. XOR-pyramid

    D. XOR-pyramid time limit per test 2 seconds memory limit per test 512 megabytes input standard inpu ...

  10. servlet3.0 新特性——异步处理

    Servlet 3.0 之前,一个普通 Servlet 的主要工作流程大致如下: 首先,Servlet 接收到请求之后,可能需要对请求携带的数据进行一些预处理: 接着,调用业务接口的某些方法,以完成业 ...