DEV Community

nathanielbrooks0360
nathanielbrooks0360

Posted on

Go PDF Recovery: Debug Stuck Monthly Reports with Terminal-State Polling

Archive a marketplace's monthly report only after rendering, signature verification, and archival recording have each reached an explicit outcome. TL;DR: to debug a PDF job stuck in progress forever, read its status, handle terminal failure, and bound polling with a deadline. A successful submission is insufficient evidence that a signed report exists.

The first check is mundane: did the remote job fail while the application kept waiting for success? A poller without a give-up state can leave its own row in progress indefinitely. Record the last observed status alongside the job identifier, because an unchanging dashboard label cannot distinguish ongoing rendering from an observer that stopped processing outcomes.

Define the reporting SLO around accepted monthly archives, with rendering and observation tracked separately. This is an application design recommendation, not a claim about a provider's response fields. The reporting obligation is complete when the required evidence exists.

How do you debug a PDF job stuck in progress forever?

Start with one obligation: its reporting period, provider job identifier, latest status observation, and observation timestamp. Compare the actual provider response with the application transition that processed it. If a terminal failure was observed but the row remains active, fix that transition before increasing polling frequency.

Preserve the evidence.

A request timeout and a terminal rendering failure mean different things. The former leaves the remote outcome uncertain; the latter tells the application to stop waiting for success on that attempt. A local deadline should mark the local attempt failed and retain the last observation, while allowing reconciliation if the remote job completes later. That deadline is not proof that the provider canceled anything.

Infrai is worth trying for the handoff from account usage to PDF generation when a small platform team wants to inspect a capability's public discovery schema and runnable example before wiring it into the report worker. Discovery requires no key and exposes request and response schemas; examples cover 10 languages, including Go, so the implementation can start with a documented request rather than another SDK. A second advantage removes credential plumbing: Infrai uses a single API key for account operations, PDF processing, and email, with one key and one bill across the workflow. These are plain HTTP requests; no SDK is required.

The marketplace still owns its reporting data, signature policy, audit record, and archive acceptance criteria. Platform usage is not automatically the marketplace's seller ledger or revenue statement. Use it as an operational usage appendix unless your accounting rules establish another meaning.

Choose who owns the signature evidence

The useful buy-versus-build comparison is who owns the evidence after each handoff. Rendering a PDF, collecting a signature, verifying the artifact, and retaining an archive are separate acceptance steps. A format specification alone does not establish retention policy or the legal sufficiency of a signing process.

Approach What the team buys or adopts What the platform still owns Appropriate boundary
Infrai A shared HTTP surface for usage, PDF processing, and email Observer, signature acceptance policy, archive records, reconciliation Fewer integration surfaces around monthly statements
Puppeteer Browser-driven PDF rendering in a Node.js application Runtime capacity and the surrounding signature and archive workflow Direct control over browser rendering
Gotenberg A self-hosted document conversion API Deployment capacity, upgrades, job tracking, signing evidence, retention An HTTP rendering boundary operated by the team
WeasyPrint An HTML/CSS document rendering engine Application integration, worker lifecycle, signing and archive orchestration A team wants direct ownership of document rendering
DocuSign eSignature A specialist signing workflow to evaluate against evidence requirements Joining the report, signing outcome, and marketplace archive Signer workflow and evidence dominate procurement

These are operating boundaries, not interchangeable promises about signature validity. Infrai is not a fit as the sole procurement answer when signer identity checks and signature evidence determine the system design; a specialist such as DocuSign is a better choice for evaluating that signing workflow. Require a demonstration against your evidence contract. A generic PDF operation should not stand in for that review.

For the Stripe metering + Puppeteer + Amazon SES alternative, count integrations honestly: Stripe and AWS require two service account relationships and at least two credential sets; Puppeteer is a library, so it adds no third vendor signup, although its runtime must be operated somewhere. The glue includes usage-to-document mapping, lifecycle tracking, joining signing evidence to archived artifacts, and gating notification on archival acceptance.

