Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rfq-relayer): add balances mutex #3039

Merged
merged 5 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 43 additions & 10 deletions services/rfq/relayer/service/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,36 @@
return nil
}

// check balance and mark it as CommitPending
err = q.commitPendingBalance(ctx, span, &request)
if err != nil {
return fmt.Errorf("could not commit pending balance: %w", err)
}

Check warning on line 169 in services/rfq/relayer/service/handlers.go

View check run for this annotation

Codecov / codecov/patch

services/rfq/relayer/service/handlers.go#L166-L169

Added lines #L166 - L169 were not covered by tests

// immediately forward the request to handleCommitPending
span.AddEvent("forwarding to handleCommitPending")
fwdErr := q.Forward(ctx, request)
if fwdErr != nil {
logger.Errorf("could not forward to handle commit pending: %w", fwdErr)
span.AddEvent("could not forward to handle commit pending")
}

Check warning on line 177 in services/rfq/relayer/service/handlers.go

View check run for this annotation

Codecov / codecov/patch

services/rfq/relayer/service/handlers.go#L172-L177

Added lines #L172 - L177 were not covered by tests

return nil

Check warning on line 179 in services/rfq/relayer/service/handlers.go

View check run for this annotation

Codecov / codecov/patch

services/rfq/relayer/service/handlers.go#L179

Added line #L179 was not covered by tests
}

// commitPendingBalance locks the balance and marks the request as CommitPending.
func (q *QuoteRequestHandler) commitPendingBalance(ctx context.Context, span trace.Span, request *reldb.QuoteRequest) (err error) {
// lock the consumed balance
key := getBalanceMtxKey(q.Dest.ChainID, request.Transaction.DestToken)
span.SetAttributes(attribute.String("balance_lock_key", key))
unlocker, ok := q.balanceMtx.TryLock(key)
if !ok {
// balance is locked due to concurrent request, try again later
span.SetAttributes(attribute.Bool("locked", true))
return nil
}
defer unlocker.Unlock()

Check warning on line 194 in services/rfq/relayer/service/handlers.go

View check run for this annotation

Codecov / codecov/patch

services/rfq/relayer/service/handlers.go#L183-L194

Added lines #L183 - L194 were not covered by tests
// get destination committable balance
committableBalance, err := q.Inventory.GetCommittableBalance(ctx, int(q.Dest.ChainID), request.Transaction.DestToken)
if errors.Is(err, inventory.ErrUnsupportedChain) {
Expand Down Expand Up @@ -211,14 +241,6 @@
return fmt.Errorf("could not update request status: %w", err)
}

// immediately forward the request to handleCommitPending
span.AddEvent("forwarding to handleCommitPending")
fwdErr := q.Forward(ctx, request)
if fwdErr != nil {
logger.Errorf("could not forward to handle commit pending: %w", fwdErr)
span.AddEvent("could not forward to handle commit pending")
}

return nil
}

Expand Down Expand Up @@ -487,12 +509,23 @@
// Error Handlers Only from this point below.
//
// handleNotEnoughInventory handles the not enough inventory status.
func (q *QuoteRequestHandler) handleNotEnoughInventory(ctx context.Context, _ trace.Span, request reldb.QuoteRequest) (err error) {
func (q *QuoteRequestHandler) handleNotEnoughInventory(ctx context.Context, span trace.Span, request reldb.QuoteRequest) (err error) {
// acquire balance lock
key := getBalanceMtxKey(q.Dest.ChainID, request.Transaction.DestToken)
span.SetAttributes(attribute.String("balance_lock_key", key))
unlocker, ok := q.balanceMtx.TryLock(key)
if !ok {
// balance is locked due to concurrent request, try again later
span.SetAttributes(attribute.Bool("locked", true))
return nil
}
defer unlocker.Unlock()

// commit destination balance

Check warning on line 524 in services/rfq/relayer/service/handlers.go

View check run for this annotation

Codecov / codecov/patch

services/rfq/relayer/service/handlers.go#L512-L524

Added lines #L512 - L524 were not covered by tests
committableBalance, err := q.Inventory.GetCommittableBalance(ctx, int(q.Dest.ChainID), request.Transaction.DestToken)
if err != nil {
return fmt.Errorf("could not get committable balance: %w", err)
}
// if committableBalance > destAmount
if committableBalance.Cmp(request.Transaction.DestAmount) > 0 {
err = q.db.UpdateQuoteRequestStatus(ctx, request.TransactionID, reldb.CommittedPending, &request.Status)
if err != nil {
Expand Down
7 changes: 5 additions & 2 deletions services/rfq/relayer/service/relayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,10 @@
decimalsCache *xsync.MapOf[string, *uint8]
// semaphore is used to limit the number of concurrent requests
semaphore *semaphore.Weighted
// handlerMtx is used to synchronize handling of relay requests
handlerMtx mapmutex.StringMapMutex
// handlerMtx is used to synchronize handling of relay requests, keyed on transaction ID
handlerMtx mapmutex.StringMapMutex
// balanceMtx is used to synchronize balance requests, keyed on a chainID and tokenAddress pair
balanceMtx mapmutex.StringMapMutex
otelRecorder iOtelRecorder
}

Expand Down Expand Up @@ -165,6 +167,7 @@
apiClient: apiClient,
semaphore: semaphore.NewWeighted(maxConcurrentRequests),
handlerMtx: mapmutex.NewStringMapMutex(),
balanceMtx: mapmutex.NewStringMapMutex(),

Check warning on line 170 in services/rfq/relayer/service/relayer.go

View check run for this annotation

Codecov / codecov/patch

services/rfq/relayer/service/relayer.go#L170

Added line #L170 was not covered by tests
otelRecorder: otelRecorder,
}
return &rel, nil
Expand Down
7 changes: 7 additions & 0 deletions services/rfq/relayer/service/statushandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@
mutexMiddlewareFunc func(func(ctx context.Context, span trace.Span, req reldb.QuoteRequest) error) func(ctx context.Context, span trace.Span, req reldb.QuoteRequest) error
// handlerMtx is the mutex for relaying.
handlerMtx mapmutex.StringMapMutex
// balanceMtx is the mutex for balances.
balanceMtx mapmutex.StringMapMutex
}

func getBalanceMtxKey(chainID uint32, token common.Address) string {
return fmt.Sprintf("%d-%s", chainID, token.Hex())

Check warning on line 60 in services/rfq/relayer/service/statushandler.go

View check run for this annotation

Codecov / codecov/patch

services/rfq/relayer/service/statushandler.go#L59-L60

Added lines #L59 - L60 were not covered by tests
}

// Handler is the handler for a quote request.
Expand Down Expand Up @@ -81,6 +87,7 @@
apiClient: r.apiClient,
mutexMiddlewareFunc: r.mutexMiddleware,
handlerMtx: r.handlerMtx,
balanceMtx: r.balanceMtx,

Check warning on line 90 in services/rfq/relayer/service/statushandler.go

View check run for this annotation

Codecov / codecov/patch

services/rfq/relayer/service/statushandler.go#L90

Added line #L90 was not covered by tests
}

// wrap in deadline middleware since the relay has not yet happened
Expand Down
Loading