- Add Proxy Configuration in AppSettings;
- 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;
This commit is contained in:
@@ -18,16 +18,22 @@ namespace xAiApi.Configurations
|
||||
/// <summary>
|
||||
/// OCR Configuration ...
|
||||
/// </summary>
|
||||
public XAiOCRDescriptor OCR { get; set; } = new ();
|
||||
public XAiOCRDescriptor OCR { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Transcript Configuration ...
|
||||
/// </summary>
|
||||
public XAiTransciptDescriptor Transcript { get; set; } = new ();
|
||||
public XAiTransciptDescriptor Transcript { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// PDF To Image Configuration ...
|
||||
/// </summary>
|
||||
public XPDFToImageDescriptor PDFToImageDescriptor {get; set;} = new ();
|
||||
public XPDFToImageDescriptor PDFToImageDescriptor { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Proxy Configuration ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
using System;
|
||||
using xAiApi.Constants;
|
||||
using xAiApi.Extensions;
|
||||
using xAiApi.Middlewares;
|
||||
using xCommons.Extensions;
|
||||
using xAiApi.Configurations;
|
||||
using xExceptions.Constants;
|
||||
using xAiApi.Providers.Extractors;
|
||||
using xAiApi.Interfaces.Extractors;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
@@ -97,6 +99,18 @@ namespace xAiApi.DI
|
||||
source.AddSingleton<IXFileContentExtractor, XFileContentExtractor>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use Model Proxy Provider ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static IApplicationBuilder UseXAiModelProxy(
|
||||
this IApplicationBuilder source
|
||||
)
|
||||
{
|
||||
return source.UseMiddleware<XAiModelProxyMiddleware>();
|
||||
}
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using xAiApi.Extensions;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xAiModels.Extensions;
|
||||
using xAiApi.Configurations;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using xIdentityService.Constants;
|
||||
using xIdentityService.Interfaces;
|
||||
using xIdentityService.Extensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityModels.Models;
|
||||
using xIdentityModels.Constants;
|
||||
|
||||
namespace xAiApi.Middlewares
|
||||
{
|
||||
public class XAiModelProxyMiddleware
|
||||
{
|
||||
private readonly RequestDelegate next;
|
||||
private readonly XAiApiConfiguration configuration;
|
||||
private readonly IHttpClientFactory httpClientFactory;
|
||||
private readonly ILogger<XAiModelProxyMiddleware> logger;
|
||||
|
||||
public XAiModelProxyMiddleware(
|
||||
RequestDelegate next,
|
||||
XAiApiConfiguration configuration,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ILogger<XAiModelProxyMiddleware> logger
|
||||
)
|
||||
{
|
||||
//
|
||||
this.next = next;
|
||||
this.logger = logger;
|
||||
this.configuration = configuration;
|
||||
this.httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle Routing ...
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public async Task InvokeAsync(
|
||||
HttpContext context,
|
||||
IXIdentityProvider identityProvider
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
var isValid =
|
||||
!configuration.IsNull() &&
|
||||
!configuration.ProxyConfiguration.IsNull() &&
|
||||
configuration.ProxyConfiguration.Enabled &&
|
||||
!configuration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty() &&
|
||||
context.Request.Path.StartsWithSegments(configuration.ProxyConfiguration.RoutePrefix, out var remaining);
|
||||
if (!isValid)
|
||||
{
|
||||
//
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Validating Segment ...
|
||||
var rawSegments = remaining.Value?
|
||||
.Trim('/')
|
||||
.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (!rawSegments.HasChild())
|
||||
{
|
||||
//
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Extract Model Name and Retrieve Model Descriptor and do Validation ...
|
||||
var modelName = Uri.UnescapeDataString(rawSegments[0]);
|
||||
var descriptor = configuration.GetModel(modelName);
|
||||
if (!descriptor.IsValid())
|
||||
{
|
||||
//
|
||||
// Handle Error ...
|
||||
await context.Response.WriteJsonAsync(
|
||||
status: HttpStatusCode.NotFound,
|
||||
data: new
|
||||
{
|
||||
error = $"Model '{modelName}' is not configured."
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
var errorMessages = new string[] { };
|
||||
var apiKey = context.ExtractApiKey();
|
||||
var clientIP = context.Request.ExtractClientIP();
|
||||
var tokenModel = await context.RetrieveTokensAsXTokenResponse();
|
||||
var isAuthenticated =
|
||||
//
|
||||
(!apiKey.IsNullOrEmpty()) |
|
||||
//
|
||||
(!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
|
||||
;
|
||||
if (isAuthenticated)
|
||||
{
|
||||
//
|
||||
// Handle Authentication ...
|
||||
if (!apiKey.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
// Try to Validate Api Key ...
|
||||
var validationResult = await identityProvider.ValidateApiKey(
|
||||
request: new XApiKeyValidationRequest
|
||||
{
|
||||
ApiKey = apiKey,
|
||||
ClientIP = clientIP,
|
||||
RequiredScope = XApiKeyScope.Read.GetStringValue()
|
||||
}
|
||||
);
|
||||
isAuthenticated = !validationResult.Errors.HasChild();
|
||||
if (!isAuthenticated)
|
||||
{
|
||||
errorMessages = [.. errorMessages, .. validationResult.Errors];
|
||||
}
|
||||
}
|
||||
else if (!tokenModel.IsNullOrDefault())
|
||||
{
|
||||
//
|
||||
// Try To Validate Token ...
|
||||
var validationResult = await identityProvider.Validate(tokenModel);
|
||||
isAuthenticated = !validationResult.IsError;
|
||||
if (!isAuthenticated)
|
||||
{
|
||||
errorMessages = [..errorMessages, validationResult.Error];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
isAuthenticated = false;
|
||||
}
|
||||
}
|
||||
if (!isAuthenticated)
|
||||
{
|
||||
//
|
||||
var error = XException.NotAuthorized.ToXError();
|
||||
error.Message = $"{error.Message}: {errorMessages.ToListString(',')}";
|
||||
await context.Response.WriteJsonAsync(
|
||||
status: HttpStatusCode.Unauthorized,
|
||||
data: error
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
var suffixPath = Uri.UnescapeDataString(string.Join('/', rawSegments.Skip(1)));
|
||||
var targetUri = BuildTargetUri(
|
||||
descriptor.Url,
|
||||
suffixPath,
|
||||
context.Request.QueryString
|
||||
);
|
||||
|
||||
//
|
||||
// Collect Headers which need to Except ...
|
||||
var exceptionHeaders = new string[]
|
||||
{
|
||||
XAuthorization.Header,
|
||||
XAuthorization.ExpiresAt,
|
||||
XAuthorization.XPoweredBy,
|
||||
XAuthorization.AccessToken,
|
||||
XAuthorization.RefreshToken,
|
||||
XHeader.ApiKey.GetStringValue(),
|
||||
XAuthorization.AccessTokenExpired,
|
||||
XHeader.ConnectionId.GetStringValue(),
|
||||
XHeader.ChecksumDigest.GetStringValue(),
|
||||
};
|
||||
|
||||
//
|
||||
using var upstreamRequest = new HttpRequestMessage(
|
||||
new HttpMethod(context.Request.Method),
|
||||
targetUri
|
||||
);
|
||||
|
||||
//
|
||||
context.CopyRequestHeaders(
|
||||
dest: upstreamRequest,
|
||||
exceptions: exceptionHeaders
|
||||
);
|
||||
|
||||
//
|
||||
if (
|
||||
context.Request.ContentLength > 0 ||
|
||||
context.Request.Headers.ContainsKey(HeaderNames.TransferEncoding)
|
||||
)
|
||||
{
|
||||
//
|
||||
context.Request.EnableBuffering();
|
||||
using var reader = new StreamReader(
|
||||
context.Request.Body,
|
||||
Encoding.UTF8,
|
||||
detectEncodingFromByteOrderMarks: true,
|
||||
bufferSize: 1024,
|
||||
leaveOpen: true
|
||||
);
|
||||
var bodyText = await reader.ReadToEndAsync();
|
||||
var actualLength = Encoding.UTF8.GetByteCount(bodyText);
|
||||
var declaredLength = context.Request.ContentLength;
|
||||
var contentType = context.Request.ContentType ?? "application/octet-stream";
|
||||
var mediaType = contentType.Split(';')[0].Trim();
|
||||
upstreamRequest.Content = new StringContent(
|
||||
bodyText,
|
||||
Encoding.UTF8,
|
||||
mediaType
|
||||
);
|
||||
context.Request.Body.Position = 0;
|
||||
context.CopyRequestHeaders(
|
||||
dest: upstreamRequest.Content,
|
||||
exceptions: exceptionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// Handle Api Key of LLM ...
|
||||
descriptor.AddModelDescriptorApiKey(
|
||||
request: upstreamRequest
|
||||
);
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
var client = httpClientFactory.CreateClient("XAiModelProxy");
|
||||
client.Timeout = Timeout.InfiniteTimeSpan;
|
||||
|
||||
//
|
||||
using var upstreamResponse = await client.SendAsync(
|
||||
upstreamRequest,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
context.RequestAborted
|
||||
);
|
||||
|
||||
//
|
||||
context.Response.StatusCode = (int)upstreamResponse.StatusCode;
|
||||
|
||||
//
|
||||
upstreamResponse.CopyHeaders(
|
||||
response: context.Response,
|
||||
exceptions: exceptionHeaders
|
||||
);
|
||||
|
||||
//
|
||||
await using var responseStream = await upstreamResponse.Content
|
||||
.ReadAsStreamAsync();
|
||||
await responseStream.CopyToAsync(
|
||||
context.Response.Body,
|
||||
context.RequestAborted
|
||||
);
|
||||
}
|
||||
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
|
||||
{ }
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
logger.LogError(ex, "Proxy failed for model {ModelName}", modelName);
|
||||
if (!context.Response.HasStarted)
|
||||
{
|
||||
//
|
||||
// Handle Error ...
|
||||
var error = XException.ActionFailed.ToXError();
|
||||
error.Message = $"{error.Message}: {ex.Message}";
|
||||
await context.Response.WriteJsonAsync(
|
||||
status: HttpStatusCode.BadGateway,
|
||||
data: error
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
private static Uri BuildTargetUri(
|
||||
string baseUrl,
|
||||
string suffixPath,
|
||||
QueryString query
|
||||
)
|
||||
{
|
||||
//
|
||||
var baseUri = new Uri(baseUrl, UriKind.Absolute);
|
||||
var builder = new UriBuilder(baseUri);
|
||||
var basePath = builder.Path.TrimEnd('/');
|
||||
|
||||
//
|
||||
builder.Path = suffixPath.IsNullOrEmpty()
|
||||
? basePath
|
||||
: $"{basePath}/{suffixPath.TrimStart('/')}";
|
||||
|
||||
//
|
||||
builder.Query = query.HasValue
|
||||
? query.Value.TrimStart('?')
|
||||
: string.Empty;
|
||||
|
||||
//
|
||||
return builder.Uri;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace xAiApi.Models
|
||||
{
|
||||
public class XAiModelProxyConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
/// Enable Proxy or not ...
|
||||
/// </summary>
|
||||
/// <value></value>
|
||||
public bool Enabled { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Proxy Prefix ...
|
||||
/// </summary>
|
||||
/// <value></value>
|
||||
public string RoutePrefix { get; set; } = "ai-model";
|
||||
}
|
||||
}
|
||||
@@ -219,6 +219,10 @@ namespace xAiApi
|
||||
// Using Cors ...
|
||||
app.UseXCors();
|
||||
|
||||
//
|
||||
// Enable Model Proxy ...
|
||||
app.UseXAiModelProxy();
|
||||
|
||||
//
|
||||
// Using Routing ...
|
||||
app.UseRouting();
|
||||
|
||||
@@ -101,6 +101,10 @@
|
||||
"MaxImageWidth": 2000,
|
||||
"MinTextLengthThreshold": 50,
|
||||
"MaxPagesForImageFallback": 0
|
||||
},
|
||||
"ProxyConfiguration": {
|
||||
"Enabled": true,
|
||||
"RoutePrefix": "/ai-model"
|
||||
}
|
||||
},
|
||||
"Logging": {
|
||||
|
||||
Reference in New Issue
Block a user