| 447 | } |
| 448 | |
| 449 | func UpdateSystemTaskState(taskID string, lockedBy string, state any) error { |
| 450 | stateText, err := marshalSystemTaskJSON(state) |
| 451 | if err != nil { |
| 452 | return err |
| 453 | } |
| 454 | now := common.GetTimestamp() |
| 455 | result := DB.Model(&SystemTask{}). |
| 456 | Where("task_id = ? AND status = ? AND locked_by = ?", taskID, SystemTaskStatusRunning, lockedBy). |
| 457 | Where("EXISTS (SELECT 1 FROM system_task_locks WHERE system_task_locks.task_id = system_tasks.task_id AND system_task_locks.locked_by = ? AND system_task_locks.locked_until >= ?)", lockedBy, now). |
| 458 | Updates(map[string]any{ |
| 459 | "state": stateText, |
| 460 | "updated_at": now, |
| 461 | }) |
| 462 | if result.Error != nil { |
| 463 | return result.Error |
| 464 | } |
| 465 | if result.RowsAffected > 0 { |
| 466 | return nil |
| 467 | } |
| 468 | // MySQL counts changed rows, not matched rows. A no-op persist of the same |
| 469 | // state in the same second therefore returns RowsAffected == 0 even while |
| 470 | // the lease is still held. Confirm the lock before treating this as loss. |
| 471 | // Reuse `now` from the UPDATE so a clock tick cannot reintroduce false |
| 472 | // lock-loss; a lease that expires during the write is caught by the next heartbeat. |
| 473 | var held int64 |
| 474 | err = DB.Model(&SystemTask{}). |
| 475 | Where("task_id = ? AND status = ? AND locked_by = ?", taskID, SystemTaskStatusRunning, lockedBy). |
| 476 | Where("EXISTS (SELECT 1 FROM system_task_locks WHERE system_task_locks.task_id = system_tasks.task_id AND system_task_locks.locked_by = ? AND system_task_locks.locked_until >= ?)", lockedBy, now). |
| 477 | Count(&held).Error |
| 478 | if err != nil { |
| 479 | return err |
| 480 | } |
| 481 | if held == 0 { |
| 482 | return ErrSystemTaskLockLost |
| 483 | } |
| 484 | return nil |
| 485 | } |
| 486 | |
| 487 | func RenewSystemTaskLock(taskID string, lockedBy string, lockUntil int64) error { |
| 488 | now := common.GetTimestamp() |