51 lines
1.7 KiB
C#
51 lines
1.7 KiB
C#
using System.Globalization;
|
|
using Flypaper.Core.Abstractions;
|
|
using Flypaper.Core.Models;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Flypaper.Core.Strategies;
|
|
|
|
public abstract class DripStrategy(
|
|
IOptionsMonitor<DripOptions> options,
|
|
IRandomSource random,
|
|
TimeProvider timeProvider) : ITarpitStrategy, IStrategyDetails
|
|
{
|
|
public abstract string Name { get; }
|
|
|
|
public abstract string MediaType { get; }
|
|
|
|
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
|
|
|
|
public string Describe()
|
|
{
|
|
var current = options.CurrentValue;
|
|
var head = current.HeadStartSize > 0 ? $" head {current.HeadStartSize}B" : "";
|
|
return string.Create(
|
|
CultureInfo.InvariantCulture,
|
|
$"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B{head}{Extra(current)}");
|
|
}
|
|
|
|
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
|
|
{
|
|
var current = options.CurrentValue;
|
|
using var fragments = Content(random, channel, current).GetEnumerator();
|
|
|
|
var head = DripSchedule.TakeHead(fragments, current.HeadStartSize);
|
|
if (head.Length > 0)
|
|
{
|
|
await channel.WriteAsync(head, ct);
|
|
}
|
|
|
|
foreach (var step in DripSchedule.Create(DripSchedule.Remaining(fragments), random, current))
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
await channel.WriteAsync(step.Chunk, ct);
|
|
await Task.Delay(step.Delay, timeProvider, ct);
|
|
}
|
|
}
|
|
|
|
protected virtual string Extra(DripOptions options) => "";
|
|
|
|
protected abstract IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options);
|
|
}
|