-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathRestController.cs
More file actions
386 lines (343 loc) · 16.8 KB
/
RestController.cs
File metadata and controls
386 lines (343 loc) · 16.8 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Mime;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Models;
using Azure.DataApiBuilder.Core.Services;
using Azure.DataApiBuilder.Core.Telemetry;
using Azure.DataApiBuilder.Service.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.Extensions.Logging;
namespace Azure.DataApiBuilder.Service.Controllers
{
/// <summary>
/// Controller to serve REST Api requests for the route /entityName.
/// This controller should adhere to the
/// <see href="https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md">Microsoft REST API Guidelines</see>.
/// </summary>
[ApiController]
[Route("{*route}")]
public class RestController : ControllerBase
{
/// <summary>
/// Service providing REST Api executions.
/// </summary>
private readonly RestService _restService;
/// <summary>
/// OpenAPI description document creation service.
/// </summary>
private readonly IOpenApiDocumentor _openApiDocumentor;
/// <summary>
/// String representing the value associated with "code" for a server error
/// </summary>
public const string SERVER_ERROR = "While processing your request the server ran into an unexpected error.";
/// <summary>
/// Every GraphQL request gets redirected to this route
/// when Banana Cake Pop UI is disabled.
/// e.g. https://servername:port/favicon.ico
/// </summary>
public const string REDIRECTED_ROUTE = "favicon.ico";
private readonly ILogger<RestController> _logger;
private readonly RuntimeConfigProvider _runtimeConfigProvider;
/// <summary>
/// Constructor.
/// </summary>
public RestController(RuntimeConfigProvider runtimeConfigProvider, RestService restService, IOpenApiDocumentor openApiDocumentor, ILogger<RestController> logger)
{
_runtimeConfigProvider = runtimeConfigProvider;
_restService = restService;
_openApiDocumentor = openApiDocumentor;
_logger = logger;
}
/// <summary>
/// Helper function returns a JsonResult with provided arguments in a
/// form that complies with vNext Api guidelines.
/// </summary>
/// <param name="code">One of a server-defined set of error codes.</param>
/// <param name="message">string provides a message associated with this error.</param>
/// <param name="status">int provides the http response status code associated with this error</param>
/// <returns></returns>
public static JsonResult ErrorResponse(string code, string message, HttpStatusCode status)
{
return new JsonResult(new
{
error = new
{
code = code,
message = message,
status = (int)status
}
});
}
/// <summary>
/// Find action serving the HttpGet verb.
/// </summary>
/// <param name="route">The entire route which gets
/// its content from the route attribute {*route} defined
/// for the class, asterisk(*) here is a wild-card/catch all.
/// Expected URL template is of the following form:
/// MsSql/PgSql: URL template: <path>/<entityName>/<primary_key_column_name>/<primary_key_value>
/// URL MUST NOT contain a queryString
/// URL example: api/Books </param>
[HttpGet]
[Produces("application/json")]
public async Task<IActionResult> Find(
string route)
{
return await HandleOperation(
route,
EntityActionOperation.Read);
}
/// <summary>
/// Insert action serving the HttpPost verb.
/// </summary>
/// <param name="route">Path and entity.</param>
/// Expected URL template is of the following form:
/// CosmosDb/MsSql/PgSql: URL template: <path>/<entityName>
/// URL MUST NOT contain a queryString
/// URL example: api/SalesOrders </param>
[HttpPost]
[Produces("application/json")]
public async Task<IActionResult> Insert(
string route)
{
return await HandleOperation(
route,
EntityActionOperation.Insert);
}
/// <summary>
/// Delete action serving the HttpDelete verb.
/// </summary>
/// <param name="route">The entire route which gets
/// its content from the route attribute {*route} defined
/// for the class, asterisk(*) here is a wild-card/catch all.
/// Expected URL template is of the following form:
/// MsSql/PgSql: URL template: <path>/<entityName>/<primary_key_column_name>/<primary_key_value>
/// URL MUST NOT contain a queryString
/// URL example: api/Books </param>
[HttpDelete]
[Produces("application/json")]
public async Task<IActionResult> Delete(
string route)
{
return await HandleOperation(
route,
EntityActionOperation.Delete);
}
/// <summary>
/// Replacement Update/Insert action serving the HttpPut verb
/// </summary>
/// <param name="route">The entire route which gets
/// its content from the route attribute {*route} defined
/// for the class, asterisk(*) here is a wild-card/catch all.
/// Expected URL template is of the following form:
/// MsSql/PgSql: URL template: <path>/<entityName>/<primary_key_column_name>/<primary_key_value>
/// URL MUST NOT contain a queryString
/// URL example: api/Books </param>
[HttpPut]
[Produces("application/json")]
public async Task<IActionResult> Upsert(
string route)
{
return await HandleOperation(
route,
EntityActionOperation.Upsert);
}
/// <summary>
/// Incremental Update/Insert action serving the HttpPatch verb
/// </summary>
/// <param name="route">The entire route which gets
/// its content from the route attribute {*route} defined
/// for the class, asterisk(*) here is a wild-card/catch all.
/// Expected URL template is of the following form:
/// MsSql/PgSql: URL template: <path>/<entityName>/<primary_key_column_name>/<primary_key_value>
/// URL MUST NOT contain a queryString
/// URL example: api/Books </param>
[HttpPatch]
[Produces("application/json")]
public async Task<IActionResult> UpsertIncremental(
string route)
{
return await HandleOperation(
route,
EntityActionOperation.UpsertIncremental);
}
/// <summary>
/// Handle the given operation.
/// </summary>
/// <param name="route">The entire route.</param>
/// <param name="operationType">The kind of operation to handle.</param>
private async Task<IActionResult> HandleOperation(
string route,
EntityActionOperation operationType)
{
if (route.Equals(REDIRECTED_ROUTE))
{
return NotFound();
}
Stopwatch stopwatch = Stopwatch.StartNew();
// This activity tracks the entire REST request.
using Activity? activity = TelemetryTracesHelper.DABActivitySource.StartActivity($"{HttpContext.Request.Method} {(route.Split('/').Length > 1 ? route.Split('/')[1] : string.Empty)}");
try
{
TelemetryMetricsHelper.IncrementActiveRequests(ApiType.REST);
if (operationType is EntityActionOperation.Upsert or EntityActionOperation.UpsertIncremental)
{
operationType = DeterminePatchPutSemantics(operationType);
}
if (activity is not null)
{
activity.TrackMainControllerActivityStarted(
Enum.Parse<HttpMethod>(HttpContext.Request.Method, ignoreCase: true),
HttpContext.Request.Headers["User-Agent"].ToString(),
operationType.ToString(),
route,
HttpContext.Request.QueryString.ToString(),
HttpContext.Request.Headers["X-MS-API-ROLE"].FirstOrDefault() ?? HttpContext.User.FindFirst("role")?.Value,
ApiType.REST);
}
// Validate the PathBase matches the configured REST path.
string routeAfterPathBase = _restService.GetRouteAfterPathBase(route);
// Explicitly handle OpenAPI description document retrieval requests.
// Supports /openapi (superset of all roles) and /openapi/{role} (role-specific)
if (string.Equals(routeAfterPathBase, OpenApiDocumentor.OPENAPI_ROUTE, StringComparison.OrdinalIgnoreCase))
{
if (_openApiDocumentor.TryGetDocument(out string? document))
{
return Content(document, MediaTypeNames.Application.Json);
}
return NotFound();
}
// Handle /openapi/{role} route for role-specific OpenAPI documents
// Only allow in Development mode for security reasons
if (routeAfterPathBase.StartsWith(OpenApiDocumentor.OPENAPI_ROUTE + "/", StringComparison.OrdinalIgnoreCase))
{
RuntimeConfig config = _runtimeConfigProvider.GetConfig();
if (config.Runtime?.Host?.Mode != HostMode.Development)
{
return NotFound();
}
string role = Uri.UnescapeDataString(
routeAfterPathBase.Substring(OpenApiDocumentor.OPENAPI_ROUTE.Length + 1));
// Validate role doesn't contain path separators (reject /openapi/foo/bar)
if (string.IsNullOrEmpty(role) || role.Contains('/'))
{
return Problem(
detail: $"Invalid role name '{role}'. Role names must not be empty or contain path separators.",
statusCode: StatusCodes.Status404NotFound,
title: "Not Found");
}
if (_openApiDocumentor.TryGetDocumentForRole(role, out string? roleDocument))
{
return Content(roleDocument, MediaTypeNames.Application.Json);
}
return Problem(
detail: $"Role '{role}' is not present in the configuration.",
statusCode: StatusCodes.Status404NotFound,
title: "Not Found");
}
(string entityName, string primaryKeyRoute) = _restService.GetEntityNameAndPrimaryKeyRouteFromRoute(routeAfterPathBase);
// This activity tracks the query execution. This will create a new activity nested under the REST request activity.
using Activity? queryActivity = TelemetryTracesHelper.DABActivitySource.StartActivity($"QUERY {entityName}");
IActionResult? result = await _restService.ExecuteAsync(entityName, operationType, primaryKeyRoute);
RuntimeConfig runtimeConfig = _runtimeConfigProvider.GetConfig();
string dataSourceName = runtimeConfig.GetDataSourceNameFromEntityName(entityName);
DatabaseType databaseType = runtimeConfig.GetDataSourceFromDataSourceName(dataSourceName).DatabaseType;
if (queryActivity is not null)
{
queryActivity.TrackQueryActivityStarted(
databaseType,
dataSourceName);
}
if (result is null)
{
throw new DataApiBuilderException(
message: $"Not Found",
statusCode: HttpStatusCode.NotFound,
subStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound);
}
int statusCode = (result as ObjectResult)?.StatusCode ?? (result as StatusCodeResult)?.StatusCode ?? (result as JsonResult)?.StatusCode ?? 200;
if (activity is not null && activity.IsAllDataRequested)
{
HttpStatusCode httpStatusCode = Enum.Parse<HttpStatusCode>(statusCode.ToString(), ignoreCase: true);
activity.TrackMainControllerActivityFinished(httpStatusCode);
}
return result;
}
catch (DataApiBuilderException ex)
{
_logger.LogError(
exception: ex,
message: "{correlationId} Error handling REST request.",
HttpContextExtensions.GetLoggerCorrelationId(HttpContext));
Response.StatusCode = (int)ex.StatusCode;
activity?.TrackMainControllerActivityFinishedWithException(ex, ex.StatusCode);
HttpMethod method = Enum.Parse<HttpMethod>(HttpContext.Request.Method, ignoreCase: true);
TelemetryMetricsHelper.TrackError(method, ex.StatusCode, route, ApiType.REST, ex);
return ErrorResponse(ex.SubStatusCode.ToString(), ex.Message, ex.StatusCode);
}
catch (Exception ex)
{
_logger.LogError(
exception: ex,
message: "{correlationId} Internal server error occured during REST request processing.",
HttpContextExtensions.GetLoggerCorrelationId(HttpContext));
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
HttpMethod method = Enum.Parse<HttpMethod>(HttpContext.Request.Method, ignoreCase: true);
activity?.TrackMainControllerActivityFinishedWithException(ex, HttpStatusCode.InternalServerError);
TelemetryMetricsHelper.TrackError(method, HttpStatusCode.InternalServerError, route, ApiType.REST, ex);
return ErrorResponse(
DataApiBuilderException.SubStatusCodes.UnexpectedError.ToString(),
SERVER_ERROR,
HttpStatusCode.InternalServerError);
}
finally
{
stopwatch.Stop();
HttpMethod method = Enum.Parse<HttpMethod>(HttpContext.Request.Method, ignoreCase: true);
HttpStatusCode httpStatusCode = Enum.Parse<HttpStatusCode>(Response.StatusCode.ToString(), ignoreCase: true);
TelemetryMetricsHelper.TrackRequest(method, httpStatusCode, route, ApiType.REST);
TelemetryMetricsHelper.TrackRequestDuration(method, httpStatusCode, route, ApiType.REST, stopwatch.Elapsed);
TelemetryMetricsHelper.DecrementActiveRequests(ApiType.REST);
}
}
/// <summary>
/// Helper function determines the correct operation based on the client
/// provided headers. Client can indicate if operation should follow
/// update or upsert semantics.
/// </summary>
/// <param name="operation">opertion to be used.</param>
/// <returns>correct opertion based on headers.</returns>
private EntityActionOperation DeterminePatchPutSemantics(EntityActionOperation operation)
{
if (HttpContext.Request.Headers.ContainsKey("If-Match"))
{
if (!string.Equals(HttpContext.Request.Headers["If-Match"], "*"))
{
throw new DataApiBuilderException(
message: "Etags not supported, use '*'",
statusCode: HttpStatusCode.BadRequest,
subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest);
}
switch (operation)
{
case EntityActionOperation.Upsert:
operation = EntityActionOperation.Update;
break;
case EntityActionOperation.UpsertIncremental:
operation = EntityActionOperation.UpdateIncremental;
break;
}
}
return operation;
}
}
}