github.com/matrixorigin/matrixone@v1.2.0/pkg/txn/client/types.go (about)

     1  // Copyright 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package client
    16  
    17  import (
    18  	"context"
    19  	"time"
    20  
    21  	"github.com/matrixorigin/matrixone/pkg/common/runtime"
    22  	"github.com/matrixorigin/matrixone/pkg/pb/lock"
    23  	"github.com/matrixorigin/matrixone/pkg/pb/timestamp"
    24  	"github.com/matrixorigin/matrixone/pkg/pb/txn"
    25  	"github.com/matrixorigin/matrixone/pkg/txn/rpc"
    26  )
    27  
    28  // TxnOption options for setup transaction
    29  // FIXME(fagongzi): refactor TxnOption to avoid mem alloc
    30  type TxnOption func(*txnOperator)
    31  
    32  // TxnClientCreateOption options for create txn
    33  type TxnClientCreateOption func(*txnClient)
    34  
    35  // TxnTimestampAware transaction timestamp aware
    36  type TxnTimestampAware interface {
    37  	// Minimum Active Transaction Timestamp
    38  	MinTimestamp() timestamp.Timestamp
    39  	// WaitLogTailAppliedAt wait log tail applied at ts
    40  	WaitLogTailAppliedAt(ctx context.Context, ts timestamp.Timestamp) (timestamp.Timestamp, error)
    41  	// GetLatestCommitTS get latest commit timestamp
    42  	GetLatestCommitTS() timestamp.Timestamp
    43  	// SyncLatestCommitTS sync latest commit timestamp
    44  	SyncLatestCommitTS(timestamp.Timestamp)
    45  	// GetSyncLatestCommitTSTimes returns times of sync latest commit ts
    46  	GetSyncLatestCommitTSTimes() uint64
    47  }
    48  
    49  type TxnAction interface {
    50  	// AbortAllRunningTxn rollback all running transactions. but still keep their workspace to avoid panic.
    51  	AbortAllRunningTxn()
    52  	// Pause the txn client to prevent new txn from being created.
    53  	Pause()
    54  	// Resume the txn client to allow new txn to be created.
    55  	Resume()
    56  }
    57  
    58  // TxnClient transaction client, the operational entry point for transactions.
    59  // Each CN node holds one instance of TxnClient.
    60  type TxnClient interface {
    61  	TxnTimestampAware
    62  	TxnAction
    63  
    64  	// New returns a TxnOperator to handle read and write operation for a
    65  	// transaction.
    66  	New(ctx context.Context, commitTS timestamp.Timestamp, options ...TxnOption) (TxnOperator, error)
    67  	// NewWithSnapshot create a txn operator from a snapshot. The snapshot must
    68  	// be from a CN coordinator txn operator.
    69  	NewWithSnapshot(snapshot []byte) (TxnOperator, error)
    70  	// Close closes client.sender
    71  	Close() error
    72  	// RefreshExpressionEnabled return true if refresh expression feature enabled
    73  	RefreshExpressionEnabled() bool
    74  	// CNBasedConsistencyEnabled return true if cn based consistency feature enabled
    75  	CNBasedConsistencyEnabled() bool
    76  	// IterTxns iter all txns
    77  	IterTxns(func(TxnOverview) bool)
    78  	// GetState returns the current state of txn client.
    79  	GetState() TxnState
    80  }
    81  
    82  type TxnState struct {
    83  	State int
    84  	// user active txns
    85  	Users int
    86  	// all active txns
    87  	ActiveTxns []string
    88  	// FIFO queue for ready to active txn
    89  	WaitActiveTxns []string
    90  	// LatestTS is the latest timestamp of the txn client.
    91  	LatestTS timestamp.Timestamp
    92  }
    93  
    94  // TxnOperator operator for transaction clients, handling read and write
    95  // requests for transactions, and handling distributed transactions across DN
    96  // nodes.
    97  // Note: For Error returned by Read/Write/WriteAndCommit/Commit/Rollback, need
    98  // to check if it is a moerr.ErrDNShardNotFound error, if so, the TN information
    99  // held is out of date and needs to be reloaded by HAKeeper.
   100  type TxnOperator interface {
   101  	// GetOverview returns txn overview
   102  	GetOverview() TxnOverview
   103  
   104  	// CloneSnapshotOp clone a read-only snapshot op from parent txn operator
   105  	CloneSnapshotOp(snapshot timestamp.Timestamp) TxnOperator
   106  	IsSnapOp() bool
   107  
   108  	// Txn returns the current txn metadata
   109  	Txn() txn.TxnMeta
   110  	// TxnOptions returns the current txn options
   111  	TxnOptions() txn.TxnOptions
   112  	// TxnRef returns pointer of current txn metadata. In RC mode, txn's snapshot ts
   113  	// will updated before statement executed.
   114  	TxnRef() *txn.TxnMeta
   115  	// Snapshot a snapshot of the transaction handle that can be passed around the
   116  	// network. In some scenarios, operations of a transaction are executed on multiple
   117  	// CN nodes for performance acceleration. But with only one CN coordinator, Snapshot
   118  	// can be used to recover the transaction operation handle at a non-CN coordinator
   119  	// node, or it can be used to pass information back to the transaction coordinator
   120  	// after the non-CN coordinator completes the transaction operation.
   121  	Snapshot() ([]byte, error)
   122  	// UpdateSnapshot in some scenarios, we need to boost the snapshotTimestamp to eliminate
   123  	// the w-w conflict.
   124  	// If ts is empty, it will use the latest commit timestamp which is received from DN.
   125  	UpdateSnapshot(ctx context.Context, ts timestamp.Timestamp) error
   126  	// SnapshotTS returns the snapshot timestamp of the transaction.
   127  	SnapshotTS() timestamp.Timestamp
   128  	// CreateTS returns the creation timestamp of the txnOperator.
   129  	CreateTS() timestamp.Timestamp
   130  	// Status returns the current transaction status.
   131  	Status() txn.TxnStatus
   132  	// ApplySnapshot CN coordinator applies a snapshot of the non-coordinator's transaction
   133  	// operation information.
   134  	ApplySnapshot(data []byte) error
   135  	// Read transaction read operation, the operator routes the message based
   136  	// on the given TN node information and waits for the read data synchronously.
   137  	// The transaction has been aborted if ErrTxnAborted returned.
   138  	// After use, SendResult needs to call the Release method
   139  	Read(ctx context.Context, ops []txn.TxnRequest) (*rpc.SendResult, error)
   140  	// Write transaction write operation, and the operator will record the DN
   141  	// nodes written by the current transaction, and when it finds that multiple
   142  	// TN nodes are written, it will start distributed transaction processing.
   143  	// The transaction has been aborted if ErrTxnAborted returned.
   144  	// After use, SendResult needs to call the Release method
   145  	Write(ctx context.Context, ops []txn.TxnRequest) (*rpc.SendResult, error)
   146  	// WriteAndCommit is similar to Write, but commit the transaction after write.
   147  	// After use, SendResult needs to call the Release method
   148  	WriteAndCommit(ctx context.Context, ops []txn.TxnRequest) (*rpc.SendResult, error)
   149  	// Commit the transaction. If data has been written to multiple TN nodes, a
   150  	// 2pc distributed transaction commit process is used.
   151  	Commit(ctx context.Context) error
   152  	// Rollback the transaction.
   153  	Rollback(ctx context.Context) error
   154  
   155  	// AddLockTable for pessimistic transactions, if the current transaction is successfully
   156  	// locked, the metadata corresponding to the lockservice needs to be recorded to the txn, and
   157  	// at transaction commit time, the metadata of all lock services accessed by the transaction
   158  	// will be committed to tn to check. If the metadata of the lockservice changes in [lock, commit],
   159  	// the transaction will be rolled back.
   160  	AddLockTable(locktable lock.LockTable) error
   161  	// AddWaitLock add wait lock for current txn
   162  	AddWaitLock(tableID uint64, rows [][]byte, opt lock.LockOptions) uint64
   163  	// RemoveWaitLock remove wait lock for current txn
   164  	RemoveWaitLock(key uint64)
   165  	// LockTableCount get quality of lock table
   166  	LockTableCount() int32
   167  	// LockSkipped return true if lock need skipped.
   168  	LockSkipped(tableID uint64, mode lock.LockMode) bool
   169  
   170  	GetWaitActiveCost() time.Duration
   171  
   172  	// AddWorkspace for the transaction
   173  	AddWorkspace(workspace Workspace)
   174  	// GetWorkspace from the transaction
   175  	GetWorkspace() Workspace
   176  
   177  	ResetRetry(bool)
   178  	IsRetry() bool
   179  
   180  	// AppendEventCallback append callback. All append callbacks will be called sequentially
   181  	// if event happen.
   182  	AppendEventCallback(event EventType, callbacks ...func(TxnEvent))
   183  
   184  	// Debug send debug request to DN, after use, SendResult needs to call the Release
   185  	// method.
   186  	Debug(ctx context.Context, ops []txn.TxnRequest) (*rpc.SendResult, error)
   187  
   188  	NextSequence() uint64
   189  
   190  	EnterRunSql()
   191  	ExitRunSql()
   192  }
   193  
   194  // TxnIDGenerator txn id generator
   195  type TxnIDGenerator interface {
   196  	// Generate returns a unique transaction id
   197  	Generate() []byte
   198  }
   199  
   200  // SetupRuntimeTxnOptions setup runtime based txn options
   201  func SetupRuntimeTxnOptions(
   202  	rt runtime.Runtime,
   203  	m txn.TxnMode,
   204  	iso txn.TxnIsolation) {
   205  	rt.SetGlobalVariables(runtime.TxnIsolation, iso)
   206  	rt.SetGlobalVariables(runtime.TxnMode, m)
   207  }
   208  
   209  // TimestampWaiter is used to wait for the timestamp to reach a specified timestamp.
   210  // In the Push mode of LogTail's Event, the TN pushes the logtail to the subscribed
   211  // CN once a transaction has been Committed. So there is a actual wait (last push commit
   212  // ts >= start ts). This is unfriendly to TP, so we can lose some freshness and use the
   213  // latest commit ts received from the current TN push as the start ts of the transaction,
   214  // which eliminates this physical wait.
   215  type TimestampWaiter interface {
   216  	// GetTimestamp get the latest commit ts as snapshot ts of the new txn. It will keep
   217  	// blocking if latest commit timestamp received from TN is less than the given value.
   218  	GetTimestamp(context.Context, timestamp.Timestamp) (timestamp.Timestamp, error)
   219  	// NotifyLatestCommitTS notify the latest timestamp that received from DN. A applied logtail
   220  	// commit ts is corresponds to an epoch. Whenever the connection of logtail of cn and tn is
   221  	// reset, the epoch will be reset and all the ts of the old epoch should be invalidated.
   222  	NotifyLatestCommitTS(appliedTS timestamp.Timestamp)
   223  	// Pause pauses the timestamp waiter and cancel all waiters in timestamp waiter.
   224  	// They will not wait for the newer timestamp anymore.
   225  	Pause()
   226  	// Resume resumes the cancel channel in the timestamp waiter after all transactions are
   227  	// aborted.
   228  	Resume()
   229  	// CancelC returns the cancel channel of timestamp waiter. If it is nil, means that
   230  	// the logtail consumer is reconnecting to logtail server and is aborting all transaction.
   231  	// At this time, we cannot open new transactions.
   232  	CancelC() chan struct{}
   233  	// Close close the timestamp waiter
   234  	Close()
   235  	// LatestTS returns the latest timestamp of the waiter.
   236  	LatestTS() timestamp.Timestamp
   237  }
   238  
   239  type Workspace interface {
   240  	// StartStatement tag a statement is running
   241  	StartStatement()
   242  	// EndStatement tag end a statement is completed
   243  	EndStatement()
   244  
   245  	// IncrStatementID incr the execute statement id. It maintains the statement id, first statement is 1,
   246  	// second is 2, and so on. If in rc mode, snapshot will updated to latest applied commit ts from dn. And
   247  	// workspace will update snapshot data for later read request.
   248  	IncrStatementID(ctx context.Context, commit bool) error
   249  	// RollbackLastStatement rollback the last statement.
   250  	RollbackLastStatement(ctx context.Context) error
   251  
   252  	UpdateSnapshotWriteOffset()
   253  	GetSnapshotWriteOffset() int
   254  
   255  	// Adjust adjust workspace, adjust update's delete+insert to correct order and merge workspace.
   256  	Adjust(writeOffset uint64) error
   257  
   258  	Commit(ctx context.Context) ([]txn.TxnRequest, error)
   259  	Rollback(ctx context.Context) error
   260  
   261  	IncrSQLCount()
   262  	GetSQLCount() uint64
   263  
   264  	CloneSnapshotWS() Workspace
   265  
   266  	BindTxnOp(op TxnOperator)
   267  }
   268  
   269  // TxnOverview txn overview include meta and status
   270  type TxnOverview struct {
   271  	// CreateAt create at
   272  	CreateAt time.Time
   273  	// Meta txn metadata
   274  	Meta txn.TxnMeta
   275  	// UserTxn true if is a user transaction
   276  	UserTxn bool
   277  	// WaitLocks wait locks
   278  	WaitLocks []Lock
   279  }
   280  
   281  // Lock wait locks
   282  type Lock struct {
   283  	// TableID table id
   284  	TableID uint64
   285  	// Rows lock rows. If granularity is row, rows contains all point lock keys, otherwise rows
   286  	// is range1start, range1end, range2start, range2end, ...
   287  	Rows [][]byte
   288  	// Options lock options, include lock type(row|range) and lock mode
   289  	Options lock.LockOptions
   290  }
   291  
   292  type TxnEvent struct {
   293  	Event     EventType
   294  	Txn       txn.TxnMeta
   295  	TableID   uint64
   296  	Err       error
   297  	Sequence  uint64
   298  	Cost      time.Duration
   299  	CostEvent bool
   300  }