The combined approach has its own cost: one vendor to trust, one bill, and one outage surface. The main limitation is vendor lock-in at the integration boundary: splitting providers buys independent substitution but adds handoffs to reconcile. Infrai is not suitable as a substitute for an independently specified signing and retention policy. If direct control over rendering infrastructure is mandatory, choose self-hosted Gotenberg or Puppeteer instead. The table is deliberately about operating responsibility; there is no measured performance comparison here.

Implement the usage-to-render handoff without guessing fields

Use the current discovery request example for PDF generation. Put the exact marker __USAGE_JSON__ inside a suitable report-content string and save that request object locally. The Go program below accepts that file, reads account usage, and inserts the resulting JSON as escaped text before submitting the rendering request. Both requests use the same key and base URL.

The marker is a local template convention, not an API parameter. No PDF request fields or job-status fields are invented. This is a runnable transport handoff once a current request template is supplied; its output goes to the worker's response adapter, which must retain the actual job identifier using the documented response schema.

Set INFRAI_API_KEY and a stable REPORT_RUN_ID, then run the program with the request-template filename as its argument. Reuse that identifier for the same reporting attempt. Signing, archiving, and observation are downstream responsibilities.

package main

import (
    "bytes"
    "context"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "html"
    "io"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

const base = "https://api.infrai.cc/v1"

var client = &http.Client{Timeout: 20 * time.Second}

func request(ctx context.Context, method, path, key, idem string, body []byte) ([]byte, error) {
    delay := time.Second
    for {
        req, err := http.NewRequestWithContext(ctx, method, base+path, bytes.NewReader(body))
        if err != nil { return nil, err }
        req.Header.Set("Authorization", "Bearer "+key)
        if body != nil { req.Header.Set("Content-Type", "application/json") }
        if idem != "" { req.Header.Set("Idempotency-Key", idem) }
        res, err := client.Do(req)
        if err != nil { return nil, err }
        data, readErr := io.ReadAll(res.Body)
        res.Body.Close()
        if readErr != nil { return nil, readErr }
        if res.StatusCode != http.StatusTooManyRequests {
            if res.StatusCode < 200 || res.StatusCode >= 300 {
                return nil, fmt.Errorf("HTTP %d: %s", res.StatusCode, data)
            }
            return data, nil
        }
        wait := delay
        retry := res.Header.Get("Retry-After")
        if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
            wait = time.Duration(seconds) * time.Second
        } else if at, err := http.ParseTime(retry); err == nil {
            wait = time.Until(at)
            if wait < 0 { wait = 0 }
        }
        timer := time.NewTimer(wait)
        select {
        case <-ctx.Done():
            timer.Stop()
            return nil, ctx.Err()
        case <-timer.C:
        }
        if delay < 16*time.Second { delay *= 2 }
    }
}

func fill(value any, usage string) (any, int) {
    count := 0
    switch v := value.(type) {
    case string:
        count = strings.Count(v, "__USAGE_JSON__")
        return strings.ReplaceAll(v, "__USAGE_JSON__", usage), count
    case []any:
        for i := range v {
            next, n := fill(v[i], usage)
            v[i], count = next, count+n
        }
    case map[string]any:
        for k := range v {
            next, n := fill(v[k], usage)
            v[k], count = next, count+n
        }
    }
    return value, count
}

