- Remap Proxy Configurations in AiApiConfiguration; - Implement AiModelProxy Middleware for Proxifing Requests to Models; - ad DI Extensions Method for Handling Proxy Middleware Usage in AiApi; - Implement Proxy Middleware for Handling Proxifying Requests to Models for Test;
248 lines
7.6 KiB
C#
248 lines
7.6 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Net.Http;
|
|
using System.Threading;
|
|
using xAiApi.Extensions;
|
|
using xCommons.Providers;
|
|
using xExceptions.Models;
|
|
using xCommons.Extensions;
|
|
using xAiModels.Extensions;
|
|
using xAiApi.Configurations;
|
|
using xExceptions.Constants;
|
|
using System.Threading.Tasks;
|
|
using xCommons.Configurations;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Http;
|
|
using xIdentityService.Interfaces;
|
|
using Microsoft.Extensions.Logging;
|
|
using xIdentityService.Controllers;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
namespace xAiApi.Controllers
|
|
{
|
|
[AllowAnonymous]
|
|
public class ProxyController : XBaseIdentityApiController
|
|
{
|
|
private readonly IServiceProvider serviceProvider;
|
|
private readonly XAiApiConfiguration apiConfiguration;
|
|
private readonly IHttpClientFactory httpClientFactory;
|
|
|
|
public ProxyController(
|
|
ILogger<ProxyController> logger,
|
|
IServiceProvider serviceProvider,
|
|
XAppConfiguration appConfiguration,
|
|
IXIdentityProvider identityProvider,
|
|
XAiApiConfiguration apiConfiguration,
|
|
IHttpClientFactory httpClientFactory,
|
|
XValidationProvider validationProvider
|
|
) : base(logger, appConfiguration, identityProvider, validationProvider)
|
|
{
|
|
this.serviceProvider = serviceProvider;
|
|
this.apiConfiguration = apiConfiguration;
|
|
this.httpClientFactory = httpClientFactory;
|
|
}
|
|
|
|
[AcceptVerbs("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD")]
|
|
[Route("{modelName}/{path}")]
|
|
public async Task Proxy(
|
|
[FromRoute] string modelName,
|
|
[FromRoute] string path = null,
|
|
object body = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
var descriptor = apiConfiguration.GetModel(modelName);
|
|
if (!descriptor.IsValid())
|
|
{
|
|
//
|
|
var error = XException.NotFound.ToXError();
|
|
error.Message = $"{error.Message}: {modelName}' is not configured.";
|
|
await WriteJsonError(
|
|
StatusCodes.Status502BadGateway,
|
|
error.ToJSON()
|
|
);
|
|
|
|
//
|
|
return;
|
|
}
|
|
|
|
//
|
|
var targetUrl = BuildTargetUrl(
|
|
remainingPath: path,
|
|
modelName: modelName,
|
|
query: Request.QueryString
|
|
);
|
|
var method = new HttpMethod(Request.Method);
|
|
using var upstreamRequest = new HttpRequestMessage(method, targetUrl);
|
|
|
|
//
|
|
// Attach Body ...
|
|
if (!body.IsNull())
|
|
{
|
|
//
|
|
var json = body.ToJSON();
|
|
upstreamRequest.Content = new StringContent(
|
|
json,
|
|
Encoding.UTF8,
|
|
"application/json"
|
|
);
|
|
}
|
|
|
|
//
|
|
Request.CopyHeaders(
|
|
exceptions: null,
|
|
dest: upstreamRequest
|
|
);
|
|
|
|
//
|
|
var client = httpClientFactory.CreateClient("XAiModelProxy");
|
|
client.Timeout = Timeout.InfiniteTimeSpan;
|
|
|
|
HttpResponseMessage upstreamResponse;
|
|
try
|
|
{
|
|
//
|
|
upstreamResponse = await client.SendAsync(
|
|
upstreamRequest,
|
|
HttpCompletionOption.ResponseHeadersRead,
|
|
cancellationToken
|
|
);
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
{
|
|
return;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
//
|
|
Logger.LogError(ex, "Proxy failed for model {Model}", modelName);
|
|
var error = XException.ActionFailed.ToXError();
|
|
error.Message = $"{error.Message}: Upstream model is unavailable.";
|
|
await WriteJsonError(
|
|
StatusCodes.Status502BadGateway,
|
|
error.ToJSON()
|
|
);
|
|
return;
|
|
}
|
|
|
|
//
|
|
using (upstreamResponse)
|
|
{
|
|
//
|
|
if (!upstreamResponse.IsSuccessStatusCode)
|
|
{
|
|
//
|
|
var statusCode = (int)upstreamResponse.StatusCode;
|
|
|
|
//
|
|
XError error;
|
|
string errorBody;
|
|
try
|
|
{
|
|
//
|
|
errorBody = await upstreamResponse.Content
|
|
.ReadAsStringAsync();
|
|
|
|
//
|
|
error = errorBody.IsXError()
|
|
? errorBody.ToXError()
|
|
: XException.BadRequest.ToXError();
|
|
}
|
|
catch
|
|
{
|
|
error = XException.BadRequest.ToXError();
|
|
}
|
|
|
|
//
|
|
await WriteJsonError(
|
|
statusCode: statusCode,
|
|
message: error.ToJSON()
|
|
);
|
|
|
|
//
|
|
return;
|
|
}
|
|
|
|
//
|
|
upstreamResponse.CopyHeaders(
|
|
exceptions: null,
|
|
response: Response
|
|
);
|
|
Response.StatusCode = (int)upstreamResponse.StatusCode;
|
|
|
|
//
|
|
using var responseStream = await upstreamResponse.Content.ReadAsStreamAsync();
|
|
await responseStream.CopyToAsync(Response.Body, cancellationToken);
|
|
}
|
|
}
|
|
|
|
// ============================================================
|
|
// Helpers
|
|
// ============================================================
|
|
|
|
private async Task WriteJsonError(
|
|
int statusCode,
|
|
string message
|
|
)
|
|
{
|
|
//
|
|
Response.StatusCode = statusCode;
|
|
Response.ContentType = "application/json; charset=utf-8";
|
|
|
|
//
|
|
await Response.WriteAsync(message);
|
|
}
|
|
|
|
private Uri BuildTargetUrl(
|
|
string modelName,
|
|
string remainingPath = null,
|
|
QueryString query = default
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
var isValid =
|
|
!modelName.IsNullOrEmpty() &&
|
|
!apiConfiguration.IsNull() &&
|
|
!apiConfiguration.ProxyConfiguration.IsNull() &&
|
|
!apiConfiguration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty();
|
|
if (!isValid)
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var baseUrls = serviceProvider.GetApplicationUrls().ToArray();
|
|
if (!baseUrls.HasChild())
|
|
{
|
|
XException.InvalidData.Throw();
|
|
}
|
|
|
|
//
|
|
var baseUrl = baseUrls[0];
|
|
|
|
//
|
|
var path = $"{baseUrl}/{apiConfiguration.ProxyConfiguration.RoutePrefix.TrimStart('/')}/{modelName}";
|
|
if (!remainingPath.IsNullOrEmpty())
|
|
{
|
|
path += "/" + remainingPath.TrimStart('/');
|
|
}
|
|
|
|
//
|
|
var builder = new UriBuilder(path)
|
|
{
|
|
Query = query.HasValue
|
|
? query.Value.TrimStart('?')
|
|
: string.Empty
|
|
};
|
|
|
|
//
|
|
var result = builder.Uri;
|
|
|
|
//
|
|
return result;
|
|
}
|
|
}
|
|
} |