Orchardcore websockets

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore websockets is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for the CrestApps Orchard Core WebSockets infrastructure module. Covers the dependency-only CrestApps.OrchardCore.WebSockets feature that adds the ASP.NET Core WebSocket middleware to the tenant pipeline, the CrestApps WebSockets configuration section bound to WebSocketOptions (KeepAliveInterv

How to use this skill

Skill file

Orchard Core WebSockets - Prompt Templates

Host Raw WebSocket Endpoints

You are an Orchard Core expert. Generate accurate code and configuration for features that accept raw WebSocket upgrades (HttpContext.WebSockets.AcceptWebSocketAsync()) in a CrestApps Orchard Core tenant.

Guidelines

Feature Overview

| Item | Value |

|---|---|

| Module package | CrestApps.OrchardCore.WebSockets (category Infrastructure) |

| Feature ID | CrestApps.OrchardCore.WebSockets (WebSocketsConstants.Feature.Area) |

| Enabled by | Dependency only (for example the CrestApps.OrchardCore.Telnyx feature) |

| Contracts package | CrestApps.OrchardCore.WebSockets.Abstractions (namespace CrestApps.OrchardCore.WebSockets) |

| Configuration section | CrestApps:WebSockets (WebSocketsConstants.ConfigurationSectionPath), bound to ASP.NET Core WebSocketOptions |

| Default registry | InMemoryWebSocketConnectionRegistry (per node) |

| Distributed registry | DistributedWebSocketConnectionRegistry, active when OrchardCore.Redis is enabled |

Depend on the Feature

using CrestApps.OrchardCore.WebSockets;
using OrchardCore.Modules.Manifest;

[assembly: Feature(
    Id = "MyCompany.MediaBridge",
    Name = "Media Bridge",
    Category = "Telephony",
    Dependencies =
    [
        WebSocketsConstants.Feature.Area,
    ]
)]

Configure the Middleware

Every key is optional; omitted keys keep the ASP.NET Core defaults (two-minute keep-alive, no origin restriction).

{
  "OrchardCore": {
    "CrestApps": {
      "WebSockets": {
        "KeepAliveInterval": "00:00:30",
        "KeepAliveTimeout": "00:00:10",
        "AllowedOrigins": [ "https://app.example.com" ]
      }
    }
  }
}

| Key | Meaning |

|---|---|

| KeepAliveInterval | Interval for server ping frames on an idle socket. |

| KeepAliveTimeout | Time to wait for a pong before aborting. Omit to disable. |

| AllowedOrigins | Accepted Origin header values. Empty accepts all. Only browser handshakes send Origin, so this does not restrict server-to-server provider callbacks. |

Environment variables use OrchardCore__CrestApps__WebSockets__KeepAliveInterval. A tenant's own App_Data/Sites/{TenantName}/appsettings.json starts at CrestApps without the OrchardCore wrapper. The options are read once when the pipeline is built, so a change needs a tenant reload.

Correlate a Provider Callback

A provider (for example Telnyx media streaming) is asked to dial back to a WebSocket endpoint. The request that asked waits for that socket; the endpoint that accepts it hands it over through the registry.

using System.Security.Cryptography;
using CrestApps.OrchardCore.WebSockets;
using Microsoft.AspNetCore.WebUtilities;

public sealed class MediaBridgeStarter
{
    private readonly IWebSocketConnectionRegistry _registry;

    public MediaBridgeStarter(IWebSocketConnectionRegistry registry)
    {
        _registry = registry;
    }

    public async Task RunAsync(CancellationToken cancellationToken)
    {
        var key = WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
        var rendezvous = await _registry.RegisterAsync(key, cancellationToken);

        try
        {
            // Ask the provider to connect to /api/my-bridge/media?key={key} here.
            var socket = await rendezvous.ConnectedTask.WaitAsync(TimeSpan.FromSeconds(15), cancellationToken);

            try
            {
                // Read and write media frames on the socket.
            }
            finally
            {
                rendezvous.Release();
            }
        }
        catch
        {
            rendezvous.Abort();
            await _registry.RemoveAsync(key, CancellationToken.None);

            throw;
        }
    }
}

The endpoint the provider dials:

routes.Map("/api/my-bridge/media", async (HttpContext httpContext, IWebSocketConnectionRegistry registry) =>
{
    if (!httpContext.WebSockets.IsWebSocketRequest)
    {
        return Results.BadRequest();
    }

    var rendezvous = await registry.TryClaimAsync(httpContext.Request.Query["key"], httpContext.RequestAborted);

    if (rendezvous is null)
    {
        // Unknown, already claimed, expired, or registered on another node.
        return Results.NotFound();
    }

    var socket = await httpContext.WebSockets.AcceptWebSocketAsync();

    rendezvous.TryComplete(socket);

    // Keep the request, and so the socket, alive until the consumer releases it.
    await rendezvous.ReleasedTask;

    return Results.Empty;
});

RegisterAsync throws on a duplicate key. TryClaimAsync atomically claims and removes the rendezvous, so a key works once.

Multi-Node Deployments

| Registry | When | Behavior |

|---|---|---|

| In-memory | Default | A key is known only on the node that registered it. A callback on another node looks like an unknown key. |

| Distributed | OrchardCore.Redis enabled for the tenant | The rendezvous still lives on the registering node, which records ownership of the key in Redis for 10 minutes. A misrouted callback is still refused, but the log names the owning node and the rendezvous stays intact for the provider's retry. If Redis is unreachable, registration falls back to node-local behavior. |

Both registries count rendezvous operations on the CrestApps.OrchardCore.WebSockets meter: crestapps.websockets.rendezvous (result = registered, conflict, claimed, miss, cross_node, removed; cross_node is a socket that arrived on a node other than the waiting one) and crestapps.websockets.rendezvous.wait.duration (registration to the provider's socket arriving). The rendezvous key never tags a metric. See orchardcore-observability.

Common Failures

| Symptom | Check |

|---|---|

| Upgrade refused or the request is not a WebSocket request | Your feature does not depend on CrestApps.OrchardCore.WebSockets, so UseWebSockets is not in the pipeline |

| Callback is refused with an unknown key | The callback reached another node, the key expired, or it was already claimed |

| Browser handshake rejected | The page origin is missing from AllowedOrigins |

| Idle sockets drop behind a proxy | Lower KeepAliveInterval below the proxy idle timeout |

Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.