fix: a crawl cancel waits for its job, and a stale crawl is ended
Cancelling a running crawl records cancel_requested_at and leaves the row running until its job stops and writes cancelled, so no second crawl starts and the row cannot be deleted or pruned meanwhile. The job writes heartbeat_at every minute; a running crawl without a heartbeat for 10 minutes is ended by the next start or delete.
This commit is contained in:
@@ -189,6 +189,55 @@ func ActiveCrawl(db *gorm.DB) (*models.Crawl, error) {
|
||||
return &rows[0], nil
|
||||
}
|
||||
|
||||
// RecoverStale ends the running crawls whose job stopped writing its
|
||||
// heartbeat (P33-60): a running row whose COALESCE(heartbeat_at,
|
||||
// started_at, created_at) is older than StaleAfter before now becomes
|
||||
// cancelled when its cancel was requested, else failed with the error
|
||||
// "the crawl job stopped without finishing (no heartbeat since <time>)",
|
||||
// with finished_at now. It answers the rows it ended, with their new
|
||||
// status, so the caller can end their conga jobs.
|
||||
func RecoverStale(tx *gorm.DB, now time.Time) ([]models.Crawl, error) {
|
||||
now = now.UTC()
|
||||
var rows []models.Crawl
|
||||
if err := tx.Where("status = ? AND COALESCE(heartbeat_at, started_at, created_at) < ?", models.CrawlRunning, now.Add(-StaleAfter)).
|
||||
Order("id ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := rows[:0]
|
||||
for _, r := range rows {
|
||||
last := r.HeartbeatAt
|
||||
if last == nil {
|
||||
last = r.StartedAt
|
||||
}
|
||||
if last == nil {
|
||||
last = r.CreatedAt
|
||||
}
|
||||
updates := map[string]any{"finished_at": now}
|
||||
if r.CancelRequestedAt != nil {
|
||||
updates["status"], updates["error"] = models.CrawlCancelled, ""
|
||||
} else {
|
||||
since := "an unknown time"
|
||||
if last != nil {
|
||||
since = last.UTC().Format(time.RFC3339)
|
||||
}
|
||||
updates["status"], updates["error"] = models.CrawlFailed, "the crawl job stopped without finishing (no heartbeat since "+since+")"
|
||||
}
|
||||
res := tx.Model(&models.Crawl{}).Where("id = ? AND status = ?", r.ID, models.CrawlRunning).Updates(updates)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
continue
|
||||
}
|
||||
r.Status = updates["status"].(string)
|
||||
r.Error = updates["error"].(string)
|
||||
r.FinishedAt = &now
|
||||
pluginLog.Warn("golem15.seo: ended a stale crawl", "crawl", r.ID, "status", r.Status)
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CurrentScope narrows an issues query to the audit's current issues: the
|
||||
// newest finished, failed or cancelled crawl's, or before any crawl the
|
||||
// stored CMS-data issues.
|
||||
|
||||
Reference in New Issue
Block a user