forked from NpgsqlRest/NpgsqlRest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlRestNoticeEventSource.cs
More file actions
177 lines (163 loc) · 7.43 KB
/
Copy pathNpgsqlRestNoticeEventSource.cs
File metadata and controls
177 lines (163 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
using Microsoft.AspNetCore.Routing;
using Npgsql;
using NpgsqlRest.Defaults;
namespace NpgsqlRest;
public readonly record struct NoticeEvent(
PostgresNotice Notice,
RoutineEndpoint? Endpoint,
string? ExecutionId);
public class NpgsqlRestNoticeEventSource(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public static readonly HashSet<string> Paths = [];
public static readonly Broadcaster<NoticeEvent> Broadcaster = new();
public async Task InvokeAsync(HttpContext context)
{
if (Paths.Contains(context.Request.Path) is false)
{
await _next(context);
return;
}
var executionId = context.Request.QueryString.HasValue ? context.Request.QueryString.Value[1..] : null;
var cancellationToken = context.RequestAborted;
context.Response.Headers.ContentType = "text/event-stream";
context.Response.Headers.CacheControl = "no-cache, no-store, must-revalidate, max-age=0";
context.Response.Headers.Connection = "keep-alive";
if (NpgsqlRestMiddleware.Options.CustomServerSentEventsResponseHeaders.Count > 0)
{
foreach (var header in NpgsqlRestMiddleware.Options.CustomServerSentEventsResponseHeaders)
{
if (context.Response.Headers.ContainsKey(header.Key))
{
context.Response.Headers[header.Key] = header.Value;
}
else
{
context.Response.Headers.Append(header.Key, header.Value);
}
}
}
var connectionId = Guid.NewGuid();
var reader = Broadcaster.Subscribe(connectionId);
try
{
await foreach (var noticeEvent in reader.ReadAllAsync(cancellationToken))
{
var endpoint = noticeEvent.Endpoint;
var scope = noticeEvent.Endpoint?.InfoEventsScope;
var infoEventsRoles = endpoint?.InfoEventsRoles;
if (string.IsNullOrEmpty(noticeEvent.Notice.Hint) is false)
{
string hint = noticeEvent.Notice.Hint;
var words = hint.SplitWords();
if (words is not null && words.Length > 0 && Enum.TryParse<InfoEventsScope>(words[0], true, out var parsedScope))
{
scope = parsedScope;
if (scope == InfoEventsScope.Authorize && words.Length > 1)
{
// if info roles already exist, merge them with the new ones
infoEventsRoles ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var word in words[1..])
{
if (infoEventsRoles.Contains(word) is false && string.IsNullOrWhiteSpace(word) is false)
{
infoEventsRoles.Add(word);
}
}
}
}
else
{
NpgsqlRestMiddleware.Logger?.LogError("Could not recognize valid value for parameter key {key}. Valid values are: {values}. Provided value is {provided}.",
words?[0], string.Join(", ", Enum.GetNames<InfoEventsScope>()), hint);
}
}
if (scope == InfoEventsScope.Self)
{
if (string.Equals(noticeEvent.ExecutionId, executionId, StringComparison.Ordinal) is false)
{
continue; // Skip events not matching the current execution ID
}
}
else if (scope == InfoEventsScope.Matching)
{
if (context.User?.Identity?.IsAuthenticated is false &&
(endpoint?.RequiresAuthorization is true || endpoint?.AuthorizeRoles is not null))
{
continue; // Skip events for unauthorized users
}
if (endpoint?.AuthorizeRoles is not null)
{
bool ok = false;
foreach (var claim in context.User?.Claims ?? [])
{
if (string.Equals(claim.Type, NpgsqlRestMiddleware.Options.AuthenticationOptions.DefaultRoleClaimType, StringComparison.Ordinal))
{
if (endpoint?.AuthorizeRoles.Contains(claim.Value) is true)
{
ok = true;
break;
}
}
}
if (ok is false)
{
continue;
}
}
}
else if (scope == InfoEventsScope.Authorize)
{
if (context.User?.Identity?.IsAuthenticated is false)
{
continue; // Skip events for unauthorized users
}
if (infoEventsRoles is not null)
{
bool ok = false;
if (context.User?.Claims is not null)
{
foreach (var claim in context.User?.Claims!)
{
if (
string.Equals(claim.Type, NpgsqlRestMiddleware.Options.AuthenticationOptions.DefaultUserIdClaimType, StringComparison.Ordinal) ||
string.Equals(claim.Type, NpgsqlRestMiddleware.Options.AuthenticationOptions.DefaultNameClaimType, StringComparison.Ordinal) ||
string.Equals(claim.Type, NpgsqlRestMiddleware.Options.AuthenticationOptions.DefaultRoleClaimType, StringComparison.Ordinal)
)
{
if (infoEventsRoles.Contains(claim.Value) is true)
{
ok = true;
break;
}
}
}
}
if (ok is false)
{
continue;
}
}
}
try
{
await context.Response.WriteAsync($"data: {noticeEvent.Notice.MessageText}\n\n", cancellationToken);
await context.Response.Body.FlushAsync(cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
NpgsqlRestMiddleware.Logger?.LogError(ex, "Failed to write notice event to response at path {path} (ExecutionId={executionId})", context.Request.Path, executionId);
continue;
}
}
}
finally
{
Broadcaster.Unsubscribe(connectionId);
}
}
}