using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
/// Bridges the host's authenticated source binding to the independent ingress contract.
public sealed class MdpIngestContractBinder(MdpIngestDatasetRegistry datasets) : ITransient
{
private static readonly PurchaseOrderSchemaRegistry BuiltIn = new();
public async Task PrepareAsync(
long tenantId, long factoryId, long sourceId, string datasetKey, ReadOnlyMemory payload, IngestLimits limits, long? configurationFactoryId = null,
IngestPayloadFormat format = IngestPayloadFormat.Json, string? schemaVersion = null)
{
var binding = await datasets.ResolveActiveBindingAsync(tenantId, configurationFactoryId ?? factoryId, sourceId, datasetKey)
?? throw new IngestContractException(IngestContractError.DatasetUnavailable);
if (schemaVersion is not null && !string.Equals(schemaVersion, binding.SourceSchemaVersion, StringComparison.Ordinal))
throw new IngestContractException(IngestContractError.UnknownSchema);
var identity = new IngestDatasetIdentity(binding.TenantId, factoryId, binding.SourceId,
binding.DatasetId, binding.SourceCode, binding.DatasetKey);
var contract = await ReadContractAsync(binding);
return new IngestBatchPreparer(contract.Registry).Prepare(identity, binding.SourceSchemaVersion, payload.Span, limits, format: format);
}
internal async Task<(ISchemaRegistry Registry, IngestContract Contract)> ReadContractAsync(MdpIngestActiveBinding binding)
{
ISchemaRegistry registry = BuiltIn;
if (BuiltIn.Find(binding.DatasetKey, binding.SourceSchemaVersion) == null)
{
var json = await datasets.ReadPublishedMapping(binding)
?? throw new IngestContractException(IngestContractError.UnknownSchema);
registry = new PurchaseVersionConfiguration(binding.DatasetKey, binding.SourceSchemaVersion, json);
}
var contract = registry.Find(binding.DatasetKey, binding.SourceSchemaVersion)
?? throw new IngestContractException(IngestContractError.UnknownSchema);
return (registry, contract);
}
}