Vapor: a complete service
This page assembles the pieces of Hokusai Vapor into one small service: three upload routes, error mapping and startup configuration. The code is compiled in CI against hokusai-vapor 2.1.0 (examples/integrations/vapor-app), so it matches the released API.
func routes(_ app: Application) throws { // Map HokusaiError to HTTP statuses for any route that evaluates a pipeline itself. let images = app.grouped(HokusaiErrorMiddleware())
// Raw body: POST /resize --data-binary @photo.jpg images.post("resize") { req async throws -> Response in try await req.hokusaiImage(maximumSize: 5 * 1024 * 1024) // 413 above 5 MiB .resize(width: 800, height: 600, fit: .cover) .webp(quality: 82) .response() // Content-Type: image/webp, streamed }
// Multipart: POST /upload with an "image" file field images.post("upload") { req async throws -> Response in try await req.hokusaiImage(field: "image") .autoOrient() .resize(width: 256, height: 256, fit: .cover, position: .attention) .png() .response(headers: ["Cache-Control": "public, max-age=3600"]) }
// A large body, streamed to a temporary file instead of held in memory images.on(.POST, "large", body: .stream) { req async throws -> Response in try await req.hokusaiImage( options: InputOptions(limits: InputLimits(maxPixels: 50_000_000)), maximumSize: 200 * 1024 * 1024 ) .resize(width: 1600, height: 1600, fit: .inside, withoutEnlargement: true) .jpeg(quality: 85) .response() }}
func configure(_ app: Application) throws { // Optional: freeze Hokusai's process-level settings before the first image. try app.hokusai.configure(.init(maxConcurrentEvaluations: .fixed(4), maxQueuedEvaluations: 64)) try routes(app)}What each part does
Section titled “What each part does”HokusaiErrorMiddlewaremaps aHokusaiErrorthrown by a route to an HTTP status by its case:invalidInput/invalidOption400,decode422,resource413 for bytes, 422 for pixels or channels, 503 for a full evaluation queue,unsupported501, andio/transform/encode/runtime500.req.hokusaiImageandresponse()already apply the mapping to what they run; the middleware covers routes that calldata()orwrite(to:)themselves./resizereads the raw body with amaximumSizeof 5 MiB. The body is read as it arrives: a declaredContent-Lengthover the limit is rejected before any byte is read, and a body without one is rejected as soon as it grows past it, both with413./uploadreads theimagefield of a multipart form, appliesautoOrient()so a phone photo is upright, makes a 256 × 256attentioncrop, and answers PNG with aCache-Controlheader./largeusesbody: .streamso Vapor does not collect the body, and a 200 MiBmaximumSize. The body is spooled to a temporary file pastmemoryLimit(1 MiB by default), so the encoded upload takes at mostmemoryLimitplus one chunk of memory; decoding is bounded separately bymaxPixels.fit: .insidewithwithoutEnlargementis the safe resize for unknown sizes (why not.cover).configurefreezesRuntimeConfigurationbefore the first image: four concurrent evaluations and a queue of 64, after which new requests fail with503instead of piling up.
Response behavior
Section titled “Response behavior”response() writes the body as it is encoded, with backpressure: a slow client slows encoding instead of growing memory, and a client disconnect cancels the request task, which stops the evaluation. Content-Type comes from the encoder. Before the response is committed the source header is read, so a missing or unreadable image is a 4xx, not a broken 200.
Production checklist
Section titled “Production checklist”- Set
maximumSize,InputLimits.maxPixelsandRuntimeConfiguration.maxOutputPixelsto your own policy. - Set
blockUntrustedOperationsif uploads come from untrusted users. - Set
maxConcurrentEvaluationsandmaxQueuedEvaluationsfrom your container limits (Docker). - Do not add a shutdown hook; Hokusai has no public shutdown.
- Test with a truncated file and a huge
resize(width:)to see your error mapping (troubleshooting).