This repository has been archived by the owner on Nov 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue.go
690 lines (635 loc) · 20.5 KB
/
queue.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
package queue
import (
"context"
"database/sql"
"errors"
"fmt"
"net/url"
"sync"
"time"
bindata "github.com/golang-migrate/migrate/v4/source/go_bindata"
"github.com/google/uuid"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/textileio/bidbot/lib/auction"
"github.com/textileio/broker-core/auctioneer"
"github.com/textileio/broker-core/broker"
"github.com/textileio/broker-core/cmd/auctioneerd/auctioneer/queue/internal/db"
"github.com/textileio/broker-core/cmd/auctioneerd/auctioneer/queue/migrations"
"github.com/textileio/broker-core/storeutil"
golog "github.com/textileio/go-log/v2"
)
var (
log = golog.Logger("auctioneer/queue")
// StartDelay is the time delay before the queue will process queued auctions on start.
StartDelay = time.Second * 10
// stuckSeconds is the seconds elapsed before an started auction is
// considered stuck and can be rescheduled.
stuckSeconds = int64(3600)
// MaxConcurrency is the maximum number of auctions that will be handled concurrently.
MaxConcurrency = 1
// ErrAuctionNotFound indicates the requested auction was not found.
ErrAuctionNotFound = errors.New("auction not found")
// ErrBidNotFound indicates the requested bid was not found.
ErrBidNotFound = errors.New("bid not found")
)
// BidEventType is an alias.
type BidEventType = db.BidEventType
const (
// BidEventTypeStartFetching is an alias.
BidEventTypeStartFetching = db.BidEventTypeStartFetching
// BidEventTypeErrorFetching is an alias.
BidEventTypeErrorFetching = db.BidEventTypeErrorFetching
// BidEventTypeStartImporting is an alias.
BidEventTypeStartImporting = db.BidEventTypeStartImporting
// BidEventTypeEndImporting is an alias.
BidEventTypeEndImporting = db.BidEventTypeEndImporting
// BidEventTypeFinalized is an alias.
BidEventTypeFinalized = db.BidEventTypeFinalized
// BidEventTypeErrored is an alias.
BidEventTypeErrored = db.BidEventTypeErrored
)
// Handler is called when an auction moves from "queued" to "started".
type Handler func(
ctx context.Context,
auction auctioneer.Auction,
addBid func(bid auctioneer.Bid) error,
) (map[auction.BidID]auctioneer.WinningBid, error)
// Finalizer is called when an auction moves from "started" to "finalized".
type Finalizer func(ctx context.Context, auction *auctioneer.Auction) error
// Queue is a persistent worker-based task queue.
type Queue struct {
conn *sql.DB
db *db.Queries
handler Handler
finalizer Finalizer
jobCh chan *auctioneer.Auction
tickCh chan struct{}
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
addBidLock sync.Mutex
}
// NewQueue returns a new Queue using handler to process auctions.
func NewQueue(postgresURI string, handler Handler, finalizer Finalizer) (*Queue, error) {
ctx, cancel := context.WithCancel(context.Background())
as := bindata.Resource(migrations.AssetNames(),
func(name string) ([]byte, error) {
return migrations.Asset(name)
})
conn, err := storeutil.MigrateAndConnectToDB(postgresURI, as)
if err != nil {
cancel()
return nil, err
}
q := &Queue{
conn: conn,
db: db.New(conn),
handler: handler,
finalizer: finalizer,
jobCh: make(chan *auctioneer.Auction, MaxConcurrency),
tickCh: make(chan struct{}, MaxConcurrency),
ctx: ctx,
cancel: cancel,
}
// Create queue workers
q.wg.Add(MaxConcurrency)
for i := 0; i < MaxConcurrency; i++ {
go q.worker(i + 1)
}
go q.start()
return q, nil
}
// Close the queue. This will wait for "started" auctions.
func (q *Queue) Close() error {
q.cancel()
q.wg.Wait()
return nil
}
// CreateAuction adds a new auction to the queue.
// The new auction will be handled immediately if workers are not busy.
func (q *Queue) CreateAuction(ctx context.Context, a auctioneer.Auction) error {
if err := validate(a); err != nil {
return fmt.Errorf("invalid auction data: %s", err)
}
params := db.CreateAuctionParams{
ID: a.ID,
BatchID: a.BatchID,
DealSize: int64(a.DealSize),
DealDuration: a.DealDuration,
DealReplication: int32(a.DealReplication),
DealVerified: a.DealVerified,
FilEpochDeadline: a.FilEpochDeadline,
ExcludedStorageProviders: a.ExcludedStorageProviders,
Providers: a.Providers,
PayloadCid: a.PayloadCid.String(),
Status: broker.AuctionStatusQueued,
Duration: int64(a.Duration),
ClientAddress: a.ClientAddress,
}
if len(a.ExcludedStorageProviders) == 0 {
params.ExcludedStorageProviders = []string{}
}
if len(a.Providers) == 0 {
params.Providers = []string{}
}
if a.Sources.CARURL != nil {
params.CarUrl = a.Sources.CARURL.URL.String()
}
params.CarIpfsAddrs = []string{}
if a.Sources.CARIPFS != nil {
params.CarIpfsCid = a.Sources.CARIPFS.Cid.String()
for _, addr := range a.Sources.CARIPFS.Multiaddrs {
params.CarIpfsAddrs = append(params.CarIpfsAddrs, addr.String())
}
}
return storeutil.WithTx(ctx, q.conn, func(tx *sql.Tx) error {
txn := q.db.WithTx(tx)
if err := txn.CreateAuction(ctx, params); err != nil {
return fmt.Errorf("creating auction: %v", err)
}
log.Debugf("created auction %s", a.ID)
q.enqueue(ctx, txn, &a)
return nil
})
}
func validate(a auctioneer.Auction) error {
if a.ID == "" {
return errors.New("auction id is empty")
}
if a.BatchID == "" {
return errors.New("batch id is empty")
}
if !a.PayloadCid.Defined() {
return errors.New("payload cid is empty")
}
if a.DealSize == 0 {
return errors.New("deal size must be greater than zero")
}
if a.DealDuration == 0 {
return errors.New("deal duration must be greater than zero")
}
if a.DealReplication == 0 {
return errors.New("deal replication must be greater than zero")
}
if err := a.Sources.Validate(); err != nil {
return err
}
if a.Status != broker.AuctionStatusUnspecified {
return errors.New("invalid initial auction status")
}
if len(a.Bids) != 0 {
return errors.New("initial bids must be empty")
}
if len(a.WinningBids) != 0 {
return errors.New("initial winning bids must be empty")
}
if !a.StartedAt.IsZero() {
return errors.New("initial started at must be zero")
}
if !a.UpdatedAt.IsZero() {
return errors.New("initial updated at must be zero")
}
if a.Duration == 0 {
return errors.New("duration must be greater than zero")
}
if a.ErrorCause != "" {
return errors.New("initial error cause must be empty")
}
return nil
}
// GetAuction returns an auction by id.
// If an auction is not found for id, ErrAuctionNotFound is returned.
func (q *Queue) GetAuction(ctx context.Context, id auction.ID) (a *auctioneer.Auction, err error) {
err = storeutil.WithTx(ctx, q.conn, func(tx *sql.Tx) error {
txn := q.db.WithTx(tx)
record, err := txn.GetAuction(ctx, id)
if err == sql.ErrNoRows {
return ErrAuctionNotFound
} else if err != nil {
return fmt.Errorf("getting auction: %v", err)
}
a, err = auctionFromDb(record)
if err != nil {
return fmt.Errorf("auction from db: %v", err)
}
bids, err := txn.GetAuctionBids(ctx, id)
if err != nil {
return fmt.Errorf("getting auction bids: %v", err)
}
a.Bids = make(map[auction.BidID]auctioneer.Bid)
a.WinningBids = make(map[auction.BidID]auctioneer.WinningBid)
for _, b := range bids {
bid, err := bidFromDb(b)
if err != nil {
return err
}
a.Bids[b.ID] = *bid
if !bid.WonAt.IsZero() {
a.WinningBids[b.ID] = auctioneer.WinningBid{
BidderID: bid.BidderID,
ProposalCid: bid.ProposalCid,
DealUID: bid.DealUID,
ErrorCause: bid.ProposalCidDeliveryError,
}
}
}
return nil
})
return
}
// GetFinalizedAuctionBid returns the bid given an auction ID and a bid ID.
// If an auction is not found for id, ErrAuctionNotFound is returned.
// If a bid is not found or id, ErrBidNotFound is returned.
// It also errors if the auction is not finalized or finalized with error.
func (q *Queue) GetFinalizedAuctionBid(
ctx context.Context,
id auction.ID,
bid auction.BidID,
) (*auctioneer.Bid, error) {
a, err := q.GetAuction(ctx, id)
if err != nil {
return nil, err
}
// Check if auction is in good standing
if a.Status != broker.AuctionStatusFinalized {
return nil, errors.New("auction is not finalized")
}
if a.ErrorCause != "" {
return nil, errors.New("auction finalized with error")
}
var matched *auctioneer.Bid
for _, b := range a.Bids {
if b.ID == bid {
matched = &b
break
}
}
if matched == nil {
return nil, ErrBidNotFound
}
return matched, nil
}
// GetProviderFailureRates gets the recent failure rate (wins the auction but
// fails to make the deal) of storage providers.
func (q *Queue) GetProviderFailureRates(ctx context.Context) (map[string]int, error) {
rows, err := q.db.GetRecentWeekFailureRate(ctx)
if err != nil {
return nil, err
}
ret := make(map[string]int, len(rows))
for _, row := range rows {
ret[row.StorageProviderID] = int(row.FailureRatePpm)
}
return ret, nil
}
// GetProviderOnChainEpoches gets the maximum epoches taken to make a deal on chain for storage providers.
func (q *Queue) GetProviderOnChainEpoches(ctx context.Context) (map[string]uint64, error) {
rows, err := q.db.GetRecentWeekMaxOnChainSeconds(ctx)
if err != nil {
return nil, err
}
ret := make(map[string]uint64, len(rows))
for _, row := range rows {
ret[row.StorageProviderID] = uint64(row.MaxOnChainSeconds) / 30
}
return ret, nil
}
// GetProviderWinningRates gets the recent winning rate of storage providers.
func (q *Queue) GetProviderWinningRates(ctx context.Context) (map[string]int, error) {
rows, err := q.db.GetRecentWeekWinningRate(ctx)
if err != nil {
return nil, err
}
ret := make(map[string]int, len(rows))
for _, row := range rows {
ret[row.StorageProviderID] = int(row.WinningRatePpm)
}
return ret, nil
}
// SetProposalCidDelivered saves the proposal CID for the bid.
func (q *Queue) SetProposalCidDelivered(
ctx context.Context,
auctionID auction.ID,
bidID auction.BidID,
identifier string) error {
return q.db.UpdateProposalCid(ctx, db.UpdateProposalCidParams{
ID: bidID,
AuctionID: auctionID,
ProposalCid: sql.NullString{String: identifier, Valid: true},
})
}
// SetProposalCidDeliveryError saves the error happened when delivering the
// proposal cid to the winner.
func (q *Queue) SetProposalCidDeliveryError(
ctx context.Context,
auctionID auction.ID,
bidID auction.BidID,
errCause string) error {
return q.db.UpdateProposalCidDeliveryError(ctx, db.UpdateProposalCidDeliveryErrorParams{
ID: bidID,
AuctionID: auctionID,
ProposalCidDeliveryError: sql.NullString{String: errCause, Valid: true},
})
}
// MarkDealAsConfirmed marks the deal as confirmed by recording its confirmation time.
func (q *Queue) MarkDealAsConfirmed(
ctx context.Context,
auctionID auction.ID,
bidID auction.BidID) error {
return q.db.UpdateDealConfirmedAt(ctx, db.UpdateDealConfirmedAtParams{
ID: bidID,
AuctionID: auctionID,
})
}
// MarkDealAsFailed marks the deal as failed by recording its failed time.
func (q *Queue) MarkDealAsFailed(
ctx context.Context,
auctionID auction.ID,
bidID auction.BidID) error {
return q.db.UpdateDealFailedAt(ctx, db.UpdateDealFailedAtParams{
ID: bidID,
AuctionID: auctionID,
})
}
// SaveStorageProvider saves the storage provider info.
func (q *Queue) SaveStorageProvider(ctx context.Context, id string, version string, dealStartWindow uint64,
cidGravityConfigured, cidGravityStrict bool) error {
return q.db.CreateOrUpdateStorageProvider(ctx, db.CreateOrUpdateStorageProviderParams{
ID: id,
BidbotVersion: version,
DealStartWindow: int64(dealStartWindow),
CidGravityConfigured: cidGravityConfigured,
CidGravityStrict: cidGravityStrict,
})
}
// SetStorageProviderUnhealthy sets the storage provider to be unhealthy at the current point.
func (q *Queue) SetStorageProviderUnhealthy(ctx context.Context, id string, err string) error {
return q.db.SetStorageProviderUnhealthy(ctx, db.SetStorageProviderUnhealthyParams{
ID: id,
LastUnhealthyError: sql.NullString{Valid: true, String: err},
})
}
// SaveBidEvent saves bid events.
func (q *Queue) SaveBidEvent(ctx context.Context, eventType BidEventType, bidID string,
attempts uint32, err string, ts time.Time) error {
return q.db.CreateBidEvent(ctx, db.CreateBidEventParams{
BidID: bidID,
EventType: eventType,
Attempts: sql.NullInt32{Valid: attempts != 0, Int32: int32(attempts)},
Error: sql.NullString{Valid: err != "", String: err},
HappenedAt: ts,
ReceivedAt: time.Now().UTC(),
})
}
func (q *Queue) enqueue(ctx context.Context, qx *db.Queries, a *auctioneer.Auction) {
if err := saveAndTransitionStatus(ctx, qx, a, broker.AuctionStatusStarted); err != nil {
log.Errorf("updating status (started): %v", err)
return
}
select {
case q.jobCh <- a:
log.Debugf("enqueued %s ", a.ID)
default:
log.Debugf("workers are busy; queueing %s ", a.ID)
if err := saveAndTransitionStatus(ctx, qx, a, broker.AuctionStatusQueued); err != nil {
log.Errorf("updating status (queued): %v", err)
}
}
}
func (q *Queue) worker(num int) {
defer q.wg.Done()
for {
select {
case <-q.ctx.Done():
return
case a := <-q.jobCh:
log.Infof("worker %d started auction %s", num, a.ID)
// Handle the auction with the handler func
wbs, err := q.handler(q.ctx, *a, func(bid auctioneer.Bid) error {
return q.addBid(a, bid)
})
if err != nil {
a.ErrorCause = err.Error()
log.Debugf("auction %s failed: %s", a.ID, a.ErrorCause)
}
// Update winning bids; some bids may have been processed even if there was an error
_ = storeutil.WithTx(q.ctx, q.conn, func(tx *sql.Tx) error {
txn := q.db.WithTx(tx)
for bidID, wb := range wbs {
updated, err := txn.UpdateWinningBid(q.ctx, db.UpdateWinningBidParams{
ID: bidID,
AuctionID: a.ID,
WonReason: sql.NullString{String: wb.WinningReason, Valid: true},
})
// failing to write db is not the end of the world. just move on.
if err != nil {
log.Errorf("error update winning bid: %v", err)
}
if updated < 1 {
log.Errorf("bid %v not found for auction %v", bidID, a.ID)
}
}
return nil
})
a.WinningBids = wbs
q.saveAndFinalizeAuction(a)
select {
case q.tickCh <- struct{}{}:
default:
}
}
}
}
func (q *Queue) saveAndFinalizeAuction(a *auctioneer.Auction) {
if err := saveAndTransitionStatus(q.ctx, q.db, a, broker.AuctionStatusFinalized); err != nil {
log.Errorf("updating status (%s): %v", broker.AuctionStatusFinalized, err)
return
}
// Finish auction with the finalizer func
if err := q.finalizer(q.ctx, a); err != nil {
a.ErrorCause = err.Error()
// Save error
if err := saveAndTransitionStatus(q.ctx, q.db, a, a.Status); err != nil {
log.Errorf("saving finalizer error: %v", err)
}
}
}
func (q *Queue) addBid(a *auctioneer.Auction, bid auctioneer.Bid) error {
start := time.Now()
if a.Status != broker.AuctionStatusStarted {
return errors.New("auction has not started")
}
// This locking is necessary since `addBid` is called by `bidHandler` which
// is called concurrently by `go-libp2p-pubsub-rpc` subscription processing mechanism.
// This "add bid to map" logic shouldn't live here since forces this shared lock
// to be used for all auctions, not per auction. And since the domain-level auctioneer.Auction
// struct is used as a DTO we can't enhance it safely.
// We should move this code to the `bidHandler` but that means checking carefully some
// `auctioneer.Auction` copies that we have in many callback indirections.
// This isn't an urgent change, nor this lock produce contention at all; but it's just odd.
q.addBidLock.Lock()
if a.Bids == nil {
a.Bids = make(map[auction.BidID]auctioneer.Bid)
}
a.Bids[bid.ID] = bid
q.addBidLock.Unlock()
if err := q.db.CreateBid(q.ctx, db.CreateBidParams{
ID: bid.ID,
AuctionID: a.ID,
StorageProviderID: bid.StorageProviderID,
WalletAddrSig: bid.WalletAddrSig,
BidderID: peer.Encode(bid.BidderID),
AskPrice: bid.AskPrice,
VerifiedAskPrice: bid.VerifiedAskPrice,
StartEpoch: int64(bid.StartEpoch),
FastRetrieval: bid.FastRetrieval,
ReceivedAt: bid.ReceivedAt,
}); err != nil {
return fmt.Errorf("saving bid: %v", err)
}
log.Debugf("adding bid %s of %s took %dms", bid.ID, bid.BidderID, time.Since(start).Milliseconds())
return nil
}
func (q *Queue) start() {
t := time.NewTimer(StartDelay)
for {
select {
case <-q.ctx.Done():
t.Stop()
return
case <-t.C:
q.processNext()
case <-q.tickCh:
q.processNext()
}
}
}
func (q *Queue) processNext() {
err := storeutil.WithTx(q.ctx, q.conn, func(tx *sql.Tx) error {
txn := q.db.WithTx(tx)
a, err := txn.GetNextReadyToExecute(q.ctx, stuckSeconds)
if err == sql.ErrNoRows {
return nil
} else if err != nil {
return fmt.Errorf("getting next in queue: %v", err)
}
log.Debugf("got auction from DB: %v", a.ID)
auction, err := auctionFromDb(a)
if err != nil {
return fmt.Errorf("auction from DB: %v", err)
}
q.enqueue(q.ctx, txn, auction)
return nil
})
if err != nil {
log.Error(err)
}
}
// saveAndTransitionStatus sets a new status, updating the started time if needed.
// Do not directly edit the auction status because it is needed to determine the correct status transition.
// Pass the desired new status with newStatus.
func saveAndTransitionStatus(ctx context.Context,
q *db.Queries,
a *auctioneer.Auction,
newStatus broker.AuctionStatus) error {
if a.Status != newStatus {
a.Status = newStatus
return q.UpdateAuctionStatusAndError(ctx, db.UpdateAuctionStatusAndErrorParams{
ID: a.ID,
Status: a.Status,
ErrorCause: a.ErrorCause,
})
}
return nil
}
func auctionFromDb(a db.Auction) (*auctioneer.Auction, error) {
payloadCid, err := cid.Parse(a.PayloadCid)
if err != nil {
return nil, fmt.Errorf("parsing payload cid: %v", err)
}
var sources auction.Sources
if a.CarUrl != "" {
u, err := url.Parse(a.CarUrl)
if err != nil {
return nil, fmt.Errorf("parsing car url: %v", err)
}
sources.CARURL = &auction.CARURL{URL: *u}
}
if a.CarIpfsCid != "" && a.CarIpfsAddrs != nil {
ipfsCid, err := cid.Parse(a.CarIpfsCid)
if err != nil {
return nil, fmt.Errorf("parsing car ipfs cid: %v", err)
}
var maddrs []multiaddr.Multiaddr
for _, s := range a.CarIpfsAddrs {
maddr, err := multiaddr.NewMultiaddr(s)
if err != nil {
return nil, fmt.Errorf("parsing car ipfs multiaddr: %v", err)
}
maddrs = append(maddrs, maddr)
}
sources.CARIPFS = &auction.CARIPFS{Cid: ipfsCid, Multiaddrs: maddrs}
}
if err := sources.Validate(); err != nil {
return nil, fmt.Errorf("validating sources: %v", err)
}
return &auctioneer.Auction{
ID: a.ID,
BatchID: a.BatchID,
DealSize: uint64(a.DealSize),
DealDuration: a.DealDuration,
DealReplication: uint32(a.DealReplication),
DealVerified: a.DealVerified,
FilEpochDeadline: a.FilEpochDeadline,
ExcludedStorageProviders: a.ExcludedStorageProviders,
Providers: a.Providers,
PayloadCid: payloadCid,
Sources: sources,
ClientAddress: a.ClientAddress,
Status: a.Status,
StartedAt: a.StartedAt,
UpdatedAt: a.UpdatedAt,
Duration: time.Duration(a.Duration),
ErrorCause: a.ErrorCause,
}, nil
}
func bidFromDb(bid db.Bid) (*auctioneer.Bid, error) {
bidderID, err := peer.Decode(bid.BidderID)
if err != nil {
return nil, fmt.Errorf("invalid bidder ID: %v", err)
}
b := &auctioneer.Bid{
ID: bid.ID,
StorageProviderID: bid.StorageProviderID,
WalletAddrSig: bid.WalletAddrSig,
BidderID: bidderID,
AskPrice: bid.AskPrice,
VerifiedAskPrice: bid.VerifiedAskPrice,
StartEpoch: uint64(bid.StartEpoch),
FastRetrieval: bid.FastRetrieval,
ReceivedAt: bid.ReceivedAt,
}
if bid.WonAt.Valid {
b.WonAt = bid.WonAt.Time
}
if bid.ProposalCid.Valid {
if _, err := uuid.Parse(bid.ProposalCid.String); err == nil {
b.DealUID = bid.ProposalCid.String
} else {
proposalCid, err := cid.Parse(bid.ProposalCid.String)
if err != nil {
return nil, fmt.Errorf("parsing proposal cid: %v", err)
}
b.ProposalCid = proposalCid
}
}
if bid.ProposalCidDeliveryError.Valid {
b.ProposalCidDeliveryError = bid.ProposalCidDeliveryError.String
}
if bid.ProposalCidDeliveredAt.Valid {
b.ProposalCidDeliveredAt = bid.ProposalCidDeliveredAt.Time
}
return b, nil
}