Appearance
Advanced
Advanced features including filters, current data-source behavior, observability, multi-tenancy, security, and testing.
Report Filters
IReportFilter exposes before-fetch, after-fetch, before-render, after-generation, and error hooks. Filters are resolved from dependency injection and run in ascending Order. Register them as IReportFilter; there is no AddReportFilter helper.
csharp
using GrydReports.Core.Abstractions;
using GrydReports.Core.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
public sealed class AuditReportFilter(ILogger<AuditReportFilter> logger) : IReportFilter
{
public int Order => 10;
public Task OnBeforeDataFetchAsync(ReportGenerationContext context, CancellationToken ct)
{
context.Items["startedAt"] = DateTime.UtcNow;
return Task.CompletedTask;
}
public Task OnAfterGenerationAsync(
ReportGenerationContext context, ReportOutput output, CancellationToken ct)
{
if (context.Items.TryGetValue("startedAt", out var value) && value is DateTime startedAt)
logger.LogInformation("Generated report {TemplateId} as {FileName} in {Elapsed} ms",
context.TemplateId, output.FileName, (DateTime.UtcNow - startedAt).TotalMilliseconds);
return Task.CompletedTask;
}
}Register the implementation in the host after its normal Reports setup:
csharp
builder.Services.AddScoped<IReportFilter, AuditReportFilter>();The maintained IReportFilter contract and ReportGenerationServiceTests show the lifecycle hooks and ordering.
Data sources and memory use
IStreamingReportDataSource is consumed by the streaming CSV export (POST /reports/export), which writes rows to the response as the source yields them and stores nothing; see Generation and Templates. /generate is unchanged: ReportGenerationService fetches the full result through IReportDataSource, then passes the materialized data to a renderer, so the built-in CSV, Excel, and PDF renderers do not stream. Use /export for a large CSV that is downloaded once, and keep /generate queries bounded by the host's memory.
Output caching
GrydReportsOptions.Caching is currently an options declaration only. The shipped generation path does not read those settings, compute cache keys, reuse report output, or expose cache invalidation. Do not rely on enabling these options to reduce generation work.
The API's synchronous generation and recurring schedules remain available. The built-in one-shot async command returns 503 REPORT_ASYNC_GENERATION_UNAVAILABLE; it does not enqueue work. See Generation for the supported paths.
Observability
GrydReports uses Core's IMetricsCollector and IActivitySourceProvider. Calling AddGrydReportsInfrastructure supplies Core defaults with TryAdd, so host registrations stay in place. The registered Reports helpers are scoped; a scoped host collector or source is resolved in the current operation scope.
Metric catalog
All durations use milliseconds. Metric tags are limited to format, outcome, reason, stage, and delivery_method; unknown enum values map to unknown. Template ids, report parameters, recipients, file names, URLs, payloads, tenant ids, and exception messages are not metric tags.
| Name | Type and unit | Meaning |
|---|---|---|
gryd_reports_generation_total | Counter, reports | Every actual render generation attempt, including early failed Results and caught exceptions. Tags: format, outcome, reason. |
gryd_reports_generation_success_total | Counter, reports | Successful render generation. This does not imply storage or delivery succeeded. |
gryd_reports_generation_failure_total | Counter, reports | Failed render generation, including missing template, unsupported format, null data, template resolution, provider/render errors, and cancellation caught by the existing contract. |
gryd_reports_generation_duration_ms | Histogram, ms | Duration of every actual render generation attempt. |
gryd_reports_stage_total | Counter, operations | Fetch, render, and store outcomes, plus delivery setup failures before a provider call. Tags: stage, format, outcome, reason. |
gryd_reports_stage_duration_ms | Histogram, ms | Fetch, render, store, and delivery durations. Delivery also has a dedicated outcome counter. |
gryd_reports_delivery_total | Counter, provider calls | Outcomes at an actual delivery provider call. accepted means the provider accepted the request; it does not mean the recipient received or opened it. Tags: delivery_method, outcome, reason. |
gryd_reports_file_size_bytes | Histogram, unit unspecified (values are bytes) | Explicit file-size observation after a report is successfully stored. Tag: format. |
gryd_reports_downloaded_total | Counter, downloads | Explicit host observation only; a host should call it only after it has evidence that a download occurred. Tag: format. |
gryd_reports_active_schedules | Gauge, schedules | Explicit host-supplied active schedule count. |
gryd_reports_schedule_created_total | Counter, schedules | Schedule persisted successfully. Failed persistence and recurring-job registration do not count. |
gryd_reports_schedule_execution_total | Counter, executions | A real active scheduled run's result after its execution and schedule bookkeeping completes. Tags: outcome, reason. |
Dashboard selector migration
The old counter names are no longer emitted. Move existing selectors to these bounded series:
| Previous selector | Replacement |
|---|---|
gryd_reports_generated_total | gryd_reports_generation_success_total for successful renders; use gryd_reports_generation_total with outcome for all attempts. |
gryd_reports_generation_failed_total | gryd_reports_generation_failure_total, or gryd_reports_generation_total{outcome="failure"}. |
gryd_reports_delivered_total | gryd_reports_delivery_total{outcome="accepted"}. |
gryd_reports_delivery_failed_total | gryd_reports_delivery_total{outcome="failure"}. |
gryd_reports_scheduled_total | gryd_reports_schedule_created_total. |
gryd_reports_schedule_executions_total | gryd_reports_schedule_execution_total{outcome="success"}. |
gryd_reports_schedule_failures_total | gryd_reports_schedule_execution_total{outcome="failure"}. |
gryd_reports_delivery_duration_ms | gryd_reports_stage_duration_ms{stage="delivery"}. |
The generation duration and file-size names remain available; their series no longer include template_id. Download and active-schedule names remain for explicit host observations only.
There is no built-in async generation queue, download confirmation, or active-schedule sampler. Issuing a signed URL is not a download. The public compatibility methods for generation and delivery record counters without inventing zero-duration samples; the file-size, download, and active-schedule methods are explicit host observations. Reports automatically records file size after successful storage, but does not poll for downloads or schedules. Observations are process telemetry, not durable accounting.
Span catalog
Activities are emitted by the Core source named by IActivitySourceProvider.Source.Name. The default name is the configured Observability.ServiceName; use that name in OpenTelemetry source subscriptions. Reports activity names are:
GrydReports.Generate
GrydReports.GenerateAndStore
GrydReports.GenerateAndDeliver
GrydReports.FetchData
GrydReports.Render
GrydReports.Store
GrydReports.Deliver
GrydReports.Schedule.Create
GrydReports.Schedule.ExecuteThe GenerateAndStore and GenerateAndDeliver workflow activities parent the generation, storage, and delivery operations so a direct call without an ambient request still has one trace. Fetch and render are children of generation; storage and delivery are siblings under the workflow. Activities carry bounded format or delivery-method tags where relevant, plus outcome and, when known, reason. Store and schedule activities may also carry their execution or schedule GUID. Template identifiers and tenant identifiers are not added by the generation path. The workflow follows the existing result contract: a provider refusal leaves a successfully stored report available and does not fail the overall result; the delivery activity and counter still report the refusal.
Export example
csharp
using Gryd.Observability.Abstractions;
using Gryd.Observability.OpenTelemetry.Extensions;
using GrydReports.Infrastructure;
using Microsoft.EntityFrameworkCore;
var connectionString = builder.Configuration.GetConnectionString("GrydReports")!;
builder.Services.AddGrydOpenTelemetry(new ObservabilityOptions
{
ServiceName = "reports-api",
ServiceVersion = "1.0.0",
OpenTelemetry = new OpenTelemetryOptions
{
Enabled = true,
Exporter = "console"
}
});
builder.Services.AddGrydReportsInfrastructure(
configureDbContext: db => db.UseNpgsql(connectionString));Core subscribes the configured source and meter when OpenTelemetry is enabled. For a custom source provider, its actual Source.Name is used. Set OpenTelemetry.Enabled = false to keep Core metrics available to local listeners while disabling the configured OpenTelemetry exporters.
Health Checks
Register the Reports database check when its connection string is available, plus the module self-check:
csharp
using GrydReports.Infrastructure.Extensions;
builder.Services.AddGrydReportsHealthChecks(builder.Configuration);The generated-file scanner and storage checks belong to GrydFiles; configure that module's health checks separately when the host needs them.
Multi-Tenancy
GrydReports inherits multi-tenancy from the Gryd.IO core framework.
Tenant Isolation
All report data (executions, schedules) is automatically scoped by TenantId. Queries automatically include tenant filtering via the base entity configuration. Generated files are stored in GrydFiles under the execution's tenant — also for scheduled runs, which take the tenant from the schedule — so a download URL is only ever issued inside that tenant.
Global reports
GrydReportsOptions.GlobalReports is declared as a set of template Type values, but the current runtime does not read it. Adding a type there does not exempt its report data or execution from tenant filtering. Keep tenant ownership explicit and do not use this option to expose cross-tenant data.
Where files are stored
Report files are GrydFiles objects in the gryd.report profile. Their keys are built by GrydFiles (tenant, profile, date, file id) and never leave the module — clients get a short-lived URL from GET /reports/{id}/download instead.
Authorization and PDF signatures
The options model declares Permissions and DigitalSignature, but the current Reports runtime does not read either setting. Reports does not enforce the per-template roles shown by those declarations, and it does not cryptographically sign generated PDFs. Apply authorization in the host before calling Reports. The QuestPDF SignatureComponent draws a visible signature line and labels; it is not a digital signature. See the current GrydReportsOptions declarations and SignatureComponent.
Testing
Use the maintained test suites as executable examples of the current contracts:
ReportGenerationServiceTestscovers generation, filters, rendering, and delivery behavior.ReportsControllerTestschecks API response contracts, including that download returns a URL DTO rather than file bytes.DownloadReportQueryHandlerTestscovers URL issuance, file-not-available errors, and download accounting.ReportsControllerAsyncUnavailableTestsverifies the built-in one-shot async request returns 503 without creating an execution.
Relational persistence tests
The Reports infrastructure persistence suite runs against the production PostgreSQL schema and migrations in an isolated database per test. The repository tests check migration history and model alignment, JSONB definition metadata, execution history filters and SQL pagination, schedule queries, tenant filters, soft deletion, and PostgreSQL uniqueness constraints. They also inspect the executed count and limit/offset queries and exercise cleanup through PostgreSQL DELETE.
Run the focused repository suite with Docker available:
sh
dotnet test tests/Modules/Reports/GrydReports.Infrastructure.Tests/GrydReports.Infrastructure.Tests.csproj \
-c Release --filter "FullyQualifiedName~PostgresTests" \
--collect:"Code Coverage" --settings coverage.runsettingsThe tests use the existing shared PostgreSQL container and create a disposable database for each case. Migration coverage checks the sole historical initial migration and proves a repeated migrate is a no-op. Tenant enforcement tests pass through AddGrydReportsInfrastructure and its registered save interceptor. Cleanup physically deletes only older, tenant-visible, non-soft-deleted executions; the global soft-delete filter keeps previously deleted rows. Schedule deletion is exercised through the tracked repository path; detached deletion and restoration are not part of that contract. Definition records are a shared template registry; IsGlobal does not assign tenant ownership. The tests verify the existing schedule JobId uniqueness rule, including after soft deletion, and allow multiple null job ids. Definition upsert updates display metadata and supported formats; it does not promise parameter or CLR type replacement. These tests establish PostgreSQL behavior only; deployed provider compatibility and load characteristics require separate checks.