π API Gateway Blueprint¶
π° What Is an API Gateway Blueprint?¶
An API Gateway Blueprint is a channel-specific contract and design document for exposing, composing, securing, and orchestrating backend APIs β tailored for a specific frontend, mobile app, or partner integration.
In the ConnectSoft AI Software Factory, this blueprint governs the creation of a custom .NET solution acting as a Backend for Frontend (BFF) layer. It aggregates multiple microservices into a unified API surface optimized for a particular user experience.
It defines not just what APIs to expose, but also how, to whom, and under what constraints and orchestration logic.
π― Why It Exists¶
Typical service architectures expose raw microservices directly β leading to coupling, over-fetching, security fragmentation, and inconsistent UX APIs.
The API Gateway Blueprint solves this by:
- β³οΈ Defining user experience-aware endpoints (web, mobile, admin, etc.)
- π Orchestrating cross-service flows (response merging, sequential calls, fallback logic)
- π Centralizing security, roles, and access controls
- π Injecting observability, metrics, trace tags, and correlation IDs
- βοΈ Enabling agent-based generation of deployable .NET gateway solutions
π Role in the AI Software Factory¶
The blueprint is generated by the Gateway Generator Agent once:
- The Vision Blueprint defines exposed actors and app types (e.g.,
Vet Mobile App,Admin Portal) - The Product Blueprint defines which microservices are relevant to the UX
- The Microservice Blueprints declare their public APIs and exposure metadata
The generated blueprint is used to:
- π§ Scaffold a .NET API Gateway Solution
- π§ Embed route metadata in memory graph and observability layer
- π Drive DevOps automation, testing, documentation, and deployment
π§ Blueprint Is:¶
| Property | Value |
|---|---|
| π§ Generated by | API Gateway Generator Agent |
| π§βπ» For frontend | Web, Mobile, Admin, Partner, External APIs |
| π¦ Consumes | Product, Microservice, Vision Blueprints |
| π Regenerable | Yes, with trace preservation and diff rules |
| π§ Memory Shape | Vector + traceId + UX channel tags |
π Output Structure¶
blueprints/gateways/{channel}/api-gateway-blueprint.md
blueprints/gateways/{channel}/api-gateway-blueprint.json
src/gateways/{channel}/
βββ Gateways.{Channel}.Api.csproj
βββ Controllers/
βββ Orchestrators/
βββ DTOs/
βββ Auth/
βββ Observability/
π Example Use Cases¶
| Channel | Blueprint Path | Purpose |
|---|---|---|
web |
blueprints/gateways/web/api-gateway-blueprint.md |
Expose APIs for browser UI |
mobile |
blueprints/gateways/mobile/api-gateway-blueprint.md |
Optimized APIs for mobile app |
admin |
blueprints/gateways/admin/api-gateway-blueprint.md |
Internal tools, reports |
π§ How Itβs Generated by Agents and CLI Templates¶
The API Gateway Blueprint is created by the π§ API Gateway Generator Agent, based on frontend requirements, exposed microservice APIs, and vision-driven routing rules. It is not a static file β it is the output of orchestration, composition, and policy-aware synthesis.
This agent assembles, normalizes, and generates all required data to build a custom .NET BFF gateway solution using a dedicated CLI template: connectsoft.apigateway-solution.
π§ Generator Agent Overview¶
| Property | Description |
|---|---|
| Name | API Gateway Generator Agent |
| Triggered By | Completion of Product + Microservice Blueprints |
| Inputs | ProductBlueprint, MicroserviceBlueprints[], VisionBlueprint, template registry |
| Outputs | api-gateway-blueprint.md/json/yaml, project scaffolding, memory traces |
| Memory Tagging | channelId, exposedApis[], routeScope, authMethod, tenantIsolation |
π Generation Flow¶
- Reads Product Blueprint for required user-facing endpoints by channel
- Filters Microservices by
exposeInGateway: trueandgatewayChannel: mobile|web|admin - Merges API metadata, security policies, and orchestration hints
- Generates Blueprint Files (
md,json,yaml) - Executes CLI Template to scaffold .NET gateway project
- Writes Trace Metadata to the memory graph
π οΈ CLI Template: connectsoft.apigateway-solution¶
dotnet new connectsoft.apigateway-solution \
--channel mobile \
--project-name ConnectSoft.Gateways.Mobile \
--exposed-apis referrals,notifications \
--auth oidc \
--tenant-aware true \
--rate-limit enabled
This template generates a fully structured gateway solution including: DI setup, route mapping, auth middleware, observability wiring, DTO adapters, health checks, and orchestration stubs.
π Example Artifact Output¶
blueprints/gateways/mobile/api-gateway-blueprint.md
blueprints/gateways/mobile/api-gateway-blueprint.json
src/gateways/mobile/ConnectSoft.Gateways.Mobile/
βββ Controllers/
βββ Auth/
βββ Orchestrators/
βββ DTOs/
βββ Observability/
βββ Health/
π§ Memory Graph Impact¶
Each route, header policy, tenant scope, and auth method is embedded with:
| Memory Dimension | Value Example |
|---|---|
traceId |
gw_web_checkout_v1 |
channel |
web |
routeSource |
ReferralsService β GetReferrals() |
securityScope |
admin:read:referrals |
vectorEmbedding |
Full JSON + Markdown + OpenAPI stub |
π§ BFF Target & Exposure Context¶
Every API Gateway Blueprint in the ConnectSoft Factory is tied to a specific frontend or external interface, following the Backend for Frontend (BFF) architectural pattern.
This ensures that each gateway is purpose-built to serve a single user-facing channel, exposing only the APIs needed for that experience β with optimized data shapes, security policies, and orchestration logic.
π§βπ» Channel-Aware Gateway Targets¶
Gateways are declared and scoped per UX context, including:
| Channel Name | Description | Examples |
|---|---|---|
web |
Browser-based UI | customer dashboards, internal portals |
mobile |
Mobile apps (iOS, Android) | Vetspire client app, vet assistant app |
admin |
Internal admin panels | Reports, controls, moderation |
partner |
External partner integrations | Referrals, insurance APIs |
public-api |
Developer-facing external APIs | Read-only or scoped public access |
Each channel is mapped to a blueprint path and service ID:
blueprints/gateways/{channel}/api-gateway-blueprint.md
src/gateways/{channel}/ConnectSoft.Gateways.{Channel}/
π― Exposure Strategy¶
The exposure logic defines:
- Which microservices are allowed to expose APIs to this gateway
- Which endpoints are allowed to be public vs. protected
- How tenant, locale, and user role affect route visibility
- What orchestration logic (merging, enrichment) is required
These rules are encoded in the blueprint fields:
{
"channel": "mobile",
"targetAudience": "Vetspire Mobile App",
"exposedServices": ["referrals", "notifications", "appointments"],
"auth": "oidc",
"routeVisibility": {
"/referrals": "authenticated",
"/announcements": "public"
}
}
π§ Why BFF Blueprints Matter¶
| Benefit | Description |
|---|---|
| π― UX-Scoped APIs | Avoids over-fetching, simplifies client logic |
| π Targeted Security | Fine-grained auth per channel |
| βοΈ Orchestration Friendly | Merge, enrich, and shape backend data |
| π Decouples Frontend & Core | Frontend evolves independently of core service structure |
| π§ Blueprint-Aware Memory | Easier tracing, observability, regeneration |
π Microservice Composition Map¶
At the heart of every API Gateway Blueprint is a clear, traceable map of which microservices the gateway integrates with β including:
- π― Which services are exposed
- π Which endpoints are orchestrated
- π Which services require authentication passthrough
- π Where the routes originate from (source traceability)
This composition map ensures the gateway is correctly wired, traceable, and aligned with upstream microservice blueprints.
π¦ Composition Map Overview¶
Each gateway defines its exposedServices, along with:
routeSource: which service the endpoint comes fromproxyMode: pass-through, orchestrated, or transformedversion: microservice version (if applicable)securedBy: auth mechanism and role scopes
Example blueprint fragment:
"composition": [
{
"service": "referrals",
"routes": ["/referrals", "/referrals/{id}"],
"proxyMode": "passthrough",
"securedBy": "oidc",
"version": "v1"
},
{
"service": "notifications",
"routes": ["/announcements"],
"proxyMode": "orchestrated",
"securedBy": "public"
}
]
πΊοΈ Composition Types¶
| Mode | Description | Use Cases |
|---|---|---|
passthrough |
Direct proxy to downstream service | CRUD endpoints |
orchestrated |
Aggregates or enriches data from multiple services | /dashboard with appointments + reminders |
transformed |
Modifies request/response DTOs for frontend needs | Mobile-optimized payloads |
π§ Agent Traceability¶
Each route is traceable via memory tags:
| Memory Dimension | Example Value |
|---|---|
routeId |
mobile/referrals/get |
sourceService |
ReferralsService |
sourceMethod |
GetReferrals() |
proxyMode |
passthrough |
versionTag |
v1 |
This enables observability, debugging, and regeneration by downstream agents.
π Composition Consistency¶
The gateway blueprint is validated against the Microservice Blueprints, ensuring:
- π« No orphan routes
- β Auth policy alignment
- π Proper DTO reuse or adaptation
- π Synchronization with OpenAPI docs
π Authentication Strategy¶
The API Gateway Blueprint explicitly defines how requests are authenticated β including token types, identity providers, claims mapping, and trusted headers. It serves as the contract between frontend identity context and backend service access.
The goal: ensure every exposed route is protected by design, declarative, and interoperable with the rest of the Factoryβs infrastructure.
π Supported Authentication Methods¶
| Method | Description |
|---|---|
oidc |
OpenID Connect β supports access tokens, ID tokens, claims via Identity Provider |
jwt |
Raw JWT token validation with symmetric/asymmetric keys |
cookie |
Session-based authentication for browser-based channels |
api-key |
Header-based API key authentication (for external/public APIs) |
none |
Explicit public route (e.g. documentation, landing pages) |
Each gateway declares the primary authentication method per channel and allows route-level overrides.
π Blueprint Structure Example¶
"authentication": {
"method": "oidc",
"identityProvider": "https://auth.connectsoft.io",
"tokenSource": "header",
"tokenType": "Bearer",
"requiredClaims": ["sub", "tenant_id", "roles"]
}
π Downstream services reuse the token validated by the gateway β with optional transformation or role injection.
π§ Route-Level Auth Policy¶
Routes can override the default method using:
"routes": [
{
"path": "/referrals",
"auth": "oidc",
"requiredScopes": ["read:referrals"]
},
{
"path": "/announcements",
"auth": "none"
}
]
π§ Memory & Trace Tags¶
Each auth configuration is embedded in the blueprintβs trace model:
| Tag | Example |
|---|---|
auth.method |
oidc |
auth.issuer |
https://auth.connectsoft.io |
auth.scope |
admin:write:appointments |
auth.overrideRoute |
["/announcements"] |
π Dev-Time Features¶
- π Auto-validates OIDC/JWT metadata with
.well-known/openid-configuration - π Inserts
AuthenticationMiddlewarein generated.NETproject - π§ͺ Emits fake tokens and test identities in
devenvironment for testing
πͺͺ Authorization & Role Scopes Mapping¶
While authentication validates who is calling the API, authorization defines what they can access. The API Gateway Blueprint includes a centralized, declarative model for role-based access control (RBAC) and scope-based policies per route or route group.
This enables predictable, agent-traceable, and enforceable API access control across frontend channels.
π― Authorization Levels¶
Each route in the blueprint can define one or more of the following:
| Level | Purpose | Example |
|---|---|---|
anonymous |
Public access, no token required | /announcements |
user |
Any authenticated user | /profile |
role |
Specific roles required (admin, etc.) |
/admin/users |
scope |
Fine-grained OAuth2-style permission | read:referrals |
tenant |
Access limited to specific tenant | tenant_id == context.tenant_id |
π§© Blueprint Structure Example¶
"authorization": {
"defaultPolicy": "authenticated",
"routePolicies": [
{
"path": "/referrals",
"roles": ["vet", "admin"],
"scopes": ["read:referrals"]
},
{
"path": "/admin/users",
"roles": ["admin"],
"scopes": ["admin:manage:users"]
},
{
"path": "/announcements",
"anonymous": true
}
]
}
π Role Mapping Engine (Factory Standard)¶
The generated API gateway solution includes a pluggable IRoleMapper interface that:
- Extracts roles/claims from JWT, OIDC, or cookie context
- Validates them against the policy in the blueprint
- Emits detailed observability metadata (
authz.scope.failed,authz.role.granted) - Enables mock identities for dev environments
π§ Memory Graph Tags¶
Each routeβs authz policy is embedded with:
| Trace Tag | Example Value |
|---|---|
authz.roles[] |
["vet", "admin"] |
authz.scopes[] |
["read:referrals"] |
authz.type |
RBAC+Scope |
authz.strict |
true |
These become searchable in the AI Factoryβs Studio and trace dashboards.
π§ͺ Authorization Test Generation¶
The blueprint can trigger auto-generation of access tests, such as:
- β Success with valid scope
- β Forbidden with missing role
- β Unauthorized without token
- β Tenant boundary respected
These are emitted to the Test Blueprint and QA Cluster automatically.
π Path Prefixes, Route Tags & Naming Conventions¶
To maintain consistency, discoverability, and traceability across all generated API gateways, the blueprint defines a standardized naming and routing scheme β including:
- Unified path prefixes by domain, tenant, and version
- Semantic tags per route (used for docs, dashboards, filtering)
- Factory-enforced naming conventions for route IDs and operations
π€οΈ Path Prefixing Strategy¶
Each route is defined relative to:
- β
Channel context (e.g.
/mobile/,/web/) - β
Versioning (
/v1,/v2) - β
Optional tenant scope (
/t/{tenantId})
"routes": [
{
"path": "/v1/referrals",
"method": "GET",
"tenantAware": true,
"tags": ["referrals", "read"]
},
{
"path": "/v1/announcements",
"method": "GET",
"tenantAware": false,
"tags": ["announcements", "public"]
}
]
π·οΈ Route Tags¶
Tags help with:
- π OpenAPI grouping
- π― UI filtering (e.g., Studio, admin portals)
- π Observability aggregation
- π Searchable memory trace metadata
Tag examples:
| Tag | Meaning |
|---|---|
auth |
Requires authentication |
public |
Open to anonymous access |
admin-only |
Visible only in admin portal |
orchestrated |
Aggregates multiple service calls |
beta |
Feature flag gated |
π Naming Convention for Routes¶
| Element | Rule/Example |
|---|---|
| Route ID | {channel}/{resource}/{action} β web/referrals/get |
| Operation ID | {Verb}{Resource}{Channel} β GetReferralsWeb |
| Tenant Route | /t/{tenantId}/v1/... |
| Public Route | /v1/... |
All generated .NET code aligns with this naming for:
- Controllers
- Orchestrators
- Middleware
- Traces and logs
π§ Embedded Memory Tags¶
| Dimension | Example Value |
|---|---|
route.id |
mobile/referrals/get |
route.tags[] |
["referrals", "auth"] |
route.version |
v1 |
route.tenantAware |
true |
These enable downstream agents to regenerate, lint, verify routing without inspecting raw YAML or code.
π¦ Aggregated API Operations Catalog¶
The API Gateway Blueprint includes a structured catalog of all operations the gateway exposes β across all composed services, enriched and unified for the target channel (e.g. mobile, web, admin).
This catalog serves as the canonical API surface available to the frontend or external consumer β and is used to:
- π Generate OpenAPI documents
- π― Validate route completeness
- π Detect conflicts and overlaps
- π§ Embed agent-traceable memory of all frontend-facing actions
π Operation Catalog Structure¶
Each operation is described using:
| Field | Purpose |
|---|---|
method |
HTTP verb (GET, POST, etc.) |
path |
Full routed path |
operationId |
Unique identifier (GetReferralsMobile) |
tags |
Functional groups |
inputDto |
DTO or payload schema |
outputDto |
Return type or response shape |
proxyMode |
passthrough, orchestrated, transformed |
auth |
Auth method and scopes (if required) |
π Example JSON Fragment¶
"operations": [
{
"operationId": "GetReferralsMobile",
"method": "GET",
"path": "/v1/referrals",
"inputDto": null,
"outputDto": "ReferralSummaryList",
"proxyMode": "passthrough",
"auth": "oidc",
"tags": ["referrals", "read"]
},
{
"operationId": "PostReferralRequest",
"method": "POST",
"path": "/v1/referrals",
"inputDto": "NewReferralRequest",
"outputDto": "ReferralId",
"proxyMode": "transformed",
"auth": "oidc",
"tags": ["referrals", "write"]
}
]
π§ͺ Validation & Linting (Factory-Aware)¶
During generation and CI:
- π« Conflicts (same path + method) are flagged
- β Operation IDs are validated against naming convention
- π§± DTO schemas are resolved and reused from known microservices
- π Auth consistency is enforced based on route settings
π OpenAPI Generation & Embedding¶
The operations catalog is used to:
- 𧬠Generate
swagger.json+.yamldocs - π Serve live API Docs in the Studio UI
- π Link each route to the original microservice endpoint
- π¦ Export compacted contract JSON for static consumption
π§ Memory and Observability Mapping¶
Each operation includes:
| Tag | Example |
|---|---|
op.id |
mobile/referrals/get |
op.sourceMethod |
ReferralsService.GetAll() |
op.auth.required |
true |
op.dto.input |
NewReferralRequest |
op.proxyMode |
transformed |
π§ These tags power AI navigation, endpoint discovery, and test case generation across the Factory.
π Orchestration Capabilities (Fan-in, Fan-out, Response Merging)¶
A key advantage of the ConnectSoft API Gateway is its ability to orchestrate backend logic across multiple services, transforming fragmented service calls into cohesive, frontend-optimized APIs.
The blueprint explicitly defines orchestration patterns such as:
- π Fan-in: Combine results from multiple services into one response
- π Fan-out: Trigger multiple service calls in parallel (fire-and-forget or aggregated)
- π§© Enrichment: Add additional context from auxiliary services (e.g., user info, tenant profile)
- π§΅ Sequential Flows: Chain dependent service calls in a predefined order
π οΈ Blueprint-Orchestrated Operation Example¶
{
"operationId": "GetDashboardSummary",
"method": "GET",
"path": "/v1/dashboard",
"proxyMode": "orchestrated",
"orchestration": {
"fanIn": [
{ "from": "AppointmentsService.GetToday" },
{ "from": "ReferralsService.GetPending" },
{ "from": "NotificationsService.GetUnread" }
],
"mergeStrategy": "flatMerge",
"responseAdapter": "DashboardSummaryDto"
},
"auth": "oidc",
"tags": ["dashboard", "read", "orchestrated"]
}
π§ Merge Strategies¶
| Strategy | Description |
|---|---|
flatMerge |
Combine multiple lists or objects into one JSON |
composeDto |
Map multiple responses into a single DTO format |
fallback |
Use secondary service if primary fails |
enrich |
Enhance base response with lookups or metadata |
π Supported Orchestration Modes¶
| Mode | Description |
|---|---|
sync |
Ordered, blocking calls |
parallel |
Concurrent calls with result aggregation |
conditional |
Branches based on intermediate response |
fireAndForget |
Non-blocking actions (e.g., audit logs) |
π§ Observability and Memory Tags¶
| Tag | Example |
|---|---|
orchestration.type |
fanIn |
orchestration.sources |
[Appointments, Referrals] |
orchestration.merge |
composeDto |
orchestration.adapter |
DashboardSummaryAdapter |
π§ͺ Auto-Generated Orchestration Tests¶
For each orchestrated route, test blueprints can auto-generate:
- β Success case with stubbed services
- β οΈ Timeout and retry behavior
- π« Missing source response handling
- π Merge strategy validation
π§± .NET Project Output¶
Generated orchestration code is placed in:
src/gateways/mobile/Orchestrators/
βββ DashboardSummaryOrchestrator.cs
βββ DashboardSummaryAdapter.cs
These classes follow a standard async orchestration contract and are testable, DI-ready, and logged.
π§© Gateway-Level DTOs, Adapters, and Translators¶
To decouple frontend contracts from internal microservice schemas, every API Gateway Blueprint defines a layer of channel-specific DTOs (Data Transfer Objects). These DTOs allow:
- π Transformation of raw microservice data into frontend-ready shapes
- π Filtering of sensitive/internal fields
- π Localization, formatting, and flattening for mobile/web needs
- π§± Aggregation and merging for orchestrated responses
This abstraction enables the gateway to act as a stable boundary even when downstream services evolve.
π¦ DTO Roles in the Gateway¶
| DTO Type | Description |
|---|---|
InputDto |
Shape expected from frontend clients |
OutputDto |
Returned payload to the client |
OrchestrationDto |
Internal struct used to combine multiple responses |
Adapter/Mapper |
Logic that converts service model β gateway DTO |
π Project Output Layout (Generated)¶
src/gateways/web/DTOs/
βββ ReferralSummaryDto.cs
βββ DashboardSummaryDto.cs
βββ NewReferralRequest.cs
src/gateways/web/Adapters/
βββ ReferralAdapter.cs
βββ DashboardAdapter.cs
Each adapter implements:
public class ReferralAdapter
{
public static ReferralSummaryDto FromService(Referral referral) { ... }
}
Adapters are:
- π¦ Automatically generated from blueprint JSON
- π§ͺ Unit testable
- π§ Embedded in orchestration logic and tracing
π§ Blueprint Definition Example¶
"dtos": {
"ReferralSummaryDto": {
"fields": [
{ "name": "id", "type": "Guid" },
{ "name": "status", "type": "string" },
{ "name": "createdAt", "type": "UtcDateTime", "format": "ISO8601" }
]
}
}
"adapters": {
"ReferralAdapter": {
"fromService": "Referral",
"toDto": "ReferralSummaryDto",
"fieldMappings": {
"referralId": "id",
"created": "createdAt",
"currentStatus": "status"
}
}
}
π§ Memory Graph Mapping¶
| Tag | Example |
|---|---|
dto.name |
ReferralSummaryDto |
dto.channel |
web |
adapter.sourceModel |
Referral |
adapter.outputDto |
ReferralSummaryDto |
These mappings power AI refactoring, regeneration, and diff detection.
π§ͺ DTO Unit Testing (Generated)¶
Each gateway generates:
- DTO serialization tests
- Adapter correctness tests with sample inputs
- Contract compatibility tests for known clients
π§ͺ Endpoint Testability, Probes, and Health Checks¶
Every API Gateway generated by the Factory includes built-in support for health monitoring, endpoint liveness, and agent-verifiable test probes β defined declaratively in the blueprint.
These checks ensure that the gateway is operational, integrated, observable, and regression-testable from day one.
π Health Endpoint Types¶
| Type | Description | Example Path |
|---|---|---|
liveness |
Is the process running? (basic self-check) | /health/live |
readiness |
Can the gateway respond to traffic (e.g., dependencies ready)? | /health/ready |
dependencies |
Downstream service probing (HTTP/gRPC, latency, error rate) | /health/dependencies |
π Blueprint Example¶
"health": {
"enabled": true,
"liveness": "/health/live",
"readiness": "/health/ready",
"dependencyChecks": [
{ "service": "ReferralsService", "url": "http://referrals/api/health", "method": "GET", "timeoutMs": 500 },
{ "service": "NotificationsService", "url": "http://notifications/api/status", "expectedStatus": "OK" }
]
}
π§ͺ Test Probes and Assertions¶
Test blueprints generated from this config include:
- β
Probe
/health/livereturns 200 - β
Probe
/health/readywaits for service resolution - π Injects failures and asserts degraded response (in dev/test)
- π Logs detailed trace metadata on readiness regressions
π Observability-First Output¶
All health checks emit logs + metrics:
gateway.health.liveness.ok/.failgateway.health.dependency.latency_msgateway.health.dependency.status_mismatchgateway.health.tenant.failures[]
These are:
- π§ Memory-traceable (via tags like
checkId,targetService) - π Ready to ingest into Grafana, Prometheus, Azure Monitor
π§± .NET Output¶
Health endpoints are injected automatically using:
Microsoft.AspNetCore.Diagnostics.HealthChecks- Custom middleware for tenant-aware readiness checks
- Probes to downstream HTTP/gRPC targets with retry/fallback
π§ Memory Tags¶
| Tag | Example Value |
|---|---|
healthCheck.type |
dependency |
healthCheck.targetService |
ReferralsService |
healthCheck.route |
/health/dependencies |
healthCheck.retryPolicy |
{ maxRetries: 2, delay: 100 } |
π Observability, Metrics & Trace Metadata Injection¶
The API Gateway Blueprint defines first-class observability hooks that govern how:
- Logs are structured
- Metrics are emitted
- Distributed traces are tagged
- Requests and responses are correlated across the system
This ensures that every request through the gateway is observable, debuggable, and traceable β even across dozens of microservices.
π Metrics & Telemetry Config¶
| Type | Description | Output Format |
|---|---|---|
request.count |
Total requests per route/method | gateway_request_total |
latency |
Request duration histogram | gateway_request_duration_seconds |
status |
HTTP status code distribution | gateway_response_status |
authz.failure |
Failed authentication or role mismatch | gateway_authz_failed_total |
Blueprint example:
"observability": {
"metrics": true,
"structuredLogging": true,
"traceInjection": true,
"correlationHeader": "X-Correlation-ID",
"logEnrichment": ["userId", "tenantId", "routeId", "channel"]
}
π§ Trace Metadata Injection¶
Each request and downstream call is enriched with:
| Tag | Source | Example Value |
|---|---|---|
traceId |
auto-generated or forwarded | web-referrals-get-123abc |
routeId |
from blueprint route definition | mobile/referrals/get |
operationId |
from OpenAPI | GetReferralsMobile |
tenantId |
from token claim or route param | vetspire-east-456 |
userId |
extracted from auth token | user-789 |
π§΅ Distributed Tracing Support¶
The generated gateway includes:
Activity-based tracing withSystem.Diagnostics-
Automatic propagation of:
-
traceparent(W3C Trace Context) X-Correlation-ID- Optional injection of OpenTelemetry-compatible spans
These traces connect to Azure Monitor, Jaeger, Zipkin, or Datadog β depending on platform configuration.
π .NET Implementation Layout¶
src/gateways/web/Observability/
βββ GatewayTelemetryMiddleware.cs
βββ TraceEnricher.cs
βββ MetricsExporter.cs
Middleware is added early in the request pipeline to capture all telemetry.
π Grafana/Dashboard Ready¶
Blueprint-tagged metrics and trace points are:
- Pre-configured with metric naming templates
- Automatically routed to dashboards by Factoryβs observability agent
- Annotated in alerting systems with
gatewayId,channel, andversion
π§ Embedded Memory Tags¶
| Tag | Example Value |
|---|---|
observability.traceId |
api-gw-mobile-referrals |
metric.route |
GET /v1/referrals |
correlation.policy |
required |
log.format |
structured_json |
π Multitenancy & Tenant Boundary Enforcement¶
To support large-scale SaaS systems, the API Gateway Blueprint includes an explicit multitenancy configuration model. This ensures each request is isolated, scoped, and validated against the correct tenant context β both in request processing and in downstream delegation.
The blueprint allows the gateway to act as a trusted policy and enforcement point for tenant-aware behavior across:
- Routes
- Orchestration logic
- DTO shaping
- Logging and observability
- Auth token validation
π§ Multitenancy Modes¶
| Mode | Description | Example Use Case |
|---|---|---|
header |
Tenant ID passed in a header (X-Tenant-ID) |
Internal APIs, platform tools |
subdomain |
Tenant derived from URL ({tenant}.api.com) |
Branded frontend channels |
claim |
Tenant from OIDC token (tenant_id claim) |
Authenticated mobile apps |
path |
Tenant ID in URL path (/t/{tenantId}/...) |
Deeply multitenant REST APIs |
π Blueprint Structure Example¶
"multitenancy": {
"mode": "claim",
"claimName": "tenant_id",
"enforced": true,
"routesRequireTenant": true,
"fallbackTenant": null
}
π§± Gateway Enforcement Logic¶
The generated gateway includes middleware that:
- Extracts tenant ID per configured mode
- Validates against a tenant registry or cache
-
Injects
TenantContextinto: -
Auth policy evaluation
- DTO shaping logic
- Orchestration steps
- Logs tenant resolution failures with trace ID and user ID
π§ Memory Tags and Context¶
| Tag | Example |
|---|---|
tenant.mode |
claim |
tenant.claimName |
tenant_id |
tenant.source |
jwt |
tenant.validated |
true |
tenant.routeBinding |
/t/{tenantId}/... |
π Observability Tags¶
gateway.tenant_idgateway.tenant_missinggateway.tenant_auth_mismatchgateway.tenant_resolution_duration_ms
These enable:
- Per-tenant dashboards
- Isolation of degraded tenants
- Tenant-aware performance breakdowns
π§ͺ Multitenancy Testing Support¶
Test cases automatically include:
- β Valid tenant resolution from each source
- π Rejection of requests with missing/invalid tenant
- π Trace matching across tenant boundaries in orchestrated calls
π§© Feature Flags, Variants, and Conditional Routes¶
The API Gateway Blueprint supports conditional route behavior based on feature flags, user segments, A/B testing, and deployment toggles. This enables safe experimentation, progressive rollouts, and custom experiences across tenants or users β without code changes or redeployments.
ποΈ Feature Flag Use Cases¶
- π¦ Gradual rollout of new routes (e.g.,
v2/referrals) - π Switch between orchestrated and passthrough mode
- π§ͺ Serve experimental DTO versions or adapters
- π Enable admin-only functionality for specific users or tenants
- 𧬠AB testing between alternative orchestrators
π§± Blueprint Structure Example¶
"features": {
"flags": ["enableNewReferrals", "mobileDashboardV2"],
"conditionalRoutes": [
{
"path": "/v1/referrals",
"flag": "enableNewReferrals",
"proxyMode": "orchestrated",
"orchestrator": "NewReferralsOrchestrator"
},
{
"path": "/v1/dashboard",
"flag": "mobileDashboardV2",
"adapter": "DashboardSummaryV2Adapter"
}
]
}
π§ Flags can be read from headers, cookies, claims, or integrated with remote flag systems (e.g., LaunchDarkly, Azure App Configuration).
π§ͺ Gateway Runtime Support¶
The generated gateway includes:
IFeatureEvaluatorinterface with DI-based injection-
Runtime middleware that:
-
Reads user and request context
- Evaluates feature toggles (local or remote)
- Selects appropriate DTO/Orchestrator
- Local development toggle file (
features.json) for testing
π¦ Feature Flag Source Modes¶
| Mode | Description |
|---|---|
header |
e.g., X-Feature-Flags: a,b,c |
cookie |
Feature selection per session/user |
claim |
Feature set embedded in OIDC token |
env |
Static flags injected via config |
external |
LaunchDarkly, Azure App Config, etc. |
π§ Embedded Tags¶
| Tag | Example |
|---|---|
feature.flag |
enableNewReferrals |
feature.route.variant |
DashboardSummaryV2Adapter |
feature.user.segment |
earlyAccess |
feature.tenant.scope |
tenant-123, tenant-456 |
π§ͺ Factory Test Generation¶
Generated tests validate:
- β Routes available only when flag is on
- π Routes hidden or disabled when flag is off
- π Variant adapter returns correct shape
- π― Flag switching has no state leakage between users
π Public API Exposure and API Key Governance¶
Some routes in the API Gateway are designed for external partners, public consumers, or open data scenarios. The blueprint provides explicit, traceable definitions for these routes, including support for:
- π₯ API key validation
- π Rate limiting and quota enforcement
- π‘οΈ Scoped key permissions
- π« Public exposure guardrails
π Public Route Declaration¶
Each route must explicitly declare its exposure level:
| Exposure Level | Description | Example Use |
|---|---|---|
private |
Internal traffic only | Frontend-backed mobile/web |
partner |
Exposed to trusted partners | Lab integrations, APIs |
public |
Fully public, no auth required | Open endpoints (e.g., FAQs) |
π API Key Definition Block¶
"apiKeys": {
"requiredFor": ["/v1/partners/*"],
"keyHeader": "X-API-Key",
"scopes": {
"read:partners": ["/v1/partners", "/v1/partners/{id}"],
"write:partners": ["/v1/partners"]
},
"store": "vault",
"rateLimit": {
"limitPerMinute": 100,
"enforce": true
}
}
π Key Validation Logic¶
The generated gateway includes:
- API key middleware (
IApiKeyValidator) - Pluggable store access (memory, Redis, Azure Key Vault)
- Matching against configured route scope
- Rejection with
401 Unauthorizedor429 Too Many Requests
π .NET Implementation Output¶
src/gateways/public/Security/
βββ ApiKeyValidator.cs
βββ RateLimiter.cs
βββ ApiKeyPolicyMiddleware.cs
π§ͺ Public/Partner Test Generation¶
- β Success with valid API key and scope
- π« Reject missing or expired key
- π Over-quota test using mock rate limiter
- π Audit trace emitted on every external call
π§ Observability & Logging Tags¶
| Tag | Example Value |
|---|---|
apikey.route |
/v1/partners/{id} |
apikey.keyId |
partner-1234 |
apikey.scope |
read:partners |
apikey.rate.exceeded |
true/false |
All key activity is audited and trace-logged, enabling downstream security and analytics agents to monitor public access patterns.
π§ͺ Synthetic Tests, Canary Routes & Validation Probes¶
To support proactive monitoring, rollout safety, and early detection of regressions, the API Gateway Blueprint allows the definition of synthetic test routes, canary paths, and health probes that are:
- Isolated from real user traffic
- Routable only under certain headers or feature flags
- Used for canary validation, pre-deployment checks, or automated smoke testing
π£οΈ Canary Route Types¶
| Type | Purpose | Example Use |
|---|---|---|
canary |
Route exercised by internal agents only | GET /canary/appointments/status |
synthetic |
Returns mock/deterministic responses | GET /synthetic/health/ping |
mirrored |
Invoked in parallel with prod traffic (no reply) | POST /mirror/referral |
testOnly |
Routes used in CI or test envs | GET /test/dashboard/mock |
π Blueprint Example¶
"synthetics": {
"canaryRoutes": [
{
"path": "/canary/referrals",
"method": "GET",
"responseMode": "static",
"expectedStatus": 200,
"tags": ["health", "referrals"]
}
],
"syntheticTests": [
{
"operationId": "SmokeDashboard",
"method": "GET",
"path": "/synthetic/dashboard",
"responseAssertion": { "containsKey": "summary" }
}
]
}
π Canary and Synthetic Route Features¶
-
Internally callable only via:
-
Factory test agents
- IP allowlist or
X-Factory-Agentheader - Static or dynamic mockable responses
- Used to trigger runtime probes from CI pipelines
- Version-tagged and isolated in OpenAPI docs
π .NET Implementation Output¶
src/gateways/web/Canaries/
βββ CanaryReferralsController.cs
βββ SyntheticDashboardMock.cs
Routes are flagged as [InternalOnly] or [SyntheticTest], with optional access guards injected.
π§ Embedded Tags¶
| Tag | Example Value |
|---|---|
synthetic.type |
canary |
synthetic.trigger |
pre-deploy |
synthetic.assertion |
containsKey(summary) |
synthetic.headerGuard |
X-Factory-Agent |
π Observability Outputs¶
gateway.synthetic.test.passedgateway.canary.response.time_msgateway.canary.degradedgateway.synthetic.assertion.failed
These are pushed to the Factoryβs Validation Plane and support automated rollback or halt conditions.
π§ Memory, Traceability & Regeneration Metadata¶
Each API Gateway Blueprint is fully memory-traceable and regenerable, which allows the platform to:
- Reconstruct the gateway at any time from upstream context
- Track every route, DTO, adapter, and orchestrator with semantic embeddings
- Enable prompt-less regeneration, impact analysis, and explainability
- Support advanced features like blueprint diffing, lineage exploration, and quality scoring
π Trace Metadata Injected per Section¶
Each section in the .json blueprint includes machine-processable metadata:
"metadata": {
"traceId": "api-gw-web-vetspire-v1",
"generatorAgent": "MicroserviceGeneratorAgent",
"sourceDocuments": [
"vision-blueprint/vetspire-referrals",
"architecture-blueprint/vetspire-system",
"product-blueprint/referrals-module"
],
"version": "v1.3",
"confidenceScore": 0.92,
"regenerationChecksum": "a4c9d1e3"
}
π§ Embedded Vector Memory Tags¶
Every route, DTO, orchestrator, and adapter is also semantically embedded using the platformβs memory engine (e.g., Azure Cognitive Search, Pinecone):
| Memory Type | Embedding Source | Used For |
|---|---|---|
route.embedding |
Path + tags + operation description | Searchable endpoint registry |
dto.embedding |
Field list + description | Refactor suggestions, doc rendering |
orchestration.embedding |
Merged services + strategy | Downstream reusability, test case coverage |
These are versioned, re-indexable, and linked to the blueprint lifecycle.
π Regeneration Workflow¶
The blueprint stores enough metadata to allow end-to-end regeneration via:
-
Regeneration triggers from:
-
π§ Vision change
- ποΈ Architecture change
- πͺ Product update
- Diff detection using previous trace checkpoints
- Semantic patching instead of full overwrite
- Output of regeneration deltas + recommendations
Agents can decide whether to reapply, revise, or roll back blueprint evolution using these deltas.
π Regeneration Metadata Files¶
blueprints/gateways/web/memory/
βββ route-embeddings.json
βββ dto-embeddings.json
βββ blueprint-trace-index.json
βββ regeneration-log-v1.3.json
π§ Observability & Lifecycle Tags¶
| Tag | Value |
|---|---|
blueprint.origin |
agent:MicroserviceGenerator |
blueprint.version |
v1.3 |
blueprint.qualityScore |
0.92 |
trace.originDocuments[] |
vision-blueprint/... |
trace.semanticHash |
a4c9d1e3 |
These are used by:
- Blueprint Auditor Agent
- Dependency Impact Analyzer Agent
- Automated Migration / Evolution Orchestrators
π OpenAPI Generation, Grouping, and Studio Presentation¶
Each API Gateway Blueprint includes automatic support for OpenAPI v3 generation, endpoint grouping, and rich Studio UI rendering, turning the gateway into a browsable, self-documenting surface for:
- Developers (internal or external)
- Test automation agents
- Frontend integrators
- QA & UAT scenarios
This supports API-first workflows, sandbox testability, and developer experience out of the box.
π OpenAPI Generation Features¶
- π οΈ Fully autogenerated
swagger.jsonandswagger.yaml - π Grouped by:
tags(functional)channels(mobile, web, admin)operationId+ trace lineage
- π§Ύ Includes:
- Request/response DTO schemas
- Auth requirements
- Example payloads (optional)
- Feature flag annotations
π§± Blueprint Configuration Example¶
"openApi": {
"enabled": true,
"groupBy": "tags",
"outputFormat": ["json", "yaml"],
"includeExamples": true,
"studioSidebar": true
}
π Output Directory Structure¶
blueprints/gateways/web/openapi/
βββ swagger.json
βββ swagger.yaml
βββ studio-index.json
π§© Studio UI Integration¶
The Studio (developer portal UI) renders:
- π Grouped endpoint views
- π§ Deep links to Blueprint origin (e.g. Product Story β Route)
- π§ͺ Try-it-out support via Postman/Swagger-style playground
-
π§ Embedded vector search across:
-
Route descriptions
- DTOs
- Tags, use cases, examples
π Observability + Feedback Loop¶
-
User interactions in Studio are logged as telemetry:
-
studio.route.viewed studio.openapi.downloadedstudio.search.queryβ powers feedback for missing docs
π§ Tags & Traceability¶
| Tag | Example |
|---|---|
openapi.routeId |
mobile/referrals/get |
openapi.tag |
referrals |
openapi.generatedBy |
MicroserviceGeneratorAgent |
openapi.version |
3.1 |
π§ͺ Factory-Aware API Contract Testing Hooks¶
The API Gateway Blueprint supports declarative definitions for automated contract testing, ensuring that:
- Gateway routes stay in sync with microservice schemas
- Orchestrated outputs conform to expected DTO shapes
- Each endpoint can be validated via generated integration tests, mock-backed simulations, or snapshot-based assertions
These hooks empower the Factory to continuously validate API correctness, both at gateway and downstream levels.
π§ Contract Testing Modes¶
| Mode | Purpose | Example Use Case |
|---|---|---|
snapshot |
Capture + compare JSON payloads over time | Regression on orchestration output |
schemaMatch |
Validate actual response matches OpenAPI spec | DTO drift detection |
mockBacked |
Use stubbed downstream services for isolated testing | CI environment testing |
dualPath |
Compare legacy vs. new orchestrators or DTOs | A/B test validation |
π Blueprint Test Hook Block¶
"contractTests": {
"enabled": true,
"testFramework": "xunit",
"assertionType": "schemaMatch",
"snapshotStore": "blob:api-contract-snapshots",
"routes": [
{
"operationId": "GetReferrals",
"method": "GET",
"path": "/v1/referrals",
"testMode": "mockBacked",
"expectedDto": "ReferralSummaryDto"
}
]
}
π§± Output Artifacts¶
tests/gateways/web/ContractTests/
βββ GetReferralsTests.cs
βββ _snapshots/
β βββ GetReferrals.v1.json
β βββ DashboardSummary.v2.json
-
Auto-generated test code includes:
-
Route setup
- DTO shape validation
- Mock server integration (e.g., WireMock.Net or Refit)
π§ Tags & Traceability¶
| Tag | Example |
|---|---|
contract.routeId |
/v1/referrals |
contract.testMode |
snapshot |
contract.dto |
ReferralSummaryDto |
contract.source |
openapi + blueprint adapter |
contract.snapshot.version |
v1.2 |
π Observability and Feedback¶
contract.test.passedcontract.test.failedcontract.test.snapshot.drift_detectedcontract.test.api_schema_mismatch
These are consumed by:
- Quality Scoring Agent
- Blueprint Auditor Agent
- CI/DevOps Pipelines
π Retry, Circuit-Breaker, and Fallback Policies¶
To ensure resilient communication with downstream services, each API Gateway Blueprint defines declarative resilience policies for:
- Retrying transient failures
- Circuit-breaking flaky services
- Fallback behavior (static, alternate path, or stub)
These are implemented via policy injection in generated middleware and observable decision logs, ensuring gateways remain stable even in partial failure modes.
π§ Resilience Modes¶
| Policy Type | Description | Example |
|---|---|---|
retry |
Automatic retries with backoff for transient errors | Retry 3 times for 503 errors |
circuitBreaker |
Temporarily disable calls to unstable services | Open after 5 failures |
fallback |
Serve cached/static/dummy response if target fails | Return empty DTO on timeout |
π Blueprint Block Example¶
"resilience": {
"policies": [
{
"type": "retry",
"target": "ReferralsService",
"maxAttempts": 3,
"backoff": "exponential",
"errors": ["TimeoutException", "503"]
},
{
"type": "circuitBreaker",
"target": "NotificationsService",
"failureThreshold": 5,
"recoveryTimeSec": 30
},
{
"type": "fallback",
"route": "/v1/referrals",
"strategy": "returnEmptyDto"
}
]
}
π§± .NET Output Snippets¶
- Polly-based policies injected using
AddPolicyHandler() - Circuit breaker metrics exposed at runtime
- Fallbacks implemented with optional DTO stubs
services.AddHttpClient("ReferralsService")
.AddPolicyHandler(Policy.Handle<TimeoutException>()
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
π§ Memory Graph & Tags¶
| Tag | Example |
|---|---|
resilience.target |
ReferralsService |
resilience.policy.type |
circuitBreaker |
resilience.route.fallback |
/v1/referrals β EmptyDto |
resilience.retry.errors |
["TimeoutException"] |
π Observability & Metrics¶
gateway.resilience.retry.countgateway.resilience.breaker.opengateway.resilience.fallback.usedgateway.resilience.route.degraded
All resilience actions are trace-tagged with traceId, userId, tenantId, and policyId.
π§ͺ Factory Testing Support¶
- Simulates retry/circuit-breaker with injected faults
- Asserts fallback activation and return shapes
- Includes chaos injection scenarios for load/performance agents
π¦ Environment-Aware Configuration & Secrets Handling¶
To support secure, reproducible deployments across multiple environments, the API Gateway Blueprint includes environment-specific configuration rules, secret referencing, and dynamic injection strategies.
This ensures the gateway can be reliably deployed in:
- Local development environments
- Staging/testing clouds
- Production clusters
All without leaking secrets or hardcoding sensitive details.
π§ Config Types Supported¶
| Type | Description | Source Examples |
|---|---|---|
envVar |
Read from Environment.GetEnvironmentVariable() |
ASPNETCORE_ENVIRONMENT, PORT |
keyVault |
Load from Azure Key Vault or HashiCorp Vault | ApiKey, DatabaseConnectionString |
configFile |
JSON/YAML injected via pipeline or mounted volume | appsettings.Production.json |
platformConfig |
Pulled from Azure App Config / AWS Parameter Store | FeatureFlags, DownstreamUrls |
π Blueprint Config Example¶
"configuration": {
"environments": ["Development", "Staging", "Production"],
"secrets": {
"gatewayApiKey": {
"provider": "keyVault",
"name": "GatewayApiKey"
},
"downstreamBaseUrl": {
"provider": "platformConfig",
"key": "ReferralsService:BaseUrl"
}
},
"injectInto": ["runtime", "swaggerDocs", "startupLogging"]
}
π§± .NET Output Layout¶
src/gateways/web/appsettings/
βββ appsettings.json
βββ appsettings.Staging.json
βββ appsettings.Production.json
src/gateways/web/Secrets/
βββ KeyVaultBindings.cs
- Config loaded using
IConfigurationBuilder - Secret references resolved via DI +
Azure.Extensions.AspNetCore.Configuration.Secrets
π Secrets Handling Logic¶
- Automatically excluded from logs and telemetry
- Secrets injected at runtime or startup phase
- Injected secrets tagged in memory as
non-deterministic
π§ Traceability Tags¶
| Tag | Example |
|---|---|
config.env |
Production |
config.source |
AzureKeyVault |
secret.reference |
GatewayApiKey |
secret.scope |
route:partners, authHeader |
π Observability & Diagnostics¶
gateway.config.source.missinggateway.secret.resolve.failuregateway.env.config.override.detected
These are surfaced in:
- π οΈ DevOps dashboards
- π§ͺ Environment audit reports
- π Blueprint Auditor Agent analysis
π‘οΈ Authentication and Role-Based Access Control (RBAC)¶
The API Gateway Blueprint includes robust, declarative support for authentication strategies and role-based access control, making the gateway a central enforcement point for security policies before requests ever reach downstream services.
π Authentication Strategies Supported¶
| Strategy | Description | Common Use Cases |
|---|---|---|
OIDC |
OpenID Connect bearer tokens | Web & mobile apps |
JWT |
JSON Web Token validation | Internal service communication |
API Key |
Custom token headers | Partner & public APIs |
Anonymous |
Public routes with optional scoping | Health checks, public endpoints |
π RBAC Rules in Blueprint¶
"security": {
"authentication": {
"type": "oidc",
"issuer": "https://login.connectsoft.io",
"audience": "connectsoft-gateway",
"tokenLocation": "AuthorizationHeader"
},
"authorization": {
"defaultPolicy": "authenticated",
"routePolicies": [
{
"path": "/v1/partners",
"roles": ["PartnerAdmin", "IntegrationBot"]
},
{
"path": "/v1/dashboard",
"roles": ["InternalUser"]
},
{
"path": "/public/docs",
"anonymous": true
}
]
}
}
π§ .NET Middleware and Services¶
- Auth middleware injected with
AddAuthentication().AddJwtBearer(...) - Role enforcement via
[Authorize(Roles = "...")]or policies - Fallback for public routes:
[AllowAnonymous] - Custom
IClaimsTransformerfor enriched context (e.g.,TenantId,Channel,SubscriptionLevel)
π Role Sources¶
| Source | Description |
|---|---|
JWT Claim |
Roles embedded in user token |
External |
Lookup from user registry service |
Header |
For testing or system-injected roles |
π§ Memory Tags & Traceability¶
| Tag | Example Value |
|---|---|
auth.strategy |
oidc |
auth.issuer |
https://login.connectsoft.io |
auth.route.requiredRoles |
["PartnerAdmin"] |
auth.token.location |
header:Authorization |
π Observability Metrics¶
gateway.auth.success.countgateway.auth.failure.countgateway.authz.role.deniedgateway.authz.anonymous.accessed
Logged with trace ID, user ID, tenant ID, route, and origin.
π§ͺ Agent & Test Integration¶
- Contract tests auto-generated for role-required routes
- Gateway asserts missing/malformed token scenarios
- Tracing spans labeled with
user.role,authz.policy, andauth.failure.reason
π API Orchestration vs. Passthrough Mode Configuration¶
The API Gateway Blueprint enables each route to operate in one of two core modes:
- Passthrough β the gateway simply proxies the request to a downstream service.
- Orchestrated β the gateway performs logic such as:
- Fetching from multiple services
- Merging DTOs
- Applying adapters, mappings, or policies
- Returning a custom shaped response
These modes are essential for Backend for Frontend (BFF) scenarios, supporting mobile/web clients, feature apps, and tailored APIs.
π§ Mode Comparison¶
| Mode | Description | Use Case |
|---|---|---|
passthrough |
Raw proxy with minimal processing | Simple read/write to a single service |
orchestrated |
Gateway executes composition logic | Dashboard, summaries, filtered results |
π Blueprint Configuration Example¶
"routes": [
{
"path": "/v1/dashboard",
"method": "GET",
"mode": "orchestrated",
"orchestrator": "DashboardSummaryOrchestrator"
},
{
"path": "/v1/referrals/{id}",
"method": "GET",
"mode": "passthrough",
"targetService": "ReferralsService",
"rewritePath": "/api/referrals/{id}"
}
]
π§± .NET Implementation¶
- Orchestrated routes invoke
IOrchestratorservices (registered via DI) - Passthrough routes use reverse proxy middleware with route rewriting
- Middleware pipeline detects route mode and delegates accordingly
if (route.Mode == "orchestrated")
return await _orchestrator.ExecuteAsync(context);
else
return await _proxy.ForwardAsync(context, route.Target);
π§ Memory Tags¶
| Tag | Value |
|---|---|
route.mode |
orchestrated / passthrough |
route.orchestrator |
DashboardSummaryOrchestrator |
route.targetService |
ReferralsService |
route.rewritePath |
/api/referrals/{id} |
π Observability Metrics¶
gateway.route.mode=orchestrated/passthroughorchestrator.invocation.duration_msorchestrator.response.shapeproxy.rewrite.appliedpassthrough.failure.status_code
Each is traceable by traceId, routeId, and orchestratorId.
π§ͺ Test Generation¶
-
Orchestrator output is tested via:
-
Mocks
- Shape assertions
- Fallback/timeout logic
- Passthrough routes are tested for correct forwarding and header propagation
π§± DTO Composition, Field Mapping, and Schema Rewriting¶
The API Gateway Blueprint enables custom response shaping via DTO composition, field-level mapping, and schema transformation. This allows the gateway to:
- Return tailored objects per client channel (web, mobile)
- Abstract multiple backend DTOs into a unified view
- Support API versioning and smooth evolution
- Inject synthetic or computed fields into responses
This is core to BFF logic and improves decoupling between frontend and backend models.
π§ Blueprint DTO Mapping Example¶
"adapters": [
{
"id": "ReferralSummaryV2Adapter",
"input": ["ReferralDto", "UserDto"],
"output": "ReferralSummaryV2",
"mappings": {
"summaryId": "referral.id",
"patientName": "user.fullName",
"status": "referral.currentStatus",
"createdOn": "referral.createdAt",
"isUrgent": "compute(referral.priority == 'High')"
}
}
]
π§ Composition Features¶
- π Multi-source DTO merging
- 𧬠Flattening of nested structures
- π§ Derived/computed field injection
- ποΈ Adapter per channel or version
- π’ Mapping to OpenAPI schema output
π§± .NET Code Output¶
public class ReferralSummaryV2Adapter : IDtoAdapter
{
public ReferralSummaryV2 Map(ReferralDto referral, UserDto user)
{
return new ReferralSummaryV2
{
SummaryId = referral.Id,
PatientName = user.FullName,
Status = referral.CurrentStatus,
CreatedOn = referral.CreatedAt,
IsUrgent = referral.Priority == "High"
};
}
}
- Adapters registered via DI
- Injected automatically into orchestrator logic
- Fully unit-testable as pure functions
π§ͺ Tests & Snapshots¶
- Auto-generated adapter test class
- JSON snapshot for each DTO shape per version
- Validates against OpenAPI spec using schema assertion
π File Layout¶
src/gateways/web/Adapters/
βββ ReferralSummaryV2Adapter.cs
tests/gateways/web/Adapters/
βββ ReferralSummaryV2AdapterTests.cs
βββ Snapshots/ReferralSummaryV2.v1.json
π§ Memory Tags¶
| Tag | Value |
|---|---|
dto.input.types |
ReferralDto, UserDto |
dto.output.type |
ReferralSummaryV2 |
dto.mapping.strategy |
computed, flatten, merge |
dto.adapter.id |
ReferralSummaryV2Adapter |
π Observability Hooks¶
dto.adapter.invokeddto.adapter.faileddto.mapping.invaliddto.output.schema.hash
Each linked to route, adapter, orchestrator, and test results.
π CI/CD, Containerization, and Gateway Deployment Automation¶
The API Gateway Blueprint includes infrastructure-ready deployment instructions, supporting automated build, containerization, publishing, and promotion workflows for each gateway instance.
This makes each gateway:
- CI/CD-compliant and versionable
- Deployable across multi-tenant environments
- Observable and rollback-ready
- Compatible with both monorepo and multi-repo structures
βοΈ CI Pipeline Instructions¶
Blueprint includes declarative CI job definition block:
"ciPipeline": {
"template": "connectsoft-dotnet-api-gateway",
"triggers": ["main", "release/*"],
"jobs": [
"build",
"unitTest",
"lint",
"generateOpenApi",
"containerize",
"publishArtifact"
]
}
This generates:
- Azure DevOps YAML (or GitHub Actions, GitLab CI)
- CI badges and status hooks
- Build version traceability via tags + traceId
π³ Containerization Blueprint¶
"container": {
"baseImage": "mcr.microsoft.com/dotnet/aspnet:8.0",
"port": 8080,
"healthEndpoint": "/_health",
"env": ["DOTNET_ENVIRONMENT=Production"],
"tags": ["api-gateway", "vetspire", "v1.4"]
}
Outputs:
βοΈ Deployment Profiles¶
- Multi-tenant aware (env injection, config binding)
- Tagged deployments (e.g.,
gateway-web:vetspire-v1.4) - Canary or blue/green deployment models
- Helm/ARM/Bicep/TF integration
π Promotion Workflows¶
- Promote
dev β stage β prod - Auto-test on deploy via Factory validation agents
- Signed container promotion logs
π§ Deployment Tags & Traceability¶
| Tag | Example |
|---|---|
deploy.version |
v1.4.3 |
container.image |
ghcr.io/connectsoft/api-gw:v1.4 |
deploy.env |
staging |
ci.pipeline.source |
connectsoft-api-gateway.yml |
traceId |
gateway-web-vetspire-v1.4 |
π CI/CD Observability¶
ci.build.success,ci.test.failed,deploy.rollback.triggered- Metrics linked to Git SHA, branch, project, container tag
β Final Summary and Memory Integration Blueprint¶
This final section summarizes the complete structure of the API Gateway Blueprint and details how it integrates with the ConnectSoft AI Software Factoryβs memory graph, enabling traceability, quality scoring, regeneration, and automation across clusters.
π§© Summary Table¶
| Aspect | Description |
|---|---|
| π Blueprint Type | API Gateway Blueprint |
| π§ Generated by | Microservice Generator Agent |
| π§± Implements | Backend-for-Frontend (BFF), composition, orchestration, observability |
| π οΈ Uses Templates | CLI template: connectsoft-api-gateway |
| π Upstream Inputs | Vision Blueprint, Architecture Blueprint, Product Blueprint |
| π€ Outputs | OpenAPI specs, orchestrators, DTOs, adapters, CI/CD config, runtime code |
| π¦ Formats | .md, .json, memory embeddings |
| π Regeneration Flow | Triggered via trace diffs, blueprint updates, or feature deltas |
| π§ Memory Scope | Vector embeddings, route lineage, adapter shape, quality scoring tags |
| π§ͺ Testing Strategy | Contract tests, snapshot tests, CI hooks, synthetic probes |
| π Deployment | CI/CD pipelines, Docker, Helm/K8s, environment binding |
| π Security Model | OIDC/JWT/AuthZ roles per route, token validation |
| π Observability Hooks | Traces, metrics, quality score, usage patterns |
| π§ Embedded Agents | Microservice Generator, Test Generator, Blueprint Auditor, Orchestrator |
π§ Memory Graph Integration¶
Each generated blueprint is injected into the memory system:
| Memory Component | Purpose |
|---|---|
gateway.routes |
Route-to-orchestrator traceability |
dto.embeddings |
Adapter mappings and client response shape indexing |
test.snapshots |
Schema evolution and regression detection |
ci.events |
Build/test/deploy lifecycle trace records |
orchestrator.graph |
Call chain and dependency graph from orchestrated flows |
authz.policy.map |
Role access coverage indexing |
π§ Quality & Regeneration Agents¶
| Agent | Role in Gateway Lifecycle |
|---|---|
Blueprint Auditor |
Validates route coverage, security, test completeness |
Test Generator |
Generates integration, adapter, and contract tests |
Evolution Agent |
Triggers regeneration and diff review |
Observability Agent |
Monitors gateway performance and telemetry traces |
ποΈ File Output Snapshot¶
blueprints/gateways/web/
βββ api-gateway-blueprint.md
βββ api-gateway-blueprint.json
βββ openapi/
βββ adapters/
βββ orchestrators/
βββ tests/
βββ ci/
βββ containers/
βββ memory/
π Traceability Tags Summary¶
| Tag Key | Purpose |
|---|---|
traceId |
Unique blueprint lineage |
blueprint.version |
Versioning and audit history |
dto.adapter.id |
Mapped to test coverage and quality |
auth.strategy |
Tracked in security validation |
deploy.version |
Links runtime to blueprint |
memory.embedding.scope |
Enables search, reuse, and scoring |
β API Gateway Blueprint is a top-level, regenerable, traceable, testable, deployable software unit. It combines integration design, security, orchestration, and delivery into one blueprint-driven asset β fully aligned with Clean Architecture, multi-agent flows, and modular platform philosophy.
Ready to proceed with the Backend Library Blueprint or another blueprint type next?