PlotDirector/PlotLine/Services/StoryIntelligenceRequestLimiter.cs

13 lines
703 B
C#

using Microsoft.Extensions.Options;
using PlotLine.Models;
namespace PlotLine.Services;
// Shared by the existing typed AI client, including web onboarding and native previews.
public sealed class StoryIntelligenceRequestLimiter(IOptions<StoryIntelligenceOptions> options)
{
private readonly SemaphoreSlim slots=new(Math.Max(1,options.Value.MaxGlobalConcurrentAiRequests));
public async Task<IDisposable> EnterAsync(CancellationToken cancellation)
{await slots.WaitAsync(cancellation);return new Lease(slots);}
private sealed class Lease(SemaphoreSlim semaphore):IDisposable{private int disposed;public void Dispose(){if(Interlocked.Exchange(ref disposed,1)==0)semaphore.Release();}}
}