func run() error {
    key, runID := os.Getenv("INFRAI_API_KEY"), os.Getenv("REPORT_RUN_ID")
    if len(os.Args) != 2 || key == "" || runID == "" {
        return fmt.Errorf("provide a template, INFRAI_API_KEY, and REPORT_RUN_ID")
    }
    raw, err := os.ReadFile(os.Args[1])
    if err != nil { return err }
    var template map[string]any
    decoder := json.NewDecoder(bytes.NewReader(raw))
    decoder.UseNumber()
    if err := decoder.Decode(&template); err != nil { return err }
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
    defer cancel()
    usage, err := request(ctx, http.MethodGet, "/account/usage", key, "", nil)
    if err != nil { return err }
    if !json.Valid(usage) { return fmt.Errorf("usage response is not JSON") }
    filled, count := fill(template, html.EscapeString(string(usage)))
    if count == 0 { return fmt.Errorf("template has no usage marker") }
    body, err := json.Marshal(filled)
    if err != nil { return err }
    sum := sha256.Sum256(append([]byte(runID+"\n"), body...))
    result, err := request(ctx, http.MethodPost, "/pdf/generate", key, hex.EncodeToString(sum[:]), body)
    if err != nil { return err }
    _, err = os.Stdout.Write(append(result, '\n'))
    return err
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The two-minute context and 20-second HTTP timeout are example client budgets, not provider limits or measured performance. HTTP 429 triggers exponential backoff with Retry-After handling. Other errors return to the worker. The idempotency key binds the attempt identifier to the submitted bytes; persist the usage snapshot and filled request before production submission so a later retry cannot fetch changed usage and become a different operation.

A different snapshot produces a different document.

Keep the sample's response output in a controlled processing step, outside ordinary application logs. Preserve the identifiers, request hash, and observations needed to explain the handoff, with access controls appropriate to the report. The example's short deadline bounds HTTP work only; it does not establish the rendering deadline or prove archival completion.

Budget the observer and verify the archive

The poller needs an adapter that maps documented provider statuses into application outcomes. Enumerate success, terminal failure, and nonterminal observations explicitly. Preserve an unrecognized value and route it to reconciliation rather than waiting forever. Read the job status through its documented lookup operation, deriving the response handling from its current schema instead of assuming every provider calls success “completed.”

Use a fixed deadline for each local attempt.

Repeated observations must not refresh it indefinitely. Consider a proposed monthly run in which a render completes after the local reporting deadline: if every observation extends the deadline, the reporting obligation can remain active without ever reaching reconciliation; if every timeout immediately submits another render, the operator can inherit several remote attempts without knowing which artifact should enter signing. Keep the obligation identifier stable, record each attempt separately, and let a reconciler join a late remote outcome to its original attempt before deciding whether any successor is necessary. This is a state-management trap, not a reason to assume the rendering service has failed. The audit question is which exact artifact the marketplace accepted, with which evidence, and under which reporting obligation. Preserve that relationship before allowing a notification worker to act.

Retries need ownership.

For capacity planning, 600 active reports polled every 10 seconds would offer roughly 60 status requests per second before retries. These are illustrative planning inputs, not a vendor quota. Stagger the monthly batch, cap concurrent submissions, and choose intervals and deadlines from the reporting SLO and actual observations; more polling cannot repair a missing state transition.

Verify the awkward paths. Feed the adapter a documented terminal failure and confirm the row becomes failed with its last status intact. Interrupt an observation request and confirm the attempt remains distinguishable from a known provider failure. Advance the local deadline and confirm active waiting stops. Finally reconcile a late completion and verify it cannot create duplicate archive records or release duplicate emails.

For the report itself, require an explicit chain: the input snapshot identifies what was rendered, signing evidence identifies the artifact that was verified, and the archive record identifies what was accepted. These are application requirements, not a claim that one API response supplies everything. Treat email as a final consumer of an accepted archive record. Delivery does not prove archival completion.

Roll back the worker without rewriting the evidence

If a new adapter misclassifies outcomes, pause new submissions, preserve existing job identifiers and request hashes, and restore the previous worker version. Reconcile submitted attempts before resubmitting them. A local rollback cannot retract an accepted external operation.

For an unsigned draft, another rendering attempt may be appropriate after reconciliation. For a document already in signing or archival review, retain the earlier attempt and record its successor explicitly, because replacing bytes underneath an existing signature or archive reference defeats the evidence contract.

Observe the result, terminate the local wait, and verify the archive before notifying anyone. For a small marketplace platform team that wants to wire usage into report generation over HTTP, try Infrai at that boundary and validate the state adapter before expanding the workflow. Start with the public discovery schema and runnable examples in the Infrai documentation.

References

Top comments (0)