feat(release): 发布管理整库视图 + R4/R5/R6/R7 修复
build / build (push) Failing after 16s

- R4:封存子进程 SIGTERM 宽限停、libraryctl 信号转 ctx;失败/超时后 agent 再做
  有界 recover,恢复失败即降级阻断封存并给出原因;启动先恢复、关闭等恢复完成
- R5:封存闸口以已存 payload 为准,同作业号换范围 409 且不入新队;重放回显真实状态
- R6:作业列表按类型查询(ListByType),不再先取全局再过滤
- R7:根目录 libraryagent 二进制移出版本库,保留运行产物并精确忽略
- UI:发布管理只保留对内/对外两目标,整合快照/完整性/作业/存储;链路未接线项禁用
  并标原因;整库版本独立导航并入;文档级旧流程折叠保留
This commit is contained in:
姚章浩
2026-10-28 12:28:04 +08:00
parent 910c0fcd76
commit bb64c32654
19 changed files with 1393 additions and 733 deletions
+44 -7
View File
@@ -1,6 +1,7 @@
package httpapi
import (
"context"
"encoding/json"
"fmt"
"net/http"
@@ -61,8 +62,13 @@ func libraryCaptureEnqueue(w http.ResponseWriter, r *http.Request, config Config
return
}
now := time.Now().UTC()
requestedID := fmt.Sprintf("library-capture-%s-%d", request.Scope, now.UnixNano())
// The idempotency key is the capture job id: the same logical capture must map
// to one queue row. Binding the scope into the key would silently create a
// second job instead of reporting a conflicting request, so the conflict is
// detected by comparing the stored payload below.
job, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: fmt.Sprintf("library-capture-%s-%d", request.Scope, now.UnixNano()),
ID: requestedID,
Type: libraryCaptureJobType,
Payload: payload,
AvailableAt: now,
@@ -73,24 +79,55 @@ func libraryCaptureEnqueue(w http.ResponseWriter, r *http.Request, config Config
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue capture job"})
return
}
// Enqueue returns the existing row for a reused key. Answer from that row, not
// from the current request: a reused job id with another scope must be refused
// instead of being reported as a job for the new scope.
var stored struct {
Scope string `json:"scope"`
CaptureJob string `json:"capture_job"`
RequestedBy string `json:"requested_by"`
}
if err = json.Unmarshal(job.Payload, &stored); err != nil || stored.CaptureJob != captureJob {
writeJSON(w, http.StatusConflict, map[string]any{
"code": "library_capture_conflict", "error": "该作业号已被另一个封存请求占用",
"existing_scope": stored.Scope, "requested_scope": request.Scope,
})
return
}
if stored.Scope != request.Scope {
writeJSON(w, http.StatusConflict, map[string]any{
"code": "library_capture_scope_conflict", "error": "同一作业号已按另一个范围投递",
"existing_scope": stored.Scope, "requested_scope": request.Scope,
})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{
"job_id": job.ID, "capture_job": captureJob, "scope": request.Scope, "state": job.State,
"job_id": job.ID, "capture_job": stored.CaptureJob, "scope": stored.Scope,
"state": job.State, "reused": job.ID != requestedID, "requested_by": stored.RequestedBy,
})
}
// libraryCaptureJobs lists recent capture jobs so the page can show real state
// instead of an optimistic spinner. It reads the queue, not the archive.
func libraryCaptureJobs(w http.ResponseWriter, r *http.Request, config Config) {
queue, err := config.Store.List(r.Context(), 200)
// Ask the store for this type only. Reading the global queue and filtering in
// the handler would hide capture jobs behind unrelated traffic and make the
// page claim "idle" while a capture is still queued.
byType, ok := config.Store.(interface {
ListByType(ctx context.Context, jobType string, limit int) ([]jobs.Job, error)
})
if !ok {
writeJSON(w, http.StatusOK, map[string]any{"available": false,
"reason": "任务存储不支持按类型查询,页面不会据此判断空闲", "jobs": []any{}})
return
}
queue, err := byType.ListByType(r.Context(), libraryCaptureJobType, 20)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture jobs"})
return
}
views := make([]map[string]any, 0, 20)
views := make([]map[string]any, 0, len(queue))
for _, job := range queue {
if job.Type != libraryCaptureJobType || len(views) >= 20 {
continue
}
var payload struct {
Scope string `json:"scope"`
CaptureJob string `json:"capture_job"`
+55 -7
View File
@@ -86,18 +86,25 @@ func TestLibraryCaptureRejectsInvalidRequest(t *testing.T) {
}
}
func TestLibraryCaptureJobsListsOnlyCaptureJobs(t *testing.T) {
store := &fakeJobStore{listResult: []jobs.Job{
{ID: "a", Type: libraryCaptureJobType, State: "completed",
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-internal-1","requested_by":"yaozhanghao"}`),
CreatedAt: time.Date(2026, 10, 28, 3, 0, 0, 0, time.UTC)},
{ID: "b", Type: "artifact.fetch", State: "completed"},
}}
func TestLibraryCaptureJobsAsksStoreForItsOwnType(t *testing.T) {
// The global queue is busy with unrelated traffic; the capture job must still
// be visible because the query is type-scoped, not filtered after the fact.
store := &fakeJobStore{
listResult: []jobs.Job{{ID: "busy", Type: "artifact.fetch", State: "running"}},
listByTypeResult: []jobs.Job{
{ID: "a", Type: libraryCaptureJobType, State: "completed",
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-internal-1","requested_by":"yaozhanghao"}`),
CreatedAt: time.Date(2026, 10, 28, 3, 0, 0, 0, time.UTC)},
},
}
recorder := httptest.NewRecorder()
libraryCaptureJobs(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/library/captures", nil), Config{Store: store})
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d", recorder.Code)
}
if store.listType != libraryCaptureJobType {
t.Fatalf("store queried with type %q", store.listType)
}
var body struct {
Available bool `json:"available"`
Jobs []map[string]any `json:"jobs"`
@@ -109,3 +116,44 @@ func TestLibraryCaptureJobsListsOnlyCaptureJobs(t *testing.T) {
t.Fatalf("unexpected body %+v", body)
}
}
// Reusing a capture job id with another scope must be refused, and the response
// must report the scope that was actually stored.
func TestLibraryCaptureRejectsScopeConflictForReusedJob(t *testing.T) {
store := &fakeJobStore{enqueueResult: &jobs.Job{ID: "existing-job", Type: libraryCaptureJobType,
State: jobs.StateCompleted,
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-shared","requested_by":"yaozhanghao"}`)}}
recorder := httptest.NewRecorder()
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"external","job":"lib-shared"}`),
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
if recorder.Code != http.StatusConflict {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
var body map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["code"] != "library_capture_scope_conflict" || body["existing_scope"] != "internal" || body["requested_scope"] != "external" {
t.Fatalf("unexpected conflict body %v", body)
}
}
// A reused job id with an identical request is answered from the stored row.
func TestLibraryCaptureReplayReportsStoredJob(t *testing.T) {
store := &fakeJobStore{enqueueResult: &jobs.Job{ID: "existing-job", Type: libraryCaptureJobType,
State: jobs.StateCompleted,
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-shared","requested_by":"yaozhanghao"}`)}}
recorder := httptest.NewRecorder()
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"internal","job":"lib-shared"}`),
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
if recorder.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
var body map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["scope"] != "internal" || body["capture_job"] != "lib-shared" || body["reused"] != true || body["job_id"] != "existing-job" {
t.Fatalf("unexpected replay body %v", body)
}
}
+13 -1
View File
@@ -1526,6 +1526,10 @@ type fakeJobStore struct {
enqueued jobs.EnqueueRequest
enqueueResult *jobs.Job
listResult []jobs.Job
listType string
listByTypeResult []jobs.Job
listByTypeLimit int
listByTypeErr error
listLimit int
assetResult governance.SourceAssetPage
assetFilter governance.SourceAssetFilter
@@ -1871,7 +1875,9 @@ func (s *fakeJobStore) ActivateUISettingsWithOperation(_ context.Context, revisi
func (s *fakeJobStore) Enqueue(_ context.Context, request jobs.EnqueueRequest, _ time.Time) (*jobs.Job, error) {
s.enqueued = request
if s.enqueueEchoRequestedID {
return &jobs.Job{ID: request.ID, Type: request.Type, State: jobs.StatePending}, nil
// The real store returns the stored row, including its payload: a reused
// idempotency key must be judged by that payload, not by the request.
return &jobs.Job{ID: request.ID, Type: request.Type, State: jobs.StatePending, Payload: request.Payload}, nil
}
return s.enqueueResult, nil
}
@@ -1881,6 +1887,12 @@ func (s *fakeJobStore) List(_ context.Context, limit int) ([]jobs.Job, error) {
return s.listResult, nil
}
func (s *fakeJobStore) ListByType(_ context.Context, jobType string, limit int) ([]jobs.Job, error) {
s.listType = jobType
s.listByTypeLimit = limit
return s.listByTypeResult, s.listByTypeErr
}
func (s *fakeJobStore) ListTestPublications(_ context.Context, filter governance.TestPublicationFilter) (governance.TestPublicationPage, error) {
s.publicationFilter = filter
return s.publicationResult, nil
+93 -3
View File
@@ -16,6 +16,7 @@ import (
"context"
"encoding/json"
"errors"
"log"
"net"
"os"
"os/exec"
@@ -23,6 +24,7 @@ import (
"regexp"
"strings"
"sync"
"syscall"
"time"
)
@@ -43,6 +45,13 @@ type Config struct {
Writers string
NonWriters string
MaxDuration time.Duration
// StopGrace bounds the graceful stop of one operation: SIGTERM first (the
// child aborts the maintenance window and restores writers), then SIGKILL
// only after this grace period. It must exceed the child's own restore budget.
StopGrace time.Duration
// RecoverTimeout bounds the recovery run performed after a failed or killed
// operation, and at agent start-up.
RecoverTimeout time.Duration
// Run executes the binary; replaced in tests.
Run func(ctx context.Context, name string, args ...string) ([]byte, error)
}
@@ -69,6 +78,11 @@ var jobPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
type Agent struct {
config Config
mu sync.Mutex
// degraded is non-empty when a failed operation could not be followed by a
// verified recovery. While set, capture requests are refused: leaving the
// source writer stopped is worse than refusing work.
degraded string
wg sync.WaitGroup
}
func New(config Config) (*Agent, error) {
@@ -81,6 +95,15 @@ func New(config Config) (*Agent, error) {
if config.MaxDuration <= 0 || config.MaxDuration > 30*time.Minute {
return nil, errors.New("library agent duration bound is invalid")
}
if config.StopGrace == 0 {
config.StopGrace = 3 * time.Minute
}
if config.RecoverTimeout == 0 {
config.RecoverTimeout = 3 * time.Minute
}
if config.StopGrace <= 0 || config.StopGrace > 10*time.Minute || config.RecoverTimeout <= 0 || config.RecoverTimeout > 10*time.Minute {
return nil, errors.New("library agent recovery/stop budget is invalid")
}
return &Agent{config: config}, nil
}
@@ -105,6 +128,13 @@ func (a *Agent) Serve(ctx context.Context) error {
if err := os.Chmod(a.config.Socket, 0600); err != nil {
return err
}
// Startup responsibility: an agent restart may have inherited a stopped
// writer from a previous killed run. Recover before accepting work; if that
// fails, stay degraded and refuse captures instead of pretending to be ready.
if err := a.recoverWriters(ctx); err != nil {
a.degraded = err.Error()
log.Printf("library agent: pending freeze recovery failed: %v", err)
}
go func() {
<-ctx.Done()
_ = listener.Close()
@@ -113,11 +143,24 @@ func (a *Agent) Serve(ctx context.Context) error {
conn, err := listener.Accept()
if err != nil {
if ctx.Err() != nil {
// Drain in-flight operations: each of them still owes a bounded
// recovery before the agent may exit.
done := make(chan struct{})
go func() { a.wg.Wait(); close(done) }()
select {
case <-done:
case <-time.After(a.config.StopGrace + a.config.RecoverTimeout):
log.Printf("library agent: shutdown deadline exceeded with operations in flight")
}
return nil
}
return err
}
go a.handle(ctx, conn)
a.wg.Add(1)
go func(conn net.Conn) {
defer a.wg.Done()
a.handle(ctx, conn)
}(conn)
}
}
@@ -143,6 +186,12 @@ func (a *Agent) execute(ctx context.Context, req request) response {
a.mu.Lock()
defer a.mu.Unlock()
out := response{Action: req.Action, Scope: req.Scope, Job: req.Job}
// Degraded blocks new captures, but recover and status must stay reachable:
// otherwise there is no way back to a verified state.
if a.degraded != "" && req.Action == "capture" {
out.Error = "封存执行边界处于降级状态(上次恢复失败:" + a.degraded + "),先执行 recover"
return out
}
var args []string
switch req.Action {
case "status":
@@ -171,12 +220,30 @@ func (a *Agent) execute(ctx context.Context, req request) response {
defer cancel()
payload, err := a.config.run(bounded, a.config.Binary, args...)
if err != nil {
out.Error = "operation failed"
detail := "operation failed"
if message := strings.TrimSpace(string(payload)); message != "" && len(message) <= 2000 {
out.Error = message
detail = message
}
// A killed or aborted child may have left the source writer stopped. The
// recovery responsibility does not end with the failed request: run the
// idempotent recovery now, and refuse further captures if it does not
// verify.
if req.Action == "capture" || req.Action == "recover" {
if recoveryErr := a.recoverWriters(ctx); recoveryErr != nil {
a.degraded = recoveryErr.Error()
out.Error = detail + ";写入者恢复失败:" + recoveryErr.Error() + "(已阻断后续封存,需人工处理)"
return out
}
detail += ";已执行 recover 并确认写入者恢复"
} else {
// status 失败不需要恢复;它不改变停机状态。
}
out.Error = detail
return out
}
if req.Action == "recover" {
a.degraded = ""
}
out.OK = true
if json.Valid(payload) {
out.Payload = json.RawMessage(payload)
@@ -186,6 +253,18 @@ func (a *Agent) execute(ctx context.Context, req request) response {
return out
}
// recoverWriters runs the idempotent recovery command with its own budget, even
// when the triggering context is already cancelled (timeout / shutdown).
func (a *Agent) recoverWriters(ctx context.Context) error {
bounded, cancel := context.WithTimeout(context.WithoutCancel(ctx), a.config.RecoverTimeout)
defer cancel()
if _, err := a.config.run(bounded, a.config.Binary, append([]string{"recover"}, a.config.declaration()...)...); err != nil {
return err
}
a.degraded = ""
return nil
}
// declaration pins every path and the writer group so a request cannot redirect
// the operation to another stack, archive or journal.
func (c Config) declaration() []string {
@@ -208,6 +287,17 @@ func (c Config) run(ctx context.Context, name string, args ...string) ([]byte, e
}
command := exec.CommandContext(ctx, name, args...)
command.Env = append(os.Environ(), "LIBRARYCTL_AGENT=1")
// Default CommandContext behaviour is SIGKILL, which would skip the child's
// window restore and leave the source writer stopped. Ask for a graceful stop
// first and only escalate after the grace period.
command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
command.Cancel = func() error {
if command.Process == nil {
return nil
}
return command.Process.Signal(syscall.SIGTERM)
}
command.WaitDelay = c.StopGrace
return command.CombinedOutput()
}
+170 -3
View File
@@ -3,6 +3,7 @@ package libraryagent
import (
"context"
"encoding/json"
"errors"
"net"
"os"
"path/filepath"
@@ -108,9 +109,9 @@ func TestAgentSocketIsPrivateAndPinsTheDeclaration(t *testing.T) {
if !out.OK || out.Job != "lib-internal-test" {
t.Fatalf("capture rejected: %+v", out)
}
recorded := calls()
recorded := captureCalls(calls())
if len(recorded) != 1 {
t.Fatalf("expected one execution, got %v", recorded)
t.Fatalf("expected one capture execution, got %v", recorded)
}
for _, want := range []string{"capture -scope internal -job lib-internal-test",
"-archive " + filepath.Join(filepath.Dir(socket), "library"),
@@ -151,11 +152,177 @@ func TestAgentRejectsUnsupportedRequestsWithoutExecuting(t *testing.T) {
t.Fatalf("accepted %q: %+v", payload, out)
}
}
if got := calls(); len(got) != 0 {
if got := captureCalls(calls()); len(got) != 0 {
t.Fatalf("rejected requests still executed: %v", got)
}
}
func captureCalls(calls []string) []string {
kept := make([]string, 0, len(calls))
for _, call := range calls {
if strings.Contains(call, " capture ") {
kept = append(kept, call)
}
}
return kept
}
func recoverCalls(calls []string) []string {
kept := make([]string, 0, len(calls))
for _, call := range calls {
if strings.Contains(call, " recover ") {
kept = append(kept, call)
}
}
return kept
}
// failingAgent builds an agent whose capture always fails and whose recovery
// outcome can be switched, to prove the recovery responsibility after a
// killed/aborted child.
func failingAgent(t *testing.T) (*Agent, string, func() []string, func(error)) {
t.Helper()
root, err := os.MkdirTemp(os.TempDir(), "kgrf-")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(root) })
if err = os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var calls []string
var recoverErr error
agent, err := New(Config{
Socket: filepath.Join(root, "agent.sock"), Binary: "/bin/echo",
ArchiveRoot: filepath.Join(root, "library"), JournalRoot: filepath.Join(root, "freeze"),
SourceApp: "app-container", SourcePG: "pg", SourceES: "es", GovernancePG: "gov",
Project: "weknora071full", Writers: "app", NonWriters: "frontend=UI only",
MaxDuration: time.Minute, StopGrace: time.Minute, RecoverTimeout: time.Minute,
Run: func(_ context.Context, name string, args ...string) ([]byte, error) {
mu.Lock()
calls = append(calls, name+" "+strings.Join(args, " "))
current := recoverErr
mu.Unlock()
if len(args) > 0 && args[0] == "recover" {
if current != nil {
return []byte("writer restart failed"), current
}
return []byte(`{"recovered":true}`), nil
}
return []byte("LIBRARYCTL_FAILED: stop outcome uncertain"), errors.New("exit status 1")
},
})
if err != nil {
t.Fatal(err)
}
return agent, filepath.Join(root, "agent.sock"), func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), calls...)
}, func(err error) {
mu.Lock()
defer mu.Unlock()
recoverErr = err
}
}
// A failed capture must be followed by a recovery attempt, not just an error.
func TestAgentRecoversWritersAfterFailedCapture(t *testing.T) {
agent, socket, calls, _ := failingAgent(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = agent.Serve(ctx) }()
waitSocket(t, socket)
out := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-fail-1"}`)
if out.OK {
t.Fatalf("failed capture reported success: %+v", out)
}
if !strings.Contains(out.Error, "已执行 recover 并确认写入者恢复") {
t.Fatalf("error does not state the recovery outcome: %q", out.Error)
}
if len(recoverCalls(calls())) == 0 {
t.Fatal("no recovery ran after the failed capture")
}
}
// If recovery itself fails, the boundary must refuse further captures instead of
// leaving the source stopped and merely marking a job failed.
func TestAgentBlocksCapturesWhenRecoveryFails(t *testing.T) {
agent, socket, calls, setRecoverErr := failingAgent(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = agent.Serve(ctx) }()
waitSocket(t, socket)
setRecoverErr(errors.New("docker restart failed"))
out := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-fail-2"}`)
if out.OK || !strings.Contains(out.Error, "写入者恢复失败") || !strings.Contains(out.Error, "已阻断后续封存") {
t.Fatalf("recovery failure not surfaced: %+v", out)
}
before := len(captureCalls(calls()))
blocked := roundTrip(t, socket, `{"action":"capture","scope":"external","job":"lib-fail-3"}`)
if blocked.OK || !strings.Contains(blocked.Error, "降级") {
t.Fatalf("degraded agent accepted a capture: %+v", blocked)
}
if got := len(captureCalls(calls())); got != before {
t.Fatalf("blocked capture still executed (%d -> %d)", before, got)
}
// A verified recovery clears the degraded state and lets work resume.
setRecoverErr(nil)
if recovered := roundTrip(t, socket, `{"action":"recover"}`); !recovered.OK {
t.Fatalf("explicit recovery failed: %+v", recovered)
}
if resumed := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-fail-4"}`); strings.Contains(resumed.Error, "降级") {
t.Fatalf("recovery did not clear the degraded state: %+v", resumed)
}
}
// The child is stopped with SIGTERM and the grace period, not an immediate kill.
func TestRunStopsChildWithSigterm(t *testing.T) {
dir := t.TempDir()
script := filepath.Join(dir, "child.sh")
// A real child that only exits 0 when it receives SIGTERM.
child := "#!/bin/sh\ntrap 'exit 0' TERM\nwhile :; do sleep 0.05; done\n"
if err := os.WriteFile(script, []byte(child), 0o700); err != nil {
t.Fatal(err)
}
agent, err := New(Config{Socket: "/tmp/irrelevant.sock", Binary: script,
ArchiveRoot: filepath.Join(dir, "library"), JournalRoot: filepath.Join(dir, "freeze"),
SourceApp: "app-container", SourcePG: "pg", SourceES: "es", GovernancePG: "gov",
Project: "weknora071full", Writers: "app", NonWriters: "frontend=UI only",
MaxDuration: 2 * time.Second, StopGrace: 5 * time.Second, RecoverTimeout: 5 * time.Second})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
started := time.Now()
_, err = agent.config.run(ctx, script)
if err == nil {
t.Fatal("cancelled run reported success")
}
if elapsed := time.Since(started); elapsed > 4*time.Second {
t.Fatalf("child was not stopped within the graceful window: %s", elapsed)
}
if ctx.Err() == nil {
t.Fatal("test did not exercise cancellation")
}
}
func waitSocket(t *testing.T, socket string) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for {
if _, err := os.Stat(socket); err == nil {
return
}
if time.Now().After(deadline) {
t.Fatal("agent socket never appeared")
}
time.Sleep(10 * time.Millisecond)
}
}
func TestNewRejectsIncompleteConfiguration(t *testing.T) {
if _, err := New(Config{}); err == nil {
t.Fatal("empty configuration accepted")
+12
View File
@@ -132,6 +132,18 @@ RETURNING job_id
SELECT id FROM updated
`
// One job type, newest first: a caller which needs "the recent jobs of MY type"
// must not page the global queue (other traffic would hide its own rows).
const listJobsByTypeSQL = `
SELECT id, type, payload, state, priority, available_at,
lease_owner, lease_until, attempt, max_attempts,
last_error, idempotency_key, created_at, updated_at
FROM jobs
WHERE type = $1
ORDER BY created_at DESC, id DESC
LIMIT $2
`
const listJobsSQL = `
SELECT id, type, payload, state, priority, available_at,
lease_owner, lease_until, attempt, max_attempts,
+25
View File
@@ -65,6 +65,31 @@ func (s *Store) Claim(ctx context.Context, workerID string, allowedTypes []strin
return job, nil
}
// ListByType lists only the requested job type, so a busy queue cannot hide the
// caller's own recent jobs behind unrelated traffic.
func (s *Store) ListByType(ctx context.Context, jobType string, limit int) ([]jobs.Job, error) {
if strings.TrimSpace(jobType) == "" || limit < 1 || limit > 200 {
return nil, errors.New("list jobs by type requires a type and a bounded limit")
}
rows, err := s.db.Query(ctx, listJobsByTypeSQL, jobType, limit)
if err != nil {
return nil, fmt.Errorf("list jobs by type: %w", err)
}
defer rows.Close()
result := make([]jobs.Job, 0, limit)
for rows.Next() {
job, err := scanJob(rows)
if err != nil {
return nil, fmt.Errorf("scan listed job: %w", err)
}
result = append(result, *job)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate jobs: %w", err)
}
return result, nil
}
func (s *Store) List(ctx context.Context, limit int) ([]jobs.Job, error) {
rows, err := s.db.Query(ctx, listJobsSQL, limit)
if err != nil {