Kanject.Core.Realtime.Provider.AwsApiGateway 1.3.0

Prefix Reserved
dotnet add package Kanject.Core.Realtime.Provider.AwsApiGateway --version 1.3.0
                    
NuGet\Install-Package Kanject.Core.Realtime.Provider.AwsApiGateway -Version 1.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Kanject.Core.Realtime.Provider.AwsApiGateway" Version="1.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Kanject.Core.Realtime.Provider.AwsApiGateway" Version="1.3.0" />
                    
Directory.Packages.props
<PackageReference Include="Kanject.Core.Realtime.Provider.AwsApiGateway" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Kanject.Core.Realtime.Provider.AwsApiGateway --version 1.3.0
                    
#r "nuget: Kanject.Core.Realtime.Provider.AwsApiGateway, 1.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Kanject.Core.Realtime.Provider.AwsApiGateway@1.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Kanject.Core.Realtime.Provider.AwsApiGateway&version=1.3.0
                    
Install as a Cake Addin
#tool nuget:?package=Kanject.Core.Realtime.Provider.AwsApiGateway&version=1.3.0
                    
Install as a Cake Tool

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.Client supplies 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

Pass each route's event to ApiGatewayWebSocketEndpoints as API Gateway sent it, and return what comes back (proposal 0067 D9). The event is read with JsonDocument and the response written with Utf8JsonWriter, so no Lambda event type or serializer is involved. Resolve the endpoints from a scope for each invocation:

public async Task<Stream> WebSocketAsync(Stream request, ILambdaContext context)
{
    await using var scope = ServiceProvider.CreateAsyncScope();
    return await scope.ServiceProvider.GetRequiredService<ApiGatewayWebSocketEndpoints>().HandleAsync(request);
}

HandleAsync serves $connect, $disconnect and $default from one function, by the event's requestContext.eventType. HandleConnectAsync, HandleDisconnectAsync and HandleMessageAsync serve one route each. Every one also takes ReadOnlyMemory<byte> and returns byte[].

Route What the adapter does
$connect Reads Sec-WebSocket-Protocol (one comma-joined value, any casing), the other headers without regard to case, and the query string; runs ConnectAsync; answers 200 with Sec-WebSocket-Protocol: kanject.v1 when the client offered it, or the refusal's 401. A browser fails the handshake without the echo
$disconnect Runs DisconnectAsync and answers 200. API Gateway sends it for a close from the client (1000), a binary frame (1003) and a dropped socket (1006), and only best effort
$default Runs MessageAsync over the frame's text, decoded first if the event marks it base64, and answers 200. API Gateway never delivers a binary frame: it closes the connection instead
Fan-out queue consumer ProcessFanOutBatchAsync(messageBody). Throws only for a batch it can't read; report the message processed otherwise

An event the adapter can't read, or another route's event passed to a one-route method, is answered 400 and logged (KANRT108). Each frame is an invocation of its own, so two frames from one connection can be handled out of order.

Under Native AOT, a [CloudFunctionHost(EnableAot = true)] host sets PublishAot and names its assembly bootstrap, and the kanject CLI deploys it on provided.al2023. Start the runtime loop in a Main of your own, over RuntimeSupport's Stream overload; Lambda Annotations' generated Main doesn't compile for a Stream-in, Stream-out function (Annotations 2.4.2, CS0121):

Func<Stream, ILambdaContext, Task<Stream>> handler = new Functions().WebSocketAsync;
await LambdaBootstrapBuilder.Create(handler).Build().RunAsync();

A host that reads the event itself can still pass plain values: ConnectAsync(new ApiGatewayConnectRequest(connectionId, secWebSocketProtocolHeader, query, headers)), DisconnectAsync(connectionId) and MessageAsync(connectionId, body).

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 QueuedFanOutThreshold connections (200) are posted inline, at most MaxConcurrentPosts (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 envelope id. 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 TenantId your authorizer returns.
  • A publish and every control act in the scope's tenant, the ITenantContext.TenantId of the scope that resolved them. They reach only that tenant's connections. With no tenant they reach only connections whose principal names none. DisconnectAsync by 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
KANRT108 A route adapter got an event it can't read, or another route's; it answered 400

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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.

Version Downloads Last Updated
1.3.0 0 11/26/2026
1.2.0 0 11/26/2026
1.1.0 45 11/26/2026
1.0.0 66 11/24/2026

- Takes Kanject.Core.Realtime 1.3.0.