MechaOnion 0.4.0-preview
dotnet add package MechaOnion --version 0.4.0-preview
NuGet\Install-Package MechaOnion -Version 0.4.0-preview
<PackageReference Include="MechaOnion" Version="0.4.0-preview" />
<PackageVersion Include="MechaOnion" Version="0.4.0-preview" />
<PackageReference Include="MechaOnion" />
paket add MechaOnion --version 0.4.0-preview
#r "nuget: MechaOnion, 0.4.0-preview"
#:package MechaOnion@0.4.0-preview
#addin nuget:?package=MechaOnion&version=0.4.0-preview&prerelease
#tool nuget:?package=MechaOnion&version=0.4.0-preview&prerelease
MechaOnion
MechaOnion is a single-assembly, modular base library for .NET (net10.0). Each module
lives in its own folder and namespace (MechaOnion.<Module>) and can be enabled or
disabled by configuration.
Current version: 0.4.0-preview. See the CHANGELOG for breaking changes.
Three-line setup
var builder = WebApplication.CreateBuilder(args);
builder.AddMechaOnion(builder.Configuration); // 1) configuration and options
builder.Services.AddMechaOnion(); // 2) services, repositories and providers
var app = builder.Build();
app.UseMechaOnion(); // 3) middlewares and endpoints
app.Run();
UseMechaOnion applies a fixed pipeline order regardless of module discovery order:
CORS → Routing → Tracing → Tenant → Permissions → Errors → endpoints → health checks.
Tracing runs before Tenant and Permissions, so their logs already carry tracing_id, step_id
and origin.
Modules
| Flag | Module | Responsibility |
|---|---|---|
Core |
Core | Entities, contracts, exceptions, attributes, helpers and validations |
Auth |
Auth | JWT validation, permissions and CORS |
Configs |
Configs | Tenant/app key-value configuration |
Tenants |
Tenants | Tenants, themes and resolution |
Users |
Users | Users, login, profiles, groups, roles and fields |
Events |
Events | Event catalog, automations (with outgoing webhooks) and integrations |
Configuration |
Configuration | Host sources, environment/project info and OpenAPI helpers |
Database |
Database | EF Core base context and repository infrastructure |
Messaging |
Messaging | Local and RabbitMQ providers, retry, scheduling and DLQ |
MessagingAdmin |
MessagingAdmin | Administration API for the local and RabbitMQ providers |
Observability |
Observability | Structured logging, W3C tracing and OpenTelemetry trace export |
HealthChecks |
HealthChecks | Readiness and liveness endpoints |
Web |
Web | CORS, error handling, ProblemDetails, JSON options and OpenAPI/Scalar docs |
Enrich |
Enrich | Data enrichment pipeline and contracts |
Scripting |
Scripting | Lua sandbox, script libraries, execution history and variables (auto-enabled) |
ScheduledTasks |
ScheduledTasks | Per-tenant Lua tasks run on a cron schedule |
Webhooks |
Webhooks | Per-tenant Lua HTTP entry points protected by webhook API keys |
Flags are combined through MechaOnion:Modules (default All). Dependencies are
auto-enabled and registered in topological order.
Configuration
"MechaOnion": {
"Modules": "All",
"ServiceName": "MechaOnion",
"EnableTenantFilter": true,
"MigrationsAssembly": "",
"DefaultTenantId": null,
"EnableSingleTenantFallback": false
}
Extending the library
Default implementations are registered with TryAdd; the last registration wins, so
consumers can replace services without editing the library.
// Replace a service through its public contract.
builder.Services.Replace(ServiceDescriptor.Scoped<IEnrichmentRepository, MyEnrichRepository>());
// Replace the database provider through options.
builder.Services.AddSingleton(new MechaOnionDbContextOptions
{
MigrationsAssembly = "MyHost",
EnableTenantFilter = true,
ConfigureProvider = options => options.UseNpgsql(connectionString),
});
// Register a custom tenant resolver after the library (last one wins).
builder.Services.AddScoped<ITenantResolver, MyTenantResolver>();
E-mail delivery is decoupled through IEmailDispatcher (MechaOnion.Communication). The
host registers an adapter for its e-mail service:
builder.Services.Replace(
ServiceDescriptor.Singleton<IEmailDispatcher, MyEmailDispatcher>());
Tracing
Every request, message consumption, internal call, scheduled task execution (root step
cronjob {taskName}) and webhook call (step webhook {slug}, child of the request) runs in a W3C
Trace Context step (System.Diagnostics.Activity). The flow id (TracingId) is the trace id and the step id is the
span id, so logs, traces and DTO metadata use the same values. Origin and flow start travel in
the mo entry of the tracestate (mo=o:<MechaOnion:ServiceName>;s:<unix-ms>). See
ADR-002.
- DTOs:
DtoBase.Tracingholds theTracingMetadataof the step that created the DTO (TracingId,StepId,ParentStepId,Origin,StartedAt,EndedAt). It is never written to nor read from JSON and has no public setter; copy it withtarget.WithTracingFrom(source). - Messaging: publications (queue, topic, batch and schedule) carry
traceparent/tracestatewith the local provider and RabbitMQ; consumers continue the flow and readcontext.Metadata.Tracing. Retries and dead letters stay in the same flow. - Logs: every event emitted in a step carries
tracing_id,step_idandorigin, plus aStep completedevent withduration_ms. - Responses and external calls never carry tracing metadata. The only exception is the
v1/MessagingAdminAPI, which exposestracingId,originandflowStartedAtper message to operators.
Internal HTTP clients (opt-in)
Outgoing propagation is disabled process-wide. The
Coremodule replaces the runtime propagator with the NoOutput one, so noHttpClientsendstraceparent/tracestate(outgoing automation webhooks, Mautic, the Luahttplibrary, third-party SDKs and your own clients included) unless it opts in. Do not pre-build HTTP handlers beforebuilder.Services.AddMechaOnion().
Mark only the clients that call your own services:
builder.Services
.AddHttpClient("orders-api", client => client.BaseAddress = new Uri("http://orders-api"))
.AddMechaOnionTracing();
The receiving MechaOnion API continues the flow in a new step. Incoming traceparent headers
are always accepted; a missing or malformed header starts a new flow with this service as origin.
Settings
Trace export reuses the LoggingSettings section:
"LoggingSettings": {
"OpenTelemetryUrl": "http://opentelemetry-collector:4317",
"EnableTracing": true,
"TracingSampleRatio": 1.0,
"TracingOpenTelemetryUrl": null
}
| Key | Default | Description |
|---|---|---|
EnableTracing |
true |
Exports traces (OTLP gRPC, batch). Off keeps metadata, propagation and logs. |
TracingSampleRatio |
1.0 |
Fraction (0–1) of flows started here that are exported; continued flows follow the origin decision. |
TracingOpenTelemetryUrl |
null |
Trace collector endpoint (http/https); falls back to OpenTelemetryUrl. |
An unavailable collector never fails requests or consumers: spans are dropped in the background.
Two-factor authentication (e-mail code)
Password login is protected by a second factor by default. After the credentials are
validated, POST /v1/Login creates a TwoFactorChallenge and sends a 6-digit code to the
user e-mail; the JWT is only issued by POST /v1/Login/VerifyTwoFactor. The code has a
single use, expires in 10 minutes, allows 5 wrong attempts per challenge and 10 per account
in 15 minutes, and the resend honours a 60 s cooldown plus 3 sends per 15 minutes.
| Route | Purpose |
|---|---|
POST /v1/Login |
Validates the password and returns code = TwoFactorRequired (9) with challengeId, codeExpiresAt and maskedEmail; no token. |
POST /v1/Login/VerifyTwoFactor |
Consumes { challengeId, code } and returns the usual token + user payload. |
POST /v1/Login/ResendTwoFactorCode |
Rotates the code of an active challenge respecting the limits. |
POST /v1/Login/RequestLoginCode / GET /v1/Login/ByCode |
Refused with code = Invalid (6) while the tenant requires the second factor. |
Breaking change: a host that upgrades without configuring anything starts requiring the code. Register a real
IEmailDispatcherbefore deploying and check the migration notes inCHANGELOG.md.
Settings
"TwoFactorSettings": {
"Enabled": true,
"CodeLength": 6,
"CodeDurationMinutes": 10,
"MaxAttemptsPerChallenge": 5,
"MaxAttemptsPerAccountWindow": 10,
"AttemptWindowMinutes": 15,
"ResendCooldownSeconds": 60,
"MaxSendsPerWindow": 3,
"MaxSendsPerIpWindow": 10,
"SendWindowMinutes": 15,
"TemplateCode": "TWO_FACTOR_CODE",
"ServiceCode": ""
}
The IConfiguration section is only the application default. The HMAC key used to store the
code hash is not part of the policy: it is generated (32 random bytes, Base64) on first
use and persisted in its own global ConfigItem (Key = "TwoFactorSettings.HashKey").
Global and per-tenant override
The effective policy is resolved on every login in this order:
ConfigItemrow of the tenant (Key = "TwoFactorSettings",TenantId = <tenant>);- global
ConfigItemrow (TenantId = ""); - the
TwoFactorSettingssection ofIConfiguration; - the built-in defaults (
Enabled = true).
A row with invalid JSON or values outside the documented ranges is logged
(TwoFactorSettingsOverrideInvalid) and ignored — the previous source is used, never an
error. To disable the second factor for one tenant, persist a row for it:
{ "Enabled": false }
A
ConfigItemrow wins overappsettings. If a global row exists, changingTwoFactorSettings:Enabledin the configuration file has no effect until the row is updated or removed. Persist overrides throughIConfigsService(the demo exposesPOST /demo/config) instead of editing the file and assuming it takes precedence.
Schema (consumer-owned)
The library does not ship migrations. Create the table in the host schema (PostgreSQL DDL
generated from MechaOnionDbContext; the demo and the integration tests use
Database.EnsureCreated()):
CREATE TABLE "TwoFactorChallenge" (
"Id" text NOT NULL,
"UserId" text NOT NULL,
"TenantId" text NOT NULL,
"CodeHash" text NOT NULL,
"PasswordFingerprint" text NOT NULL,
"ExpirationDate" timestamp with time zone NOT NULL,
"Attempts" integer NOT NULL,
"LastAttemptAt" timestamp with time zone NULL,
"SendCount" integer NOT NULL,
"SendWindowStart" timestamp with time zone NOT NULL,
"LastSentAt" timestamp with time zone NOT NULL,
"IpAddress" text NULL,
"Remember" boolean NOT NULL,
"CreatedAt" timestamp with time zone NOT NULL,
"ConsumedAt" timestamp with time zone NULL,
CONSTRAINT "PK_TwoFactorChallenge" PRIMARY KEY ("Id")
);
CREATE INDEX "IX_TwoFactorChallenge_UserId" ON "TwoFactorChallenge" ("UserId");
CREATE INDEX "IX_TwoFactorChallenge_IpAddress_CreatedAt"
ON "TwoFactorChallenge" ("IpAddress", "CreatedAt");
xmin (the PostgreSQL system column) is the optimistic concurrency token used to guarantee
single use of a code; no extra column is required. The table contains only the HMAC-SHA256
hash — the clear code exists only in memory and in the e-mail.
Host without an e-mail provider
NullEmailDispatcher is the fallback and never throws. When TwoFactorSettings.Enabled is
true and the registered dispatcher is still the null one, the startup emits a
TwoFactorEmailDispatcherMissing warning and every login attempt fails with
TwoFactorDeliveryException (HTTP 200 + code = Error): the user never receives a
"code sent" answer for a code that did not leave. The escapes are registering a real
IEmailDispatcher or disabling the flag globally/for the tenant.
Known bypasses and operational notes
- E-mail validation keeps issuing tokens without the second factor, as before. It is a
documented risk (outside the scope of this change) and should be reviewed before relying on
2FA as the only barrier. The legacy webhook bypass (impersonation plus a JWT handed to the
script) was removed in
0.4.0-preview. - Password recovery is unchanged; the next login after it still requires the code.
- Session renewal does not require a new code (
Refreshkeeps the authenticated session). - Reverse proxies: the per-IP limit uses
HttpContext.Connection.RemoteIpAddress. Behind nginx/ingress withoutUseForwardedHeaders, every user shares the proxy IP and theMaxSendsPerIpWindowlimit can throttle the whole tenant. Configure forwarded headers in the host. - Logs carry
TwoFactorChallengeCreated,TwoFactorChallengeConsumed,TwoFactorChallengeResent,TwoFactorVerificationFailed,TwoFactorRateLimited(Scope = User|Ip|Resend),TwoFactorEmailDispatchFailed,TwoFactorAccountLocked,TwoFactorIpThrottledandTwoFactorChallengeInvalidated. They never contain the code or the hash, and the e-mail/IP are masked (j***@example.com,203.0.***.***). - Rollback: setting
Enabled = false(globally or per tenant) restores the password-only login; the table stays unused and can be dropped later.
Automations: scheduled tasks and webhooks
Tenants register automations through the API, with no deploy (ADR-003):
- Scheduled tasks (
ScheduledTasks) run a Lua script on a cron expression (standard 5-field format) in an IANA time zone, exactly once per occurrence across all instances. - Webhooks (
Webhooks) run a Lua script synchronously when an integrator callsv1/Hooks/{tenantId}/{slug}with a webhook API key, and answer with the response built by the script.
Both depend on Scripting, which is enabled automatically. Each module can be turned on alone
("Modules": "ScheduledTasks" or "Modules": "Webhooks"). The library ships no migrations: create
the tables with the DDL in the CHANGELOG (0.4.0-preview).
Roles, tenant and permissions
| Permission | Routes |
|---|---|
scheduled_tasks_manage |
v1/ScheduledTasks, v1/ScheduledTask[/{id}], /{id}/Enable, /{id}/Disable |
webhooks_manage |
v1/Webhooks, v1/Webhook[/{id}], /{id}/Enable, /{id}/Disable |
webhook_keys_manage |
v1/WebhookApiKeys, v1/WebhookApiKey[/{id}], /{id}/Revoke |
scheduled_tasks_manage or webhooks_manage |
v1/ScriptVariables, v1/ScriptVariable[/{id}] |
| any of the three | v1/ScriptExecutions, v1/ScriptExecution/{id} (filters sourceType, sourceId, status, from, to) |
Every route also accepts system_admin, and admin passes as a wildcard. A tenant
administrator (admin or system_admin) sees every item of the tenant and may assign any role
of the tenant to any task or webhook. Other users see and change only their own items, cannot assign
a role (403) and link keys only to webhooks they created (403 otherwise). When a non-admin edits
the content of an item that has an assigned role, the role is removed and the response carries
roleCleared = true; enabling or disabling keeps it.
An automation runs with the permissions of its role, or with the live permissions of its creator
when no role is assigned. They are read on every execution: an inactive or removed creator, or a
removed role, refuses the run (Denied in the history, 403 on a webhook call).
Settings
"ScriptingSettings": {
"QueueDestinations": [
{ "Name": "billing-close", "Kind": "Queue", "Permission": "billing_admin" },
{ "Name": "crm-events", "Kind": "Topic", "Permission": "crm_integration" }
],
"Http": { "Enabled": true, "AllowedHosts": ["api.partner.com"], "MaxRequestsPerExecution": 20, "MaxResponseBytes": 1048576 },
"MaxQueueMessagesPerExecution": 100,
"MaxLogBytes": 4096,
"RetentionDays": 7,
"MaxConcurrentExecutions": 8
},
"ScheduledTasksSettings": { "TimeoutSeconds": 30, "CatalogPollSeconds": 5, "FullResyncMinutes": 5 },
"WebhooksSettings": { "TimeoutSeconds": 10, "MaxBodyBytes": 1048576, "MaxKeyLifetimeDays": 365 }
| Key | Default | Description |
|---|---|---|
ScriptingSettings:QueueDestinations |
[] |
The only queues/topics queue.send may publish to, each with the permission required from the automation role. An entry without Name, Kind (Queue/Topic) or Permission fails the startup. |
ScriptingSettings:Http:Enabled |
true |
false removes the http library. |
ScriptingSettings:Http:AllowedHosts |
[] |
Hosts allowed even when they resolve to an internal address (blocked by default). |
ScriptingSettings:RetentionDays |
7 |
Days the execution history is kept. |
ScriptingSettings:MaxConcurrentExecutions |
8 |
Scheduled executions running at the same time per instance. |
ScheduledTasksSettings:TimeoutSeconds |
30 |
Maximum duration of a task execution. |
ScheduledTasksSettings:CatalogPollSeconds |
5 |
Interval of the version check that reloads the schedule in every instance. |
ScheduledTasksSettings:FullResyncMinutes |
5 |
Unconditional reload of the schedule. |
WebhooksSettings:TimeoutSeconds |
10 |
Maximum duration of a webhook script (504 when exceeded). |
WebhooksSettings:MaxBodyBytes |
1048576 |
Largest accepted request body (413 above it). |
WebhooksSettings:MaxKeyLifetimeDays |
365 |
Longest expiration accepted for a new API key. |
Calling a webhook
POST v1/Webhook returns the call address in url, and POST v1/WebhookApiKey returns the key
(mow_<prefix8>_<secret>) only once; afterwards only the prefix, status and dates are visible.
The database stores only the SHA-256 hash of the key.
curl -X POST "https://api.example.com/v1/Hooks/<tenantId>/<slug>" \
-H "X-API-Key: mow_1a2b3c4d_..." \
-H "Content-Type: application/json" \
-d '{"id":"o-7","items":[1,2,3]}'
The key may also go in ?api_key=. The webhook accepts one method (GET, POST, PUT, PATCH
or DELETE).
| Status | When |
|---|---|
| defined by the script | Valid call (default 200 with an empty body) |
401 |
Key missing, unknown, expired, revoked, from another tenant or not linked to the webhook (same message for all), or X-Tenant-Id different from the route tenant |
404 |
Unknown or disabled slug (only answered to a valid key) |
405 |
Method different from the configured one (Allow header) |
413 / 400 |
Body above MaxBodyBytes / invalid JSON with application/json (the script does not run) |
403 |
Creator inactive or removed, or role removed |
500 / 504 |
Script error (generic body) / timeout |
Revoking a key, disabling or deleting a webhook takes effect on the next call. Changes to
scheduled tasks reach every instance in up to CatalogPollSeconds.
Lua reference
Scripts run in a MoonSharp sandbox (Lua 5.2) without io, os.execute, load,
loadstring, dofile, require and debug, and are interrupted at the timeout.
| Global | Available in | Content |
|---|---|---|
ctx |
both | Task: trigger = "schedule", taskId, taskName, scheduledFor (ISO-8601). Webhook: trigger = "http", method, webhookId, slug |
headers, queryParameters |
webhook | Request headers and query (string tables; the API key is removed) |
body / rawBody |
webhook | JSON body as a table (nil otherwise) / body text when it is not JSON |
response |
webhook | status (200), body (string or table → JSON) and headers set by the script |
| Library | Contract |
|---|---|
json.encode(value) / json.decode(text) |
JSON ↔ Lua table |
log.write(message) |
String or { message = , body = }; kept in the history (up to MaxLogBytes) and logged. print(...) writes to the same execution log, never to the host console |
http.request{ method, url, headers, body } |
Returns { status, body, headers }. Up to 20 calls per execution, response ≤ 1 MB, no redirects, timeout ≤ 10 s. Internal addresses (loopback, private ranges, link-local and cloud metadata, 100.64.0.0/10, fc00::/7, fe80::/10, fec0::/10, and IPv4 embedded in IPv6 via NAT64/6to4/IPv4-mapped) are blocked unless the host is in AllowedHosts; only http/https |
variables.get(key) / variables.set{ key = , value = } |
Key-value store of the automation creator (values ≤ 64 KB); a script never reads variables of another user |
queue.send(name, payload) |
Publishes the table to an allowed queue or topic (≤ 100 messages of ≤ 256 KB per execution). Denied when the destination is not allowed or the role lacks its permission. The message carries TenantId (automation tenant), UserId (creator) and the tracing flow |
-- Scheduled task: close the billing of the day through a queue consumer of the host.
queue.send('billing-close', { day = ctx.scheduledFor, requestedBy = ctx.taskName })
-- Webhook: validate and enqueue an order, answering the integrator.
if body == nil or body.id == nil then
response.status = 400
response.body = { error = 'id is required' }
return
end
queue.send('crm-events', { orderId = body.id, items = #body.items })
log.write('order ' .. body.id .. ' enqueued')
response.status = 202
response.body = { accepted = body.id }
Lua 5.2 vs 5.4: scripts written for Lua 5.3/5.4 (for example the Ao-Tomato ones) must replace
the bitwise operators (&, |, ~, <<, >>) with bit32, integer division // with
math.floor(a / b), and drop <const>/<close> and the utf8 library. goto, os.time and
os.date are available.
Execution history
Every run is recorded in ScriptExecution with origin (Schedule/Http), start, end, status
(Running, Succeeded, Failed, Skipped, Denied, TimedOut), error, log messages and the
TracingId of the flow; request bodies, headers and query are never stored. An occurrence that
finds the previous run of the same task still active is recorded as Skipped; occurrences missed
while the application was down are not recovered. Records older than RetentionDays are removed
hourly. Queue consumers must be idempotent: an instance that dies during a run does not repeat it.
Persistence and migrations
The library does not apply migrations; the consumer owns the schema. The sample host
uses MechaOnionDbContext directly with Database.EnsureCreated():
using var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<MechaOnionDbContext>();
dbContext.Database.EnsureCreated();
A production host can inherit from MechaOnionDbContext to add its own mappings and seeds,
and keep the migrations in its own assembly:
public sealed class AppDbContext : MechaOnionDbContext
{
public AppDbContext(
DatabaseSettings databaseSettings,
ITenantContext? tenantContext = null,
MechaOnionDbContextOptions? options = null)
: base(databaseSettings, tenantContext, options)
{
}
}
Set MechaOnion:MigrationsAssembly (or MechaOnionDbContextOptions.MigrationsAssembly) to
the assembly that contains the migrations.
Tenant resolution
The tenant is resolved in this order:
X-Tenant-Idheadertenant_idclaimtenantIdroute valueMechaOnion:DefaultTenantId(fixed fallback)- Single-tenant fallback (
MechaOnion:EnableSingleTenantFallback)
The single-tenant fallback queries the Tenant table on demand. It only applies when the
endpoint requires a tenant and no other resolver found one:
- Multi-tenant: leave
EnableSingleTenantFallbackdisabled. Requests without an explicit tenant keep returning400. - Single-tenant: enable
EnableSingleTenantFallback. If the database contains exactly one tenant, that tenant is used automatically. If it contains zero or multiple tenants, the request still fails with400. - Fixed tenant: set
DefaultTenantIdwhen the fallback must be a specific tenant regardless of the database contents.
API documentation
The Web module registers and maps the OpenAPI document and the Scalar UI:
GET /docs— Scalar UIGET /openapi/v1.json— OpenAPI document
Both endpoints are anonymous and explicitly opt out of the tenant requirement, so they
can be opened directly in a browser without X-Tenant-Id, a tenant route value or a
resolved tenant. Mapping is skipped when EnvironmentSettings:EnvironmentType is
production.
Messaging administration (v1/MessagingAdmin)
The MessagingAdmin module (MechaOnionModules.MessagingAdmin) exposes a single
v1/MessagingAdmin API over two providers:
- local — messages persisted in the application database through the local messaging
provider (
MechaOnionDbContext); - rabbitmq — queues and exchanges of a vhost accessed through the RabbitMQ Management HTTP API (the management plugin must be enabled).
Enabling the module is just a flag: MechaOnion:Modules = "All" already includes it. The
Messaging, Auth, Database and Configuration dependencies are auto-enabled, and the
permissions remain system_admin/admin.
Settings
"MessagingAdminSettings": {
"ManagementUrl": "http://rabbitmq:15672",
"Username": "",
"Password": "",
"VirtualHost": "/",
"TimeoutSeconds": 10,
"MaxPageSize": 200
}
Username and Password are sensitive: provide them through environment variables,
user-secrets or the orchestrator's secret manager — never commit real credentials.
Without ManagementUrl/credentials the local provider keeps working; rabbitmq
responds 503 with an explicit message.
Provider selection
Every route accepts provider=local|rabbitmq as an optional query parameter:
- without
provider, the default islocalwhenMessagingSettings.Local=trueandrabbitmqwhenfalse; provider=localwithMessagingSettings.Local=falsereturns409 Conflict;provider=rabbitmqforces the external provider regardless ofMessagingSettings.Local;- an unknown
providerreturns400 Bad Request; - Management API errors never fall back silently to the local provider:
401/403unauthorized,404not found,409duplicate,502invalid response and503timeout/unavailable.
Capability matrix
| Operation | local | rabbitmq |
|---|---|---|
| List/detail queues and topics/exchanges | ✅ | ✅ |
| Create/remove queues and exchanges | ✅ | ✅ |
| List paginated messages | ✅ (queues and topics) | ✅ (queues only) |
| Inspect a message without consuming | ✅ | ✅ (ack_requeue_true, MaxPageSize window) |
| Individual message removal | ✅ | ❌ (400, capability not available) |
| Purge | ✅ (pending/scheduled; optional DLQ) | ✅ (queues only) |
| Purge an exchange | ✅ (local topics) | ❌ (not offered by the Management API) |
| Requeue/reprocess | ✅ (back to Pending) |
✅ (publish + best-effort removal) |
Limitations
- Exchange purge: the RabbitMQ Management API does not support purging an exchange;
the operation returns
400citing the missing capability. - Individual message removal: the Management API cannot remove an arbitrary message;
the
rabbitmqprovider refuses with400. - Listing messages from an exchange: exchanges do not store messages, so listing and
inspection on RabbitMQ exchanges return
400. - Best-effort requeue: the external message is republished to its origin
(
x-death[0].queue) or to the explicittarget, and the origin is removed withack_requeue_false. The operation is at-least-once; duplicates and concurrency are possible. Withoutx-deathand withouttarget, the response is400. - Credentials: they never appear in logs, responses or exceptions;
Authorizationis not logged.
Running the sample
The MechaOnion.Demo host composes the library with the three lines, creates its own
schema with EnsureCreated() and seeds a tenant, an admin role and an admin user. It covers
login, tenant, configuration and messaging. The sample keeps the second factor
explicitly disabled (TwoFactorSettings.Enabled = false) so the password login stays the
shortest path to try the library; remove the override to exercise the two-step flow.
dotnet run --project samples/MechaOnion.Demo/MechaOnion.Demo.csproj
The JWT secret comes from MECHAONION_DEMO_JWT_SECRET; without the variable the demo
generates an ephemeral key valid only for the current process.
Build, test and pack
dotnet restore MechaOnion.slnx
dotnet build MechaOnion.slnx
dotnet test tests/MechaOnion.Tests/MechaOnion.Tests.csproj
dotnet pack src/MechaOnion/MechaOnion.csproj -c Release -o artifacts
Integration tests use PostgreSQL and are skipped unless a test connection is configured:
MECHAONION_TEST_DB_CONNECTION="Host=localhost;Database=mechaonion;Username=postgres;Password=postgres" \
dotnet test tests/MechaOnion.Tests/MechaOnion.Tests.csproj
Continuous integration and NuGet publishing
.github/workflows/ci.ymlruns on every pull request, on pushes tomainand on manual dispatch: builds the solution on Linux, macOS and Windows and runs the suite (without database, so PostgreSQL tests are skipped), plus a Linux job with a PostgreSQL service that runs the full suite..github/workflows/publish.ymlruns on every push tomain(and on manual dispatch with an optional version): it restores, builds, runs the full suite against PostgreSQL, packs and pushes the package to nuget.org with--skip-duplicate.- The published version comes from
<Version>insrc/MechaOnion/MechaOnion.csproj. To publish a new package, bump that value in the merge tomain; without a bump the push is a no-op (--skip-duplicate). - Requires the repository secret
NUGET_API_KEY(nuget.org API key scoped topushof theMechaOnionpackage). A manual run can override the version from the workflow inputs.
The user (or role) in the connection string needs permission to create databases: the demo
acceptance test owns <database>_demo, created from the same connection string, so it never
shares schema or configuration rows with the other integration tests.
The optional RabbitMQ end-to-end tests are skipped unless the Management API is configured:
MECHAONION_TEST_RABBITMQ_MANAGEMENT_URL="http://localhost:15672" \
MECHAONION_TEST_RABBITMQ_USER="guest" \
MECHAONION_TEST_RABBITMQ_PASSWORD="guest" \
dotnet test tests/MechaOnion.Tests/MechaOnion.Tests.csproj --filter "FullyQualifiedName~RabbitMq"
Preview limitations
- The library does not apply migrations, does not include ASP.NET Identity, social login, a database per tenant or automatic data migration.
License
MIT. See LICENSE.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- AutoMapper (= 14.0.0)
- Cronos (>= 0.13.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.9)
- Microsoft.AspNetCore.OpenApi (>= 10.0.9)
- Microsoft.EntityFrameworkCore (>= 10.0.9)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.9)
- MoonSharp (>= 2.0.0)
- Npgsql (>= 10.0.3)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 10.0.2)
- OpenTelemetry.Exporter.OpenTelemetryProtocol (>= 1.21.0)
- OpenTelemetry.Extensions.Hosting (>= 1.21.0)
- OpenTelemetry.Instrumentation.AspNetCore (>= 1.21.0)
- OpenTelemetry.Instrumentation.Http (>= 1.21.0)
- RabbitMQ.Client (>= 6.8.1)
- Scalar.AspNetCore (>= 2.16.7)
- Serilog (>= 4.3.1)
- Serilog.Enrichers.AspNetCore (>= 1.0.0)
- Serilog.Enrichers.Environment (>= 3.0.1)
- Serilog.Enrichers.Process (>= 3.0.0)
- Serilog.Sinks.Console (>= 6.1.1)
- Serilog.Sinks.OpenTelemetry (>= 4.2.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.4.0-preview | 50 | 11/20/2026 |
| 0.3.0-preview | 59 | 11/18/2026 |
| 0.2.0-preview | 55 | 11/17/2026 |
| 0.1.0-preview | 82 | 11/8/2026 |