43 lines
1.1 KiB
Go
43 lines
1.1 KiB
Go
package job
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/example/storage-appliance/internal/domain"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Runner struct {
|
|
DB *sql.DB
|
|
}
|
|
|
|
func (r *Runner) Enqueue(ctx context.Context, j domain.Job) (string, error) {
|
|
id := uuid.New().String()
|
|
if j.ID == "" {
|
|
j.ID = domain.UUID(id)
|
|
}
|
|
j.Status = "queued"
|
|
j.CreatedAt = time.Now()
|
|
j.UpdatedAt = time.Now()
|
|
_, err := r.DB.ExecContext(ctx, `INSERT INTO jobs (id, type, status, progress, owner, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
j.ID, j.Type, j.Status, j.Progress, j.Owner, j.CreatedAt, j.UpdatedAt)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
log.Printf("enqueued job %s (%s)", j.ID, j.Type)
|
|
// run async worker (very simple worker for skeleton)
|
|
go func() {
|
|
time.Sleep(1 * time.Second)
|
|
r.updateStatus(ctx, j.ID, "succeeded", 100)
|
|
}()
|
|
return id, nil
|
|
}
|
|
|
|
func (r *Runner) updateStatus(ctx context.Context, id domain.UUID, status string, progress int) error {
|
|
_, err := r.DB.ExecContext(ctx, `UPDATE jobs SET status = ?, progress = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, status, progress, id)
|
|
return err
|
|
}
|