-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathConfigurationHotReloadTests.cs
More file actions
1041 lines (906 loc) · 42.2 KB
/
ConfigurationHotReloadTests.cs
File metadata and controls
1041 lines (906 loc) · 42.2 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Service.Tests.SqlTests;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Azure.DataApiBuilder.Service.Tests.Configuration.HotReload;
[TestClass]
public class ConfigurationHotReloadTests
{
private const string MSSQL_ENVIRONMENT = TestCategory.MSSQL;
private static TestServer _testServer;
private static HttpClient _testClient;
private static RuntimeConfigProvider _configProvider;
private static StringWriter _writer;
private static readonly object _writerLock = new();
private const string CONFIG_FILE_NAME = "hot-reload.dab-config.json";
private const string GQL_QUERY_NAME = "books";
private const string HOT_RELOAD_SUCCESS_MESSAGE = "Validated hot-reloaded configuration file";
private const string HOT_RELOAD_FAILURE_MESSAGE = "Unable to hot reload configuration file due to";
private const int HOT_RELOAD_TIMEOUT_SECONDS = 120;
private const string GQL_QUERY = @"{
books(first: 100) {
items {
id
title
publisher_id
}
}
}";
private static string _bookDBOContents;
private static void GenerateConfigFile(
string schema = "",
DatabaseType databaseType = DatabaseType.MSSQL,
string sessionContext = "true",
string connectionString = "",
string restPath = "rest",
string restEnabled = "true",
string gQLPath = "/graphQL",
string gQLEnabled = "true",
string logFilter = "debug",
string entityName = "Book",
string sourceObject = "books",
string gQLEntityEnabled = "true",
string gQLEntitySingular = "book",
string gQLEntityPlural = "books",
string restEntityEnabled = "true",
string entityBackingColumn = "title",
string entityExposedName = "title",
string mcpEnabled = "true",
string configFileName = CONFIG_FILE_NAME)
{
File.WriteAllText(configFileName, @"
{
""$schema"": """ + schema + @""",
""data-source"": {
""database-type"": """ + databaseType + @""",
""options"": {
""set-session-context"": " + sessionContext + @"
},
""connection-string"": """ + connectionString + @"""
},
""runtime"": {
""rest"": {
""enabled"": " + restEnabled + @",
""path"": ""/" + restPath + @""",
""request-body-strict"": true
},
""graphql"": {
""enabled"": " + gQLEnabled + @",
""path"": """ + gQLPath + @""",
""allow-introspection"": true
},
""mcp"": {
""enabled"": " + mcpEnabled + @"
},
""host"": {
""cors"": {
""origins"": [
""http://localhost:5000""
],
""allow-credentials"": false
},
""authentication"": {
""provider"": ""AppService""
},
""mode"": ""development""
},
""telemetry"": {
""log-level"": {
""default"": """ + logFilter + @"""
}
}
},
""entities"": {
""" + entityName + @""": {
""source"": {
""object"": """ + sourceObject + @""",
""type"": ""table""
},
""graphql"": {
""enabled"": " + gQLEntityEnabled + @",
""type"": {
""singular"": """ + gQLEntitySingular + @""",
""plural"": """ + gQLEntityPlural + @"""
}
},
""rest"": {
""enabled"": " + restEntityEnabled + @"
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""*""
}
]
},
{
""role"": ""authenticated"",
""actions"": [
{
""action"": ""*""
}
]
}
],
""mappings"": {
""" + entityBackingColumn + @""": """ + entityExposedName + @"""
}
},
""Publisher"": {
""source"": {
""object"": ""publishers"",
""type"": ""table""
},
""graphql"": {
""enabled"": true,
""type"": {
""singular"": ""Publisher"",
""plural"": ""Publishers""
}
},
""rest"": {
""enabled"": true
},
""permissions"": [
{
""role"": ""anonymous"",
""actions"": [
{
""action"": ""*""
}
]
},
{
""role"": ""authenticated"",
""actions"": [
{
""action"": ""*""
}
]
}
]
}
}
}");
}
/// <summary>
/// Initialize the test fixture by creating the initial configuration file and starting
/// the test server with it. Validate that the test server returns OK status when handling
/// valid requests.
/// </summary>
[ClassInitialize]
public static async Task ClassInitializeAsync(TestContext context)
{
// Arrange
GenerateConfigFile(connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}");
int maxRetries = 3;
int retryDelayMs = 2000;
Exception lastException = null;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
Console.WriteLine($"Initializing test server (attempt {attempt}/{maxRetries})...");
_testServer = new(Program.CreateWebHostBuilder(new string[] { "--ConfigFileName", CONFIG_FILE_NAME }));
_testClient = _testServer.CreateClient();
_configProvider = _testServer.Services.GetService<RuntimeConfigProvider>();
// Give the server a moment to fully initialize
await Task.Delay(1000);
string query = GQL_QUERY;
object payload = new { query };
HttpRequestMessage request = new(HttpMethod.Post, "/graphQL")
{
Content = JsonContent.Create(payload)
};
HttpResponseMessage restResult = await _testClient.GetAsync("/rest/Book");
HttpResponseMessage gQLResult = await _testClient.SendAsync(request);
// Assert rest and graphQL requests return status OK.
Assert.AreEqual(HttpStatusCode.OK, restResult.StatusCode,
$"REST request failed on attempt {attempt}. Response: {await restResult.Content.ReadAsStringAsync()}");
Assert.AreEqual(HttpStatusCode.OK, gQLResult.StatusCode,
$"GraphQL request failed on attempt {attempt}. Response: {await gQLResult.Content.ReadAsStringAsync()}");
// Save the contents from request to validate results after hot-reloads.
string restContent = await restResult.Content.ReadAsStringAsync();
using JsonDocument doc = JsonDocument.Parse(restContent);
_bookDBOContents = doc.RootElement.GetProperty("value").ToString();
Console.WriteLine($"Test server initialized successfully on attempt {attempt}");
return;
}
catch (Exception ex)
{
lastException = ex;
Console.WriteLine($"Test server initialization attempt {attempt} failed: {ex.Message}");
// Clean up failed attempt
try
{
_testClient?.Dispose();
_testServer?.Dispose();
}
catch { /* Ignore cleanup errors */ }
if (attempt < maxRetries)
{
Console.WriteLine($"Waiting {retryDelayMs}ms before retry...");
await Task.Delay(retryDelayMs);
}
}
}
// If we got here, all retries failed
throw new Exception($"Failed to initialize test server after {maxRetries} attempts. Last error: {lastException?.Message}", lastException);
}
[ClassCleanup]
public static void ClassCleanup()
{
try
{
if (File.Exists(CONFIG_FILE_NAME))
{
File.Delete(CONFIG_FILE_NAME);
}
_testClient?.Dispose();
_testServer?.Dispose();
Console.WriteLine("Test cleanup completed successfully");
}
catch (Exception ex)
{
Console.WriteLine($"Error during test cleanup: {ex.Message}");
}
}
/// <summary>
/// Thread-safe helper to check if the writer contains a specific message
/// </summary>
private static bool WriterContains(string message)
{
lock (_writerLock)
{
return _writer.ToString().Contains(message);
}
}
/// <summary>
/// Hot reload the configuration by saving a new file with different rest and graphQL paths.
/// Validate that the response is correct when making a request with the newly hot-reloaded paths.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod("Hot-reload runtime paths.")]
public async Task HotReloadConfigRuntimePathsEndToEndTest()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
string restBookContents = $"{{\"value\":{_bookDBOContents}}}";
string restPath = "restApi";
string gQLPath = "/gQLApi";
string query = GQL_QUERY;
object payload =
new { query };
HttpRequestMessage request = new(HttpMethod.Post, "/graphQL")
{
Content = JsonContent.Create(payload)
};
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
restPath: restPath,
gQLPath: gQLPath);
// Wait for hot-reload to complete successfully
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Act
HttpResponseMessage badPathRestResult = await _testClient.GetAsync($"rest/Book");
HttpResponseMessage badPathGQLResult = await _testClient.SendAsync(request);
// After hot-reload, the engine may still be re-initializing metadata providers.
// Poll the REST endpoint to allow time for the engine to become fully ready.
using HttpResponseMessage result = await WaitForRestEndpointAsync($"{restPath}/Book", HttpStatusCode.OK);
string reloadRestContent = await result.Content.ReadAsStringAsync();
// Poll the GraphQL endpoint to allow time for the engine to become fully ready.
(bool querySucceeded, JsonElement reloadGQLContents) = await WaitForGraphQLEndpointAsync(GQL_QUERY_NAME, GQL_QUERY);
// Assert
// Old paths are not found.
Assert.AreEqual(HttpStatusCode.BadRequest, badPathRestResult.StatusCode);
Assert.AreEqual(HttpStatusCode.NotFound, badPathGQLResult.StatusCode);
// Hot reloaded paths return correct response.
Assert.IsTrue(querySucceeded, "GraphQL query did not return valid results after hot-reload.");
Assert.IsTrue(SqlTestHelper.JsonStringsDeepEqual(restBookContents, reloadRestContent));
SqlTestHelper.PerformTestEqualJsonStrings(_bookDBOContents, reloadGQLContents.GetProperty("items").ToString());
}
/// <summary>
/// Hot reload the configuration file by saving a new file with the rest enabled property
/// set to false. Validate that the response from the server is NOT FOUND when making a request after
/// the hot reload.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod("Hot-reload rest enabled.")]
public async Task HotReloadConfigRuntimeRestEnabledEndToEndTest()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
string restEnabled = "false";
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
restEnabled: restEnabled);
// Wait for hot-reload to complete successfully
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Act
HttpResponseMessage restResult = await _testClient.GetAsync($"rest/Book");
// Assert
Assert.AreEqual(HttpStatusCode.NotFound, restResult.StatusCode);
}
/// <summary>
/// Hot reload the configuration file by saving a new file with the graphQL enabled property
/// set to false. Validate that the response from the server is NOT FOUND when making a request after
/// the hot reload.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod("Hot-reload gql enabled.")]
public async Task HotReloadConfigRuntimeGQLEnabledEndToEndTest()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
string gQLEnabled = "false";
string query = GQL_QUERY;
object payload =
new { query };
HttpRequestMessage request = new(HttpMethod.Post, "/graphQL")
{
Content = JsonContent.Create(payload)
};
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
gQLEnabled: gQLEnabled);
// Wait for hot-reload to complete successfully
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Act
HttpResponseMessage gQLResult = await _testClient.SendAsync(request);
// Assert
Assert.AreEqual(HttpStatusCode.NotFound, gQLResult.StatusCode);
}
/// <summary>
/// Hot reload the configuration file by saving a new file with the graphQL enabled property
/// set to false at the entity level. Validate that the response from the server is INTERNAL SERVER ERROR when making a request after
/// the hot reload since no such entity exist in the query.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod("Hot-reload gql disabled at entity level.")]
[Ignore] // This test requires GraphQL schema reload. See: issue #3019
public async Task HotReloadEntityGQLEnabledFlag()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
string gQLEntityEnabled = "false";
string query = @"{
book_by_pk(id: 1) {
title
}
}";
object payload =
new { query };
HttpRequestMessage request = new(HttpMethod.Post, "/graphQL")
{
Content = JsonContent.Create(payload)
};
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
gQLEntityEnabled: gQLEntityEnabled);
// Wait for hot-reload to complete successfully
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Act
HttpResponseMessage gQLResult = await _testClient.SendAsync(request);
// Assert
Assert.AreEqual(HttpStatusCode.BadRequest, gQLResult.StatusCode);
string errorContent = await gQLResult.Content.ReadAsStringAsync();
Assert.IsTrue(errorContent.Contains("The field `book_by_pk` does not exist on the type `Query`."));
}
/// <summary>
/// Hot reload the configuration file by replacing an old entity book with a new entity author.
/// Validate that the new entity is accessible via GraphQL after the hot reload and the old one isn't.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod]
[Ignore] // This test requires GraphQL schema reload. See: issue #3019
public async Task HotReloadConfigAddEntity()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
string newEntityName = "Author";
string newEntitySource = "authors";
string newEntityGQLSingular = "author";
string newEntityGQLPlural = "authors";
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
entityName: newEntityName,
sourceObject: newEntitySource,
gQLEntitySingular: newEntityGQLSingular,
gQLEntityPlural: newEntityGQLPlural);
// Wait for hot-reload to complete successfully
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Act
string queryWithOldEntity = @"{
books(filter: {id: {eq: 1}}) {
items {
title
}
}
}";
object payload =
new { query = queryWithOldEntity };
HttpRequestMessage request = new(HttpMethod.Post, "/graphQL")
{
Content = JsonContent.Create(payload)
};
HttpResponseMessage gQLResultWithOldEntity = await _testClient.SendAsync(request);
string queryWithNewEntity = @"{
authors(filter: {id: {eq: 123}}) {
items {
name
}
}
}";
payload = new { query = queryWithNewEntity };
request = new(HttpMethod.Post, "/graphQL")
{
Content = JsonContent.Create(payload)
};
HttpResponseMessage gQLResultWithNewEntity = await _testClient.SendAsync(request);
// Assert
Assert.AreEqual(HttpStatusCode.BadRequest, gQLResultWithOldEntity.StatusCode);
string errorContent = await gQLResultWithOldEntity.Content.ReadAsStringAsync();
Assert.IsTrue(errorContent.Contains("The field `books` does not exist on the type `Query`."));
Assert.AreEqual(HttpStatusCode.OK, gQLResultWithNewEntity.StatusCode);
string responseContent = await gQLResultWithNewEntity.Content.ReadAsStringAsync();
JsonDocument jsonResponse = JsonDocument.Parse(responseContent);
JsonElement items = jsonResponse.RootElement.GetProperty("data").GetProperty("authors").GetProperty("items");
string expectedResponse = @"[
{
""name"": ""Jelte""
}
]";
JsonDocument expectedJson = JsonDocument.Parse(expectedResponse);
Assert.IsTrue(SqlTestHelper.JsonStringsDeepEqual(expectedJson.RootElement.ToString(), items.ToString()));
}
/// <summary>
/// Here, we updated the old mappings of the entity book field "title" to "bookTitle".
/// Validate that the response from the server is correct, by ensuring that the old mappings when used in the query
/// results in bad request, while the new mappings results in a correct response as "title" field is no longer valid.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod]
[Ignore] // This test requires GraphQL schema reload. See: issue #3019
public async Task HotReloadConfigUpdateMappings()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
string newMappingFieldName = "bookTitle";
// Update the configuration with new mappings
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
entityBackingColumn: "title",
entityExposedName: newMappingFieldName);
// Wait for hot-reload to complete successfully
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Act
string queryWithOldMapping = @"{
books(filter: { id: { eq: 1 } }) {
items {
title
}
}
}";
object payload = new { query = queryWithOldMapping };
HttpRequestMessage request = new(HttpMethod.Post, "/graphQL")
{
Content = JsonContent.Create(payload)
};
HttpResponseMessage gQLResultWithOldMapping = await _testClient.SendAsync(request);
string queryWithNewMapping = @"{
books(filter: { id: { eq: 1 } }) {
items {
bookTitle
}
}
}";
payload = new { query = queryWithNewMapping };
request = new(HttpMethod.Post, "/graphQL")
{
Content = JsonContent.Create(payload)
};
HttpResponseMessage gQLResultWithNewMapping = await _testClient.SendAsync(request);
// Assert
Assert.AreEqual(HttpStatusCode.BadRequest, gQLResultWithOldMapping.StatusCode);
string errorContent = await gQLResultWithOldMapping.Content.ReadAsStringAsync();
Assert.IsTrue(errorContent.Contains("The field `title` does not exist on the type `book`."));
Assert.AreEqual(HttpStatusCode.OK, gQLResultWithNewMapping.StatusCode);
string responseContent = await gQLResultWithNewMapping.Content.ReadAsStringAsync();
JsonDocument jsonResponse = JsonDocument.Parse(responseContent);
JsonElement items = jsonResponse.RootElement.GetProperty("data").GetProperty("books").GetProperty("items");
string expectedResponse = @"[
{
""bookTitle"": ""Awesome book""
}
]";
JsonDocument expectedJson = JsonDocument.Parse(expectedResponse);
Assert.IsTrue(SqlTestHelper.JsonStringsDeepEqual(expectedJson.RootElement.ToString(), items.ToString()));
}
/// <summary>
/// Hot reload the configuration file by saving a new session-context and connection string.
/// Validate that the response from the server is correct, by ensuring that the session-context
/// inside the DataSource parameter is different from the session-context before hot reload.
/// By asserting that hot reload worked properly for the session-context it also implies that
/// the new connection string with additional parameters is also valid.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod]
public async Task HotReloadConfigDataSource()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
RuntimeConfig previousRuntimeConfig = _configProvider.GetConfig();
MsSqlOptions previousSessionContext = previousRuntimeConfig.DataSource.GetTypedOptions<MsSqlOptions>();
// String has additions that are not in original connection string
string expectedConnectionString = $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}" + "Trusted_Connection=True;";
// Act
GenerateConfigFile(
sessionContext: "false",
connectionString: expectedConnectionString);
// Wait for hot-reload to complete successfully
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
RuntimeConfig updatedRuntimeConfig = _configProvider.GetConfig();
MsSqlOptions actualSessionContext = updatedRuntimeConfig.DataSource.GetTypedOptions<MsSqlOptions>();
// Poll the GraphQL endpoint to allow time for the engine to become fully ready.
(bool querySucceeded, JsonElement reloadGQLContents) = await WaitForGraphQLEndpointAsync(GQL_QUERY_NAME, GQL_QUERY, maxRetries: 10);
// Assert
Assert.IsTrue(querySucceeded, "GraphQL query did not return valid results after hot-reload. Metadata initialization may not have completed.");
Assert.AreNotEqual(previousSessionContext, actualSessionContext);
Assert.AreEqual(false, actualSessionContext.SetSessionContext);
SqlTestHelper.PerformTestEqualJsonStrings(_bookDBOContents, reloadGQLContents.GetProperty("items").ToString());
}
/// <summary>
/// Hot reload the configuration file so that it updated the log-level property.
/// Then we assert that the log-level property is properly updated by ensuring it is
/// not the same as the previous log-level and asserting it is the expected log-level.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod]
public async Task HotReloadLogLevel()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
LogLevel expectedLogLevel = LogLevel.Trace;
string expectedFilter = "trace";
RuntimeConfig previousRuntimeConfig = _configProvider.GetConfig();
LogLevel previouslogLevel = previousRuntimeConfig.GetConfiguredLogLevel();
// Act
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
logFilter: expectedFilter);
// Wait for hot-reload to complete successfully
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
RuntimeConfig updatedRuntimeConfig = _configProvider.GetConfig();
LogLevel actualLogLevel = updatedRuntimeConfig.GetConfiguredLogLevel();
// Assert
Assert.AreNotEqual(previouslogLevel, actualLogLevel);
Assert.AreEqual(expectedLogLevel, actualLogLevel);
}
/// <summary>
/// Hot reload the configuration file so that it changes from one connection string
/// to an invalid connection string, then it hot reloads once more to the original
/// connection string. Lastly, we assert that the first reload fails while the second one succeeds.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod]
public async Task HotReloadConfigConnectionString()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
// Act
// Hot Reload should fail here
GenerateConfigFile(
connectionString: $"WrongConnectionString");
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_FAILURE_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Log that shows that hot-reload was not able to validate properly
string failedConfigLog;
lock (_writerLock)
{
failedConfigLog = _writer.ToString();
_writer.GetStringBuilder().Clear();
}
// Hot Reload should succeed here
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}");
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Log that shows that hot-reload validated properly
string succeedConfigLog;
lock (_writerLock)
{
succeedConfigLog = _writer.ToString();
}
// After hot-reload, the engine may still be re-initializing metadata providers.
// Poll the REST endpoint to allow time for the engine to become fully ready.
using HttpResponseMessage restResult = await WaitForRestEndpointAsync("/rest/Book", HttpStatusCode.OK);
// Assert
Assert.IsTrue(failedConfigLog.Contains(HOT_RELOAD_FAILURE_MESSAGE));
Assert.IsTrue(succeedConfigLog.Contains(HOT_RELOAD_SUCCESS_MESSAGE));
Assert.AreEqual(HttpStatusCode.OK, restResult.StatusCode);
}
/// <summary>
/// /// (Warning: This test only currently works in the pipeline due to constrains of not
/// being able to change from one database type to another, under normal circumstances
/// hot reload allows changes from one database type to another)
/// Hot reload the configuration file so that it changes from one database type to another.
/// Then it hot reloads once more to the original database type. We assert that the
/// first reload fails while the second one succeeds.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod]
public async Task HotReloadConfigDatabaseType()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
// Act
// Hot Reload should fail here
GenerateConfigFile(
databaseType: DatabaseType.PostgreSQL,
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.POSTGRESQL).Replace("\\", "\\\\")}");
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_FAILURE_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Log that shows that hot-reload was not able to validate properly
string failedConfigLog;
lock (_writerLock)
{
failedConfigLog = _writer.ToString();
_writer.GetStringBuilder().Clear();
}
// Hot Reload should succeed here
GenerateConfigFile(
databaseType: DatabaseType.MSSQL,
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}");
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_SUCCESS_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
// Log that shows that hot-reload validated properly
string succeedConfigLog;
lock (_writerLock)
{
succeedConfigLog = _writer.ToString();
}
// After hot-reload, the engine may still be re-initializing metadata providers.
// Poll the REST endpoint to allow time for the engine to become fully ready.
using HttpResponseMessage restResult = await WaitForRestEndpointAsync("/rest/Book", HttpStatusCode.OK);
// Assert
Assert.IsTrue(failedConfigLog.Contains(HOT_RELOAD_FAILURE_MESSAGE));
Assert.IsTrue(succeedConfigLog.Contains(HOT_RELOAD_SUCCESS_MESSAGE));
Assert.AreEqual(HttpStatusCode.OK, restResult.StatusCode);
}
/// <summary>
/// Creates a hot reload scenario in which the configuration file has validation errors
/// which causes hot reload to fail, then we check that the program is still able to work
/// properly by validating that the DAB engine is still using the same configuration file
/// from before the hot reload.
///
/// Invalid change: Setting both REST, GraphQL, and MCP to disabled, which is not allowed.
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod]
public async Task HotReloadValidationFail()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
RuntimeConfig lkgRuntimeConfig = _configProvider.GetConfig();
Assert.IsNotNull(lkgRuntimeConfig);
// Capture properties to verify config hasn't changed
bool originalRestEnabled = lkgRuntimeConfig.Runtime.Rest.Enabled;
bool originalGraphQLEnabled = lkgRuntimeConfig.Runtime.GraphQL.Enabled;
bool originalMcpEnabled = lkgRuntimeConfig.Runtime.Mcp.Enabled;
// Act
// Generate a config that will fail validation by disabling REST, GraphQL, and MCP (which is not allowed)
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
restEnabled: "false",
gQLEnabled: "false",
mcpEnabled: "false");
// Wait for hot-reload to fail
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_FAILURE_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
RuntimeConfig newRuntimeConfig = _configProvider.GetConfig();
// Assert - Verify the configuration hasn't changed by comparing properties
Assert.IsNotNull(newRuntimeConfig, "RuntimeConfig should not be null after failed hot-reload.");
Assert.AreEqual(originalRestEnabled, newRuntimeConfig.Runtime.Rest.Enabled,
"REST enabled setting should remain unchanged after hot-reload failure.");
Assert.AreEqual(originalGraphQLEnabled, newRuntimeConfig.Runtime.GraphQL.Enabled,
"GraphQL enabled setting should remain unchanged after hot-reload failure.");
Assert.AreEqual(originalMcpEnabled, newRuntimeConfig.Runtime.Mcp.Enabled,
"MCP enabled setting should remain unchanged after hot-reload failure.");
}
/// <summary>
/// Creates a hot reload scenario in which the updated configuration file is invalid causing
/// hot reload to fail, then we check that the program is still able to work properly by
/// showing us that it is still using the same configuration file from before the hot reload.
///
/// Invalid change that was added is the word "invalid" in the config file where the only
/// valid options are "true" or "false".
/// </summary>
[TestCategory(MSSQL_ENVIRONMENT)]
[TestMethod]
public async Task HotReloadParsingFail()
{
// Arrange
_writer = new StringWriter();
Console.SetOut(_writer);
RuntimeConfig lkgRuntimeConfig = _configProvider.GetConfig();
Assert.IsNotNull(lkgRuntimeConfig);
// Capture properties to verify config hasn't changed
bool originalRestEnabled = lkgRuntimeConfig.Runtime.Rest.Enabled;
bool originalGraphQLEnabled = lkgRuntimeConfig.Runtime.GraphQL.Enabled;
// Act
GenerateConfigFile(
connectionString: $"{ConfigurationTests.GetConnectionStringFromEnvironmentConfig(TestCategory.MSSQL).Replace("\\", "\\\\")}",
restEnabled: "invalid",
gQLEnabled: "invalid");
// Wait for hot-reload to fail (parsing error should trigger failure message)
await WaitForConditionAsync(
() => WriterContains(HOT_RELOAD_FAILURE_MESSAGE),
TimeSpan.FromSeconds(HOT_RELOAD_TIMEOUT_SECONDS),
TimeSpan.FromMilliseconds(500));
RuntimeConfig newRuntimeConfig = _configProvider.GetConfig();
// Assert - Verify the configuration hasn't changed by comparing properties
Assert.IsNotNull(newRuntimeConfig, "RuntimeConfig should not be null after failed hot-reload.");
Assert.AreEqual(originalRestEnabled, newRuntimeConfig.Runtime.Rest.Enabled,
"REST enabled setting should remain unchanged after hot-reload failure.");
Assert.AreEqual(originalGraphQLEnabled, newRuntimeConfig.Runtime.GraphQL.Enabled,
"GraphQL enabled setting should remain unchanged after hot-reload failure.");
}
/// <summary>
/// Helper function that waits and checks multiple times if the condition is completed before the time interval,
/// if at any point to condition is completed then the program will continue with no delays, else it will fail.
/// </summary>
private static async Task WaitForConditionAsync(Func<bool> condition, TimeSpan timeout, TimeSpan pollingInterval)
{
System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
int attemptCount = 0;
while (stopwatch.Elapsed < timeout)
{
attemptCount++;
if (condition())
{
Console.WriteLine($"Hot-reload condition met after {stopwatch.Elapsed.TotalSeconds:F2} seconds ({attemptCount} attempts)");
return;
}
if (attemptCount % 10 == 0) // Log every 10 attempts (every 5 seconds)
{
Console.WriteLine($"Still waiting for hot-reload condition... Elapsed: {stopwatch.Elapsed.TotalSeconds:F2}s, Attempts: {attemptCount}");
}
await Task.Delay(pollingInterval);
}
Console.WriteLine($"Hot-reload timeout after {stopwatch.Elapsed.TotalSeconds:F2} seconds ({attemptCount} attempts)");
lock (_writerLock)
{
Console.WriteLine($"Console output captured:\n{_writer.ToString()}");
}
throw new TimeoutException("The condition was not met within the timeout period.");
}
/// <summary>
/// Polls a REST endpoint until it returns the expected status code.
/// After a successful hot-reload, the engine may still be re-initializing
/// metadata providers, so an immediate request can intermittently fail.
/// </summary>
private static async Task<HttpResponseMessage> WaitForRestEndpointAsync(
string requestUri,
HttpStatusCode expectedStatus,
int maxRetries = 5,
int delayMilliseconds = 1000)
{
HttpResponseMessage response = null;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
response = await _testClient.GetAsync(requestUri);
if (response.StatusCode == expectedStatus)
{
return response;
}
Console.WriteLine($"REST {requestUri} returned {response.StatusCode} on attempt {attempt}/{maxRetries}, retrying...");
// Dispose unsuccessful responses to avoid leaking connections/sockets.
if (attempt < maxRetries)
{
response.Dispose();
}
await Task.Delay(delayMilliseconds);
}
// Return the last response (undisposed) so the caller can inspect/assert on it.
return response;
}
/// <summary>
/// Polls a GraphQL endpoint until it returns a valid response containing
/// the expected property. After a successful hot-reload, the engine may
/// still be re-initializing metadata providers, so an immediate request