github.com/matrixorigin/matrixone@v1.2.0/pkg/tnservice/replica.go (about) 1 // Copyright 2021 - 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 tnservice 16 17 import ( 18 "context" 19 "sync" 20 21 "github.com/matrixorigin/matrixone/pkg/common/log" 22 "github.com/matrixorigin/matrixone/pkg/common/moerr" 23 "github.com/matrixorigin/matrixone/pkg/common/runtime" 24 "github.com/matrixorigin/matrixone/pkg/pb/metadata" 25 "github.com/matrixorigin/matrixone/pkg/pb/txn" 26 "github.com/matrixorigin/matrixone/pkg/txn/service" 27 "github.com/matrixorigin/matrixone/pkg/txn/util" 28 ) 29 30 // replica tn shard replica. 31 type replica struct { 32 rt runtime.Runtime 33 logger *log.MOLogger 34 shard metadata.TNShard 35 service service.TxnService 36 startedC chan struct{} 37 38 mu struct { 39 sync.RWMutex 40 starting bool 41 } 42 } 43 44 func newReplica(shard metadata.TNShard, rt runtime.Runtime) *replica { 45 return &replica{ 46 rt: rt, 47 shard: shard, 48 logger: rt.Logger().With(util.TxnTNShardField(shard)), 49 startedC: make(chan struct{}), 50 } 51 } 52 53 func (r *replica) start(txnService service.TxnService) error { 54 r.mu.Lock() 55 if r.mu.starting { 56 r.mu.Unlock() 57 return nil 58 } 59 r.mu.starting = true 60 r.mu.Unlock() 61 62 defer close(r.startedC) 63 r.service = txnService 64 return r.service.Start() 65 } 66 67 func (r *replica) close(destroy bool) error { 68 r.mu.RLock() 69 defer r.mu.RUnlock() 70 if !r.mu.starting { 71 return nil 72 } 73 r.waitStarted() 74 return r.service.Close(destroy) 75 } 76 77 func (r *replica) handleLocalRequest(ctx context.Context, request *txn.TxnRequest, response *txn.TxnResponse) error { 78 r.waitStarted() 79 prepareResponse(request, response) 80 81 switch request.Method { 82 case txn.TxnMethod_GetStatus: 83 return r.service.GetStatus(ctx, request, response) 84 case txn.TxnMethod_Prepare: 85 return r.service.Prepare(ctx, request, response) 86 case txn.TxnMethod_CommitTNShard: 87 return r.service.CommitTNShard(ctx, request, response) 88 case txn.TxnMethod_RollbackTNShard: 89 return r.service.RollbackTNShard(ctx, request, response) 90 default: 91 return moerr.NewNotSupported(ctx, "unknown txn request method: %s", request.Method.String()) 92 } 93 } 94 95 func (r *replica) waitStarted() { 96 <-r.startedC 97 }