Designing PaperLab's job pipeline
A Go server wrapping Poppler, Ghostscript, qpdf, Tesseract and LibreOffice for 41 PDF tools: per-job directories, engine detection, capped subprocess output and a private-network URL check.
On this page
The job
PaperLab does 41 things to documents, from merging two PDFs to OCR and Office conversion. The heavy work is done by command-line programs that already do it well: Poppler, Ghostscript, qpdf, Tesseract, LibreOffice and headless Chromium. The Go server wraps them safely and predictably.
That comes down to four problems: slow operations, missing programs, untrusted input and cleanup.
Jobs, not long requests
OCR on a 200-page scan can take minutes. An HTTP request held open that long is fragile behind proxies and shows no progress. So every operation is a job:
POST /api/jobs upload files, pick a tool → job ID
GET /api/jobs/:id status, progress, message, outputs
GET /api/jobs/:id/files/:f download one output
DELETE /api/jobs/:id delete now instead of waiting for expiry
A new job gets a random 128-bit ID and a private directory tree, and the uploads move in:
$DATA_DIR/3f9c…a1/
├── in/ f1-report.pdf, f2-appendix.pdf
├── work/ scratch space for the tool
└── out/ whatever the tool produces
Everything a tool touches is under that one directory, mode 0700. Jobs can't see each other's files, and deleting a job is one os.RemoveAll. Uploads are renamed into place, and only copied when staging is on a different filesystem.
Each job runs in its own goroutine under a timeout context. Tools report progress through a callback. A panic inside a tool is recovered and becomes a plain error instead of taking the server down:
func() {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("internal processing error")
log.Printf("job %s panic: %v", job.ID, r)
}
}()
err = tool.Run(tctx)
}()
A tool that finishes without writing output also counts as failed, so nobody downloads an empty result.
A tool registry
Each tool registers an ID, a UI group, the engines it needs and a Run function:
Register(&Tool{
ID: "merge", Name: "Merge PDF", Group: "organize",
Description: "Combine PDFs in the order you want, with optional bookmarks.",
Run: mergePDFs,
})
A duplicate ID panics at registration. A copy-paste mistake becomes a startup failure, not a tool silently shadowing another.
Detect engines, don't assume them
The Docker image bundles every engine, but many people will run the bare binary and only need merge and compress. So the server never assumes a program exists. At startup it looks for each binary once, records its version, and for Tesseract lists the installed OCR languages:
e.PopplerPath = find("pdftoppm")
e.GSPath = find("gs", "gswin64c", "gswin32c")
e.LibreOfficePath = find(loOverride, "soffice", "libreoffice")
e.Poppler = e.PopplerPath != "" && find("pdftotext") != "" && find("pdfinfo") != ""
/api/tools reports each tool with available and a reason, and the front end shows what can't run on this install. A job for an unavailable tool fails immediately, naming the missing engine, before any file moves. The AI tools follow the same rule: with no provider configured, summaries and document chat fall back to local text extraction and retrieval, and translation reports itself unavailable unless a model or LibreTranslate is set up.
Subprocesses with limits
Every engine call goes through one function. It runs the command under the job's context, so the timeout kills a hung LibreOffice, and caps captured output at 128 KB:
limited := &limitedWriter{w: &buf, remaining: 128 * 1024}
cmd.Stdout = limited
cmd.Stderr = limited
Ghostscript can print a warning per page of a damaged file. Without the cap, one bad upload could fill memory with log text. On failure, only the last 1,200 characters go into the error message. That is usually where the useful line is.
Don't fetch the private network
HTML-to-PDF loads a URL in headless Chromium. On a shared server that's server-side request forgery: someone asks PaperLab to render http://169.254.169.254/ and reads cloud metadata, or a router page on the local network.
Before Chromium sees a URL, PaperLab:
- parses it and rejects anything that isn't
httporhttps, or that has embedded credentials - resolves the host
- refuses if any resolved address is loopback, private, link-local, multicast, CGNAT, a documentation range, or an IPv6 transition prefix that can wrap an IPv4 address
The check has a known gap, and the code says so in a comment. PaperLab resolves the name, then Chromium resolves it again. A malicious DNS server can answer with a public address the first time and 127.0.0.1 the second. Closing that properly takes a filtering proxy Chromium is forced through, or an egress firewall, and the comment recommends exactly that for untrusted deployments. A documented limit beats a check that pretends to be complete.
Cleanup
A ticker runs every 5 minutes. It deletes finished jobs older than the TTL (2 hours by default), then sweeps the data directory for folders that belong to no job in memory, which catches leftovers from a crash or restart. Running jobs are never removed, and the timeout stops them running forever.
Open items
- Concurrency limit. Every job gets a goroutine immediately. Thirty simultaneous Office conversions start thirty LibreOffice processes. A small semaphore per engine would keep the server responsive.
- Persistent job state. Jobs live in an in-memory map, so a restart forgets running jobs (the sweep still deletes their files). A small SQLite table would let a restart report "interrupted" instead of "not found".
- Streaming progress. Polling works everywhere. Server-sent events would make the progress bar smoother on long OCR runs.