-
Notifications
You must be signed in to change notification settings - Fork 1
/
discussion.go
314 lines (263 loc) · 8.51 KB
/
discussion.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package rpc
import (
"context"
"fmt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/c13n-io/c13n-go/app"
"github.com/c13n-io/c13n-go/model"
pb "github.com/c13n-io/c13n-go/rpc/services"
"github.com/c13n-io/c13n-go/slog"
)
type discussionServiceServer struct {
Log *slog.Logger
App *app.App
pb.UnimplementedDiscussionServiceServer
}
func (s *discussionServiceServer) logError(err error) error {
if err != nil {
s.Log.Errorf("%+v", err)
}
return err
}
// Interface implementation
// GetDiscussions returns information about all discussions
// over the provided grpc stream.
func (s *discussionServiceServer) GetDiscussions(_ *pb.GetDiscussionsRequest, srv pb.DiscussionService_GetDiscussionsServer) error {
ctx := srv.Context()
ctx, cancel := context.WithCancel(ctx)
defer func() {
cancel()
}()
discussions, err := s.App.GetDiscussions(ctx)
if err != nil {
return associateStatusCode(s.logError(err))
}
for _, disc := range discussions {
discInfo, err := discussionModelToDiscussionInfo(&disc)
if err != nil {
return associateStatusCode(s.logError(err))
}
discResp := &pb.GetDiscussionsResponse{
Discussion: discInfo,
}
if err := srv.Send(discResp); err != nil {
return associateStatusCode(s.logError(err))
}
}
return nil
}
// GetDiscussionHistoryByID returns previously exchanged messages
// associated with the discussion over the provided stream,
// respecting the pagination options parameter.
func (s *discussionServiceServer) GetDiscussionHistoryByID(req *pb.GetDiscussionHistoryByIDRequest, srv pb.DiscussionService_GetDiscussionHistoryByIDServer) error {
ctx := srv.Context()
ctx, cancel := context.WithCancel(ctx)
defer func() {
cancel()
}()
var pageOptions model.PageOptions
if pageOpts := req.GetPageOptions(); pageOpts != nil {
pageOptions = model.PageOptions{
LastID: pageOpts.GetLastId(),
PageSize: uint64(pageOpts.GetPageSize()),
Reverse: pageOpts.GetReverse(),
}
}
messages, err := s.App.GetDiscussionHistory(ctx, req.GetId(), pageOptions)
if err != nil {
return associateStatusCode(s.logError(err))
}
for _, message := range messages {
msg, err := newMessage(&message)
if err != nil {
return associateStatusCode(s.logError(err))
}
resp := &pb.GetDiscussionHistoryResponse{
Message: msg,
}
if err := srv.Send(resp); err != nil {
return associateStatusCode(s.logError(err))
}
}
return nil
}
// GetDiscussionStatistics returns statistics for the provided discussion.
func (s *discussionServiceServer) GetDiscussionStatistics(ctx context.Context, req *pb.GetDiscussionStatisticsRequest) (*pb.GetDiscussionStatisticsResponse, error) {
stats, err := s.App.GetDiscussionStatistics(ctx, req.GetId())
if err != nil {
return nil, associateStatusCode(s.logError(err))
}
return &pb.GetDiscussionStatisticsResponse{
AmtMsatSent: stats.AmtMsatSent,
AmtMsatReceived: stats.AmtMsatReceived,
AmtMsatFees: stats.AmtMsatFees,
MessagesSent: stats.MessagesSent,
MessagesReceived: stats.MessagesReceived,
}, nil
}
// AddDiscussion adds a discussion to the database.
// The discussion to be added is provided in the request.
func (s *discussionServiceServer) AddDiscussion(ctx context.Context, req *pb.AddDiscussionRequest) (*pb.AddDiscussionResponse, error) {
discussion := discussionInfoToDiscussionModel(req.GetDiscussion())
if len(discussion.Participants) < 1 {
return nil, status.Error(codes.InvalidArgument,
"Participant set empty for discussion")
}
// Disallow anonymous group discussions
if len(discussion.Participants) > 1 && discussion.Options.Anonymous {
return nil, status.Error(codes.InvalidArgument,
"Anonymous group discussions are disallowed")
}
savedDiscussion, err := s.App.AddDiscussion(ctx, &discussion)
if err != nil {
return nil, associateStatusCode(s.logError(err))
}
responseDiscussion, err := discussionModelToDiscussionInfo(savedDiscussion)
if err != nil {
return nil, associateStatusCode(s.logError(err))
}
return &pb.AddDiscussionResponse{
Discussion: responseDiscussion,
}, nil
}
// UpdateDiscussionLastRead updates the last read message id of a discussion.
func (s *discussionServiceServer) UpdateDiscussionLastRead(ctx context.Context,
req *pb.UpdateDiscussionLastReadRequest) (*pb.UpdateDiscussionResponse, error) {
discussionID, lastReadID := req.DiscussionId, req.LastReadMsgId
if err := s.App.UpdateDiscussionLastRead(ctx, discussionID, lastReadID); err != nil {
return nil, associateStatusCode(s.logError(err))
}
return &pb.UpdateDiscussionResponse{}, nil
}
// RemoveDiscussion removes a discussion from the database,
// based on the id request field.
func (s *discussionServiceServer) RemoveDiscussion(ctx context.Context, req *pb.RemoveDiscussionRequest) (*pb.RemoveDiscussionResponse, error) {
err := s.App.RemoveDiscussion(ctx, req.GetId())
if err != nil {
return nil, associateStatusCode(s.logError(err))
}
return &pb.RemoveDiscussionResponse{}, nil
}
// Send sends a message over a payment.
// If a payment request is specified the discussion with the recipient is used,
// (creating it with default options if it does not exist).
func (s *discussionServiceServer) Send(ctx context.Context, req *pb.SendRequest) (*pb.SendResponse, error) {
msgAggregate, err := s.App.SendMessage(ctx,
req.GetDiscussionId(), req.GetAmtMsat(), req.GetPayReq(),
req.GetPayload(), messageOptionsFromRequest(req.GetOptions()))
// SendMessage can partially succeed, in which case log the failures.
if err != nil {
rpcErr := associateStatusCode(s.logError(err))
if msgAggregate == nil {
return nil, rpcErr
}
}
message, err := newMessage(msgAggregate)
if err != nil {
return nil, associateStatusCode(s.logError(err))
}
return &pb.SendResponse{
SentMessage: message,
}, nil
}
// Subscribe creates a subscription stream for sent and received messages.
func (s *discussionServiceServer) Subscribe(_ *pb.SubscribeMessagesRequest,
srv pb.DiscussionService_SubscribeServer) error {
ctx, cancel := context.WithCancel(srv.Context())
defer cancel()
msgChannel, err := s.App.SubscribeMessages(ctx)
if err != nil {
return associateStatusCode(s.logError(
fmt.Errorf("client subscription failed: %w", err)))
}
messageLoop:
for {
select {
case <-ctx.Done():
s.Log.Printf("client subscription ended")
break messageLoop
case msg, ok := <-msgChannel:
if !ok {
s.Log.Printf("subscription channel closed")
break messageLoop
}
message, err := newMessage(&msg)
if err != nil {
return associateStatusCode(s.logError(err))
}
if err := srv.Send(message); err != nil {
return associateStatusCode(s.logError(err))
}
}
}
return nil
}
func newMessage(aggregate *model.MessageAggregate) (*pb.Message, error) {
if aggregate == nil {
return nil, nil
}
raw := aggregate.RawMessage
payload, _, err := raw.UnmarshalPayload()
if err != nil {
return nil, err
}
msg := &pb.Message{
Id: raw.ID,
DiscussionId: raw.DiscussionID,
Sender: raw.Sender,
SenderVerified: raw.SignatureVerified,
Payload: payload,
}
var amtMsat uint64
var sentAt, receivedAt *timestamppb.Timestamp
switch {
case raw.InvoiceSettleIndex != 0:
invoice, err := newInvoice(aggregate.Invoice)
if err != nil {
return nil, err
}
amtMsat = invoice.GetAmtPaidMsat()
sentAt = invoice.GetCreatedTimestamp()
receivedAt = invoice.GetSettledTimestamp()
msg.LightningData = &pb.Message_Invoice{
Invoice: invoice,
}
case len(raw.PaymentIndexes) != 0:
payments := make([]*pb.Payment, len(aggregate.Payments))
for i, pmnt := range aggregate.Payments {
payment, err := newPayment(pmnt)
if err != nil {
return nil, err
}
if payment.GetState() == pb.PaymentState_PAYMENT_SUCCEEDED {
amtMsat += payment.GetAmtMsat()
}
createdAt := payment.GetCreatedTimestamp()
if sentAt.AsTime().After(createdAt.AsTime()) || sentAt == nil {
sentAt = createdAt
}
resolvedAt := payment.GetResolvedTimestamp()
if receivedAt.AsTime().Before(resolvedAt.AsTime()) {
receivedAt = resolvedAt
}
payments[i] = payment
}
msg.LightningData = &pb.Message_Payments{
Payments: &pb.Payments{
Payments: payments,
},
}
}
msg.AmtMsat = int64(amtMsat)
msg.SentTimestamp, msg.ReceivedTimestamp = sentAt, receivedAt
return msg, nil
}
// NewDiscussionServiceServer initializes a new discussion service.
func NewDiscussionServiceServer(app *app.App) pb.DiscussionServiceServer {
return &discussionServiceServer{
Log: slog.NewLogger("discussion-service"),
App: app,
}
}