Skip to content

Handling File Operations with Generated REST Resources ​

Legacy approach

The custom resource examples below predate generated owned-payload boundaries. Use httpPayloads for multipart upload and authorised download of Connector-owned PayloadReference values. Use Object Ingest when an external object event starts the Pipeline.

This guide explains how to handle file operations such as downloads and uploads when using the auto-generated REST resources in The Pipeline Framework.

Generated owned-payload boundaries ​

Version 3 templates can declare HTTP boundaries around an ordinary typed Pipeline. Each declaration names a record field of type payload_ref, an existing bound Object Publish target or Object Ingest source, media types, and an authorisation scope. REST/COMPUTE uses a direct HTTP stream; REST/FUNCTION requires an S3 object provider and delegates payload bytes to S3.

yaml
httpPayloads:
  invoice-file:
    direction: upload
    object: invoices       # a bound object target under publish
    canonicalType: InvoiceInput
    referenceField: payload_ref
    contentTypes: [application/pdf]
    maxBytes: 10485760
    authorizationScope: invoice.write
  invoice-result:
    direction: download
    object: results        # a bound object source under sources
    canonicalType: InvoiceResult
    referenceField: payload_ref
    contentTypes: [application/pdf]
    authorizationScope: invoice.read

On COMPUTE, the generated upload route is POST /tpf/payloads/invoice-file/upload. Send one multipart file part. The adapter reads the live request stream, checks its framing with bounded headers, and waits for each Connector write before reading more bytes. It creates no payload temporary file. Set quarkus.http.limits.max-body-size above the largest declared maxBytes plus multipart framing; the boundary also enforces its own limit. The response contains the provider-issued reference under payload_ref; submit that value through the Pipeline's usual typed admission route. Uploading does not start a Pipeline execution. The generated download route is POST /tpf/payloads/invoice-result/download, with the owned PayloadReference as its JSON body. It streams the content with a private, non-cacheable response. Byte-range requests receive HTTP 416 in this version.

On FUNCTION, the generated upload boundary is a small control API:

  1. POST /tpf/payloads/invoice-file/upload/initiate with JSON { "contentType": "application/pdf", "bytes": 6291456, "sha256": "<64 hex digits>", "idempotencyKey": "client-stable-key" }. It returns a signed reservation token, part size, and expiry. Repeating the call with the same key and owner returns the reservation.
  2. POST .../upload/part with { "token": "...", "partNumber": 1 } returns a short-lived URL for that S3 part. Upload each part directly to S3, with every part except the last exactly the returned part size.
  3. POST .../upload/complete with { "token": "..." } verifies S3's actual parts, size, and SHA-256, then returns the owned reference under payload_ref. POST .../upload/abort with the same body cancels an unfinished upload.

The FUNCTION download route accepts the owned reference as JSON and returns a five-minute S3 GET capability with expected byte count and SHA-256. The client checks those values while consuming the response. The URL is a temporary transport credential; only the returned PayloadReference can be submitted to a Pipeline or used for another authorised download request. S3 may serve byte ranges through its capability even though the COMPUTE route itself rejects Range.

Both routes require an authenticated principal and exactly one application or host PayloadBoundaryAuthorizer bean. The X-Tenant-Id and X-Scope-Id headers are untrusted requests; the authoriser must verify them against the authenticated principal and return the authorised PayloadBoundaryOwner. Downloads compare that owner with signed reference metadata before opening the Connector. The host rejects an unavailable binding or modified reference. Public deployments must configure durable provider capability authority so issued references remain usable across instances and restarts.

Overview ​

The Pipeline Framework automatically generates REST adapters when the pipeline transport is set to REST in your pipeline.yaml. However, the generated resources focus on standard DTO processing and may not handle specialized operations like file downloads directly.

Generated REST Resources vs. Manual Resources ​

Generated REST Resources ​

When you use:

java
@PipelineStep
public class ProcessFileReactiveService implements ReactiveStreamingClientService<InputType, OutputFileType> {
    // ...
}

The framework generates a resource like:

java
@Path("/api/v1/process-file-reactive")
public class ProcessFileResource {
    // Standard process method for DTOs
    @POST
    @Path("/process")
    public Uni<OutputFileTypeDto> process(Multi<InputTypeDto> inputDtos) {
        // Implementation using mappers and service
    }

    // ServerExceptionMapper for error handling
    @ServerExceptionMapper
    public RestResponse handleRuntimeException(RuntimeException ex) {
        return RestResponse.status(Response.Status.BAD_REQUEST, "Error processing request: " + ex.getMessage());
    }
}

Manual Resources for File Operations ​

For specialized operations like file downloads, you might need to complement the generated resource with custom endpoints:

java
@Path("/api/v1/process-file-reactive")
public class ProcessFileRestResource {

    private static final Logger LOG = LoggerFactory.getLogger(ProcessFileRestResource.class);

    @Inject
    ProcessFileReactiveService domainService;

