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# 操作Word 文档——添加Word页眉、页脚和页码

    在Word文档中,我们可以通过添加页眉.页脚的方式来丰富文档内容.添加页眉.页脚时,可以添加时间.日期.文档标题,文档引用信息.页码.内容解释.图片/LOGO等多种图文信息.同时也可根据需要调整文字或 ...

  2. 简单了解AJAX

    // ajax的俩个版本: var xmlhttp; if(window.xmlHttpRequest){ xmlhttp = new xmlHttpRequest(); }else{ xmlhttp ...

  3. private static final 修饰符

    java修饰符分类修饰符字段修饰符方法修饰符根据功能同主要分下几种 1.权限访问修饰符 public,protected,default,private,四种级别修饰符都用来修饰类.方法和字段 包外 ...

  4. Linux的chkconfig命令详解

    chkconfig命令主要用来更新(启动或停止)和查询系统服务的运行级信息.谨记chkconfig不是立即自动禁止或激活一个服务,它只是简单的改变了符号连接. 使用语法: chkconfig [--a ...

  5. 解决记录:win10 无法安装VS2017,visual studio installer下载进度始终为0

    问题描述:win10 下无法安装VS2017,visual studio installer下载进度始终为0,点击取消按钮后,也没有反应,visual studio installer也关闭不掉: 具 ...

  6. 一步一步设置Joomla!开发环境

    转载自:http://h2appy.blog.51cto.com/609721/373414 虽然是英文,可是写的非常浅显易懂,再配合截图,更是明了. http://docs.joomla.org/S ...

  7. AngularJS数据绑定中数据监控的机制说明

    from : http://docs.angularjs.org/guide/scope When the browser calls into JavaScript the code execute ...

  8. “蝉原则”与CSS3随机多背景随机圆角等效果

    一.什么是“蝉原则”? “蝉原则”,英文称作“cicada principle”,是一种让事物的重复出现符合“自然随机性”的规则,为什么这么说呢? “蝉原则”源自于北美,中国似乎并未有这样的说法,这背 ...

  9. log4j配置及使用

    一.使用方法: 1.将log4j.properties放到你创建项目的src中 2.引入log4j.jar import org.apache.log4j.*; public class log4jT ...

  10. 再次实践 MySQL chart - 每天5分钟玩转 Docker 容器技术(166)

    学习了 chart 结构和模板的知识后,现在重新实践一次 MySQL chart,相信会有更多收获. chart 安装前的准备 作为准备工作,安装之前需要先清楚 chart 的使用方法.这些信息通常记 ...