2024-01-22 09:27:07 +00:00
using Logging ;
using Utils ;
namespace TestNetRewarder
{
public class TimeSegmenter
{
private readonly ILog log ;
private readonly TimeSpan segmentSize ;
private DateTime start ;
public TimeSegmenter ( ILog log , Configuration configuration )
{
this . log = log ;
if ( configuration . Interval < 0 ) configuration . Interval = 15 ;
2024-01-22 10:47:28 +00:00
if ( configuration . CheckHistoryTimestamp = = 0 ) throw new Exception ( "'check-history' unix timestamp is required. Set it to the start/launch moment of the testnet." ) ;
2024-01-22 09:27:07 +00:00
segmentSize = TimeSpan . FromSeconds ( configuration . Interval ) ;
2024-01-22 10:47:28 +00:00
start = DateTimeOffset . FromUnixTimeSeconds ( configuration . CheckHistoryTimestamp ) . UtcDateTime ;
2024-01-22 09:27:07 +00:00
log . Log ( "Starting time segments at " + start ) ;
log . Log ( "Segment size: " + Time . FormatDuration ( segmentSize ) ) ;
}
public async Task WaitForNextSegment ( Func < TimeRange , Task > onSegment )
{
var now = DateTime . UtcNow ;
var end = start + segmentSize ;
2024-01-22 10:47:28 +00:00
var waited = false ;
2024-01-22 09:27:07 +00:00
if ( end > now )
{
// Wait for the entire time segment to be in the past.
var delay = ( end - now ) . Add ( TimeSpan . FromSeconds ( 3 ) ) ;
2024-01-22 10:47:28 +00:00
waited = true ;
2024-01-22 09:27:07 +00:00
await Task . Delay ( delay , Program . CancellationToken ) ;
}
if ( Program . CancellationToken . IsCancellationRequested ) return ;
2024-01-22 10:47:28 +00:00
var postfix = "(Catching up...)" ;
if ( waited ) postfix = "(Real-time)" ;
log . Log ( $"Time segment [{start} to {end}] {postfix}" ) ;
2024-01-22 09:27:07 +00:00
var range = new TimeRange ( start , end ) ;
start = end ;
await onSegment ( range ) ;
}
}
}