fix(publish): prevent stuck publish queue and duplicate posting
Desktop Client Build / Resolve Build Metadata (push) Successful in 41s
Backend CI / Backend (push) Failing after 7m14s
Desktop Client Build / Build Desktop Client (push) Successful in 23m46s
Desktop Client Build / Publish Client Artifacts to NAS (push) Successful in 56s

The desktop publish queue could stall for a long time and end users assumed
the software was broken. Root cause: a hung adapter held its execution slot
with no wall-clock timeout while auto-renewing its lease forever, so the
server never reclaimed it and every queued task behind it stayed 等待发布.
Auto-recovery also risked silently re-posting a non-idempotent article.

Client (Electron):
- per-task wall-clock deadline + abort; progress-gated lease renewal that
  stops and aborts a stalled task instead of renewing it forever
- decouple the concurrency cap from CDP-induced CPU/memory pressure
  (admission gate instead of self-throttling collapse); 15s watchdog pump
- all adapter network I/O now has fetch timeouts and honors context.signal;
  bounded image-upload concurrency with per-image timeout
- surface live adapter progress, elapsed time, queue position and a
  working-vs-queued distinction in the publish view

Server (tenant-api):
- publish lease-recovery worker (every 3m) + supporting index: reclaim
  expired in_progress publish leases, requeue (<3 attempts) or terminal-fail
- 3-minute lease TTL with client-presence-gated extension; max 3 attempts

Idempotency (production-grade core):
- durable publish_submit_started_at marker, set before the irreversible
  platform submit POST; recovery and abort route a maybe-submitted task to
  unknown (manual reconcile, kept in the dedup set) instead of re-posting
- desktop UI requires explicit confirmation before retrying a possibly-
  already-published task

