-
Notifications
You must be signed in to change notification settings - Fork 402
/
service.go
420 lines (339 loc) · 11.3 KB
/
service.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package payouts
import (
"context"
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/spacemonkeygo/monkit/v3"
"github.com/zeebo/errs"
"go.uber.org/zap"
"storj.io/common/storj"
"storj.io/storj/private/date"
"storj.io/storj/storagenode/reputation"
"storj.io/storj/storagenode/satellites"
"storj.io/storj/storagenode/trust"
)
var (
// ErrPayoutService defines payout service error.
ErrPayoutService = errs.Class("payouts service")
// ErrBadPeriod defines that period has wrong format.
ErrBadPeriod = errs.Class("wrong period format")
mon = monkit.Package()
)
// Service retrieves info from satellites using an rpc client.
//
// architecture: Service
type Service struct {
log *zap.Logger
stefanSatellite storj.NodeID
db DB
reputationDB reputation.DB
satellitesDB satellites.DB
trust *trust.Pool
}
// NewService creates new instance of service.
func NewService(log *zap.Logger, db DB, reputationDB reputation.DB, satelliteDB satellites.DB, trust *trust.Pool) (_ *Service, err error) {
id, err := storj.NodeIDFromString("118UWpMCHzs6CvSgWd9BfFVjw5K9pZbJjkfZJexMtSkmKxvvAW")
if err != nil {
return &Service{}, err
}
return &Service{
log: log,
stefanSatellite: id,
db: db,
reputationDB: reputationDB,
satellitesDB: satelliteDB,
trust: trust,
}, nil
}
// SatellitePayStubMonthly retrieves held amount for particular satellite for selected month from storagenode database.
func (service *Service) SatellitePayStubMonthly(ctx context.Context, satelliteID storj.NodeID, period string) (payStub *PayStub, err error) {
defer mon.Task()(&ctx, &satelliteID, &period)(&err)
payStub, err = service.db.GetPayStub(ctx, satelliteID, period)
if err != nil {
if ErrNoPayStubForPeriod.Has(err) {
return nil, nil
}
return nil, ErrPayoutService.Wrap(err)
}
payStub.UsageAtRestTbM()
return payStub, nil
}
// AllPayStubsMonthly retrieves held amount for all satellites per selected period from storagenode database.
func (service *Service) AllPayStubsMonthly(ctx context.Context, period string) (payStubs []PayStub, err error) {
defer mon.Task()(&ctx, &period)(&err)
payStubs, err = service.db.AllPayStubs(ctx, period)
if err != nil {
return payStubs, ErrPayoutService.Wrap(err)
}
for i := 0; i < len(payStubs); i++ {
payStubs[i].UsageAtRestTbM()
}
return payStubs, nil
}
// SatellitePayStubPeriod retrieves held amount for all satellites for selected months from storagenode database.
func (service *Service) SatellitePayStubPeriod(ctx context.Context, satelliteID storj.NodeID, periodStart, periodEnd string) (payStubs []PayStub, err error) {
defer mon.Task()(&ctx, &satelliteID, &periodStart, &periodEnd)(&err)
periods, err := parsePeriodRange(periodStart, periodEnd)
if err != nil {
return []PayStub{}, err
}
for _, period := range periods {
payStub, err := service.db.GetPayStub(ctx, satelliteID, period)
if err != nil {
if ErrNoPayStubForPeriod.Has(err) {
continue
}
return []PayStub{}, ErrPayoutService.Wrap(err)
}
payStubs = append(payStubs, *payStub)
}
for i := 0; i < len(payStubs); i++ {
payStubs[i].UsageAtRestTbM()
}
return payStubs, nil
}
// AllPayStubsPeriod retrieves held amount for all satellites for selected range of months from storagenode database.
func (service *Service) AllPayStubsPeriod(ctx context.Context, periodStart, periodEnd string) (payStubs []PayStub, err error) {
defer mon.Task()(&ctx, &periodStart, &periodEnd)(&err)
periods, err := parsePeriodRange(periodStart, periodEnd)
if err != nil {
return []PayStub{}, err
}
for _, period := range periods {
payStub, err := service.db.AllPayStubs(ctx, period)
if err != nil {
if ErrNoPayStubForPeriod.Has(err) {
continue
}
return []PayStub{}, ErrPayoutService.Wrap(err)
}
payStubs = append(payStubs, payStub...)
}
for i := 0; i < len(payStubs); i++ {
payStubs[i].UsageAtRestTbM()
}
return payStubs, nil
}
// SatellitePeriods retrieves all periods for concrete satellite in which we have some payouts data.
func (service *Service) SatellitePeriods(ctx context.Context, satelliteID storj.NodeID) (_ []string, err error) {
defer mon.Task()(&ctx)(&err)
return service.db.SatellitePeriods(ctx, satelliteID)
}
// AllPeriods retrieves all periods in which we have some payouts data.
func (service *Service) AllPeriods(ctx context.Context) (_ []string, err error) {
defer mon.Task()(&ctx)(&err)
return service.db.AllPeriods(ctx)
}
// AllHeldbackHistory retrieves heldback history for all satellites from storagenode database.
func (service *Service) AllHeldbackHistory(ctx context.Context) (result []SatelliteHeldHistory, err error) {
defer mon.Task()(&ctx)(&err)
satellitesIDs := service.trust.GetSatellites(ctx)
satellitesIDs = append(satellitesIDs, service.stefanSatellite)
for i := 0; i < len(satellitesIDs); i++ {
var history SatelliteHeldHistory
helds, err := service.db.SatellitesHeldbackHistory(ctx, satellitesIDs[i])
if err != nil {
return nil, ErrPayoutService.Wrap(err)
}
if helds == nil {
continue
}
disposed, err := service.db.SatellitesDisposedHistory(ctx, satellitesIDs[i])
if err != nil {
return nil, ErrPayoutService.Wrap(err)
}
for i, amountPeriod := range helds {
switch i {
case 0, 1, 2:
history.HoldForFirstPeriod += amountPeriod.Amount
history.TotalHeld += amountPeriod.Amount
case 3, 4, 5:
history.HoldForSecondPeriod += amountPeriod.Amount
history.TotalHeld += amountPeriod.Amount
case 6, 7, 8:
history.HoldForThirdPeriod += amountPeriod.Amount
history.TotalHeld += amountPeriod.Amount
default:
}
}
history.TotalDisposed = disposed
history.SatelliteID = satellitesIDs[i]
history.SatelliteName = "stefan-benten"
if satellitesIDs[i] != service.stefanSatellite {
url, err := service.trust.GetNodeURL(ctx, satellitesIDs[i])
if err != nil {
return nil, ErrPayoutService.Wrap(err)
}
history.SatelliteName = url.Address
}
stats, err := service.reputationDB.Get(ctx, satellitesIDs[i])
if err != nil {
return nil, ErrPayoutService.Wrap(err)
}
history.JoinedAt = stats.JoinedAt.Round(time.Minute)
result = append(result, history)
}
return result, nil
}
// AllSatellitesPayoutPeriod retrieves paystub and payment receipt for specific month from all satellites.
func (service *Service) AllSatellitesPayoutPeriod(ctx context.Context, period string) (result []SatellitePayoutForPeriod, err error) {
defer mon.Task()(&ctx)(&err)
satelliteIDs := service.trust.GetSatellites(ctx)
satelliteIDs = append(satelliteIDs, service.stefanSatellite)
for i := 0; i < len(satelliteIDs); i++ {
var payoutForPeriod SatellitePayoutForPeriod
paystub, err := service.db.GetPayStub(ctx, satelliteIDs[i], period)
if err != nil {
if ErrNoPayStubForPeriod.Has(err) {
continue
}
return nil, ErrPayoutService.Wrap(err)
}
receipt, err := service.db.GetReceipt(ctx, satelliteIDs[i], period)
if err != nil {
if !ErrNoPayStubForPeriod.Has(err) {
return nil, ErrPayoutService.Wrap(err)
}
}
stats, err := service.reputationDB.Get(ctx, satelliteIDs[i])
if err != nil {
return nil, ErrPayoutService.Wrap(err)
}
satellite, err := service.satellitesDB.GetSatellite(ctx, satelliteIDs[i])
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
payoutForPeriod.IsExitComplete = false
}
return nil, ErrPayoutService.Wrap(err)
}
if satelliteIDs[i] != service.stefanSatellite {
url, err := service.trust.GetNodeURL(ctx, satelliteIDs[i])
if err != nil {
return nil, ErrPayoutService.Wrap(err)
}
payoutForPeriod.SatelliteURL = url.Address
}
if satellite.Status == satellites.ExitSucceeded {
payoutForPeriod.IsExitComplete = true
}
if paystub.SurgePercent == 0 {
paystub.SurgePercent = 100
}
earned, surge := paystub.GetEarnedWithSurge()
periodTime := Period(paystub.Period)
heldPeriod, err := periodTime.Time()
if err != nil {
return nil, ErrPayoutService.Wrap(err)
}
heldPercent := GetHeldRate(stats.JoinedAt, heldPeriod)
payoutForPeriod.Held = paystub.Held
payoutForPeriod.Receipt = receipt
payoutForPeriod.Surge = surge
payoutForPeriod.AfterHeld = surge - paystub.Held
payoutForPeriod.Age = int64(date.MonthsCountSince(stats.JoinedAt))
payoutForPeriod.Disposed = paystub.Disposed
payoutForPeriod.Earned = earned
payoutForPeriod.SatelliteID = satelliteIDs[i].String()
payoutForPeriod.SurgePercent = paystub.SurgePercent
payoutForPeriod.Paid = paystub.Paid
payoutForPeriod.HeldPercent = heldPercent
payoutForPeriod.Distributed = paystub.Distributed
result = append(result, payoutForPeriod)
}
return result, nil
}
// HeldAmountHistory retrieves held amount history for all satellites.
func (service *Service) HeldAmountHistory(ctx context.Context) (_ []HeldAmountHistory, err error) {
defer mon.Task()(&ctx)(&err)
heldHistory, err := service.db.HeldAmountHistory(ctx)
if err != nil {
return nil, ErrPayoutService.Wrap(err)
}
trustedSatellites := service.trust.GetSatellites(ctx)
for _, trustedSatellite := range trustedSatellites {
var found bool
for _, satelliteHeldHistory := range heldHistory {
if trustedSatellite.Compare(satelliteHeldHistory.SatelliteID) == 0 {
found = true
break
}
}
if !found {
heldHistory = append(heldHistory, HeldAmountHistory{
SatelliteID: trustedSatellite,
})
}
}
return heldHistory, nil
}
// parsePeriodRange creates period range form start and end periods.
// TODO: move to separate struct.
func parsePeriodRange(periodStart, periodEnd string) (periods []string, err error) {
var yearStart, yearEnd, monthStart, monthEnd int
start := strings.Split(periodStart, "-")
if len(start) != 2 {
return nil, ErrBadPeriod.New("period start has wrong format")
}
end := strings.Split(periodEnd, "-")
if len(start) != 2 {
return nil, ErrBadPeriod.New("period end has wrong format")
}
yearStart, err = strconv.Atoi(start[0])
if err != nil {
return nil, ErrBadPeriod.New("period start has wrong format")
}
monthStart, err = strconv.Atoi(start[1])
if err != nil || monthStart > 12 || monthStart < 1 {
return nil, ErrBadPeriod.New("period start has wrong format")
}
yearEnd, err = strconv.Atoi(end[0])
if err != nil {
return nil, ErrBadPeriod.New("period end has wrong format")
}
monthEnd, err = strconv.Atoi(end[1])
if err != nil || monthEnd > 12 || monthEnd < 1 {
return nil, ErrBadPeriod.New("period end has wrong format")
}
if yearEnd < yearStart {
return nil, ErrBadPeriod.New("period has wrong format")
}
if yearEnd == yearStart && monthEnd < monthStart {
return nil, ErrBadPeriod.New("period has wrong format")
}
for ; yearStart <= yearEnd; yearStart++ {
lastMonth := 12
if yearStart == yearEnd {
lastMonth = monthEnd
}
for ; monthStart <= lastMonth; monthStart++ {
format := "%d-%d"
if monthStart < 10 {
format = "%d-0%d"
}
periods = append(periods, fmt.Sprintf(format, yearStart, monthStart))
}
monthStart = 1
}
return periods, nil
}
// GetHeldRate returns held rate for specific period from join date of node.
func GetHeldRate(joinTime time.Time, requestTime time.Time) (heldRate float64) {
monthsSinceJoin := date.MonthsBetweenDates(joinTime, requestTime)
switch monthsSinceJoin {
case 0, 1, 2:
heldRate = 75
case 3, 4, 5:
heldRate = 50
case 6, 7, 8:
heldRate = 25
default:
heldRate = 0
}
return heldRate
}