forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 11
/
throttle.go
52 lines (41 loc) · 1.14 KB
/
throttle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package scc
import (
"context"
"github.com/hyperledger/fabric-chaincode-go/shim"
pb "github.com/hyperledger/fabric-protos-go/peer"
"github.com/hyperledger/fabric/common/semaphore"
)
func Throttle(limit int, systemCC SelfDescribingSysCC) *ThrottledSysCC {
return &ThrottledSysCC{
SelfDescribingSysCC: systemCC,
semaphore: semaphore.New(limit),
}
}
type ThrottledSysCC struct {
SelfDescribingSysCC
semaphore semaphore.Semaphore
}
func (t *ThrottledSysCC) Chaincode() shim.Chaincode {
return &ThrottledChaincode{
chaincode: t.SelfDescribingSysCC.Chaincode(),
semaphore: t.semaphore,
}
}
type ThrottledChaincode struct {
chaincode shim.Chaincode
semaphore semaphore.Semaphore
}
func (t *ThrottledChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
return t.chaincode.Init(stub)
}
func (t *ThrottledChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
if err := t.semaphore.Acquire(context.Background()); err != nil {
return shim.Error(err.Error())
}
defer t.semaphore.Release()
return t.chaincode.Invoke(stub)
}