-
-
Notifications
You must be signed in to change notification settings - Fork 49
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: add parallel bulk processing #1568
Draft
altitude
wants to merge
1
commit into
main
Choose a base branch
from
feat/ledger-bulk-parallel
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,18 +5,17 @@ import ( | |
"encoding/json" | ||
"fmt" | ||
"math/big" | ||
"sync" | ||
|
||
"github.com/formancehq/ledger/internal/opentelemetry/tracer" | ||
|
||
sharedapi "github.com/formancehq/stack/libs/go-libs/api" | ||
|
||
ledger "github.com/formancehq/ledger/internal" | ||
"github.com/formancehq/ledger/internal/engine" | ||
"github.com/formancehq/ledger/internal/machine" | ||
"github.com/formancehq/ledger/internal/opentelemetry/tracer" | ||
sharedapi "github.com/formancehq/stack/libs/go-libs/api" | ||
"github.com/formancehq/stack/libs/go-libs/metadata" | ||
|
||
ledger "github.com/formancehq/ledger/internal" | ||
"github.com/formancehq/ledger/internal/api/backend" | ||
"github.com/formancehq/ledger/internal/engine/command" | ||
"github.com/formancehq/stack/libs/go-libs/metadata" | ||
) | ||
|
||
const ( | ||
|
@@ -42,168 +41,193 @@ type Result struct { | |
ResponseType string `json:"responseType"` // Added for sdk generation (discriminator in oneOf) | ||
} | ||
|
||
func ProcessBulk(ctx context.Context, l backend.Ledger, bulk Bulk, continueOnFailure bool) ([]Result, bool, error) { | ||
func processBulkElement( | ||
ctx context.Context, | ||
l backend.Ledger, | ||
parameters command.Parameters, | ||
element Element, | ||
i int, | ||
) (error, string, any) { | ||
switch element.Action { | ||
case ActionCreateTransaction: | ||
req := &ledger.TransactionRequest{} | ||
if err := json.Unmarshal(element.Data, req); err != nil { | ||
return fmt.Errorf("error parsing element %d: %s", i, err), "", nil | ||
} | ||
rs := req.ToRunScript() | ||
|
||
tx, err := l.CreateTransaction(ctx, parameters, *rs) | ||
if err != nil { | ||
var code string | ||
switch { | ||
case machine.IsInsufficientFundError(err): | ||
code = ErrInsufficientFund | ||
case engine.IsCommandError(err): | ||
code = ErrValidation | ||
default: | ||
code = sharedapi.ErrorInternal | ||
} | ||
return err, code, nil | ||
} else { | ||
return nil, "", tx | ||
} | ||
case ActionAddMetadata: | ||
type addMetadataRequest struct { | ||
TargetType string `json:"targetType"` | ||
TargetID json.RawMessage `json:"targetId"` | ||
Metadata metadata.Metadata `json:"metadata"` | ||
} | ||
req := &addMetadataRequest{} | ||
if err := json.Unmarshal(element.Data, req); err != nil { | ||
return fmt.Errorf("error parsing element %d: %s", i, err), "", nil | ||
} | ||
|
||
var targetID any | ||
switch req.TargetType { | ||
case ledger.MetaTargetTypeAccount: | ||
targetID = "" | ||
case ledger.MetaTargetTypeTransaction: | ||
targetID = big.NewInt(0) | ||
} | ||
if err := json.Unmarshal(req.TargetID, &targetID); err != nil { | ||
return err, "", nil | ||
} | ||
|
||
if err := l.SaveMeta(ctx, parameters, req.TargetType, targetID, req.Metadata); err != nil { | ||
var code string | ||
switch { | ||
case command.IsSaveMetaError(err, command.ErrSaveMetaCodeTransactionNotFound): | ||
code = sharedapi.ErrorCodeNotFound | ||
default: | ||
code = sharedapi.ErrorInternal | ||
} | ||
return err, code, nil | ||
} else { | ||
return nil, "", nil | ||
} | ||
case ActionRevertTransaction: | ||
type revertTransactionRequest struct { | ||
ID *big.Int `json:"id"` | ||
Force bool `json:"force"` | ||
AtEffectiveDate bool `json:"atEffectiveDate"` | ||
} | ||
req := &revertTransactionRequest{} | ||
if err := json.Unmarshal(element.Data, req); err != nil { | ||
return fmt.Errorf("error parsing element %d: %s", i, err), "", nil | ||
} | ||
|
||
tx, err := l.RevertTransaction(ctx, parameters, req.ID, req.Force, req.AtEffectiveDate) | ||
if err != nil { | ||
var code string | ||
switch { | ||
case engine.IsCommandError(err): | ||
code = ErrValidation | ||
default: | ||
code = sharedapi.ErrorInternal | ||
} | ||
return err, code, nil | ||
} else { | ||
return nil, "", tx | ||
} | ||
case ActionDeleteMetadata: | ||
type deleteMetadataRequest struct { | ||
TargetType string `json:"targetType"` | ||
TargetID json.RawMessage `json:"targetId"` | ||
Key string `json:"key"` | ||
} | ||
req := &deleteMetadataRequest{} | ||
if err := json.Unmarshal(element.Data, req); err != nil { | ||
return err, "", nil | ||
} | ||
|
||
var targetID any | ||
switch req.TargetType { | ||
case ledger.MetaTargetTypeAccount: | ||
targetID = "" | ||
case ledger.MetaTargetTypeTransaction: | ||
targetID = big.NewInt(0) | ||
} | ||
if err := json.Unmarshal(req.TargetID, &targetID); err != nil { | ||
return err, "", nil | ||
} | ||
|
||
err := l.DeleteMetadata(ctx, parameters, req.TargetType, targetID, req.Key) | ||
if err != nil { | ||
var code string | ||
switch { | ||
case command.IsDeleteMetaError(err, command.ErrSaveMetaCodeTransactionNotFound): | ||
code = sharedapi.ErrorCodeNotFound | ||
default: | ||
code = sharedapi.ErrorInternal | ||
} | ||
return err, code, nil | ||
} else { | ||
return nil, "", nil | ||
} | ||
} | ||
|
||
return fmt.Errorf("unknown action %s", element.Action), "", nil | ||
} | ||
|
||
func ProcessBulk( | ||
ctx context.Context, | ||
ledger backend.Ledger, | ||
bulk Bulk, | ||
continueOnFailure bool, | ||
parallel bool, | ||
) ([]Result, bool, error) { | ||
|
||
ctx, span := tracer.Start(ctx, "Bulk") | ||
defer span.End() | ||
|
||
ret := make([]Result, 0, len(bulk)) | ||
ret := make([]Result, len(bulk)) | ||
|
||
errorsInBulk := false | ||
var bulkError = func(action, code string, err error) { | ||
ret = append(ret, Result{ | ||
|
||
var bulkError = func(index int, action, code string, err error) { | ||
ret[index] = Result{ | ||
ErrorCode: code, | ||
ErrorDescription: err.Error(), | ||
ResponseType: "ERROR", | ||
}) | ||
} | ||
errorsInBulk = true | ||
} | ||
|
||
var bulkSuccess = func(index int, action string, data any) { | ||
ret[index] = Result{ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since you allow parallelism, you need to use a lock on the |
||
Data: data, | ||
ResponseType: action, | ||
} | ||
} | ||
|
||
wg := sync.WaitGroup{} | ||
|
||
for i, element := range bulk { | ||
parameters := command.Parameters{ | ||
DryRun: false, | ||
IdempotencyKey: element.IdempotencyKey, | ||
} | ||
|
||
switch element.Action { | ||
case ActionCreateTransaction: | ||
req := &ledger.TransactionRequest{} | ||
if err := json.Unmarshal(element.Data, req); err != nil { | ||
return nil, errorsInBulk, fmt.Errorf("error parsing element %d: %s", i, err) | ||
} | ||
rs := req.ToRunScript() | ||
wg.Add(1) | ||
|
||
tx, err := l.CreateTransaction(ctx, parameters, *rs) | ||
go func(element Element, index int) { | ||
err, code, data := processBulkElement(ctx, ledger, parameters, element, index) | ||
if err != nil { | ||
var code string | ||
switch { | ||
case machine.IsInsufficientFundError(err): | ||
code = ErrInsufficientFund | ||
case engine.IsCommandError(err): | ||
code = ErrValidation | ||
default: | ||
code = sharedapi.ErrorInternal | ||
} | ||
bulkError(element.Action, code, err) | ||
if !continueOnFailure { | ||
return ret, errorsInBulk, nil | ||
} | ||
bulkError(index, element.Action, code, err) | ||
} else { | ||
ret = append(ret, Result{ | ||
Data: tx, | ||
ResponseType: element.Action, | ||
}) | ||
} | ||
case ActionAddMetadata: | ||
type addMetadataRequest struct { | ||
TargetType string `json:"targetType"` | ||
TargetID json.RawMessage `json:"targetId"` | ||
Metadata metadata.Metadata `json:"metadata"` | ||
} | ||
req := &addMetadataRequest{} | ||
if err := json.Unmarshal(element.Data, req); err != nil { | ||
return nil, errorsInBulk, fmt.Errorf("error parsing element %d: %s", i, err) | ||
bulkSuccess(index, element.Action, data) | ||
} | ||
wg.Done() | ||
}(element, i) | ||
|
||
var targetID any | ||
switch req.TargetType { | ||
case ledger.MetaTargetTypeAccount: | ||
targetID = "" | ||
case ledger.MetaTargetTypeTransaction: | ||
targetID = big.NewInt(0) | ||
} | ||
if err := json.Unmarshal(req.TargetID, &targetID); err != nil { | ||
return nil, errorsInBulk, err | ||
} | ||
|
||
if err := l.SaveMeta(ctx, parameters, req.TargetType, targetID, req.Metadata); err != nil { | ||
var code string | ||
switch { | ||
case command.IsSaveMetaError(err, command.ErrSaveMetaCodeTransactionNotFound): | ||
code = sharedapi.ErrorCodeNotFound | ||
default: | ||
code = sharedapi.ErrorInternal | ||
} | ||
bulkError(element.Action, code, err) | ||
if !continueOnFailure { | ||
return ret, errorsInBulk, nil | ||
} | ||
} else { | ||
ret = append(ret, Result{ | ||
ResponseType: element.Action, | ||
}) | ||
} | ||
case ActionRevertTransaction: | ||
type revertTransactionRequest struct { | ||
ID *big.Int `json:"id"` | ||
Force bool `json:"force"` | ||
AtEffectiveDate bool `json:"atEffectiveDate"` | ||
} | ||
req := &revertTransactionRequest{} | ||
if err := json.Unmarshal(element.Data, req); err != nil { | ||
return nil, errorsInBulk, fmt.Errorf("error parsing element %d: %s", i, err) | ||
} | ||
|
||
tx, err := l.RevertTransaction(ctx, parameters, req.ID, req.Force, req.AtEffectiveDate) | ||
if err != nil { | ||
var code string | ||
switch { | ||
case engine.IsCommandError(err): | ||
code = ErrValidation | ||
default: | ||
code = sharedapi.ErrorInternal | ||
} | ||
bulkError(element.Action, code, err) | ||
if !continueOnFailure { | ||
return ret, errorsInBulk, nil | ||
} | ||
} else { | ||
ret = append(ret, Result{ | ||
Data: tx, | ||
ResponseType: element.Action, | ||
}) | ||
} | ||
case ActionDeleteMetadata: | ||
type deleteMetadataRequest struct { | ||
TargetType string `json:"targetType"` | ||
TargetID json.RawMessage `json:"targetId"` | ||
Key string `json:"key"` | ||
} | ||
req := &deleteMetadataRequest{} | ||
if err := json.Unmarshal(element.Data, req); err != nil { | ||
return nil, errorsInBulk, fmt.Errorf("error parsing element %d: %s", i, err) | ||
} | ||
|
||
var targetID any | ||
switch req.TargetType { | ||
case ledger.MetaTargetTypeAccount: | ||
targetID = "" | ||
case ledger.MetaTargetTypeTransaction: | ||
targetID = big.NewInt(0) | ||
} | ||
if err := json.Unmarshal(req.TargetID, &targetID); err != nil { | ||
return nil, errorsInBulk, err | ||
} | ||
|
||
err := l.DeleteMetadata(ctx, parameters, req.TargetType, targetID, req.Key) | ||
if err != nil { | ||
var code string | ||
switch { | ||
case command.IsDeleteMetaError(err, command.ErrSaveMetaCodeTransactionNotFound): | ||
code = sharedapi.ErrorCodeNotFound | ||
default: | ||
code = sharedapi.ErrorInternal | ||
} | ||
bulkError(element.Action, code, err) | ||
if !continueOnFailure { | ||
return ret, errorsInBulk, nil | ||
} | ||
} else { | ||
ret = append(ret, Result{ | ||
ResponseType: element.Action, | ||
}) | ||
} | ||
if !parallel { | ||
wg.Wait() | ||
} | ||
} | ||
|
||
if parallel { | ||
wg.Wait() | ||
} | ||
|
||
return ret, errorsInBulk, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well-structured function for processing individual bulk elements. Consider adding detailed logging for each action type to improve traceability.