Appearance
Report Generation
GrydReports supports synchronous on-demand generation and recurring generation through the optional scheduling integration. The public one-shot asynchronous command remains available for host customizations, but its built-in handler returns REPORT_ASYNC_GENERATION_UNAVAILABLE because no one-shot background executor is registered. C# methods ending in Async use Task for awaited request work; that naming alone does not mean work is queued.
Generation Pipeline
Request → Validate Parameters → Fetch Data → Render → Store File → Deliver (optional)
│ │ │ │ │
IReportFilter IReportDataSource IReportRenderer IServerFileStore IReportDelivery
(OnBefore...) (FetchDataAsync) (RenderAsync) (GrydFiles) (DeliverAsync)Generated files are stored in GrydFiles, in process, under the gryd.report profile. Each file is registered on behalf of its execution: when the file module's scan releases it, the execution holds a reference with owner scope gryd.report-execution and owner key equal to the execution id. The profile waives the antivirus (the file never left this process), but the server still computes the SHA-256 and checks the content against the declared type, so a renderer that produces something other than its format is rejected. Retention is UntilReleased: deleting the execution releases the reference, and the file is purged by the retention job after the grace period.
Breaking change — download returns a URL (GrydFiles)
GET /api/v1/reports/{id}/download used to stream the file. It now answers 200 with { "url": "…", "expiresAt": "…" }, a presigned URL valid for a few minutes, and the file is fetched from that URL, straight from storage. There is no route, flag or wrapper that still serves the bytes. Callers adapt in two steps: request the URL, then GET it (or redirect the browser to it). A report whose file is still being verified answers 409 FILE_NOT_AVAILABLE_CONFLICT; ask again a moment later. ReportResultDto.downloadUrl and ReportExecutionDto.fileUri were replaced by storedFileId, and IReportGenerator.GenerateAndStoreAsync/GenerateAndDeliverAsync now take the persisted ReportExecution instead of a template id and format. Ships in the next major version.
Synchronous Generation
Returns the generated file immediately. Best for small-to-medium reports:
Via API
bash
POST /api/v1/reports/generate
Content-Type: application/json
{
"templateId": "monthly-sales",
"format": 1,
"parameters": {
"month": 1,
"year": 2026
},
"requestedBy": "user@company.com"
}Response 201 Created:
json
{
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"templateId": "monthly-sales",
"reportName": "Sales Report - January 2026",
"format": 1,
"status": 3,
"fileName": "monthly-sales-2026-01.pdf",
"fileSizeBytes": 245760,
"storedFileId": "0b8e2f51-7c3d-4e6a-9f10-2a4b6c8d0e12",
"generationDuration": "00:00:02.341",
"createdAt": "2026-02-19T10:30:00Z"
}Via MediatR
csharp
var result = await mediator.Send(new GenerateReportCommand(
TemplateId: "monthly-sales",
Format: ReportFormat.Pdf,
Parameters: new Dictionary<string, object?>
{
["month"] = 1,
["year"] = 2026
},
RequestedBy: "user@company.com"
));
if (result.IsSuccess)
{
var report = result.Data!;
Console.WriteLine($"Generated: {report.FileName} ({report.FileSizeBytes} bytes)");
}
else
{
Console.WriteLine($"Error: {result.ErrorMessage}");
}Asynchronous Generation
The built-in one-shot asynchronous handler does not queue work. It returns 503 Service Unavailable with REPORT_ASYNC_GENERATION_UNAVAILABLE before creating an execution, serializing parameters, or returning a tracking ID. Use synchronous generation, or configure a recurring schedule when generation should run in the background. A host can replace the handler with its own durable queue integration.
Via API
bash
POST /api/v1/reports/generate-async
Content-Type: application/json
{
"templateId": "annual-financial",
"format": 2,
"parameters": {
"year": 2025
},
"delivery": {
"method": 2,
"recipients": ["cfo@company.com", "finance@company.com"],
"emailSubject": "Annual Financial Report 2025",
"emailBody": "Please find the attached annual financial report."
},
"requestedBy": "admin@company.com"
}Built-in response: 503 Service Unavailable with code REPORT_ASYNC_GENERATION_UNAVAILABLE. A host-provided handler may return 202 Accepted only after it has accepted the request for processing.
Via MediatR
csharp
var result = await mediator.Send(new GenerateReportAsyncCommand(
TemplateId: "annual-financial",
Format: ReportFormat.Excel,
Parameters: new Dictionary<string, object?> { ["year"] = 2025 },
Delivery: new DeliveryOptions
{
Method = DeliveryMethod.Email,
Recipients = ["cfo@company.com"]
},
RequestedBy: "admin@company.com"
));
// The built-in handler returns REPORT_ASYNC_GENERATION_UNAVAILABLE.
if (result.IsFailure)
Console.WriteLine(result.ErrorMessage);Polling for Status
Polling requires an execution ID from synchronous or recurring generation, or from a host-provided async handler that accepted the request. The built-in one-shot async request is rejected and returns no tracking ID.
bash
GET /api/v1/reports/{trackingId}Status transitions for executions that exist: Queued (1) → Generating (2) → Completed (3) → Delivered (5), or Generating (2) → Failed (4).
IReportGenerator
The central orchestrator that wires everything together:
csharp
public interface IReportGenerator
{
// Generate and return the output stream
Task<Result<ReportOutput>> GenerateAsync<TData, TParams>(
string templateId, TParams parameters, ReportFormat format,
CancellationToken ct = default);
// Generate + store in GrydFiles on behalf of a persisted execution
Task<Result<ReportResultDto>> GenerateAndStoreAsync<TData, TParams>(
ReportExecution execution, TParams parameters,
CancellationToken ct = default);
// Generate + store + deliver the rendered bytes via the configured channel
Task<Result<ReportResultDto>> GenerateAndDeliverAsync<TData, TParams>(
ReportExecution execution, TParams parameters,
DeliveryOptions delivery, CancellationToken ct = default);
// List all registered report templates
IReadOnlyList<ReportDefinitionDto> GetAvailableReports();
}The execution must already be persisted: its tenant and id are what the file is stored under and on whose behalf. Scheduled runs create an execution for the schedule's tenant and go through the same path.
Download
Request a short-lived URL to a previously generated report:
bash
GET /api/v1/reports/{id}/downloadResponse 200 OK:
json
{
"url": "https://storage.example.com/…?X-Amz-Signature=…",
"expiresAt": "2026-09-10T18:05:00Z"
}Then fetch the file from url. The URL serves it as an attachment with the name the report was stored under, and each URL issued is written to the audit trail with the purpose report-download. Do not store the URL — ask for a new one when it expires. 409 FILE_NOT_AVAILABLE_CONFLICT means the file is still being verified; 409 FILE_PURGED_CONFLICT means retention already collected it.
Execution History
Query past report executions with filters. A format value is usable only when its renderer is registered; this release does not ship an HTML renderer:
bash
GET /api/v1/reports/history?templateId=monthly-sales&status=3&format=1&pageNumber=1&pageSize=20Query Parameters:
| Parameter | Type | Description |
|---|---|---|
templateId | string? | Filter by template |
status | int? | Filter by status (1=Queued, 2=Generating, 3=Completed, 4=Failed, 5=Delivered, 6=Cancelled) |
format | int? | Filter by format (1=PDF, 2=Excel, 3=CSV, 4=HTML) |
fromDate | DateTime? | Start of date range |
toDate | DateTime? | End of date range |
pageNumber | int | Page number (default: 1) |
pageSize | int | Page size (default: 20) |
Delete
Soft-delete a report execution and release its stored file (GrydFiles purges it after the retention grace period):
bash
DELETE /api/v1/reports/{id}Returns 204 No Content on success.
Streaming export (/export)
POST /api/v1/reports/export writes a CSV to the response row by row as the data source yields it. Nothing is stored: no ReportExecution, no file in GrydFiles, no cache. There is therefore no history entry, no download URL and no way to fetch the same export again. It needs generate:reports, like /generate.
http
POST /api/v1/reports/export
Content-Type: application/json
{
"templateId": "transactions",
"format": "Csv",
"parameters": { "fromDate": "2026-01-01" },
"columns": ["Date", "Amount"]
}Filters travel in the body, never in the URL. parameters is the JSON object of the template's parameter type; an unknown property is refused rather than ignored, so a misspelled filter cannot export everything.
| Use | When |
|---|---|
/export | A screen's "export" button: a CSV of the current filters, downloaded once. |
/generate | A report that must be kept, listed in the history, downloaded again or delivered; PDF, Excel and HTML. |
Columns. columns is optional. Omitted or empty, the file has every column the export offers; with it, only those, in that order. A name the export does not offer — or repeats — is REPORT_EXPORT_COLUMNS_INVALID. The columns are the record's public scalar properties (text, numbers, booleans, dates, enums, GUIDs; never navigations or collections), in declaration order, minus any marked [ReportExportIgnore]. [ReportExportColumn("Nome")] sets the header written for a property; the column is still selected by the property name.
What an export offers. GET /api/v1/reports/export/{templateId} (same permission) answers { templateId, columns: [{ name, header }], filters: [{ field, type, operators }] }, so a screen can build its column picker and filter fields without hard-coding them. filters is empty for a template with its own parameter type, and lists the filterable fields of an entity export.
Two phases. After the first byte the response can no longer carry an error status, so everything that can fail with one is decided first: the template has an export registered, the format has a stream writer, the parameters deserialize and validate, and the source's estimated row count is within MaxExportRows. Each failure is a ProblemDetails:
| Code | Meaning |
|---|---|
REPORT_EXPORT_NOT_REGISTERED | The template has no export. There is no fallback to the in-memory path. |
REPORT_EXPORT_FORMAT_NOT_SUPPORTED | No stream writer is registered for the format (only CSV ships). |
REPORT_EXPORT_PARAMETERS_INVALID | The body does not match the parameter type, or its validator refused it. |
REPORT_EXPORT_COLUMNS_INVALID | A requested column is not offered, or is repeated. |
REPORT_EXPORT_TOO_LARGE | The estimate is above MaxExportRows (default 100,000). Narrow the filters. |
After the first byte. The estimate is only an estimate, so rows are counted while they are written. If the source passes MaxExportRows, the client disconnects or SyncGenerationTimeout runs out, the connection is aborted: the download fails on the client instead of ending as a short file that looks complete.
The file. UTF-8 with BOM and ; as delimiter, like the rest of the module. A cell that starts with =, +, -, @, tab or carriage return is prefixed with ' (CsvHelper InjectionOptions.Escape), because an export is opened in a spreadsheet. The name comes from the template id, made safe, plus a UTC timestamp, and is sent in Content-Disposition (filename* for non-ASCII). A browser client on another origin needs Content-Disposition in the CORS exposed headers; the GrydAuth CORS helper already exposes it.
Tenant. The data is the session's tenant's. The request carries no tenant, and the data source reads under the session like every other repository.
Log. One line at the end: template, format, rows, bytes, duration and outcome (completed, cancelled, timeout, too_large, failed). The filter values are never logged.
Registration is in Templates.
Declared size and timeout options
MaxSyncGenerationSize, SyncGenerationTimeout, and ForceAsyncAboveBytes are declared options that /generate does not consume. They do not limit generation, set a timeout, or queue large reports. The streaming export is the exception: it applies SyncGenerationTimeout and MaxExportRows. Enforce host-specific resource limits outside this module. The built-in one-shot async command remains unavailable unless a host supplies its own handler.
ReportOutput
The output object returned from generation:
csharp
public sealed class ReportOutput : IDisposable
{
public Stream Content { get; init; } // File content stream
public string FileName { get; init; } // e.g. "report.pdf"
public string ContentType { get; init; } // e.g. "application/pdf"
public ReportFormat Format { get; init; } // Pdf, Excel, Csv, Html
public long FileSizeBytes { get; init; } // Size in bytes
public ReportMetadata Metadata { get; init; } // Title, Author, etc.
public TimeSpan GenerationDuration { get; init; }
public void Dispose() => Content?.Dispose();
}Resource Management
ReportOutput implements IDisposable. Always dispose when using the output directly:
csharp
using var output = (await generator.GenerateAsync<SalesData, SalesParams>(
"sales", parameters, ReportFormat.Pdf)).Data!;
// Use output.Content stream...