-
Notifications
You must be signed in to change notification settings - Fork 98
feat(workers): Add canvas node cleanup worker (#1196) #3164
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
Open
abhishek818
wants to merge
2
commits into
superplanehq:main
Choose a base branch
from
abhishek818:feat/canvas-node-cleanup-worker
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.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| package workers | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "time" | ||
|
|
||
| "github.com/google/uuid" | ||
| "golang.org/x/sync/semaphore" | ||
| "gorm.io/gorm" | ||
|
|
||
| log "github.com/sirupsen/logrus" | ||
| "github.com/superplanehq/superplane/pkg/database" | ||
| "github.com/superplanehq/superplane/pkg/models" | ||
| "github.com/superplanehq/superplane/pkg/telemetry" | ||
| ) | ||
|
|
||
| type CanvasNodeCleanupWorker struct { | ||
| semaphore *semaphore.Weighted | ||
| logger *log.Entry | ||
| maxResourcesPerTick int | ||
| } | ||
|
|
||
| func NewCanvasNodeCleanupWorker() *CanvasNodeCleanupWorker { | ||
| return &CanvasNodeCleanupWorker{ | ||
| semaphore: semaphore.NewWeighted(25), | ||
| logger: log.WithFields(log.Fields{"worker": "CanvasNodeCleanupWorker"}), | ||
| maxResourcesPerTick: 500, | ||
| } | ||
| } | ||
|
|
||
| func (w *CanvasNodeCleanupWorker) Start(ctx context.Context) { | ||
| ticker := time.NewTicker(30 * time.Second) | ||
| defer ticker.Stop() | ||
|
|
||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| return | ||
| case <-ticker.C: | ||
| tickStart := time.Now() | ||
| nodes, err := models.ListDeletedCanvasNodes() | ||
| if err != nil { | ||
| w.logger.Errorf("Error finding deleted nodes: %v", err) | ||
| continue | ||
| } | ||
|
|
||
| telemetry.RecordNodeCleanupWorkerNodesCount(context.Background(), len(nodes)) | ||
|
|
||
| for _, node := range nodes { | ||
| if err := w.semaphore.Acquire(context.Background(), 1); err != nil { | ||
| w.logger.Errorf("Error acquiring semaphore: %v", err) | ||
| continue | ||
| } | ||
|
|
||
| go func(node models.CanvasNode) { | ||
| defer w.semaphore.Release(1) | ||
|
|
||
| if err := w.LockAndProcessNode(node); err != nil { | ||
| w.logger.Errorf("Error processing node %s from canvas %s: %v", node.NodeID, node.WorkflowID, err) | ||
| } | ||
| }(node) | ||
| } | ||
|
|
||
| telemetry.RecordNodeCleanupWorkerTickDuration(context.Background(), time.Since(tickStart)) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func (w *CanvasNodeCleanupWorker) LockAndProcessNode(node models.CanvasNode) error { | ||
| return database.Conn().Transaction(func(tx *gorm.DB) error { | ||
| lockedNode, err := models.LockDeletedCanvasNode(tx, node.WorkflowID, node.NodeID) | ||
| if err != nil { | ||
| w.logger.Infof("Node %s from canvas %s already being processed - skipping", node.NodeID, node.WorkflowID) | ||
| return nil | ||
| } | ||
|
|
||
| w.logger.Infof("Processing deleted node %s from canvas %s", lockedNode.NodeID, lockedNode.WorkflowID) | ||
| return w.processNode(tx, *lockedNode) | ||
| }) | ||
| } | ||
|
|
||
| func (w *CanvasNodeCleanupWorker) processNode(tx *gorm.DB, node models.CanvasNode) error { | ||
| if !node.DeletedAt.Valid { | ||
| w.logger.Infof("Skipping non-deleted node %s from canvas %s", node.NodeID, node.WorkflowID) | ||
| return nil | ||
| } | ||
|
|
||
| resourcesDeleted, allResourcesDeleted, err := w.deleteNodeResourcesBatched(tx, node.WorkflowID, node.NodeID, w.maxResourcesPerTick) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to delete resources for node %s: %w", node.NodeID, err) | ||
| } | ||
|
|
||
| if !allResourcesDeleted { | ||
| w.logger.Infof("Partially cleaned node %s from canvas %s (deleted %d resources, more remain)", node.NodeID, node.WorkflowID, resourcesDeleted) | ||
| return nil | ||
| } | ||
|
|
||
| if err := tx.Unscoped().Where("workflow_id = ? AND node_id = ?", node.WorkflowID, node.NodeID).Delete(&models.CanvasNode{}).Error; err != nil { | ||
| return fmt.Errorf("failed to delete canvas node %s: %w", node.NodeID, err) | ||
| } | ||
|
|
||
| w.logger.Infof("Successfully cleaned up node %s from canvas %s (deleted %d resources)", node.NodeID, node.WorkflowID, resourcesDeleted) | ||
| return nil | ||
| } | ||
|
|
||
| func (w *CanvasNodeCleanupWorker) deleteNodeResourcesBatched(tx *gorm.DB, workflowID uuid.UUID, nodeID string, maxResources int) (resourcesDeleted int, allResourcesDeleted bool, err error) { | ||
| resourceTypes := []struct { | ||
| model any | ||
| tableName string | ||
| }{ | ||
| {&models.CanvasNodeRequest{}, "canvas_node_requests"}, | ||
| {&models.CanvasNodeExecutionKV{}, "canvas_node_execution_kvs"}, | ||
| {&models.CanvasNodeExecution{}, "canvas_node_executions"}, | ||
| {&models.CanvasNodeQueueItem{}, "canvas_node_queue_items"}, | ||
| {&models.CanvasEvent{}, "canvas_events"}, | ||
| } | ||
|
|
||
| totalDeleted := 0 | ||
| allDeleted := true | ||
|
|
||
| for _, resourceType := range resourceTypes { | ||
| if totalDeleted >= maxResources { | ||
| allDeleted = false | ||
| break | ||
| } | ||
|
|
||
| remaining := maxResources - totalDeleted | ||
|
|
||
| // Delete in batches with LIMIT | ||
| result := tx.Unscoped().Where("workflow_id = ? AND node_id = ?", workflowID, nodeID).Limit(remaining).Delete(resourceType.model) | ||
| if result.Error != nil { | ||
| return totalDeleted, false, fmt.Errorf("failed to delete %s: %w", resourceType.tableName, result.Error) | ||
| } | ||
|
|
||
| deleted := int(result.RowsAffected) | ||
| totalDeleted += deleted | ||
|
|
||
| if deleted != remaining { | ||
| continue | ||
| } | ||
|
|
||
| var count int64 | ||
|
|
||
| if err := tx.Unscoped().Model(resourceType.model).Where("workflow_id = ? AND node_id = ?", workflowID, nodeID).Count(&count).Error; err != nil { | ||
| return totalDeleted, false, fmt.Errorf("failed to count remaining %s: %w", resourceType.tableName, err) | ||
| } | ||
|
|
||
| if count > 0 { | ||
| allDeleted = false | ||
| break | ||
| } | ||
| } | ||
|
|
||
| return totalDeleted, allDeleted, nil | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.