Add data management, randomized HTML drip and public README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-14 16:08:45 +01:00
1 parent 3671019e60
commit f5d8ca7484
46 files changed
+1601 -172

No files matched your search

@@ -1,6 +1,7 @@
using Flypaper.Core.Abstractions;
using Flypaper.Storage.Dashboard;
using Flypaper.Storage.Events;
using Flypaper.Storage.Maintenance;
using Flypaper.Storage.Settings;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
@@ -19,6 +20,7 @@ public static class FlypaperStorageExtensions
builder.Configuration.Add(source);
builder.Services.AddSingleton(source);
builder.Services.AddSingleton<RuntimeSettingsStore>();
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
builder.Services.AddFlypaperStorage(connectionString);
return builder;
@@ -32,6 +34,8 @@ public static class FlypaperStorageExtensions
services.AddHostedService<TrapEventWriter>();
services.AddHostedService<OriginBackfill>();
services.AddSingleton<DashboardQueries>();
services.AddSingleton<TrapDataMaintenance>();
services.AddHostedService<RetentionCleanup>();
return services;
}
@@ -0,0 +1,62 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Flypaper.Storage.Maintenance;
internal sealed partial class RetentionCleanup(
TrapDataMaintenance maintenance,
IOptionsMonitor<RetentionOptions> options,
TimeProvider timeProvider,
ILogger<RetentionCleanup> logger) : BackgroundService
{
private const int VacuumThreshold = 5_000;
private static readonly TimeSpan Interval = TimeSpan.FromDays(1);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (true)
{
try
{
await CleanupAsync(stoppingToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogCleanupFailed(ex);
}
await Task.Delay(Interval, timeProvider, stoppingToken);
}
}
internal async Task<int> CleanupAsync(CancellationToken ct)
{
var days = options.CurrentValue.Days;
if (days <= 0)
{
return 0;
}
var cutoff = timeProvider.GetUtcNow().UtcDateTime.AddDays(-days);
var deleted = await maintenance.DeleteOlderThanAsync(cutoff, ct);
if (deleted == 0)
{
return 0;
}
LogDeleted(deleted, days);
if (deleted >= VacuumThreshold)
{
await maintenance.VacuumAsync(ct);
}
return deleted;
}
[LoggerMessage(Level = LogLevel.Information, Message = "Deleted {Count} trap events older than {Days} days")]
private partial void LogDeleted(int count, int days);
[LoggerMessage(Level = LogLevel.Warning, Message = "Retention cleanup failed")]
private partial void LogCleanupFailed(Exception exception);
}
@@ -0,0 +1,8 @@
namespace Flypaper.Storage.Maintenance;
public sealed class RetentionOptions
{
public const string SectionName = "Flypaper:Retention";
public int Days { get; set; } = 90;
}
@@ -0,0 +1,64 @@
using System.Net;
using Flypaper.Core.Networking;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Maintenance;
public sealed class TrapDataMaintenance(IDbContextFactory<FlypaperDbContext> dbContextFactory)
{
private const int DeleteChunkSize = 500;
public async Task<TrapDataStats> GetStatsAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var count = await db.TrapEvents.CountAsync(ct);
var oldest = count == 0 ? (DateTime?)null : await db.TrapEvents.MinAsync(e => e.StartedAt, ct);
return new TrapDataStats(count, oldest, DatabaseSize(db));
}
public async Task<int> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.TrapEvents.Where(e => e.StartedAt < cutoffUtc).ExecuteDeleteAsync(ct);
}
public async Task<int> DeletePrivateAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var privateIps = (await db.TrapEvents.Select(e => e.RemoteIp).Distinct().ToListAsync(ct))
.Where(ip => IPAddress.TryParse(ip, out var address) && PrivateNetworks.Contains(address))
.ToList();
var deleted = 0;
foreach (var chunk in privateIps.Chunk(DeleteChunkSize))
{
deleted += await db.TrapEvents.Where(e => chunk.Contains(e.RemoteIp)).ExecuteDeleteAsync(ct);
}
return deleted;
}
public async Task<int> DeleteAllAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.TrapEvents.ExecuteDeleteAsync(ct);
}
public async Task VacuumAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
await db.Database.ExecuteSqlRawAsync("VACUUM", ct);
}
private static long? DatabaseSize(FlypaperDbContext db)
{
var path = db.Database.GetDbConnection().DataSource;
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
return null;
}
var wal = new FileInfo(path + "-wal");
return new FileInfo(path).Length + (wal.Exists ? wal.Length : 0);
}
}
@@ -0,0 +1,3 @@
namespace Flypaper.Storage.Maintenance;
public sealed record TrapDataStats(int Count, DateTime? Oldest, long? DatabaseBytes);
@@ -0,0 +1,121 @@
// <auto-generated />
using System;
using Flypaper.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Flypaper.Storage.Migrations
{
[DbContext(typeof(FlypaperDbContext))]
[Migration("20261114150222_RemoveDripIntervalSetting")]
partial class RemoveDripIntervalSetting
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
{
b.Property<string>("Key")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("Settings");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("Asn")
.HasColumnType("INTEGER");
b.Property<long>("BytesSent")
.HasColumnType("INTEGER");
b.Property<string>("City")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ClientInfo")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.Property<string>("Country")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("CountryCode")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.Property<long>("DurationMs")
.HasColumnType("INTEGER");
b.Property<DateTime>("EndedAt")
.HasColumnType("TEXT");
b.Property<string>("Outcome")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Protocol")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Provider")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<Guid>("SessionId")
.HasColumnType("TEXT");
b.Property<DateTime>("StartedAt")
.HasColumnType("TEXT");
b.Property<string>("Strategy")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<string>("Target")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Asn");
b.HasIndex("CountryCode");
b.HasIndex("RemoteIp");
b.HasIndex("StartedAt");
b.ToTable("TrapEvents");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class RemoveDripIntervalSetting : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM \"Settings\" WHERE \"Key\" = 'Flypaper:Drip:Interval';");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}