Verified: go build/vet/test (incl. resolvePublishRecoveryOutcome), vue-tsc,
vitest 141/141, gofmt all clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-30 19:52:17 +08:00
parent 9d6181260a
commit fa51a3455f
41 changed files with 2124 additions and 358 deletions
@@ -420,7 +420,7 @@ func (q *Queries) CreateDesktopTaskAttempt(ctx context.Context, arg CreateDeskto
const extendDesktopTaskLease = `-- name: ExtendDesktopTaskLease :one
UPDATE desktop_tasks
SET lease_expires_at = now() + interval '10 minutes',
SET lease_expires_at = now() + CASE WHEN kind = 'publish' THEN interval '3 minutes' ELSE interval '10 minutes' END,
updated_at = now()
WHERE desktop_id = $1
AND lease_token_hash = $2
@@ -564,6 +564,10 @@ WITH candidate AS (
$4::text IS NULL
OR dt.kind = $4::text
)
AND (
dt.kind <> 'publish'
OR dt.attempts < 3
)
AND (
dt.kind <> 'publish'
OR NOT EXISTS (
@@ -584,9 +588,10 @@ WITH candidate AS (
UPDATE desktop_tasks AS t
SET active_attempt_id = $1,
lease_token_hash = $2,
lease_expires_at = now() + interval '10 minutes',
lease_expires_at = now() + CASE WHEN t.kind = 'publish' THEN interval '3 minutes' ELSE interval '10 minutes' END,
status = 'in_progress',
attempts = t.attempts + 1,
started_at = COALESCE(t.started_at, now()),
updated_at = now()
FROM candidate
WHERE t.desktop_id = candidate.desktop_id
@@ -650,13 +655,18 @@ const leaseQueuedDesktopTaskByDesktopID = `-- name: LeaseQueuedDesktopTaskByDesk
UPDATE desktop_tasks
SET active_attempt_id = $1,
lease_token_hash = $2,
lease_expires_at = now() + interval '10 minutes',
lease_expires_at = now() + CASE WHEN kind = 'publish' THEN interval '3 minutes' ELSE interval '10 minutes' END,
status = 'in_progress',
attempts = attempts + 1,
started_at = COALESCE(started_at, now()),
updated_at = now()
WHERE desktop_id = $3
AND target_client_id = $4
AND status = 'queued'
AND (
kind <> 'publish'
OR attempts < 3
)
RETURNING id, desktop_id, job_id, tenant_id, workspace_id, target_account_id, target_client_id, platform_id, kind, payload, status, dedup_key, active_attempt_id, lease_token_hash, lease_expires_at, attempts, result, error, created_at, updated_at, priority, lane, lane_weight, source, scheduler_group_key, monitor_task_id, supersedes_task_id, control_flags, interrupt_generation, started_at, interrupted_at, interrupt_reason, enqueued_at
`
@@ -754,7 +764,7 @@ SET status = CASE
active_attempt_id = NULL,
lease_token_hash = NULL,
lease_expires_at = NULL,
attempts = attempts + CASE WHEN $1::text = 'retry' THEN 1 ELSE 0 END,
attempts = CASE WHEN $1::text = 'retry' THEN 0 ELSE attempts END,
updated_at = now()
WHERE desktop_id = $4
AND workspace_id = $5
@@ -17,4 +17,29 @@ func TestLeaseNextQueuedDesktopTaskLocksOnlyDesktopTasks(t *testing.T) {
if !strings.Contains(query, "NOT EXISTS") {
t.Fatalf("lease query must filter non-queued publish jobs without joining the lock target; query:\n%s", query)
}
if !strings.Contains(query, "dt.attempts < 3") {
t.Fatalf("lease query must cap publish retries; query:\n%s", query)
}
if !strings.Contains(query, "interval '3 minutes'") {
t.Fatalf("lease query must use short publish lease ttl; query:\n%s", query)
}
}
func TestExtendDesktopTaskLeaseUsesShortPublishTTL(t *testing.T) {
query := extendDesktopTaskLease
if !strings.Contains(query, "CASE WHEN kind = 'publish' THEN interval '3 minutes' ELSE interval '10 minutes' END") {
t.Fatalf("extend query must keep publish lease ttl short; query:\n%s", query)
}
}
func TestReconcileDesktopTaskRetryResetsAttempts(t *testing.T) {
query := reconcileDesktopTask
if !strings.Contains(query, "attempts = CASE WHEN $1::text = 'retry' THEN 0 ELSE attempts END") {
t.Fatalf("retry reconcile must reset attempts so manual retry can be leased; query:\n%s", query)
}
if strings.Contains(query, "attempts + CASE") {
t.Fatalf("retry reconcile must not increment attempts; query:\n%s", query)
}
}
@@ -634,6 +634,93 @@ type MediaPlatform struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type MediaSupplyOrder struct {
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
WorkspaceID int64 `json:"workspace_id"`
BrandID int64 `json:"brand_id"`
UserID int64 `json:"user_id"`
ArticleID pgtype.Int8 `json:"article_id"`
Supplier string `json:"supplier"`
ModelID int32 `json:"model_id"`
Status string `json:"status"`
Title string `json:"title"`
ContentSnapshot string `json:"content_snapshot"`
Remark pgtype.Text `json:"remark"`
OrderBrand pgtype.Text `json:"order_brand"`
ExternalOrderID pgtype.Text `json:"external_order_id"`
ExternalOrderCode pgtype.Text `json:"external_order_code"`
SupplierStatus pgtype.Text `json:"supplier_status"`
CostTotalCents int64 `json:"cost_total_cents"`
SellTotalCents int64 `json:"sell_total_cents"`
WalletDebitCents int64 `json:"wallet_debit_cents"`
WalletDebitedAt pgtype.Timestamptz `json:"wallet_debited_at"`
WalletRefundedAt pgtype.Timestamptz `json:"wallet_refunded_at"`
RequestPayloadJson []byte `json:"request_payload_json"`
ResponsePayloadJson []byte `json:"response_payload_json"`
ErrorMessage pgtype.Text `json:"error_message"`
AttemptCount int32 `json:"attempt_count"`
NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`
QueuedAt pgtype.Timestamptz `json:"queued_at"`
SubmittedAt pgtype.Timestamptz `json:"submitted_at"`
CompletedAt pgtype.Timestamptz `json:"completed_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
DeletedAt pgtype.Timestamptz `json:"deleted_at"`
}
type MediaSupplyOrderItem struct {
ID int64 `json:"id"`
OrderID int64 `json:"order_id"`
ResourceID int64 `json:"resource_id"`
SupplierResourceID string `json:"supplier_resource_id"`
PriceType string `json:"price_type"`
ResourceNameSnapshot string `json:"resource_name_snapshot"`
LockedCostPriceCents int64 `json:"locked_cost_price_cents"`
LockedSellPriceCents int64 `json:"locked_sell_price_cents"`
Status string `json:"status"`
ExternalArticleUrl pgtype.Text `json:"external_article_url"`
RawJson []byte `json:"raw_json"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type MediaSupplySyncJob struct {
ID int64 `json:"id"`
Supplier string `json:"supplier"`
ModelID pgtype.Int4 `json:"model_id"`
Status string `json:"status"`
RequestedBy pgtype.Int8 `json:"requested_by"`
StartedAt pgtype.Timestamptz `json:"started_at"`
FinishedAt pgtype.Timestamptz `json:"finished_at"`
ErrorMessage pgtype.Text `json:"error_message"`
AttemptCount int32 `json:"attempt_count"`
StatsJson []byte `json:"stats_json"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type MediaSupplyUserWallet struct {
TenantID int64 `json:"tenant_id"`
UserID int64 `json:"user_id"`
BalanceCents int64 `json:"balance_cents"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type MediaSupplyWalletLedger struct {
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
UserID int64 `json:"user_id"`
OrderID pgtype.Int8 `json:"order_id"`
DeltaCents int64 `json:"delta_cents"`
BalanceAfterCents int64 `json:"balance_after_cents"`
Reason string `json:"reason"`
Note pgtype.Text `json:"note"`
CreatedBy pgtype.Int8 `json:"created_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type Plan struct {
ID int64 `json:"id"`
PlanCode string `json:"plan_code"`
@@ -797,6 +884,45 @@ type ScheduleTask struct {
ConsecutiveFailures int32 `json:"consecutive_failures"`
}
type SupplierMediaPriceOverride struct {
ID int64 `json:"id"`
ResourceID int64 `json:"resource_id"`
PriceType string `json:"price_type"`
SellPriceCents int64 `json:"sell_price_cents"`
Enabled bool `json:"enabled"`
UpdatedBy pgtype.Int8 `json:"updated_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type SupplierMediaResource struct {
ID int64 `json:"id"`
Supplier string `json:"supplier"`
SupplierResourceID string `json:"supplier_resource_id"`
ModelID int32 `json:"model_id"`
Name string `json:"name"`
Status string `json:"status"`
CostPriceCents int64 `json:"cost_price_cents"`
CostPricesJson []byte `json:"cost_prices_json"`
SalePriceLabel pgtype.Text `json:"sale_price_label"`
ResourceUrl pgtype.Text `json:"resource_url"`
BaiduWeight pgtype.Int4 `json:"baidu_weight"`
ResourceRemark pgtype.Text `json:"resource_remark"`
CustomerVisible bool `json:"customer_visible"`
ChannelType pgtype.Text `json:"channel_type"`
Region pgtype.Text `json:"region"`
InclusionEffect pgtype.Text `json:"inclusion_effect"`
LinkType pgtype.Text `json:"link_type"`
PublishRate pgtype.Text `json:"publish_rate"`
DeliverySpeed pgtype.Text `json:"delivery_speed"`
SupplierUpdatedAt pgtype.Timestamptz `json:"supplier_updated_at"`
LastSyncedAt pgtype.Timestamptz `json:"last_synced_at"`
RawJson []byte `json:"raw_json"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
DeletedAt pgtype.Timestamptz `json:"deleted_at"`
}
type TaskRecord struct {
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`