    @Inject
    InputTypeMapper inputTypeMapper;

    @POST
    @Path("/process-download")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Uni<Response> processAndDownload(List<InputTypeDto> request) {
        // Convert DTOs to domain objects
        Multi<InputType> domainInput = Multi.createFrom().iterable(request)
            .onItem().transform(inputTypeMapper::fromDto);

        // Process data using the same service
        Uni<OutputFileType> domainResult = domainService.process(domainInput);

        return domainResult
            .onItem().transformToUni(file -> createFileDownloadResponse(file));
    }

    private Uni<Response> createFileDownloadResponse(OutputFileType file) {
        java.nio.file.Path filePath = file.getFilepath();
        String fileName = filePath.getFileName().toString();

        StreamingOutput output = outputStream -> {
            Files.copy(filePath, outputStream);
        };

        return Uni.createFrom().item(
            Response.ok(output)
                .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                .header("Content-Type", "text/csv")
                .build())
            .onTermination().invoke(() -> cleanupTempFile(filePath));
    }

    private void cleanupTempFile(java.nio.file.Path filePath) {
        try {
            Files.deleteIfExists(filePath);
        } catch (IOException e) {
            LOG.warn("Failed to delete temporary file: {}", filePath, e);
        }
    }
}

Connector-first approach ​

Use a connector when the application needs to admit files or object-store entries as pipeline input. Start with Object Ingest and use this page only for request/response file endpoints that are truly custom application APIs.

Option 2: Hybrid generated/custom REST approach ​

Keep both the generated resource for standard operations and create custom resources for file operations:

  1. Set transport: REST in your pipeline YAML for standard DTO processing
  2. Create a separate resource class for specialized file operations
  3. Re-use the same service instance to avoid duplication of business logic
yaml
steps:
  - name: process-file-reactive
    service: com.app.file.ProcessFileReactiveService
    cardinality: MANY_TO_ONE
    input: InputType
    output: OutputFileType
java
// In your service class - marker only
@PipelineStep
public class ProcessFileReactiveService implements ReactiveStreamingClientService<InputType, OutputFileType> {
    // Your service business logic
}

// Separate resource for file download functionality
@Path("/api/v1/custom-file-processing")
public class CustomFileProcessingResource {

    @Inject
    ProcessFileReactiveService domainService;

    @POST
    @Path("/download")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Uni<Response> downloadFile(List<InputTypeDto> request) {
        // Use the same domain service for processing
        // Add file download specific logic
    }
}

Option 3: Custom Annotation Configuration ​

For common patterns, you can implement custom handling by keeping the generated functionality but extending it:

java
@ApplicationScoped
public class FileDownloadService {

    @Inject
    ProcessFileReactiveService domainService;

    // Generic file download endpoint that can work with multiple service types
    public <T, S> Uni<Response> createDownloadResponse(
        Multi<T> inputs,
        Function<Multi<T>, Uni<S>> processingFunction,
        Function<S, Response> fileResponseFunction) {

        return processingFunction.apply(inputs)
            .onItem().transform(fileResponseFunction);
    }
}

Key Considerations ​

1. Separation of Concerns ​

  • Generated resources handle standard DTO → Domain → Service processing
  • Custom resources handle specialized operations like file I/O, complex streaming, etc.

2. Consistent Error Handling ​

  • Generated resources include @ServerExceptionMapper for runtime exceptions
  • Ensure custom resources use similar error handling patterns

3. Resource Management ​

  • Custom file operations should properly manage resources (files, streams, etc.)
  • Consider file cleanup, permissions, and potential disk space issues

4. Testing Strategy ​

  • Generated resources come with basic functionality that's automatically tested
  • Custom resources for file operations will need additional test coverage

5. Security Considerations ​

  • Validate and sanitize file paths to prevent path traversal in custom file operations
  • Enforce authorization checks before any file access or streaming begins
  • Normalize file names to remove special characters and path components
  • Enforce maximum file size limits and disk quota checks for uploads and temp files
  • Validate or scan file content for malicious payloads before persistence or streaming
  • Use secure temporary file creation with strict permissions and safe locations, and clean up via the same resource management patterns described above

Best Practices ​

  1. Prefer connectors for ingestion: Use object/file connectors for pipeline input admission when possible
  2. Start with Generated Resources: Use the auto-generated REST endpoints for standard DTO request/response operations
  3. Add Custom Resources for Specialized Needs: Implement custom resources when you need file handling, streaming, or other specialized operations
  4. Share Service Logic: Re-use the same service instances to avoid duplicating business logic
  5. Maintain Consistency: Follow similar patterns for error handling and response formats
  6. Document Differences: Clearly document which endpoints are auto-generated vs. custom

Example Implementation ​

For a complete implementation, see the reference implementation where manual resources handle file download operations while the framework generates standard DTO processing endpoints.

This approach provides the best of both worlds: automatic generation for standard operations and custom handling for specialized requirements.

Diagram