PlotDirector/PlotLine/Services/DiscretionaryAi.cs

67 lines
5.0 KiB
C#

using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services;
public interface IDiscretionaryAi
{
Task<AiOperationQuote> Quote(int user,string operation);
Task<AiUsageReservation> Reserve(int user,string operation,Guid key,int scope,int expectedCredits);
Task<AiUsageReservation> Claim(Guid reservation);
Task Release(Guid reservation,Guid? lease=null);
}
public sealed class DiscretionaryAi(ISubscriptionService subscriptions,IDiscretionaryAiRepository repository):IDiscretionaryAi
{
// Calendar UTC months give annual subscribers monthly renewal and survive tier/billing changes.
public static (DateTime Start,DateTime End) MonthlyPeriod(DateTime anchor,DateTime now)
{
anchor=DateTime.SpecifyKind(anchor,DateTimeKind.Utc);now=DateTime.SpecifyKind(now,DateTimeKind.Utc);
if(anchor>now)return(anchor,anchor.AddMonths(1));
var months=(now.Year-anchor.Year)*12+now.Month-anchor.Month;
var start=anchor.AddMonths(months);if(start>now)start=anchor.AddMonths(--months);
return(start,anchor.AddMonths(months+1));
}
private async Task<(EffectiveEntitlement Entitlement,DateTime Start,DateTime End)> Context(int user)
{
var now=DateTime.UtcNow;var entitlement=await subscriptions.GetEffectiveEntitlementAsync(user,now);
var anchor=new DateTime(now.Year,now.Month,1,0,0,0,DateTimeKind.Utc);
var period=MonthlyPeriod(anchor,now);return(entitlement,period.Start,period.End);
}
public async Task<AiOperationQuote> Quote(int user,string operation)
{
var context=await Context(user);var tier=context.Entitlement.EffectiveLevel;
if(tier is null)return new(null,new(){PeriodStartUtc=context.Start,PeriodEndUtc=context.End},false,"This operation requires an AI-enabled subscription.");
var (policy,allowance)=await repository.Read(user,tier.SubscriptionLevelID,operation,context.Start,context.End);
var entitled=context.Entitlement.IsActive&&tier.Name!="DraftDesk"&&allowance.Enabled;
return new(policy,allowance,entitled,!entitled?"This operation requires an AI-enabled subscription.":policy is not {Enabled:true,RequiredEntitlement:"discretionary-ai"}?"This AI operation is currently disabled or unconfigured.":allowance.Remaining<(policy?.CreditCost??int.MaxValue)?$"Insufficient monthly AI credits. Your allowance renews {context.End:d MMM yyyy}.":"");
}
public async Task<AiUsageReservation> Reserve(int user,string operation,Guid key,int scope,int expectedCredits)
{
if(key==Guid.Empty)throw new InvalidOperationException("An AI operation request identifier is required.");
var context=await Context(user);var tier=context.Entitlement.EffectiveLevel;
if(!context.Entitlement.IsActive||tier is null||tier.Name=="DraftDesk")throw new InvalidOperationException("This operation requires an AI-enabled subscription.");
try{return await repository.Reserve(user,tier.SubscriptionLevelID,operation,key,context.Start,context.End,scope,expectedCredits);}catch(SqlException e)when(e.Number is >=51020 and <=51025){throw new InvalidOperationException(e.Message,e);}
}
public async Task<AiUsageReservation> Claim(Guid reservation)
{
var record=await repository.Get(reservation)??throw new InvalidOperationException("AI reservation is unavailable.");
var entitlement=await subscriptions.GetEffectiveEntitlementAsync(record.UserID);
if(!entitlement.IsActive||entitlement.EffectiveLevel?.Name is null or "DraftDesk"){await Release(reservation);throw new InvalidOperationException("This operation requires an AI-enabled subscription.");}
var quote=await Quote(record.UserID,record.OperationID);if(!quote.Entitled||quote.Operation is not {Enabled:true,RequiredEntitlement:"discretionary-ai"}){await Release(reservation);throw new InvalidOperationException(quote.Message);}
try{return await repository.Claim(reservation,Guid.NewGuid());}catch(SqlException e)when(e.Number is >=51020 and <=51025){throw new InvalidOperationException(e.Message,e);}
}
public Task Release(Guid reservation,Guid? lease=null)=>repository.Settle(reservation,lease,false);
}
// The existing provider client reads this execution scope. Every HTTP retry reserves its own durable budget slot.
public sealed class AiExecutionScope:IDisposable
{
private static readonly AsyncLocal<AiExecutionScope?> Slot=new();
public static AiExecutionScope? Current=>Slot.Value;
private readonly AiExecutionScope? previous;
public AiUsageReservation Reservation{get;}
public IDiscretionaryAiRepository Repository{get;}
public CancellationTokenSource Timeout{get;}
private AiExecutionScope(AiUsageReservation reservation,IDiscretionaryAiRepository repository,CancellationToken cancellationToken){Reservation=reservation;Repository=repository;previous=Slot.Value;Slot.Value=this;Timeout=CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);Timeout.CancelAfter(TimeSpan.FromSeconds(reservation.MaxDurationSeconds));}
public static AiExecutionScope Enter(AiUsageReservation reservation,IDiscretionaryAiRepository repository,CancellationToken cancellationToken=default)=>new(reservation,repository,cancellationToken);
public void Dispose(){Slot.Value=previous;Timeout.Dispose();}
}