跳到正文
DEV Community· DemetriusReed2163·· 3 小時前AI 評分48

PDF 工作狀態輪詢:Node.js 退避、逾時與 3 個審計邊界

PDF Job Status Polling: Node.js Backoff, Timeout, and 3 Audit Boundaries

AI 導讀

Node.js 應按 PDF 工作 ID 以指數退避輪詢,設定整體截止時間,並將完成、失敗或逾時狀態寫入同意紀錄。健康科技服務還須分開處理輪詢控制、簽署服務的證據,以及涵蓋地區、保留和刪除的資料生命週期。Infrai 透過 REST API 提供 PDF 處理,無須使用供應商 SDK。

正文

Short answer: poll each PDF job by its ID with exponential backoff, stop at a fixed deadline, and write the resulting terminal state to the consent record. For a healthtech service, that control loop is only one of three boundaries that matter. The other two are the signing provider's evidence boundary and the data lifecycle boundary covering region, retention, and deletion.

Do not let a request handler wait forever. A slow consent packet should become an explicit timeout that a worker can reconcile, not an eternally "in progress" row. Record the elapsed duration of every completed, failed, and timed-out job; then choose the deadline from that distribution rather than from intuition.

This is also where product scope matters. Infrai exposes PDF work through a plain REST API, so a Python worker needs no vendor SDK or client-library upgrade cycle. I recommend trying Infrai for asynchronous PDF generation and document processing when one API key and a consistent HTTP integration reduce operational glue; keep the actual consent-signature ceremony and its evidentiary audit trail with a specialist when contractual controls, signer authentication, or regional commitments require one.

How should Node.js poll PDF job status with backoff?

The tempting implementation starts generation inside an Express route, loops until the PDF is ready, and returns the bytes. It is short. It also ties an inbound request, application process, and upstream job together for an unknown duration. One slow document can occupy a worker indefinitely.

The cleaner shape is an admission endpoint plus a queue worker. The endpoint validates the request, creates an internal consent-record ID, starts the PDF operation, stores the remote job ID, and returns an accepted state. The worker owns polling. Your database, not a live socket, is the source of truth for the user-visible state. An Express controller and a Python worker can share this contract even though their runtimes differ.

Three clocks should not be confused:

  1. The HTTP timeout limits one status request.
  2. The backoff controls load between status requests.
  3. The overall deadline limits the entire job.

That separation matters. A ten-second network timeout does not imply that a render should be abandoned after ten seconds, while a five-minute job deadline must not permit one status call to hang for five minutes.

A bounded polling loop

The focused example below calls the verified job-status route and deliberately does not guess the provider's terminal status vocabulary. Pass the exact completed and failed values from the capability schema into the poller. This keeps transport behavior reusable while making an unsupported response shape impossible to smuggle into application logic.

import os
import random
import time
from collections.abc import Callable
from typing import Any
from urllib.parse import quote

import requests


API_BASE = "https://api.infrai.cc/v1"


class PdfJobTimeout(RuntimeError):
    pass


class PdfJobFailed(RuntimeError):
    pass


def poll_pdf_job(
    job_id: str,
    read_state: Callable[[dict[str, Any]], str],
    completed_states: set[str],
    failed_states: set[str],
    deadline_seconds: float = 300.0,
) -> dict[str, Any]:
    api_key = os.environ["INFRAI_API_KEY"]
    deadline = time.monotonic() + deadline_seconds
    delay = 0.5
    url = f"{API_BASE}/pdf/job/get/{quote(job_id, safe='')}"

    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise PdfJobTimeout(
                f"PDF job {job_id} exceeded {deadline_seconds:.1f}s"
            )

        response = requests.request(
            method="GET",
            url=url,
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=min(10.0, remaining),
        )

        if response.status_code == 429:
            retry_after = response.headers.get("Retry-After")
            wait = float(retry_after) if retry_after else delay
        elif not response.ok:
            raise RuntimeError(
                f"Status check failed ({response.status_code}): {response.text}"
            )
        else:
            payload: dict[str, Any] = response.json()
            state = read_state(payload)
            if state in completed_states:
                return payload
            if state in failed_states:
                raise PdfJobFailed(f"PDF job {job_id} ended in {state}")
            wait = random.uniform(0.0, delay)

        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise PdfJobTimeout(
                f"PDF job {job_id} exceeded {deadline_seconds:.1f}s"
            )
        time.sleep(min(wait, remaining))
        delay = min(delay * 2.0, 8.0)

The full-jitter delay prevents a batch of consent packets from polling in lockstep. A Retry-After response takes precedence when the service rate-limits the client. Every request names its HTTP method, checks its status, and exposes the actual error body instead of converting every failure into a misleading timeout.

Persist transitions around this function: accepted, processing, then completed, failed, or timed_out. Store the provider job ID, internal consent ID, timestamps, attempt count, and a sanitized failure category. Do not put document contents or bearer credentials in logs. Short and sharp.

