Repository navigation
Expand file tree
/
Copy pathNpgsqlRestEndpoint.cs
More file actions
3962 lines (3710 loc) · 181 KB
/
Copy pathNpgsqlRestEndpoint.cs
File metadata and controls
3962 lines (3710 loc) · 181 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Data;
using System.IO.Pipelines;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Primitives;
using Npgsql;
using NpgsqlRest.Auth;
using NpgsqlRest.HttpClientType;
using NpgsqlRest.UploadHandlers;
using NpgsqlRest.UploadHandlers.Handlers;
using static System.Net.Mime.MediaTypeNames;
using static NpgsqlRest.ParameterParser;
namespace NpgsqlRest;
public partial class NpgsqlRestEndpoint(
NpgsqlRestMetadataEntry entry,
FrozenDictionary<string, NpgsqlRestMetadataEntry> overloads)
{
// Signals a non-value exit from inside a cache GetOrCreateAsync factory, so the result is never
// cached and concurrent waiters observe the same outcome. NoRow → the command returned no row
// (caller maps to 500); ResponseAlreadyWritten → PrepareCommand short-circuited via
// CommandCallbackAsync and already wrote the lead caller's response (caller just returns).
private enum CacheFactoryAbortReason { NoRow, ResponseAlreadyWritten }
private sealed class CacheFactoryAbortException(CacheFactoryAbortReason reason) : Exception
{
public CacheFactoryAbortReason Reason { get; } = reason;
}
// Per-cache-key execution gates for the streaming records/sets path. That path cannot use the
// value-shaped GetOrCreateAsync factory model because it streams rows to the client and disables
// caching mid-stream once a response exceeds MaxCacheableRows. The gate serializes concurrent
// requests for the same key: the lead executes and (when within limits) populates the cache, so
// the rest get a cache hit instead of re-executing; over-limit responses simply run one-at-a-time,
// which still caps concurrent DB executions per key at one.
//
// The outer map is keyed by the cache instance itself (reference identity, so distinct cache
// profiles never share a gate even if they reuse a key string) and an inner map holds one gate per
// key. A gate exists only while requests hold or wait for it: it is reference-counted and removed by
// the last one to leave. (Gates used to stay forever - one per distinct key ever requested, and keys
// contain request values, so callers could grow the map without limit.)
private static readonly ConcurrentDictionary<IRoutineCache, ConcurrentDictionary<string, RecordCacheGate>> _recordCacheGates
= new(ReferenceEqualityComparer.Instance);
internal static int RecordCacheGateCount => _recordCacheGates.Values.Sum(static g => g.Count);
private sealed class RecordCacheGate(ConcurrentDictionary<string, RecordCacheGate> owner, string key)
{
private readonly SemaphoreSlim _semaphore = new(1, 1);
private int _users; // requests holding or waiting; -1 = retired (removed from owner). Guarded by lock(this).
private static RecordCacheGate Enter(IRoutineCache cache, string key)
{
var gates = _recordCacheGates.GetOrAdd(cache, static _ => new(StringComparer.Ordinal));
while (true)
{
var gate = gates.GetOrAdd(key, static (k, g) => new RecordCacheGate(g, k), gates);
lock (gate)
{
if (gate._users >= 0)
{
gate._users++;
return gate;
}
}
// retired by its last user between GetOrAdd and lock: take (or create) the current one
}
}
/// <summary>
/// Enters the gate for <paramref name="key"/> and waits for it. If the wait is cancelled, the gate is left
/// without releasing (it was never acquired) and the cancellation propagates.
/// </summary>
public static async Task<RecordCacheGate> AcquireAsync(IRoutineCache cache, string key, CancellationToken cancellationToken)
{
var gate = Enter(cache, key);
try
{
await gate._semaphore.WaitAsync(cancellationToken);
}
catch
{
gate.Leave(acquired: false);
throw;
}
return gate;
}
public void Leave(bool acquired = true)
{
if (acquired)
{
_semaphore.Release();
}
lock (this)
{
if (--_users == 0)
{
_users = -1;
owner.TryRemove(new KeyValuePair<string, RecordCacheGate>(key, this));
}
}
}
}
public Task InvokeAsync(HttpContext context, IServiceProvider? serviceProvider, CancellationToken cancellationToken = default)
=> RunAsync(context, serviceProvider, cancellationToken).AsTask();
/// <summary>Route handler (see NpgsqlRestBuilder): the service provider is resolved from the request only when needed.</summary>
internal Task HandleRequestAsync(HttpContext context, CancellationToken cancellationToken)
=> RunAsync(context, null, cancellationToken).AsTask();
/// <summary>The route handler as a RequestDelegate: what the endpoint calls when it has no endpoint filters (see NpgsqlRestBuilder).</summary>
internal Task HandleDirectAsync(HttpContext context)
=> RunAsync(context, null, context.RequestAborted).AsTask();
/// <summary>
/// A request, start to end. This method only sequences the stages: everything a request needs lives in one pooled
/// <see cref="RequestState"/>, so while the request waits for the database only a few small async frames are
/// suspended (this one holds the state and nothing else).
/// </summary>
// Pooled builder (as on the stage methods below): without Runtime Async, the state machine box of a method that
// waits on I/O is reused across requests instead of allocated; AsTask() above then allocates only a small Task.
// With Runtime Async the attribute has no effect - the runtime keeps a method's state itself.
[System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))]
private async ValueTask RunAsync(HttpContext context, IServiceProvider? serviceProvider, CancellationToken cancellationToken)
{
// ASP.NET Core's antiforgery middleware (UseAntiforgery) only *records* a failed token validation in
// IAntiforgeryValidationFeature and continues - rejecting the request is left to the endpoint (MVC and
// minimal-API form binding do it). So when the endpoint carries antiforgery metadata and the token was
// missing or invalid, the request is rejected here, before anything runs.
if (context.Features.Get<Microsoft.AspNetCore.Antiforgery.IAntiforgeryValidationFeature>() is { IsValid: false })
{
await Results.Problem(
type: null,
statusCode: StatusCodes.Status400BadRequest,
title: "Bad Request",
detail: "Invalid or missing antiforgery token.").ExecuteAsync(context);
return;
}
var s = RequestState.Rent();
s.context = context;
s.cancellationToken = cancellationToken;
s.serviceProvider = serviceProvider;
s.endpoint = entry.Endpoint;
s.routine = entry.Endpoint.Routine;
s.formatter = entry.Formatter;
s.shouldLog = Options.LogCommands && Logger != null;
if (s.endpoint.RequestHeadersMode == RequestHeadersMode.Context)
{
SearializeHeader(Options, context, ref s.headers);
}
// proxy_out: capture function output into a buffer instead of writing to the real response
if (s.endpoint.IsProxyOut && Options.ProxyOptions.Enabled)
{
s.proxyOutBuffer = new MemoryStream();
s.proxyOutOriginalBody = context.Response.Body;
context.Response.Body = s.proxyOutBuffer;
}
// The response's own pipe: Response.BodyWriter. (Wrapping Response.Body in a new StreamPipeWriter allocated a
// writer per request and copied every byte once more through the stream into the same pipe.) BodyWriter stays
// consistent with Response.Body when middleware replaces it (e.g. response compression).
s.writer = s.proxyOutBuffer is not null
? PipeWriter.Create(context.Response.Body, new StreamPipeWriterOptions(leaveOpen: true))
: context.Response.BodyWriter;
try
{
// A stage returns false when the request is finished: a response was written or its status set.
if (await BeginRequestAsync(s) is false || await PrepareParametersAsync(s) is false)
{
return;
}
if (s.endpoint.IsProxy && Options.ProxyOptions.Enabled && await ProxyAsync(s) is false)
{
return;
}
await SetRequestContextAsync(s);
if (s.endpoint.Upload is true && s.uploadHandler is not null)
{
await UploadAsync(s);
}
if ((s.endpoint.Login is true || s.endpoint.Logout is true || s.endpoint.InvalidateCache is true)
&& await LoginLogoutOrInvalidateAsync(s) is false)
{
return;
}
// The routine runs and its result is rendered: one method per shape, so each keeps little state alive
// while it waits for the database.
if (s.routine.IsMultiCommand && s.routine.MultiCommandInfo is not null)
{
await RenderMultiCommandAsync(s);
}
else if (s.routine.IsVoid || s.endpoint.Void)
{
await RenderVoidAsync(s);
}
else if (s.routine.ReturnsSet == false && s.routine.ColumnCount == 1 && s.routine.ReturnsRecordType is false)
{
if (s.resolvedCache is not null && s.endpoint.Cached is true && s.bypassCache is false)
{
await RenderCachedScalarAsync(s);
}
else
{
await RenderScalarAsync(s);
}
}
else
{
await RenderRecordsAsync(s);
}
}
catch (Exception exception)
{
await HandleExceptionAsync(s, exception);
}
finally
{
try
{
await CompleteRequestAsync(s);
}
finally
{
RequestState.Return(s);
}
}
}
/// <summary>
/// First stage of a request: the connection, the notice handler, upfront authentication and authorization, the
/// command, the request body and parameter binding. Returns false when the request is finished (a response was
/// written or its status set).
/// </summary>
[System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))]
private async ValueTask<bool> BeginRequestAsync(RequestState s)
{
var context = s.context;
var cancellationToken = s.cancellationToken;
var serviceProvider = s.serviceProvider;
var endpoint = s.endpoint;
var routine = s.routine;
var formatter = s.formatter;
var shouldLog = s.shouldLog;
NpgsqlConnection? connection = null;
StringBuilder? cmdLog = null;
StringBuilder? cacheKeys = null;
StringBuilder? commandTextBuilder = null;
if (Options.AmbientConnectionAccessor?.Invoke() is { } ambientConnection)
{
// Ambient connection override (SQL test runner): run on the caller's already-open
// connection/transaction and never dispose it. The caller owns the connection lifecycle.
s.connection = connection = ambientConnection;
s.shouldDispose = false;
}
else if (endpoint.ConnectionName is not null)
{
// First check if there's a data source for this connection name (for multi-host support)
if (Options.DataSources?.TryGetValue(endpoint.ConnectionName, out var namedDataSource) is true)
{
s.connection = connection = namedDataSource.CreateConnection();
}
else if (Options.ConnectionStrings?.TryGetValue(endpoint.ConnectionName, out var connectionString) is true)
{
s.connection = connection = new(connectionString);
}
else
{
await ReturnErrorAsync($"Connection name {endpoint.ConnectionName} could not be found in options DataSources or ConnectionStrings dictionaries.", true, context, cancellationToken);
return false;
}
}
else if (Options.ServiceProviderMode != ServiceProviderObject.None)
{
serviceProvider ??= context.RequestServices;
if (serviceProvider is null)
{
await ReturnErrorAsync($"ServiceProvider must be provided when ServiceProviderMode is set to {Options.ServiceProviderMode}.", true, context, cancellationToken);
return false;
}
if (Options.ServiceProviderMode == ServiceProviderObject.NpgsqlDataSource)
{
s.connection = connection = serviceProvider.GetRequiredService<NpgsqlDataSource>().CreateConnection();
await connection.OpenRetryAsync(Options.ConnectionRetryOptions, cancellationToken);
}
else if (Options.ServiceProviderMode == ServiceProviderObject.NpgsqlConnection)
{
s.shouldDispose = false;
s.connection = connection = serviceProvider.GetRequiredService<NpgsqlConnection>();
}
}
else
{
if (Options.DataSource is not null)
{
s.connection = connection = Options.DataSource.CreateConnection();
}
else
{
s.connection = connection = new(Options.ConnectionString);
}
}
if (connection is null)
{
await ReturnErrorAsync("Connection did not initialize!", log: true, context, cancellationToken);
return false;
}
// Three reasons to attach a notice handler:
// 1. LogConnectionNoticeEvents — log every notice regardless of SSE wiring.
// 2. Endpoint publishes to broadcaster — forward matching notices to subscribers.
// 3. WarnUnboundSseNotices — and the project actually uses SSE somewhere; warn when a
// RAISE in a non-publishing endpoint matches the SSE forwarding level (a likely
// missing @sse_publish annotation).
bool noticeWarnEnabled = Options.WarnUnboundSseNotices
&& Logger != null
&& NpgsqlRestSseEventSource.HasAnySseEndpoints
&& endpoint.SsePublishEnabled is false;
if ((Options.LogConnectionNoticeEvents && Logger != null)
|| endpoint.SsePublishEnabled
|| noticeWarnEnabled)
{
s.noticeHandler = CreateNoticeHandler(context, endpoint, noticeWarnEnabled);
connection.Notice += s.noticeHandler;
}
// Basic Auth for the primary endpoint (see _basicAuthUpfront); remembered so it is not repeated below.
if (Options.AuthenticationOptions.BasicAuth.Enabled is true || _basicAuthUpfront)
{
s.basicAuthCheckedFor = endpoint;
if (Options.AuthenticationOptions.BasicAuth.ChallengeCommand is not null || endpoint.BasicAuth?.ChallengeCommand is not null)
{
await OpenConnectionAsync(connection, context, endpoint, cancellationToken);
}
await BasicAuthHandler.HandleAsync(context, endpoint, connection, cancellationToken);
if (context.Response.HasStarted is true)
{
return false;
}
}
// Upfront authorization (see _rejectAnonymousUpfront): reject before any request processing work.
if ((_rejectAnonymousUpfront || _checkRolesUpfront)
&& await RejectUnauthorizedAsync(context, endpoint, checkAuthentication: _rejectAnonymousUpfront, checkRoles: _checkRolesUpfront))
{
return false;
}
// Disposed with the request (see CompleteRequestAsync).
var command = s.command = NpgsqlRestCommand.Create(connection);
if (shouldLog)
{
cmdLog = s.cmdLog = StringBuilderPool.Rent();
cmdLog.Append("-- ");
cmdLog.Append(context.Request.Method);
cmdLog.Append(' ');
if (Options.AuthenticationOptions.ObfuscateAuthParameterLogValues && endpoint.IsAuth)
{
cmdLog.Append(context.Request.Scheme);
cmdLog.Append("://");
cmdLog.Append(context.Request.Host);
cmdLog.Append(context.Request.Path);
}
else
{
cmdLog.Append(context.Request.GetDisplayUrl());
}
cmdLog.Append(Environment.NewLine);
}
if (formatter.IsFormattable is false)
{
// Use pooled StringBuilder for non-formattable commands to avoid string.Concat allocations
commandTextBuilder = s.commandTextBuilder = StringBuilderPool.Rent(routine.Expression.Length + routine.ParamCount * 16);
commandTextBuilder.Append(routine.Expression);
}
// paramsList
JsonObject? jsonObj = null;
Dictionary<string, JsonNode?>? bodyDict = null;
string? body = null;
// Use IQueryCollection directly to avoid ToDictionary() allocation
IQueryCollection? queryCollection = null;
// Skip local upload handling if proxy will forward the upload content
var skipUploadForProxy = endpoint.Upload is true &&
endpoint.IsProxy &&
Options.ProxyOptions.Enabled &&
Options.ProxyOptions.ForwardUploadContent;
s.uploadHandler = (endpoint.Upload is true && !skipUploadForProxy) ? endpoint.CreateUploadHandler() : null;
s.customHttpTypes = Options.HttpClientOptions.Enabled ? new(routine.Parameters.Length) : null!;
if (endpoint.Cached is true)
{
var prefixLen = endpoint.CacheKeyPrefix?.Length ?? 0;
cacheKeys = s.cacheKeys = StringBuilderPool.Rent(routine.Expression.Length + prefixLen + (endpoint.CachedParams?.Count ?? 0) * 32);
if (endpoint.CacheKeyPrefix is not null)
{
cacheKeys.Append(endpoint.CacheKeyPrefix);
cacheKeys.Append(NpgsqlRestParameter.GetCacheKeySeparator());
}
cacheKeys.Append(routine.Expression);
}
if (endpoint.RequestParamType == RequestParamType.QueryString)
{
queryCollection = context.Request.Query;
}
if (endpoint.HasBodyParameter || endpoint.RequestParamType == RequestParamType.BodyJson)
{
context.Request.EnableBuffering();
context.Request.Body.Position = 0;
using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true))
{
body = await reader.ReadToEndAsync(cancellationToken);
}
if (endpoint.RequestParamType == RequestParamType.BodyJson)
{
JsonNode? node = null;
try
{
node = JsonNode.Parse(string.IsNullOrWhiteSpace(body) ? "{}" : body);
}
catch (JsonException e)
{
Logger?.CouldNotParseJson(body, context.Request.Path, e.Message);
node = null;
}
if (node is not null)
{
try
{
jsonObj = node?.AsObject();
bodyDict = jsonObj?.ToDictionary();
}
catch (Exception e)
{
Logger?.CouldNotParseJson(body, context.Request.Path, e.Message);
bodyDict = null;
}
}
}
}
// Claim-bound user parameters (user_params) are filled by the server: for signed-in callers the claim
// always wins (see the parameter loops). Anonymous callers must not be able to supply them either -
// otherwise ?userId=1 would impersonate user 1 on an endpoint that allows anonymous access. Their
// request values are dropped, so the routine sees "not provided" (its default, else NULL).
// Login endpoints are the exception: their callers are anonymous by definition and their parameters
// are the credentials being checked (a login routine typically has a _username or _user_name
// parameter, which collides with the claim mapping). Dropping those would make every login fail.
if (endpoint.UseUserParameters && endpoint.Login is false && context.User?.Identity?.IsAuthenticated is not true)
{
RemoveClientSuppliedUserParameters(routine, ref queryCollection, bodyDict);
}
// Parameter binding (query string or JSON body). It may resolve an overload: s.routine, s.endpoint and
// s.formatter are then the overload's.
s.queryCollection = queryCollection;
s.bodyDict = bodyDict;
s.body = body;
s.jsonObj = jsonObj;
if (endpoint.RequestParamType == RequestParamType.QueryString)
{
return await BindQueryStringParametersAsync(s);
}
if (endpoint.RequestParamType == RequestParamType.BodyJson)
{
return await BindBodyParametersAsync(s);
}
return true;
}
/// <summary>
/// The per-request connection notice handler. A separate method so its closure is allocated only for the requests
/// that attach a handler (it captures the request and the endpoint, never the pooled request state).
/// </summary>
private static NoticeEventHandler CreateNoticeHandler(HttpContext context, RoutineEndpoint currentEndpointCaptured, bool noticeWarnEnabled)
{
return (sender, args) =>
{
if (Options.LogConnectionNoticeEvents && Logger != null)
{
NpgsqlRestLogger.LogConnectionNotice(args.Notice, Options.LogConnectionNoticeEventsMode);
}
if (currentEndpointCaptured.SsePublishEnabled
&& currentEndpointCaptured.SseEventNoticeLevel is not null
&& string.Equals(args.Notice.Severity, currentEndpointCaptured.SseEventNoticeLevel.ToString(), StringComparison.OrdinalIgnoreCase))
{
NpgsqlRestSseEventSource
.Broadcaster
.Broadcast(new SseEvent(args.Notice, currentEndpointCaptured, context.Request.Headers[Options.ExecutionIdHeaderName].FirstOrDefault()));
}
else if (noticeWarnEnabled
&& string.Equals(args.Notice.Severity, Options.DefaultSseEventNoticeLevel.ToString(), StringComparison.OrdinalIgnoreCase)
&& SseUnboundWarner.TryMarkWarned(currentEndpointCaptured.Path))
{
Logger!.UnboundSseRaise(args.Notice.Severity, currentEndpointCaptured.Path);
}
};
}
/// <summary>
/// Second stage: the parameters are bound. Validation, encryption, authorization of the resolved routine, the
/// command text, resolved parameter expressions, placeholder values, response headers, HTTP Custom Types and the
/// cache key. Returns false when the request is finished.
/// </summary>
[System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))]
private async ValueTask<bool> PrepareParametersAsync(RequestState s)
{
var context = s.context;
var cancellationToken = s.cancellationToken;
var endpoint = s.endpoint;
var routine = s.routine;
var formatter = s.formatter;
var connection = s.connection!;
var command = s.command;
var commandTextBuilder = s.commandTextBuilder;
var cacheKeys = s.cacheKeys;
var body = s.body;
var customHttpTypes = s.customHttpTypes;
string? commandText = null;
if (s.hasNulls && routine.IsStrict)
{
context.Response.StatusCode = (int)HttpStatusCode.NoContent;
await context.Response.CompleteAsync();
return false;
}
// parameters are ready !!!
// Validate parameters before any further processing (authorization, proxy, etc.)
if (endpoint.ParameterValidations is not null)
{
if (!await ValidateParametersAsync(command.Parameters, endpoint, context, cancellationToken))
{
return false;
}
}
// Encrypt parameters marked with encrypt annotation
if (Options.AuthenticationOptions.DefaultDataProtector is not null &&
(endpoint.EncryptAllParameters || endpoint.EncryptParameters is not null))
{
var protector = Options.AuthenticationOptions.DefaultDataProtector;
for (int p = 0; p < command.Parameters.Count; p++)
{
var param = (NpgsqlRestParameter)command.Parameters[p];
if (param.Value is string strValue &&
(endpoint.EncryptAllParameters ||
endpoint.EncryptParameters!.Contains(param.ActualName) ||
endpoint.EncryptParameters!.Contains(param.ConvertedName)))
{
param.Value = protector.Protect(strValue);
}
}
}
// Basic Auth for the routine the request resolved to, when it was not done upfront for it: an overload with
// its own basic_auth (it used to run without credentials when the primary had none), or a path whose
// overloads do not all use Basic Auth (the public ones used to be challenged by the primary's).
if (ReferenceEquals(s.basicAuthCheckedFor, endpoint) is false && endpoint.BasicAuth?.Enabled is true)
{
if (endpoint.BasicAuth.ChallengeCommand is not null || Options.AuthenticationOptions.BasicAuth.ChallengeCommand is not null)
{
await OpenConnectionAsync(connection, context, endpoint, cancellationToken);
}
await BasicAuthHandler.HandleAsync(context, endpoint, connection, cancellationToken);
if (context.Response.HasStarted is true)
{
return false;
}
}
// authorization check for the endpoint the request resolved to (it may be an overload)
if (endpoint.Login is false
&& await RejectUnauthorizedAsync(context, endpoint, checkAuthentication: true, checkRoles: true))
{
return false;
}
if (formatter.IsFormattable is true)
{
if (formatter.RefContext)
{
commandText = formatter.FormatCommand(routine, command.Parameters, context);
if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK)
{
return false;
}
}
else
{
commandText = formatter.FormatCommand(routine, command.Parameters);
}
}
if (formatter.IsFormattable is false)
{
if (formatter.RefContext)
{
commandTextBuilder!.Append(formatter.AppendEmpty(context));
if (formatter.IsFormattable)
{
if (context.Response.HasStarted || context.Response.StatusCode != (int)HttpStatusCode.OK)
{
return false;
}
}
}
else
{
commandTextBuilder!.Append(formatter.AppendEmpty());
}
// Convert StringBuilder to string for final commandText
commandText = commandTextBuilder.ToString();
}
s.commandText = commandText;
if (commandText is null)
{
s.shouldCommit = false;
s.uploadHandler?.OnError(connection, context, null);
context.Response.StatusCode = StatusCodes.Status404NotFound;
await context.Response.CompleteAsync();
return false;
}
// Resolve parameter expressions: execute SQL expressions to fill resolved parameter values
if (endpoint.ResolvedParameterExpressions is not null && endpoint.ResolvedParameterExpressions.Count > 0)
{
await OpenConnectionAsync(connection, context, endpoint, cancellationToken);
foreach (var (resolvedParamName, sqlExpression) in endpoint.ResolvedParameterExpressions)
{
var (parameterizedSql, sqlParams) = Formatter.ParameterizeSqlExpression(sqlExpression, command.Parameters);
await using var resolveCmd = new NpgsqlCommand(parameterizedSql, connection);
for (int p = 0; p < sqlParams.Count; p++)
{
resolveCmd.Parameters.Add(new NpgsqlParameter { Value = sqlParams[p].Value ?? DBNull.Value });
}
var resolvedValue = await resolveCmd.ExecuteScalarAsync(cancellationToken);
// Update the parameter value in the main command
for (int p = 0; p < command.Parameters.Count; p++)
{
var param = (NpgsqlRestParameter)command.Parameters[p];
if (string.Equals(param.ActualName, resolvedParamName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(param.ConvertedName, resolvedParamName, StringComparison.OrdinalIgnoreCase))
{
param.Value = resolvedValue ?? DBNull.Value;
break;
}
}
}
}
Dictionary<string, string>? customParameters = endpoint.CustomParameters;
Dictionary<string, string>.AlternateLookup<ReadOnlySpan<char>>? lookup = null;
// HTTP Custom Type URLs get their own lookup: values that come from the request are percent-encoded there
// (env var values - operator configuration such as a base URL - are not), so a request value cannot
// change the outbound request's path, query or host.
Dictionary<string, string>.AlternateLookup<ReadOnlySpan<char>>? urlLookup = null;
if (endpoint.HeadersNeedParsing is true || endpoint.CustomParamsNeedParsing || HttpClientTypes.NeedsParsing)
{
// Case-insensitive so `{name}` placeholders match parameter names regardless of casing,
// consistent with the resolved-parameter SQL expression resolver (Formatter.ParameterizeSqlExpression).
var envVars = Options.SubstitutionEnvironmentVariables;
Dictionary<string, string> replacements = new(command.Parameters.Count * 4 + (envVars?.Count ?? 0), StringComparer.OrdinalIgnoreCase);
Dictionary<string, string>? urlReplacements = HttpClientTypes.NeedsParsing
? new(command.Parameters.Count * 4 + (envVars?.Count ?? 0), StringComparer.OrdinalIgnoreCase)
: null;
// Allowlisted env vars first (base); parameter values added below overwrite them on a name
// collision, so a routine parameter always wins over an env var of the same name.
// Entries under a "!NAME" key mark names that resolved to a real value - that is what the
// {!NAME}/{!NAME:fallback} forms key off in Formatter.TryResolveToken.
if (envVars is not null)
{
foreach (var (name, value) in envVars)
{
replacements[name] = value;
if (urlReplacements is not null)
{
urlReplacements[name] = value;
}
}
}
for (var i = 0; i < command.Parameters.Count; i++)
{
var isNull = command.Parameters[i].Value is null || command.Parameters[i].Value == DBNull.Value;
var value = isNull ? "" : command.Parameters[i].Value?.ToString() ?? "";
var param = (NpgsqlRestParameter)command.Parameters[i];
// A parameter wins over an env var in BOTH forms: a non-null value registers its own
// "!name" key; a null value removes any "!name" an env var of the same name left behind,
// so {!name:fallback} then yields the fallback instead of the env value.
var urlValue = urlReplacements is null ? null : Uri.EscapeDataString(value);
void AddParam(string key)
{
replacements[key] = value;
if (isNull is false)
{
replacements[string.Concat("!", key)] = value;
}
else if (envVars is not null)
{
replacements.Remove(string.Concat("!", key));
}
if (urlReplacements is not null)
{
urlReplacements[key] = urlValue!;
if (isNull is false)
{
urlReplacements[string.Concat("!", key)] = urlValue!;
}
else if (envVars is not null)
{
urlReplacements.Remove(string.Concat("!", key));
}
}
}
if (!string.IsNullOrEmpty(param.ActualName))
{
AddParam(param.ActualName);
}
AddParam(param.ConvertedName);
if (param.TypeDescriptor.CustomTypeName is not null)
{
AddParam(param.TypeDescriptor.CustomTypeName);
}
}
lookup = replacements.GetAlternateLookup<ReadOnlySpan<char>>();
urlLookup = urlReplacements?.GetAlternateLookup<ReadOnlySpan<char>>();
}
if (endpoint.HeadersNeedParsing is true || endpoint.CustomParamsNeedParsing)
{
if (endpoint.CustomParamsNeedParsing && endpoint.CustomParameters is not null)
{
customParameters = new Dictionary<string, string>(endpoint.CustomParameters.Count, StringComparer.OrdinalIgnoreCase);
foreach (var (key, value) in endpoint.CustomParameters)
{
// SQL-valued parameters (row_command) are never formatted: request values in SQL text = SQL injection.
customParameters[key] = Defaults.DefaultCommentParser.IsSqlCustomParameter(key)
? value
: Formatter.FormatString(value, lookup!.Value).ToString();
}
}
}
if (endpoint.ResponseContentType is not null || endpoint.ResponseHeaders.Count > 0)
{
if (endpoint.HeadersNeedParsing is true)
{
if (endpoint.ResponseContentType is not null)
{
context.Response.ContentType = Formatter.FormatString(endpoint.ResponseContentType, lookup!.Value).ToString();
}
if (endpoint.ResponseHeaders.Count > 0)
{
foreach (var (headerKey, headerValue) in endpoint.ResponseHeaders)
{
context.Response.Headers.Append(headerKey, Formatter.FormatString(headerValue.ToString(), lookup!.Value).ToString());
}
}
}
else
{
if (endpoint.ResponseContentType is not null)
{
context.Response.ContentType = endpoint.ResponseContentType;
}
if (endpoint.ResponseHeaders.Count > 0)
{
foreach (var (headerKey, headerValue) in endpoint.ResponseHeaders)
{
context.Response.Headers.Append(headerKey, headerValue);
}
}
}
}
if (Options.HttpClientOptions.Enabled && customHttpTypes.Count > 0)
{
// Set self base URL for relative path resolution (lazy, once)
if (HttpClientTypeHandler.SelfBaseUrl is null)
{
if (Options.HttpClientOptions.SelfBaseUrl is not null)
{
HttpClientTypeHandler.SelfBaseUrl = Options.HttpClientOptions.SelfBaseUrl.TrimEnd('/');
}
else
{
var server = context.RequestServices.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as Microsoft.AspNetCore.Hosting.Server.IServer;
var addresses = server?.Features.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>();
var addr = addresses?.Addresses.FirstOrDefault();
HttpClientTypeHandler.SelfBaseUrl = addr ?? $"{context.Request.Scheme}://{context.Request.Host}";
}
}
await HttpClientTypeHandler.InvokeAllAsync(customHttpTypes, lookup, command.Parameters, cancellationToken, urlLookup);
}
// A proxied response depends on the whole forwarded request, not only on the routine parameters:
// query string keys that are not routine parameters are forwarded too, and so is the request body.
if (cacheKeys is not null && endpoint.IsProxy)
{
var rawQuery = context.Request.QueryString.Value ?? "";
cacheKeys.Append(NpgsqlRestParameter.GetCacheKeySeparator()).Append("?=").Append(rawQuery.Length).Append(':').Append(rawQuery);
if (body is not null)
{
cacheKeys.Append(NpgsqlRestParameter.GetCacheKeySeparator()).Append("body=").Append(body.Length).Append(':').Append(body);
}
}
// Cache the cache key string once to avoid repeated ToString() allocations
string? cacheKeyString = cacheKeys?.ToString();
// Resolve cache backend: profile's instance if set, otherwise the root DefaultRoutineCache.
var resolvedCache = endpoint.ResolvedCache ?? Options.CacheOptions.DefaultRoutineCache;
// Evaluate the When rules once. First match decides:
// - Skip = true → bypass cache entirely (no read, no write).
// - Skip = false → use rule's TTL override when writing (read still hits cache normally).
// - No match → no override; endpoint.CacheExpiresIn is used.
// Invalidation requests are NOT subject to bypass — they must always remove on demand.
var whenResult = endpoint.InvalidateCache is false ? EvaluateCacheWhenRules(endpoint, command) : default;
bool bypassCache = whenResult.Skip;
TimeSpan? cacheTtlOverride = whenResult.Skip ? null : whenResult.TtlOverride;
s.customParameters = customParameters;
s.cacheKeyString = cacheKeyString;
s.resolvedCache = resolvedCache;
s.bypassCache = bypassCache;
s.cacheTtlOverride = cacheTtlOverride;
return true;
}
/// <summary>
/// Reverse proxy endpoints: forwards the request upstream. Returns true when the routine still has to run (the
/// upstream response was mapped to its parameters), false when the proxied response was written.
/// </summary>
[System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))]
private async ValueTask<bool> ProxyAsync(RequestState s)
{
// Locals, not the pooled request state: the cache factory below captures them.
var context = s.context;
var cancellationToken = s.cancellationToken;
var endpoint = s.endpoint;
var command = s.command;
var body = s.body;
var shouldLog = s.shouldLog;
var cmdLog = s.cmdLog;
var commandText = s.commandText!;
var resolvedCache = s.resolvedCache;
var cacheKeyString = s.cacheKeyString;
var bypassCache = s.bypassCache;
var cacheTtlOverride = s.cacheTtlOverride;
var claimsDict = s.claimsDict;
// Handle reverse proxy endpoints
if (endpoint.IsProxy && Options.ProxyOptions.Enabled)
{
// Set self base URL for relative path proxy resolution (lazy, once)
if (Proxy.ProxyRequestHandler.SelfBaseUrl is null)
{
if (Options.ProxyOptions.SelfBaseUrl is not null)
{
Proxy.ProxyRequestHandler.SelfBaseUrl = Options.ProxyOptions.SelfBaseUrl.TrimEnd('/');
}
else
{
var proxyServer = context.RequestServices.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as Microsoft.AspNetCore.Hosting.Server.IServer;
var proxyAddresses = proxyServer?.Features.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>();
var proxyAddr = proxyAddresses?.Addresses.FirstOrDefault();
Proxy.ProxyRequestHandler.SelfBaseUrl = proxyAddr ?? $"{context.Request.Scheme}://{context.Request.Host}";
}
}
// Passthrough proxy endpoints (those without proxy response parameters) may be cached;
// the cache read/execute/coalesce is handled at the InvokeAsync call below.
bool isPassthroughProxy = !endpoint.HasProxyResponseParameters;
// Build user context headers if UserContext is enabled
Dictionary<string, string>? userContextHeaders = null;
if (endpoint.UserContext is true)
{
userContextHeaders = [];
claimsDict = s.claimsDict ??= context.User.BuildClaimsDictionary(Options.AuthenticationOptions);
// Add IP address header
if (Options.AuthenticationOptions.IpAddressContextKey is not null)
{
var ipAddress = context.Request.GetClientIpAddress();
if (!string.IsNullOrEmpty(ipAddress))
{
userContextHeaders[Options.AuthenticationOptions.IpAddressContextKey] = ipAddress;
}
}
if (context.User?.Identity?.IsAuthenticated is true)
{
// Add claims JSON header
if (Options.AuthenticationOptions.ClaimsJsonContextKey is not null)
{
var claimsJson = claimsDict.GetUserClaimsDbParam();
if (claimsJson is string claimsJsonStr)
{
userContextHeaders[Options.AuthenticationOptions.ClaimsJsonContextKey] = claimsJsonStr;
}
}
// Add individual claim headers from ContextKeyClaimsMapping
foreach (var mapping in Options.AuthenticationOptions.ContextKeyClaimsMapping)
{
var claimValue = claimsDict!.GetClaimDbContextParam(mapping.Value);
if (claimValue is string claimValueStr)
{
userContextHeaders[mapping.Key] = claimValueStr;
}
}
}
}
// Cacheable passthrough proxy: route the upstream call through GetOrCreateAsync so a burst
// of identical requests coalesces into a single upstream call (stampede protection), and
// the response is cached for subsequent hits.
bool proxyCacheable = isPassthroughProxy && endpoint.Cached is true && bypassCache is false && resolvedCache is not null;
if (proxyCacheable)
{
bool factoryRan = false;
var cachedProxy = await resolvedCache!.GetOrCreateAsync(
endpoint,
cacheKeyString!,
async ct =>
{
factoryRan = true;
return await Proxy.ProxyRequestHandler.InvokeAsync(context, endpoint, body, command.Parameters, userContextHeaders, ct);
},
cacheTtlOverride,
cancellationToken);
if (shouldLog && factoryRan is false)
{
cmdLog?.AppendLine("/* proxy response from cache */");
NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", commandText);
}
if (cachedProxy is Proxy.ProxyResponse cachedProxyResponse)
{
await Proxy.ProxyRequestHandler.WriteResponseAsync(context, cachedProxyResponse, Options.ProxyOptions, cancellationToken);
}
return false;
}
var proxyResponse = await Proxy.ProxyRequestHandler.InvokeAsync(context, endpoint, body, command.Parameters, userContextHeaders, cancellationToken);
if (endpoint.HasProxyResponseParameters)
{
// Map proxy response to parameters and continue with routine execution
MapProxyResponseToParameters(proxyResponse, command.Parameters, endpoint);
}
else
{
// No proxy parameters and not cacheable - return proxy response directly without PostgreSQL.
await Proxy.ProxyRequestHandler.WriteResponseAsync(context, proxyResponse, Options.ProxyOptions, cancellationToken);
return false;
}
}
return true;
}
/// <summary>
/// Sets the request context on the connection before the routine runs: request headers, user claims and IP
/// address, BeforeRoutineCommands, and the request transaction when WrapInTransaction is on. Does nothing (and
/// does not open the connection) when none of them applies.
/// </summary>
[System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))]
private async ValueTask SetRequestContextAsync(RequestState s)
{
var context = s.context;
var cancellationToken = s.cancellationToken;
var endpoint = s.endpoint;
var connection = s.connection!;
var headers = s.headers;
var transaction = s.transaction;
var claimsDict = s.claimsDict;