-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage_draft.go
245 lines (206 loc) · 5.27 KB
/
message_draft.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package sockety
import (
"errors"
"github.com/google/uuid"
"github.com/sockety/sockety-go/internal/done_signal"
"io"
"sync"
)
// TODO: Consider with pointers
type MessageDraft struct {
HasStream bool
Action string
Data []byte
//Files []FileTransfer // TODO
}
// Constructor
func NewMessageDraft(action string) *MessageDraft {
return &MessageDraft{
Action: action,
}
}
// Builder pattern
func (m *MessageDraft) RawData(data []byte) *MessageDraft {
m2 := *m
mCopy := m2
mCopy.Data = data
return &mCopy
}
func (m *MessageDraft) Stream() *MessageDraft {
m2 := *m
mCopy := m2
mCopy.HasStream = true
return &mCopy
}
func (m *MessageDraft) NoStream() *MessageDraft {
m2 := *m
mCopy := m2
mCopy.HasStream = true
return &mCopy
}
// Producer interface
func send(m MessageDraft, id uuid.UUID, w Writer, stream *messageStreamWriter, providedChannel *ChannelID, expectsResponse bool) error {
// TODO: Cache calculations (?)
// Estimate action size
actionSize := len(m.Action)
actionSizeBytes := getNameSizeBytes(actionSize)
// Estimate data size
dataSize := len(m.Data)
dataSizeBytes := getDataSizeBytes(dataSize)
// Estimate files count & size
filesCount := 0
filesCountBytes := getFilesCountBytes(filesCount)
totalFilesSize := 0
totalFilesSizeBytes := getFilesSizeBytes(totalFilesSize, filesCount)
// Build message flags
flags := getNameSizeFlag(actionSizeBytes) | getDataSizeFlag(dataSizeBytes) | getFilesCountFlag(filesCountBytes) | getFilesSizeFlag(totalFilesSizeBytes)
// Estimate "Message" packet size
messageSize := 17 + offset(actionSizeBytes) + offset(actionSize) + offset(dataSizeBytes) + offset(filesCountBytes) + offset(totalFilesSizeBytes)
// Build signature
signature := uint8(packetMessageBits)
if expectsResponse {
signature |= expectsResponseBits
}
if m.HasStream {
signature |= hasStreamBits
}
// Build "Message" packet
p := newPacket(signature, messageSize)
p = p.Uint8(flags)
p = p.UUID(id)
p = p.Uint(Uint48(actionSize), actionSizeBytes)
p = p.String(m.Action)
if dataSizeBytes != 0 {
p = p.Uint(Uint48(dataSize), dataSizeBytes)
}
if filesCount > 0 {
p = p.Uint(Uint48(filesCount), filesCountBytes)
p = p.Uint(Uint48(totalFilesSize), totalFilesSizeBytes)
}
// Fast-track when there is no stream, data and files
if dataSizeBytes == 0 && filesCount == 0 && !m.HasStream {
return w.Write(p)
}
// Write message packet
var channel ChannelID
if providedChannel == nil {
channel = w.ObtainChannel()
} else {
channel = *providedChannel
}
err := w.WriteAtChannel(channel, p)
if err != nil {
return err
}
// Prepare wait group for all async message parts
wg := sync.WaitGroup{}
var finalErr error
// Write data
if dataSizeBytes > 0 {
wg.Add(1)
// TODO: Support splitting >uint32 size
// TODO: Consider worker pools
go func() {
err = w.WriteExternalWithSignatureAtChannel(channel, packetDataBits, m.Data)
if err != nil {
finalErr = err
}
wg.Done()
}()
}
// Write stream
if m.HasStream {
// Fast-track when there is no stream, but needs to be simulated
if stream == nil {
err = w.WriteRawAtChannel(channel, []byte{packetStreamEndBits})
if err != nil {
finalErr = err
}
} else {
wg.Add(1)
stream.mu.Unlock() // Start accepting data in Stream
// TODO: Support splitting >uint32 size
go func() {
<-stream.Done()
err = stream.Err()
if err != nil {
finalErr = err
}
wg.Done()
}()
}
}
// TODO: Build packets for files too
// Wait for all parts sent and notify
wg.Wait()
w.ReleaseChannel(channel)
return finalErr
}
func (m *MessageDraft) pass(writer Writer) error {
return send(*m, uuid.New(), writer, nil, nil, false)
}
func (m *MessageDraft) create(writer Writer) Request {
return &messageRequest{
id: uuid.New(),
w: writer,
m: m,
initiated: done_signal.New(),
done: done_signal.New(),
}
}
func (m *MessageDraft) RequestTo(c Conn) Request {
if cc, ok := c.(*conn); ok {
return m.create(cc.w)
}
panic("passed connection without internal producer's support")
}
func (m *MessageDraft) PassTo(c Conn) error {
if cc, ok := c.(*conn); ok {
return m.pass(cc.w)
}
panic("passed connection without internal producer's support")
}
type messageRequest struct {
id uuid.UUID
m *MessageDraft
w Writer
mu sync.Mutex
initiated *done_signal.DoneSignal
done *done_signal.DoneSignal
stream *messageStreamWriter
}
func (m *messageRequest) Id() uuid.UUID {
return m.id
}
func (m *messageRequest) Send() error {
// Allow sending request only once
if !m.mu.TryLock() {
return errors.New("request is already sent")
}
// If stream is expected, obtain channel and prepare stream
if m.m.HasStream {
channel := m.w.ObtainChannel()
m.stream = newMessageStreamWriter(channel, m.w)
m.initiated.Close()
err := send(*m.m, m.id, m.w, m.stream, &channel, true)
m.done.Close()
return err
}
// Otherwise, just send
err := send(*m.m, m.id, m.w, nil, nil, true)
m.done.Close()
return err
}
func (m *messageRequest) Stream() io.WriteCloser {
if m.initiated.Load() {
return m.stream
}
<-m.initiated.Get()
return m.stream
}
func (m *messageRequest) Initiated() <-chan struct{} {
return m.initiated.Get()
}
func (m *messageRequest) Done() <-chan struct{} {
return m.done.Get()
}