Configurable background task execution

This commit is contained in:
Lorenzo Bolla
2021-09-08 15:50:54 +02:00
parent bd4c3a246d
commit 9b28d8984f
18 changed files with 427 additions and 214 deletions

View File

@@ -3,7 +3,9 @@ package api
import (
"fmt"
"log"
"sort"
"strings"
"github.com/aptly-dev/aptly/aptly"
"github.com/aptly-dev/aptly/deb"
@@ -97,11 +99,11 @@ func releaseDatabaseConnection() error {
// runs tasks in background. Acquires database connection first.
func runTaskInBackground(name string, resources []string, proc task.Process) (task.Task, *task.ResourceConflictError) {
return context.TaskList().RunTaskInBackground(name, resources, func(out *task.Output, detail *task.Detail) error {
return context.TaskList().RunTaskInBackground(name, resources, func(out aptly.Progress, detail *task.Detail) (int, error) {
err := acquireDatabaseConnection()
if err != nil {
return err
return -1, err
}
defer releaseDatabaseConnection()
@@ -109,6 +111,39 @@ func runTaskInBackground(name string, resources []string, proc task.Process) (ta
})
}
func truthy(value string) bool {
switch strings.ToLower(value) {
case "y", "yes", "t", "true":
return true
}
return false
}
func maybeRunTaskInBackground(c *gin.Context, name string, resources []string, proc task.Process) {
// Run this task in background if configured globally or per-request
background := context.Config().AsyncAPI || truthy(c.Query("_async"))
if background {
log.Println("Executing task asynchronously")
task, conflictErr := runTaskInBackground(name, resources, proc)
if conflictErr != nil {
c.AbortWithError(409, conflictErr)
return
}
c.JSON(202, task)
} else {
log.Println("Executing task synchronously")
out := context.Progress()
detail := task.Detail{}
retCode, err := proc(out, &detail)
if err != nil {
c.AbortWithError(retCode, err)
return
}
response := detail.Load()
c.JSON(retCode, response)
}
}
// Common piece of code to show list of packages,
// with searching & details if requested
func showPackages(c *gin.Context, reflist *deb.PackageRefList, collectionFactory *deb.CollectionFactory) {