| | | 1 | | |
| | | 2 | | |
| | | 3 | | using System.Security.Claims; |
| | | 4 | | using Kestrun.SignalR; |
| | | 5 | | using Microsoft.AspNetCore.Http.Features; |
| | | 6 | | |
| | | 7 | | namespace Kestrun.Models; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Represents the context for a Kestrun request, including the request, response, HTTP context, and host. |
| | | 11 | | /// </summary> |
| | | 12 | | public sealed record KestrunContext |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Initializes a new instance of the <see cref="KestrunContext"/> class. |
| | | 16 | | /// This constructor is used when creating a new KestrunContext from an existing HTTP context. |
| | | 17 | | /// It initializes the KestrunRequest and KestrunResponse based on the provided HttpContext |
| | | 18 | | /// </summary> |
| | | 19 | | /// <param name="host">The Kestrun host.</param> |
| | | 20 | | /// <param name="request">The Kestrun request.</param> |
| | | 21 | | /// <param name="response">The Kestrun response.</param> |
| | | 22 | | /// <param name="httpContext">The associated HTTP context.</param> |
| | 48 | 23 | | public KestrunContext(Hosting.KestrunHost host, KestrunRequest request, KestrunResponse response, HttpContext httpCo |
| | | 24 | | { |
| | 48 | 25 | | ArgumentNullException.ThrowIfNull(host); |
| | 48 | 26 | | ArgumentNullException.ThrowIfNull(request); |
| | 48 | 27 | | ArgumentNullException.ThrowIfNull(response); |
| | 48 | 28 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | | 29 | | |
| | 48 | 30 | | Host = host; |
| | 48 | 31 | | Request = request; |
| | 48 | 32 | | Response = response; |
| | 48 | 33 | | HttpContext = httpContext; |
| | 48 | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Initializes a new instance of the <see cref="KestrunContext"/> class. |
| | | 38 | | /// This constructor is used when creating a new KestrunContext from an existing HTTP context. |
| | | 39 | | /// It initializes the KestrunRequest and KestrunResponse based on the provided HttpContext |
| | | 40 | | /// </summary> |
| | | 41 | | /// <param name="host">The Kestrun host.</param> |
| | | 42 | | /// <param name="httpContext">The associated HTTP context.</param> |
| | 1 | 43 | | public KestrunContext(Hosting.KestrunHost host, HttpContext httpContext) |
| | | 44 | | { |
| | 1 | 45 | | ArgumentNullException.ThrowIfNull(host); |
| | 1 | 46 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | | 47 | | |
| | 1 | 48 | | Host = host; |
| | 1 | 49 | | HttpContext = httpContext; |
| | | 50 | | |
| | 1 | 51 | | Request = KestrunRequest.NewRequestSync(HttpContext); |
| | 1 | 52 | | Response = new KestrunResponse(Request); |
| | 1 | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// The Kestrun host associated with this context. |
| | | 57 | | /// </summary> |
| | 51 | 58 | | public Hosting.KestrunHost Host { get; init; } |
| | | 59 | | /// <summary> |
| | | 60 | | /// The Kestrun request associated with this context. |
| | | 61 | | /// </summary> |
| | 77 | 62 | | public KestrunRequest Request { get; init; } |
| | | 63 | | /// <summary> |
| | | 64 | | /// The Kestrun response associated with this context. |
| | | 65 | | /// </summary> |
| | 81 | 66 | | public KestrunResponse Response { get; init; } |
| | | 67 | | /// <summary> |
| | | 68 | | /// The ASP.NET Core HTTP context associated with this Kestrun context. |
| | | 69 | | /// </summary> |
| | 78 | 70 | | public HttpContext HttpContext { get; init; } |
| | | 71 | | /// <summary> |
| | | 72 | | /// Returns the ASP.NET Core session if the Session middleware is active; otherwise null. |
| | | 73 | | /// </summary> |
| | 14 | 74 | | public ISession? Session => HttpContext.Features.Get<ISessionFeature>()?.Session; |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// True if Session middleware is active for this request. |
| | | 78 | | /// </summary> |
| | 4 | 79 | | public bool HasSession => Session is not null; |
| | | 80 | | |
| | | 81 | | /// <summary> |
| | | 82 | | /// Try pattern to get session without exceptions. |
| | | 83 | | /// </summary> |
| | | 84 | | public bool TryGetSession(out ISession? session) |
| | | 85 | | { |
| | 2 | 86 | | session = Session; |
| | 2 | 87 | | return session is not null; |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// Gets the cancellation token that is triggered when the HTTP request is aborted. |
| | | 92 | | /// </summary> |
| | 1 | 93 | | public CancellationToken Ct => HttpContext.RequestAborted; |
| | | 94 | | /// <summary> |
| | | 95 | | /// Gets the collection of key/value pairs associated with the current HTTP context. |
| | | 96 | | /// </summary> |
| | 3 | 97 | | public IDictionary<object, object?> Items => HttpContext.Items; |
| | | 98 | | |
| | | 99 | | /// <summary> |
| | | 100 | | /// Gets the user associated with the current HTTP context. |
| | | 101 | | /// </summary> |
| | 2 | 102 | | public ClaimsPrincipal User => HttpContext.User; |
| | | 103 | | |
| | | 104 | | /// <summary> |
| | | 105 | | /// Gets the connection information for the current HTTP context. |
| | | 106 | | /// </summary> |
| | 0 | 107 | | public ConnectionInfo Connection => HttpContext.Connection; |
| | | 108 | | |
| | | 109 | | /// <summary> |
| | | 110 | | /// Returns a string representation of the KestrunContext, including path, user, and session status. |
| | | 111 | | /// </summary> |
| | | 112 | | public override string ToString() |
| | 2 | 113 | | => $"KestrunContext{{ Host={Host}, Path={HttpContext.Request.Path}, User={User?.Identity?.Name ?? "<anon>"}, Has |
| | | 114 | | |
| | | 115 | | |
| | | 116 | | /// <summary> |
| | | 117 | | /// Asynchronously broadcasts a log message to all connected SignalR clients using the IRealtimeBroadcaster service. |
| | | 118 | | /// </summary> |
| | | 119 | | /// <param name="level">The log level (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 120 | | /// <param name="message">The log message to broadcast.</param> |
| | | 121 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 122 | | /// <returns>True if the log was broadcast successfully; otherwise, false.</returns> |
| | | 123 | | public async Task<bool> BroadcastLogAsync(string level, string message, CancellationToken cancellationToken = defaul |
| | | 124 | | { |
| | 0 | 125 | | var svcProvider = HttpContext.RequestServices; |
| | | 126 | | |
| | 0 | 127 | | if (svcProvider == null) |
| | | 128 | | { |
| | 0 | 129 | | Host.Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 0 | 130 | | return false; |
| | | 131 | | } |
| | 0 | 132 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 133 | | { |
| | 0 | 134 | | Host.Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Ke |
| | 0 | 135 | | return false; |
| | | 136 | | } |
| | | 137 | | try |
| | | 138 | | { |
| | 0 | 139 | | await broadcaster.BroadcastLogAsync(level, message, cancellationToken); |
| | 0 | 140 | | Host.Logger.Debug("Broadcasted log message via SignalR: {Level} - {Message}", level, message); |
| | 0 | 141 | | return true; |
| | | 142 | | } |
| | 0 | 143 | | catch (Exception ex) |
| | | 144 | | { |
| | 0 | 145 | | Host.Logger.Error(ex, "Failed to broadcast log message: {Level} - {Message}", level, message); |
| | 0 | 146 | | return false; |
| | | 147 | | } |
| | 0 | 148 | | } |
| | | 149 | | |
| | | 150 | | /// <summary> |
| | | 151 | | /// Synchronous wrapper for BroadcastLogAsync. |
| | | 152 | | /// </summary> |
| | | 153 | | /// <param name="level">The log level (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 154 | | /// <param name="message">The log message to broadcast.</param> |
| | | 155 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 156 | | /// <returns>True if the log was broadcast successfully; otherwise, false.</returns> |
| | | 157 | | public bool BroadcastLog(string level, string message, CancellationToken cancellationToken = default) => |
| | 0 | 158 | | BroadcastLogAsync(level, message, cancellationToken).GetAwaiter().GetResult(); |
| | | 159 | | |
| | | 160 | | |
| | | 161 | | /// <summary> |
| | | 162 | | /// Asynchronously broadcasts a custom event to all connected SignalR clients using the IRealtimeBroadcaster service |
| | | 163 | | /// </summary> |
| | | 164 | | /// <param name="eventName">The event name (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 165 | | /// <param name="data">The event data to broadcast.</param> |
| | | 166 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 167 | | /// <returns>True if the event was broadcast successfully; otherwise, false.</returns> |
| | | 168 | | public async Task<bool> BroadcastEventAsync(string eventName, object? data, CancellationToken cancellationToken = de |
| | | 169 | | { |
| | 0 | 170 | | var svcProvider = HttpContext.RequestServices; |
| | | 171 | | |
| | 0 | 172 | | if (svcProvider == null) |
| | | 173 | | { |
| | 0 | 174 | | Host.Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 0 | 175 | | return false; |
| | | 176 | | } |
| | 0 | 177 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 178 | | { |
| | 0 | 179 | | Host.Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Ke |
| | 0 | 180 | | return false; |
| | | 181 | | } |
| | | 182 | | try |
| | | 183 | | { |
| | 0 | 184 | | await broadcaster.BroadcastEventAsync(eventName, data, cancellationToken); |
| | 0 | 185 | | Host.Logger.Debug("Broadcasted event via SignalR: {EventName} - {Data}", eventName, data); |
| | 0 | 186 | | return true; |
| | | 187 | | } |
| | 0 | 188 | | catch (Exception ex) |
| | | 189 | | { |
| | 0 | 190 | | Host.Logger.Error(ex, "Failed to broadcast event: {EventName} - {Data}", eventName, data); |
| | 0 | 191 | | return false; |
| | | 192 | | } |
| | 0 | 193 | | } |
| | | 194 | | |
| | | 195 | | /// <summary> |
| | | 196 | | /// Synchronous wrapper for BroadcastEventAsync. |
| | | 197 | | /// </summary> |
| | | 198 | | /// <param name="eventName">The event name (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 199 | | /// <param name="data">The event data to broadcast.</param> |
| | | 200 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 201 | | /// <returns>True if the event was broadcast successfully; otherwise, false.</returns> |
| | | 202 | | public bool BroadcastEvent(string eventName, object? data, CancellationToken cancellationToken = default) => |
| | 0 | 203 | | BroadcastEventAsync(eventName, data, cancellationToken).GetAwaiter().GetResult(); |
| | | 204 | | |
| | | 205 | | |
| | | 206 | | /// <summary> |
| | | 207 | | /// Asynchronously broadcasts a message to a specific group of SignalR clients using the IRealtimeBroadcaster servic |
| | | 208 | | /// </summary> |
| | | 209 | | /// <param name="groupName">The name of the group to broadcast the message to.</param> |
| | | 210 | | /// <param name="method">The name of the method to invoke on the client.</param> |
| | | 211 | | /// <param name="message">The message to broadcast.</param> |
| | | 212 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 213 | | /// <returns></returns> |
| | | 214 | | public async Task<bool> BroadcastToGroupAsync(string groupName, string method, object? message, CancellationToken ca |
| | | 215 | | { |
| | 0 | 216 | | var svcProvider = HttpContext.RequestServices; |
| | | 217 | | |
| | 0 | 218 | | if (svcProvider == null) |
| | | 219 | | { |
| | 0 | 220 | | Host.Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 0 | 221 | | return false; |
| | | 222 | | } |
| | 0 | 223 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 224 | | { |
| | 0 | 225 | | Host.Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Ke |
| | 0 | 226 | | return false; |
| | | 227 | | } |
| | | 228 | | try |
| | | 229 | | { |
| | 0 | 230 | | await broadcaster.BroadcastToGroupAsync(groupName, method, message, cancellationToken); |
| | 0 | 231 | | Host.Logger.Debug("Broadcasted log message to group via SignalR: {GroupName} - {Method} - {Message}", groupN |
| | 0 | 232 | | return true; |
| | | 233 | | } |
| | 0 | 234 | | catch (Exception ex) |
| | | 235 | | { |
| | 0 | 236 | | Host.Logger.Error(ex, "Failed to broadcast log message: {GroupName} - {Method} - {Message}", groupName, meth |
| | 0 | 237 | | return false; |
| | | 238 | | } |
| | 0 | 239 | | } |
| | | 240 | | |
| | | 241 | | /// <summary> |
| | | 242 | | /// Synchronous wrapper for BroadcastToGroupAsync. |
| | | 243 | | /// </summary> |
| | | 244 | | /// <param name="groupName">The name of the group to broadcast the message to.</param> |
| | | 245 | | /// <param name="method">The name of the method to invoke on the client.</param> |
| | | 246 | | /// <param name="message">The message to broadcast.</param> |
| | | 247 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 248 | | /// <returns></returns> |
| | | 249 | | public bool BroadcastToGroup(string groupName, string method, object? message, CancellationToken cancellationToken = |
| | 0 | 250 | | BroadcastToGroupAsync(groupName, method, message, cancellationToken).GetAwaiter().GetResult(); |
| | | 251 | | } |
| | | 252 | | |