-
Notifications
You must be signed in to change notification settings - Fork 321
/
types.go
89 lines (75 loc) · 1.99 KB
/
types.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package apitypes
import (
"encoding/json"
"errors"
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-core/blockchain/block"
)
// MaxResponseSize is the max size of response
var MaxResponseSize = 1024 * 1024 * 100 // 100MB
type (
// Web3ResponseWriter is writer for web3 request
Web3ResponseWriter interface {
Write(interface{}) (int, error)
}
// Responder responds to new block
Responder interface {
Respond(string, *block.Block) error
Exit()
}
// Listener pass new block to all responders
Listener interface {
Start() error
Stop() error
ReceiveBlock(*block.Block) error
AddResponder(Responder) (string, error)
RemoveResponder(string) (bool, error)
}
// BlockWithReceipts includes block and its receipts
BlockWithReceipts struct {
Block *block.Block
Receipts []*action.Receipt
}
)
// responseWriter for server
type responseWriter struct {
writeHandler func(interface{}) (int, error)
}
// NewResponseWriter returns a new responseWriter
func NewResponseWriter(handler func(interface{}) (int, error)) Web3ResponseWriter {
return &responseWriter{handler}
}
func (w *responseWriter) Write(in interface{}) (int, error) {
return w.writeHandler(in)
}
// BatchWriter for multiple web3 requests
type BatchWriter struct {
totalSize int
writer Web3ResponseWriter
buf []json.RawMessage
}
// NewBatchWriter returns a new BatchWriter
func NewBatchWriter(singleWriter Web3ResponseWriter) *BatchWriter {
return &BatchWriter{
writer: singleWriter,
buf: make([]json.RawMessage, 0),
}
}
// Write adds data into batch buffer
func (w *BatchWriter) Write(in interface{}) (int, error) {
raw, err := json.Marshal(in)
if err != nil {
return 0, err
}
w.totalSize += len(raw)
if w.totalSize > MaxResponseSize {
return w.totalSize, errors.New("response size exceeds limit")
}
w.buf = append(w.buf, raw)
return w.totalSize, nil
}
// Flush writes data in batch buffer
func (w *BatchWriter) Flush() error {
_, err := w.writer.Write(w.buf)
return err
}