Kanject.Core.Realtime.Provider.AwsApiGateway
1.0.0
Prefix Reserved
See the version list below for details.
dotnet add package Kanject.Core.Realtime.Provider.AwsApiGateway --version 1.0.0
NuGet\Install-Package Kanject.Core.Realtime.Provider.AwsApiGateway -Version 1.0.0
<PackageReference Include="Kanject.Core.Realtime.Provider.AwsApiGateway" Version="1.0.0" />
<PackageVersion Include="Kanject.Core.Realtime.Provider.AwsApiGateway" Version="1.0.0" />
<PackageReference Include="Kanject.Core.Realtime.Provider.AwsApiGateway" />
paket add Kanject.Core.Realtime.Provider.AwsApiGateway --version 1.0.0
#r "nuget: Kanject.Core.Realtime.Provider.AwsApiGateway, 1.0.0"
#:package Kanject.Core.Realtime.Provider.AwsApiGateway@1.0.0
#addin nuget:?package=Kanject.Core.Realtime.Provider.AwsApiGateway&version=1.0.0
#tool nuget:?package=Kanject.Core.Realtime.Provider.AwsApiGateway&version=1.0.0
Kanject.Core.Realtime.Provider.AwsApiGateway
Realtime push over API Gateway WebSocket APIs (Core proposal 0058 P2). UseApiGatewayWebSockets() posts to each connected client through IAmazonApiGatewayManagementApi. A connection registry you choose, IRealtimeConnectionRegistry, says who is connected and who listens to what. Core's default keeps it in your service's own DynamoDB table. Large audiences go through Kanject.Core.Queue. It provides every connection control in 0058 D10: listing, ending, server-side subscriptions, renew and the registry sweep.
Installation
dotnet add package Kanject.Core.Realtime.Provider.AwsApiGateway
dotnet add package Kanject.Core.Realtime.Provider.AwsApiGateway.Registry.DynamoDb # Core's registry, or bring your own
Targets .NET 9, .NET 10 and .NET 11.
The host
// The host's own context first; its table declares GSI1 (Gsi1Pk / Gsi1Sk), which the registry's sweep uses.
builder.Services.AddDbContext<AppDbContext>(config => config.TableName = config["Table"]!);
builder.Services.AddRealtime(realtime =>
{
realtime.AuthorizeWith<ChatRealtimeAuthorizer>();
realtime.UseApiGatewayWebSockets(options =>
{
options.ConnectionsEndpoint = config["Realtime:ConnectionsEndpoint"]!; // https://{api}.execute-api.{region}.amazonaws.com/{stage}
options.FanOutQueueName = "realtime-fanout"; // optional: a Kanject.Core.Queue queue you registered
});
realtime.UseDynamoDbConnectionRegistry<AppDbContext>(); // the registry, in the host's table
});
The provider never creates the API, its routes or the queue. You hand it them, as proposal 0051 says:
- Credentials are a static pair only when both halves are set; otherwise the default chain.
- The management client is registered under its key and in the unkeyed slot when that's free (0052).
options.Clientsupplies your own. - A missing or out-of-range setting stops the host at startup (KANRT100), and so does a subscription cap above what the registry renews atomically.
- No registry registered stops the transport when it's first resolved (KANRT107).
- With the DynamoDB registry, a host table without GSI1 is refused at binding (KANCFD159).
The Lambda's routes
Resolve ApiGatewayWebSocketEndpoints from a scope for each invocation and pass plain values:
| Route | Call | Notes |
|---|---|---|
$connect |
ConnectAsync(new ApiGatewayConnectRequest(connectionId, secWebSocketProtocolHeader, query, headers)) |
Return StatusCode, plus Sec-WebSocket-Protocol: {EchoSubprotocol} when it's set. A browser fails the handshake without the echo |
$disconnect |
DisconnectAsync(connectionId) |
Best effort; nothing depends on it arriving |
$default |
MessageAsync(connectionId, body) |
Core's reserved frames, then your IRealtimeInboundHandler |
| Fan-out queue consumer | ProcessFanOutBatchAsync(messageBody) |
Throws only for a batch it can't read; report the message processed otherwise |
The client sends its token as a subprotocol, new WebSocket(url, ["kanject.v1", token]), never in the URL. AllowQueryStringToken exists only for older clients.
A new connection can't be posted to until $connect returns. API Gateway answers 410 until then. Send a welcome in answer to the client's first frame, not from the observer's Connected notice.
Reserved frames
Every reserved frame is answered with a realtime.ack envelope, {"action","ok","reason"?,"kind"?,"id"?}. A frame may carry a requestId, which comes back in the envelope.
| Frame | Effect |
|---|---|
{"action":"subscribe","kind":"Conversations","id":"…"} |
Core's rules, then your CanSubscribeAsync, within the cap (40; the DynamoDB registry allows at most 48). An optional "tenant" must be the connection's own |
{"action":"unsubscribe","kind":…,"id":…} |
Stops that topic |
{"action":"ping"} |
Keeps the connection alive. Send one inside API Gateway's 10-minute idle timeout |
{"action":"renew","token":…} |
A fresh token for the same user moves the connection's and its subscriptions' expiry in one transaction |
Every frame stamps the connection's last-seen time, at most once a minute. A row not seen for 11 minutes is treated as gone.
Delivery
- Up to
QueuedFanOutThresholdconnections (200) are posted inline, at mostMaxConcurrentPosts(64) at once, with a 429 backed off. The result counts delivered, gone and failed. - Above the threshold, the publish is queued in batches of
FanOutBatchSize(200), and the result says queued. A queue can deliver a batch twice, so a client drops a repeated envelopeid. With no queue set, the publish is sent inline and KANRT103 is logged once. - A 410 removes the connection's rows, except within
NewConnectionGrace(30 s) of its connect, where it counts as not delivered. - An expired principal's connection is ended when a publish or a frame meets it. A connection lives two hours at most.
- The registry's reads and writes run in a scope of their own, so a publish never adds to a transaction your code has open.
The registry
The transport keeps connections and subscriptions only through IRealtimeConnectionRegistry. Its remarks are the
contract: consistent reads, a connection removed or renewed with its subscriptions atomically, every row expiring with
its connection, and no caller transaction. To use another store, implement it, register it as a singleton, and run
RealtimeConnectionRegistryContractTests from Kanject.Core.Realtime.Provider.AwsApiGateway.TestKit against it. The
TestKit's InMemoryRealtimeConnectionRegistry (UseInMemoryConnectionRegistry()) serves tests and local runs.
Core's DynamoDB registry puts two library entities in your table, under the prefixes RealtimeConnections# and RealtimeTopic#, and the index names RealtimeApiGatewayConnection, RealtimeUserConnection and RealtimeConnectionSubscription. Don't reuse those prefixes or index names for your own entities. Core checks the prefixes (KANJECT018) but not index names yet (0058 OQ22). Every row carries the connection's expiry, so DynamoDB's TTL removes all of them.
Schedule IRealtimeConnections.SyncAsync() if your presence must stay right when a $disconnect is missed. It lists the connections of the last two hours from the registry (the DynamoDB one reads GSI1) and asks API Gateway about each one.
Tenants
With Kanject.Core.Tenancy registered, tenants are kept apart (0058 OQ19):
- A connection belongs to its principal's tenant, the
TenantIdyour authorizer returns. - A publish and every control act in the scope's tenant, the
ITenantContext.TenantIdof the scope that resolved them. They reach only that tenant's connections. With no tenant they reach only connections whose principal names none.DisconnectAsyncby connection id ignores another tenant's connection. - A topic is a tenant's. The same topic in two tenants has two sets of subscribers. A subscribe frame may name a tenant (
"tenant"), and naming any but the connection's own is refused (AnotherTenant). - A renew must present a token for the same user and the same tenant.
- Tenant ids compare ordinally, exactly as given.
The DynamoDB registry puts a tenant's segment in each topic partition's key: a name-based Guid of the tenant id (proposal 0065), so any tenant id fits.
Diagnostics
| Code | Meaning |
|---|---|
| KANRT100 | A setting is missing or out of range |
| KANRT102 | A frame came from a connection the registry doesn't hold; it was closed |
| KANRT103 | A large audience was sent inline because no queue was set (logged once) |
| KANRT104 | The queue refused a fan-out batch |
| KANRT105 | A post failed for a reason other than gone or throttled |
| KANRT106 | A fan-out batch couldn't be read and was dropped |
| KANRT107 | No IRealtimeConnectionRegistry is registered |
License
Licensed under the Kanject Code Libraries License Agreement (KCLLA); the full text ships in this package as LICENSE.md. Organizations whose trailing-twelve-month gross revenue and total funding raised are each below US$250,000 may use it at no cost under the Free Tier. At or above either threshold a commercial license is required — contact commercial@kanjectbusiness.com.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. 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. net11.0 is compatible. |
-
net10.0
- AWSSDK.ApiGatewayManagementApi (>= 4.1.0.2)
- Kanject.Core.Annotations (>= 4.0.1)
- Kanject.Core.Queue.Abstractions (>= 4.3.0)
- Kanject.Core.Realtime (>= 1.0.0)
-
net11.0
- AWSSDK.ApiGatewayManagementApi (>= 4.1.0.2)
- Kanject.Core.Annotations (>= 4.0.1)
- Kanject.Core.Queue.Abstractions (>= 4.3.0)
- Kanject.Core.Realtime (>= 1.0.0)
-
net9.0
- AWSSDK.ApiGatewayManagementApi (>= 4.1.0.2)
- Kanject.Core.Annotations (>= 4.0.1)
- Kanject.Core.Queue.Abstractions (>= 4.3.0)
- Kanject.Core.Realtime (>= 1.0.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Kanject.Core.Realtime.Provider.AwsApiGateway:
| Package | Downloads |
|---|---|
|
Kanject.Core.Realtime.Provider.AwsApiGateway.TestKit
Kanject Core realtime over API Gateway WebSockets, test kit (xUnit, proposal 0058 OQ23): RealtimeConnectionRegistryContractTests, the tests every IRealtimeConnectionRegistry passes, and InMemoryRealtimeConnectionRegistry, a registry for tests, registered with UseInMemoryConnectionRegistry(). |
GitHub repositories
This package is not used by any popular GitHub repositories.
- Takes Kanject.Core.Queue.Abstractions 4.3.0.
- Takes Kanject.Core.Realtime 1.0.0.