"""Private, transactional Core → VPS delivery; never a second tracker operation.""" import json import time from collections.abc import Callable from typing import TYPE_CHECKING from .independent_equipment import Document if TYPE_CHECKING: from .vps_hosts import VPSHosts def attempt( hosts: "VPSHosts", source: Document, operation_id: str, send: Callable[..., Document] ) -> Document | None: # The caller owns hosts.lock. Claim the backoff durably before network I/O. # A process restart cannot generate a new ID, body, destination or deadline. with hosts.equipment.db() as db: db.execute("BEGIN IMMEDIATE") row = db.execute( "SELECT instance,host,target,body,attempts,next_attempt FROM network_outbox WHERE id=?", (operation_id,), ).fetchone() if row is None or row[1] != source["id"] or source["state"] != "paired": return None instance = hosts.equipment._find(db, "instances", row[0]) op = instance.get("network_operation", {}) body = json.loads(row[3]) now = time.time() if ( op.get("id") != operation_id or op.get("state") != "submitting" or (not op.get("durable") and min(op["expires_at"], body["not_after"]) <= now) or row[5] > now ): return None # Up to 30 s between retries, with stable per-operation staggering. delay = min(30, 2 ** min(row[4] + 1, 5)) + int(operation_id[-4:], 16) / 65536 db.execute( "UPDATE network_outbox SET attempts=attempts+1,next_attempt=? WHERE id=?", (now + delay, operation_id), ) target = next((h for h in hosts.rows() if h["id"] == row[2] and h["state"] == "paired"), None) if target is None: return None hosts.sync(target) # Sync may consume the remaining deadline; do not send stale requests. if not op.get("durable") and time.time() >= body["not_after"]: return None return send(source, "POST", "/v1/operations" if op.get("durable") else "/v1/commands", body)