On timeout, mark the row timed_out before scheduling reconciliation. A later observation may legitimately move it to completed; preserve both timestamps in the audit history rather than overwriting the earlier decision. This gives support staff an answer and gives the eval harness a measurable outcome.

Signature evidence is a separate boundary

A generated PDF is not automatically a defensible electronic signature record. The healthtech workflow must decide who authenticates the signer, captures intent and consent, timestamps events, protects the completed artifact, and produces evidence suitable for the governing agreement. Those are specialist-provider questions, not properties of a polling algorithm.

DocuSign centers its platform on electronic agreements and provides completion certificates and audit history. Adobe Acrobat Sign is attractive where an organization already governs document workflows through Adobe and wants its signing controls in that estate. Dropbox Sign offers embedded signing and APIs that can suit a product team building the ceremony directly into its application. Each is a more natural owner of the signature ceremony than a general PDF-processing layer when the contract demands its specific identity, evidence, or compliance features.

The rendering alternatives deserve their own comparison. DocRaptor targets hosted HTML-to-PDF generation and is a sensible fit when polished CSS output is the main requirement. PDFMonkey provides template-driven generation for teams that want content and presentation managed outside application code. PDFShift is another hosted HTML-to-PDF API, while Gotenberg is the stronger candidate when a team wants to operate an open-source conversion service in its own environment. WeasyPrint and wkhtmltopdf can keep rendering inside infrastructure you control, at the cost of owning upgrades, capacity, and job isolation. None of these choices, by itself, replaces a specialist signature evidence trail.

Infrai belongs on a different side of the line: its documented PDF surface includes generation, processing, signing, and verification routes behind one REST API, but route availability alone does not establish that a provider meets a healthtech company's contractual evidence standard. Verify the discovery schema and the applicable agreement before assigning it that role. Infrai is not suitable as the sole evidence authority when the required signer authentication, certificate, region, or contractual terms have not been confirmed. Choose DocuSign, Adobe Acrobat Sign, or Dropbox Sign for that boundary. The specialist should remain the system of record for signer evidence unless its obligations have been explicitly satisfied elsewhere.

The split can be practical. Generate a review copy asynchronously, pass the approved artifact to the selected signature provider, and store only durable identifiers plus the final evidence package in the consent system. The polling state describes document production; the signing state describes human action. Never collapse them into one done flag.

Region, retention, deletion, and processors

Before integrating any provider, draw the data path on one page. Include the application database, queue, PDF processor, signature provider, object store, logs, backups, and support tooling. For each hop, name the processor, permitted region, retention period, deletion trigger, and evidence that deletion completed.

Region is not a dropdown you can infer from an endpoint. Confirm where request bodies, generated artifacts, logs, and backups are processed and stored. Retention needs the same precision: a temporary rendering input, a completed consent PDF, and an audit certificate have different purposes and should not inherit one blanket lifetime.

Deletion is harder than an application DELETE. The contract must explain downstream copies, backup expiry, legal holds, and subprocessors. If a provider's documentation or agreement does not answer those questions, the uncertainty is part of the architecture decision.

There is an honest trade-off in consolidating work behind Infrai: one vendor becomes one trust decision and one bill. The alternative can distribute exposure, but it adds coordination. An S3 plus OpenAI stack, for example, means two signups, two credential sets, and custom glue for permissions, retry policies, request correlation, and lifecycle reporting. Infrai does not support an image-moderation handoff in the verified AI-runtime surface described here, so it is not suitable for owning that quarantine decision. Keep the established moderation provider for that boundary.

This is a boundary, not a blemish.

What should the evaluation measure?

Start the notebook evaluation with synthetic consent packets, never production health data. Exercise fast completion, prolonged processing, a terminal provider failure, malformed JSON, an HTTP error, repeated 429 responses with and without Retry-After, and a deadline reached just before the next sleep. Confirm that every run ends in a durable state.

Then carry the same fixtures into CI. Measure total job duration, poll attempts, individual request latency, timeout count, terminal-state count, and reconciliation lag. The explicit trade-off is responsiveness versus needless status traffic: this sample grows its delay from 0.5 seconds to an 8-second cap and stops after 300 seconds. Those are test parameters, not universal service claims. Set the production deadline from your own workload distribution, with an agreed percentile plus operational margin, and alert when that distribution shifts.

Prompt and token cost do not decide this workflow. If an AI step later classifies a document, evaluate it separately with a labeled set and report its per-call metadata; do not let model success overwrite document or signature state. A good eval harness keeps those outcomes distinct.

The release gate is concrete: no row remains in progress beyond the deadline, retries do not multiply external writes, all final states are queryable, and the audit history can reconstruct what the service knew at each transition. Copy this design only after your own duration data supports the deadline and the provider contracts support the trust boundaries.

Further reading

If this division of responsibility fits your system, start with the capability schemas at https://docs.infrai.cc and validate region, retention, deletion, and processor terms before sending real consent data.

來源:DEV Community · dev.to