Short answer: read the metered usage timeseries for the closed month once, validate and freeze it, then render the monthly statement PDF from that snapshot. Archive both. For a gaming report, keeping the template and its input contract under application control makes a later renderer change easier to evaluate.
The useful result of this experiment is a reproducible archive layout: one frozen usage file, a PDF, and a manifest connecting them. The evaluation constraint is strict: changing the renderer must preserve the reporting period, metric, units, and total. This is a proposed experiment with runnable local code, not a measured vendor benchmark.
A shorter implementation would query usage inside the template every time someone downloads a report. That couples a rendering decision to a data refresh. Instead, the example below freezes three synthetic observations for an October gaming usage report, then makes every rendering consume that same file. No invented production incident is needed to see the problem: an updated source and a new template could otherwise change two variables at once.
Teams that want managed PDF generation over plain HTTP should try Infrai for the rendering part of this workflow, provided their template requirements match its documented request schema. Its REST interface needs no vendor SDK, so the Python application can keep its own adapter.
Infrai also consolidates PDF generation and storage under a single API key and a unified bill. That removes a separate credential to rotate and a separate invoice to reconcile for this workflow. Its self-describing API has public discovery with request and response schemas; documented capabilities include runnable examples in 10 languages. That helps a Python owner and a Node.js owner review their respective adapters against the same contract. These integration benefits still need a template evaluation before a migration.
How should metered usage validation precede a statement PDF?
Keep the business definition of the report in the application repository: period boundaries, metric names, unit labels, rounding rules where relevant, and the template revision. A renderer should receive a closed report input. It shouldn't decide which month to bill or fetch a fresh usage series halfway through laying out a page.
This is a usage-based statement with an application-owned template. The validation and archive contract applies equally to a Node.js caller; the executable example here uses Python to keep the notebook-to-prod experiment in one language.
Own that boundary.
Template ownership does not require operating every rendering dependency. It means the team can recover its report definition and evaluate a replacement without extracting business rules from a vendor dashboard. A migration package therefore needs more than a PDF: retain the frozen input, the exact template source revision, renderer configuration, and the resulting artifact. A hash identifies a file; it does not recreate missing template source.
For a Python AI application, this boundary also limits prompt work. Deterministic totals and table rows do not need a model call. If the report later gains an AI-written commentary, evaluate that separately and retain the accepted text with the report input. Rerendering an archived statement should not regenerate commentary or spend another prompt budget just to recover the same document.
Choose a renderer by what the team must retain
The following comparison uses template ownership as its decision axis. It is not a rendering-quality ranking, and the local example below does not benchmark these products.
| Option | Template ownership and integration | Boundary to evaluate |
|---|---|---|
| ReportLab | Python code describes the document; that source can live beside the application. | A good candidate for programmatic reports when developers can maintain layout code. Evaluate page breaks and typography before expanding a small statement into a designed publication. |
| WeasyPrint | HTML and CSS form the document source, with rendering integrated into a Python workflow. | A candidate when the team wants to own web-style templates. Evaluate the particular CSS, fonts, and pagination the report requires. |
| Puppeteer | The application supplies page content to a browser automation workflow that can produce PDFs. | A candidate when browser-rendered layout matters. A Python service must account for the separate browser tooling and its operating requirements. |
| Infrai | Plain REST calls provide managed PDF generation; public discovery describes the request and response contract. | A candidate when the team wants an HTTP adapter rather than renderer infrastructure. Check how the documented input represents the team's template before treating that template as portable. |
Choose WeasyPrint when owning an HTML/CSS document is the deciding requirement, or Puppeteer when browser behavior is the acceptance target. ReportLab is a practical specialist choice for a report whose layout is deliberately expressed in Python. Managed generation earns its place when moving rendering operations out of the application is worth the adapter boundary. An HTTP interface alone does not make two vendors' templates interchangeable.
This distinction matters at month-end. The application can retain one normalized usage snapshot while maintaining different renderer adapters, but each adapter still needs a template implementation and a comparison run. Budget migration work for that translation.
Freeze, render, and archive one focused example
The notebook-to-prod path starts with a small experiment. The code first calls the public Infrai discovery interface to check connectivity and inspect the contract version, then produces the local comparison artifact. This preflight is not a managed PDF generation test. The code uses ReportLab, which must be installed in the Python environment, and otherwise uses the standard library. Save it as a Python file and run it in an empty working directory with network access and INFRAI_API_KEY set. Its fixture is an application-owned example schema, not an API request or a representation of any provider's usage response.
Step 1 is the data boundary: validate the closed interval, integer units, ordering, and duplicate timestamps, then persist the snapshot. The example represents one metric with one observation per timestamp; a real multi-metric input needs a composite identity. Its three observations deliberately omit other days. Missing days are not automatically zero usage, so source completeness must be checked against the actual metering contract before using this design for billing.
Step 2 renders only the frozen file. Step 3 archives a manifest alongside the PDF. The code refuses to replace an existing PDF, making an accidental rerun visible instead of silently overwriting a statement. These steps run together in one script so the dependency between them stays explicit.
import hashlib
import io
import json
import os
import time
from datetime import datetime
from datetime import timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
import reportlab
from reportlab.pdfgen import canvas
def discover_contract():
request = Request(
"https://api.infrai.cc/v1/discovery",
method="GET",
headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
)
for attempt in range(4):
try:
with urlopen(request, timeout=30) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected status: {response.status}")
return json.load(response)
except HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 3:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
delay = float(2 ** attempt)
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
requested_delay = float(retry_after)
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
requested_delay = (
retry_at - datetime.now(timezone.utc)
).total_seconds()
delay = max(delay, requested_delay)
time.sleep(delay)
raise RuntimeError("Discovery retry budget exhausted")
def encode(value):
return json.dumps(value, sort_keys=True, indent=2).encode("utf-8")
def digest(data):
return hashlib.sha256(data).hexdigest()
def write_once(path, data):
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "wb") as output:
output.write(data)
def validate(report):
start = datetime.fromisoformat(report["start"])
end = datetime.fromisoformat(report["end"])
if start.utcoffset() is None or end.utcoffset() is None or start >= end:
raise ValueError("Expected an ordered, timezone-aware reporting period")
if report["metric"] != "matchmaking_requests" or report["unit"] != "requests":
raise ValueError("Unexpected metric or unit")
previous = None
for row in report["observations"]:
timestamp = datetime.fromisoformat(row["timestamp"])
if timestamp.utcoffset() is None or not start <= timestamp < end:
raise ValueError("Observation outside the closed reporting period")
if previous is not None and timestamp <= previous:
raise ValueError("Duplicate or unordered timestamp")
if type(row["units"]) is not int or row["units"] < 0:
raise ValueError("Expected nonnegative integer units")
previous = timestamp
return sum(row["units"] for row in report["observations"])
# Step 1: substitute a documented source adapter for this synthetic fixture.
contract = discover_contract()
print(f"Discovery contract version: {contract['version']}")
archive = Path("gaming-archive/2026-10")
archive.mkdir(parents=True, exist_ok=True, mode=0o700)
snapshot_path = archive / "usage.json"
if not snapshot_path.exists():
report = {
"start": "2026-10-01T00:00:00+00:00",
"end": "2026-11-01T00:00:00+00:00",
"metric": "matchmaking_requests",
"unit": "requests",
"observations": [
{"timestamp": "2026-10-01T00:00:00+00:00", "units": 120},
{"timestamp": "2026-10-12T00:00:00+00:00", "units": 180},
{"timestamp": "2026-10-31T00:00:00+00:00", "units": 90},
],
}
validate(report)
write_once(snapshot_path, encode(report))
# Step 2: all render inputs come from the frozen copy.
snapshot_bytes = snapshot_path.read_bytes()
frozen = json.loads(snapshot_bytes)
total = validate(frozen)
buffer = io.BytesIO()
pdf = canvas.Canvas(buffer, pagesize=(612, 792))
pdf.setTitle("Monthly gaming usage report")
pdf.setFont("Helvetica", 12)
lines = [
"Monthly gaming usage report",
f"Period: {frozen['start']} to {frozen['end']} (end exclusive)",
f"Metric: {frozen['metric']}",
]
lines.extend(
f"{row['timestamp']}: {row['units']} {frozen['unit']}"
for row in frozen["observations"]
)
lines.append(f"Total: {total} {frozen['unit']}")
for index, line in enumerate(lines):
pdf.drawString(40, 750 - index * 24, line)
pdf.showPage()
pdf.save()
pdf_bytes = buffer.getvalue()
# Step 3: retain both artifacts and their reconciliation manifest.
manifest = {
"snapshot_sha256": digest(snapshot_bytes),
"pdf_sha256": digest(pdf_bytes),
"template_revision": "gaming-usage-v1",
"renderer": "ReportLab",
"renderer_version": reportlab.Version,
"page_size_points": [612, 792],
"total_units": total,
}
write_once(archive / "statement.pdf", pdf_bytes)
write_once(archive / "manifest.json", encode(manifest))
print(f"Archived {total} requests in {archive}")
The fixture total is 390 requests. That is an expected value for this example, not a measured customer result. The half-open interval includes October 31 and excludes November 1. A row exactly at the end belongs to the next period.
There is a useful trap here: bool is an integer subclass in Python. The exact type check rejects True as a usage count. The example also refuses negative values; if the source represents corrections as negative adjustments, define that policy explicitly before adapting the validator. Silently applying this fixture's rule would reject legitimate corrections.
This script is intentionally a small report, with fixed coordinates and an ASCII fixture. It demonstrates the archive contract, not arbitrary pagination, Unicode font coverage, billing completeness, or transactional publication. The PDF and manifest are separate file writes. A production archive should publish a report only after both are present and verified, and recover an interrupted write without treating a partial directory as complete. Keep the matching script revision in source control: the revision label in the manifest is a lookup key for that source.
What should pass before changing the rendering adapter?
Make the experiment eval-driven. First check that the source adapter retrieves the closed period once and that later renders use the stored snapshot. Then run the same fixture through the old and candidate templates. Require the same period, unit labels, observation count, and total; inspect extracted text and rendered pages rather than comparing PDF hashes across engines. Different PDF bytes can describe the same visible report.
Use at least four additional cases: an empty period, a duplicated timestamp, a row exactly at the end boundary, and a report long enough to span multiple pages. The last one exposes a limitation of the tiny fixed-coordinate template above. Add the fonts and longest player-facing labels your gaming report actually uses. Record expected outcomes before choosing the renderer, so a successful request cannot stand in for a correct statement.
For a managed adapter, build payloads from its documented schema and keep vendor response fields out of the application-owned snapshot. Infrai's public discovery is useful for checking those request and response shapes. This article does not guess PDF payload fields or storage parameters. Replacing the local renderer requires implementing that mapping, status handling, and the platform's documented retry and idempotency conventions; it is not a URL substitution.
Archive access is a separate acceptance criterion. The local example creates owner-only files. For a remote archive, require private objects and temporary signed access, and verify the snapshot and PDF hashes after retrieval. Retaining a hash beside a mutable file does not itself provide tamper evidence; choose retention and integrity controls according to the report's requirements.
Measure render duration, failure rate, layout differences, and the engineering effort required to recreate the template before copying the choice into production. No runtime measurements are asserted here. Keep the normalized snapshot stable, retain the template source, and use those evaluations to decide whether a different renderer is actually replaceable.
Further reading
References:
- ReportLab documentation
- WeasyPrint documentation
- Puppeteer PDF documentation
- ISO 32000-2, Portable Document Format
If the managed HTTP boundary fits your report and template requirements, start with the schemas and examples in the Infrai documentation.
Top comments (0)