M1: scheletro del servizio, PostgreSQL, accesso all'interfaccia e schermata d'errore

Soluzione .NET 10 con un solo pacchetto esterno (Npgsql): registri su file e in
memoria senza simboli, impostazioni in una riga jsonb con conferma «DAL VIVO»,
migrazioni SQL incorporate e partizioni mensili per bids/resets/bot_decisions,
coda di scrittura a lotti che regge il database assente. Kestrel serve la schermata
d'errore di configurazione (il bot riprova ogni 30 s) oppure l'interfaccia protetta
da UI_PASSWORD con cookie firmato e attese crescenti; /salute per il HEALTHCHECK.
Dockerfile su Debian 13 con Chromium vero, entrypoint con PUID/PGID, compose di
sviluppo con postgres:18, workflow di verifica e rilascio, template Unraid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-09-26 16:40:20 +02:00
1 parent 5f300fa495
commit 13f2413320
47 files changed
+4854 -8

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Ciò che non serve nel contesto di build dell'immagine.
.git
.gitignore
.gitattributes
.vscode
.claude
.gitea
**/bin
**/obj
**/TestResults
out
legacy
docs
tools
unraid
*.md
Modifiche.txt
+11
View File
@@ -0,0 +1,11 @@
# I file che finiscono nel container o sul runner Linux restano LF anche su Windows:
# uno script con CRLF nel shebang non parte ("bad interpreter").
*.sh text eol=lf
*.sql text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
Dockerfile text eol=lf
*.xml text eol=lf
*.png binary
*.ico binary
+55
View File
@@ -0,0 +1,55 @@
# Rilascio a ogni tag vX.Y.Z: controlla che il tag coincida con <Version> di
# Directory.Build.props, costruisce e pubblica l'immagine sul registry del Gitea
# (192.168.30.23:3000/alby96/bidoo-bidbot:X.Y.Z e :latest), poi crea la release con la
# sezione del CHANGELOG e il template Unraid allegato.
#
# Segreti del repository: REGISTRY_USER e REGISTRY_TOKEN (token con package: read and
# write e repository: read and write). Il registry è in HTTP: il demone Docker del runner
# (quello di Unraid, se il runner monta il suo socket) deve averlo fra gli insecure-registries.
name: Rilascio
on:
push:
tags: ['v*']
jobs:
immagine:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Versione coerente con il tag
run: |
V=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props)
[ "v$V" = "${GITHUB_REF_NAME}" ] || { echo "tag ${GITHUB_REF_NAME} diverso da <Version> $V"; exit 1; }
echo "VERSION=$V" >> "$GITHUB_ENV"
- name: Login al registry
run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login 192.168.30.23:3000 -u "${{ secrets.REGISTRY_USER }}" --password-stdin
- name: Costruzione e pubblicazione dell'immagine
run: |
IMG=192.168.30.23:3000/alby96/bidoo-bidbot
docker build -f docker/Dockerfile \
--build-arg VERSION=$VERSION \
--build-arg GIT_COMMIT="${GITHUB_SHA::12}" \
-t $IMG:$VERSION -t $IMG:latest .
docker push $IMG:$VERSION
docker push $IMG:latest
- name: Release su Gitea con il template Unraid
env:
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
run: |
set -eu
NOTE=$(awk -v v="$VERSION" '/^## /{p=($2==v)} p' CHANGELOG.md)
[ -n "$NOTE" ] || NOTE="Versione $VERSION"
ID=$(curl -sf -H "Authorization: token $TOKEN" "$API/releases/tags/${GITHUB_REF_NAME}" | jq -r '.id // empty' || true)
if [ -z "$ID" ]; then
ID=$(curl -sf -X POST "$API/releases" \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d "$(jq -n --arg t "$GITHUB_REF_NAME" --arg n "$NOTE" '{tag_name:$t, name:("Bidoo BidBot " + $t), body:$n}')" | jq -r .id)
fi
curl -sf -X POST "$API/releases/$ID/assets?name=bidoo-bidbot.xml" \
-H "Authorization: token $TOKEN" -F attachment=@unraid/bidoo-bidbot.xml > /dev/null
+30 -8
View File
@@ -1,3 +1,8 @@
# Verifica a ogni push su main e a ogni pull request: compilazione con gli avvisi come
# errori e tutti i test, compresi quelli su PostgreSQL 18 (servizio del job).
#
# Serve un runner Linux con Docker e l'etichetta ubuntu-latest: se non c'è, il README
# (sezione «Sviluppo») spiega come registrarne uno su Unraid con gitea/act_runner.
name: Verifica
on:
@@ -7,26 +12,43 @@ on:
jobs:
test:
runs-on: windows
runs-on: ubuntu-latest
services:
postgres:
image: postgres:18
env:
POSTGRES_PASSWORD: test
POSTGRES_USER: admin
POSTGRES_DB: bidbot_test
ports: ["5432:5432"]
options: >-
--health-cmd "pg_isready -U admin -d bidbot_test"
--health-interval 5s
--health-retries 10
steps:
- name: Sorgenti
uses: actions/checkout@v4
- uses: actions/checkout@v4
- name: .NET 10
uses: actions/setup-dotnet@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- name: Compila
run: dotnet build Tests/AutoBidder.Tests.csproj -c Debug --nologo -v q --artifacts-path "${{ runner.temp }}/AutoBidder.Verifica"
run: dotnet build BidooBidBot.sln -c Release --nologo
- name: Test
run: dotnet test Tests/AutoBidder.Tests.csproj -c Debug --no-build --nologo --artifacts-path "${{ runner.temp }}/AutoBidder.Verifica" --logger "trx;LogFileName=risultati.trx"
env:
TEST_DB_HOST: postgres
TEST_DB_USER: admin
TEST_DB_PASSWORD: test
TEST_DB_NAME: bidbot_test
run: >-
dotnet test tests/BidooBidBot.Tests -c Release --no-build --nologo
--logger "trx;LogFileName=risultati.trx" --results-directory out/test
- name: Risultati
if: always()
uses: actions/upload-artifact@v4
with:
name: risultati-test
path: ${{ runner.temp }}/AutoBidder.Verifica/**/*.trx
path: out/test/*.trx
if-no-files-found: ignore
+5
View File
@@ -0,0 +1,5 @@
# Bidoo BidBot: dati delle prove locali e risultati
tools/dev/config/
tools/dev/config-simulatore/
out/
*.trx
+56
View File
@@ -0,0 +1,56 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BidooBidBot", "src\BidooBidBot\BidooBidBot.csproj", "{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BidooBidBot.Tests", "tests\BidooBidBot.Tests\BidooBidBot.Tests.csproj", "{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|x64.ActiveCfg = Debug|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|x64.Build.0 = Debug|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|x86.ActiveCfg = Debug|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|x86.Build.0 = Debug|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|Any CPU.Build.0 = Release|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|x64.ActiveCfg = Release|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|x64.Build.0 = Release|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|x86.ActiveCfg = Release|Any CPU
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|x86.Build.0 = Release|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|x64.ActiveCfg = Debug|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|x64.Build.0 = Debug|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|x86.ActiveCfg = Debug|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|x86.Build.0 = Debug|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|Any CPU.Build.0 = Release|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|x64.ActiveCfg = Release|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|x64.Build.0 = Release|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|x86.ActiveCfg = Release|Any CPU
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{5CA3665D-BD05-4811-B099-12CB5BE6D9B9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
EndGlobal
+40
View File
@@ -0,0 +1,40 @@
<Project>
<!--
Unica origine della versione: la leggono il binario (/salute, barra dell'interfaccia,
/config/versione.txt), l'immagine Docker (build-arg VERSION) e il workflow di rilascio,
che rifiuta un tag vX.Y.Z diverso da questo numero.
-->
<PropertyGroup>
<Version>1.0.0</Version>
<Product>Bidoo BidBot</Product>
<Company>Alberto Balbo</Company>
<Copyright>Uso personale</Copyright>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Deterministic>true</Deterministic>
<NeutralLanguage>it-IT</NeutralLanguage>
<SatelliteResourceLanguages>it</SatelliteResourceLanguages>
</PropertyGroup>
<!--
Motore a bassa latenza (specifica §6.3). GC di workstation concorrente: pause brevi e
prevedibili contano più del rendimento; il GC di server alloca un heap per core e fa
pause più lunghe, ed è pensato per molte richieste indipendenti, non per un thread
cecchino che deve svegliarsi al millisecondo. Globalizzazione vera (non invariante):
numeri e date all'italiana.
-->
<PropertyGroup>
<ServerGarbageCollection>false</ServerGarbageCollection>
<ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
<TieredPGO>true</TieredPGO>
<InvariantGlobalization>false</InvariantGlobalization>
</PropertyGroup>
</Project>
+97
View File
@@ -0,0 +1,97 @@
# syntax=docker/dockerfile:1.7
#
# Bidoo BidBot: un solo container con motore, interfaccia web e Chromium per l'accesso
# assistito a Bidoo.
#
# docker build -f docker/Dockerfile --build-arg VERSION=1.0.0 --build-arg GIT_COMMIT=$(git rev-parse --short=12 HEAD) -t bidoo-bidbot:1.0.0 .
#
# Stadi: build (restore + compilazione), test (i test di logica pura; quelli su PostgreSQL
# saltano da soli senza TEST_DB_HOST), publish (ReadyToRun per linux-x64), runtime.
#
# Il runtime è Debian 13 con il runtime ASP.NET copiato dall'immagine ufficiale: per .NET 10
# Microsoft pubblica solo immagini Ubuntu/Alpine/Azure Linux, e su Ubuntu «apt install
# chromium» installa soltanto il rimando a snap, che in un container non funziona. Su Debian
# il pacchetto chromium è il browser vero (docs/adr/0010-immagine-debian-con-runtime-copiato.md).
ARG DOTNET_VERSION=10.0
# ─────────────────────────────────────────────────────────────── build
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build
WORKDIR /src
COPY Directory.Build.props BidooBidBot.sln ./
COPY src/BidooBidBot/BidooBidBot.csproj src/BidooBidBot/
COPY tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj tests/BidooBidBot.Tests/
RUN dotnet restore src/BidooBidBot/BidooBidBot.csproj -r linux-x64 \
&& dotnet restore tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj
COPY src/ src/
COPY tests/ tests/
RUN dotnet build tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj -c Release --no-restore -nologo
# ─────────────────────────────────────────────────────────────── test
FROM build AS test
RUN dotnet test tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj -c Release --no-build --nologo -v q \
&& touch /tmp/test-ok
# ─────────────────────────────────────────────────────────────── publish
FROM build AS publish
# La publish parte solo con i test verdi.
COPY --from=test /tmp/test-ok /tmp/test-ok
RUN dotnet publish src/BidooBidBot/BidooBidBot.csproj -c Release -r linux-x64 --self-contained false \
-p:PublishReadyToRun=true -nologo -o /app
# ─────────────────────────────────────────────────────────────── runtime ASP.NET
FROM mcr.microsoft.com/dotnet/aspnet:${DOTNET_VERSION} AS dotnet
# ─────────────────────────────────────────────────────────────── runtime
FROM debian:trixie-slim AS runtime
ARG VERSION=dev
ARG GIT_COMMIT=n/d
LABEL org.opencontainers.image.title="bidoo-bidbot" \
org.opencontainers.image.description="Bidoo BidBot: segue le aste al centesimo di Bidoo, decide con un modello appreso se puntare. Parte in modalità OSSERVA." \
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.revision="${GIT_COMMIT}" \
org.opencontainers.image.authors="Alberto Balbo" \
org.opencontainers.image.source="http://192.168.30.23:3000/Alby96/bidoo-bidbot"
# Dipendenze del runtime .NET (ICU, OpenSSL, zlib), fuso orario, certificati, Chromium con
# i caratteri per l'accesso assistito, setpriv (util-linux) per scendere a PUID/PGID.
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates tzdata libicu76 libssl3t64 libstdc++6 zlib1g libgcc-s1 \
chromium fonts-liberation util-linux \
&& rm -rf /var/lib/apt/lists/*
COPY --from=dotnet /usr/share/dotnet /usr/share/dotnet
RUN ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
ENV DOTNET_ROOT=/usr/share/dotnet \
DOTNET_gcServer=0 \
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=0 \
DOTNET_NOLOGO=1 \
ASPNETCORE_URLS= \
ASPNETCORE_HTTP_PORTS= \
PORT=8080 \
TZ=Europe/Rome \
PUID=99 \
PGID=100
WORKDIR /app
COPY --from=publish /app ./
COPY docker/entrypoint.sh /entrypoint.sh
RUN sed -i 's/\r$//' /entrypoint.sh && chmod +x /entrypoint.sh && mkdir -p /config
VOLUME ["/config"]
EXPOSE 8080
# /salute risponde 200 solo con configurazione e database a posto. Nell'immagine non c'è
# curl: la sonda è il programma stesso con --salute.
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD ["dotnet", "/app/BidooBidBot.dll", "--salute"]
# SIGTERM arriva al processo dotnet (exec nell'entrypoint): spegnimento ordinato in 10 s.
STOPSIGNAL SIGTERM
ENTRYPOINT ["/entrypoint.sh"]
CMD ["dotnet", "/app/BidooBidBot.dll"]
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Bidoo BidBot: entrypoint del container.
#
# 1. Fuso orario da TZ (tzdata è nell'immagine).
# 2. Utente e gruppo da PUID/PGID (predefiniti 99/100, «nobody:users» di Unraid): /config
# passa a quell'utente, così i file scritti dal bot si leggono dalla share appdata.
# 3. exec del processo finale con setpriv: PID 1 è dotnet e SIGTERM arriva a lui.
#
# Con PUID=0 il bot resta root: sconsigliato, ammesso per il debug.
set -eu
PUID="${PUID:-99}"
PGID="${PGID:-100}"
if [ -n "${TZ:-}" ] && [ -f "/usr/share/zoneinfo/${TZ}" ]; then
ln -sf "/usr/share/zoneinfo/${TZ}" /etc/localtime
echo "${TZ}" > /etc/timezone
fi
mkdir -p /config
if [ "${PUID}" = "0" ]; then
echo "bidoo-bidbot: avvio come root (PUID=0), fuso ${TZ:-UTC}"
exec "$@"
fi
if ! getent group "${PGID}" >/dev/null 2>&1; then
groupadd -g "${PGID}" bidbot
fi
GROUP_NAME="$(getent group "${PGID}" | cut -d: -f1)"
if ! getent passwd "${PUID}" >/dev/null 2>&1; then
useradd -r -o -u "${PUID}" -g "${PGID}" -M -d /config -s /usr/sbin/nologin bidbot
fi
chown -R "${PUID}:${PGID}" /config
# Chromium vuole una home scrivibile per la cache: la sua sta dentro /config/browser.
export HOME=/config
echo "bidoo-bidbot: avvio come uid ${PUID} gid ${PGID} (${GROUP_NAME}), fuso ${TZ:-UTC}"
exec setpriv --reuid="${PUID}" --regid="${PGID}" --init-groups "$@"
+31
View File
@@ -0,0 +1,31 @@
using System.Globalization;
using System.Reflection;
namespace BidooBidBot;
/// <summary>Versione e identità del programma, da <c>Directory.Build.props</c>.</summary>
public static class AppInfo
{
public const string Name = "Bidoo BidBot";
/// <summary>MAJOR.MINOR.PATCH, senza l'hash del commit che il compilatore aggiunge dopo il «+».</summary>
public static string Version { get; } = ReadVersion();
public static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
/// <summary>Il fuso con cui si mostrano gli orari (TZ del container, di solito Europe/Rome).</summary>
public static TimeZoneInfo TimeZone { get; set; } = TimeZoneInfo.Local;
public static DateTime LocalNow => TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZone);
public static DateTime ToLocal(DateTime utc) =>
TimeZoneInfo.ConvertTime(utc.Kind == DateTimeKind.Utc ? utc : DateTime.SpecifyKind(utc, DateTimeKind.Utc), TimeZone);
private static string ReadVersion()
{
var info = typeof(AppInfo).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
if (string.IsNullOrEmpty(info)) return typeof(AppInfo).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
var plus = info.IndexOf('+');
return plus > 0 ? info[..plus] : info;
}
}
@@ -0,0 +1 @@
{}
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<OutputType>Exe</OutputType>
<RootNamespace>BidooBidBot</RootNamespace>
<AssemblyName>BidooBidBot</AssemblyName>
<!-- Kestrel e il suo WebSocket vengono dal framework ASP.NET Core: nessun pacchetto. -->
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<UserSecretsId></UserSecretsId>
</PropertyGroup>
<ItemGroup>
<!-- Unico pacchetto esterno del servizio (specifica §0): il driver di PostgreSQL. -->
<PackageReference Include="Npgsql" Version="10.0.3" />
</ItemGroup>
<ItemGroup>
<!-- Migrazioni e valori di fabbrica viaggiano dentro il binario. -->
<EmbeddedResource Include="Data\Migrations\*.sql" LogicalName="Migrations.%(Filename)%(Extension)" />
<EmbeddedResource Include="Bidoo\bidoo.default.json" LogicalName="bidoo.default.json" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="BidooBidBot.Tests" />
</ItemGroup>
</Project>
@@ -0,0 +1,64 @@
namespace BidooBidBot.Config;
/// <summary>
/// Le cartelle dentro <c>/config</c> (volume <c>appdata</c> di Unraid): file che non servono
/// in fretta o che l'utente può voler leggere o correggere a mano.
/// </summary>
public sealed class ConfigPaths
{
public string Root { get; }
public ConfigPaths(string root) => Root = root;
/// <summary>Cookie di Bidoo cifrati, chiave, segreto dei cookie dell'interfaccia.</summary>
public string Session => Path.Combine(Root, "sessione");
/// <summary><c>bidoo.json</c>: indirizzi ed espressioni del sito, ricaricati a caldo.</summary>
public string References => Path.Combine(Root, "riferimenti");
/// <summary>Registri giornalieri: applicativo e aste.</summary>
public string Logs => Path.Combine(Root, "registri");
public string Exports => Path.Combine(Root, "esportazioni");
/// <summary>Profilo di Chromium per l'accesso assistito.</summary>
public string Browser => Path.Combine(Root, "browser");
public string Backups => Path.Combine(Root, "backup");
/// <summary>Copie che servono a database fermo (impostazioni di Telegram).</summary>
public string Cache => Path.Combine(Root, "cache");
public string VersionFile => Path.Combine(Root, "versione.txt");
public void EnsureAll()
{
foreach (var dir in new[] { Root, Session, References, Logs, Exports, Browser, Backups, Cache })
Directory.CreateDirectory(dir);
}
/// <summary>La cartella è scrivibile? Serve alla schermata d'errore di configurazione.</summary>
public (bool Ok, string? Error) CheckWritable()
{
try
{
Directory.CreateDirectory(Root);
var probe = Path.Combine(Root, $".prova-{Environment.ProcessId}");
File.WriteAllText(probe, "ok");
File.Delete(probe);
return (true, null);
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
/// <summary>Permessi 0600 su Linux per i file con segreti; su Windows non fa nulla.</summary>
public static void RestrictToOwner(string file)
{
if (OperatingSystem.IsWindows()) return;
try { File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite); }
catch { /* file system che non supporta i permessi: si accetta */ }
}
}
@@ -0,0 +1,97 @@
using System.Globalization;
using BidooBidBot.Data;
namespace BidooBidBot.Config;
/// <summary>
/// La configurazione del container: solo le variabili della specifica (§10.1). Tutto il
/// resto vive nel database (impostazioni) o in <c>/config</c>.
///
/// <para>Obbligatorie <c>DB_HOST</c>, <c>DB_PASSWORD</c>, <c>UI_PASSWORD</c>; facoltative
/// <c>DB_USER</c> (admin), <c>DB_NAME</c> (autobidder), <c>DB_PORT</c> (5432), <c>PORT</c>
/// (8080), <c>TZ</c>, <c>PUID</c>/<c>PGID</c> (le usa l'entrypoint). Le password non escono
/// mai da qui: <see cref="Describe"/> non le contiene.</para>
/// </summary>
public sealed class EnvConfig
{
public string? DbHostRaw { get; init; }
public string DbHost { get; init; } = "";
public int DbPort { get; init; } = 5432;
public string DbUser { get; init; } = "admin";
public string DbName { get; init; } = "autobidder";
public string? DbPassword { get; init; }
public string? UiPassword { get; init; }
public int HttpPort { get; init; } = 8080;
public string ConfigDir { get; init; } = "/config";
public string TimeZone { get; init; } = "Europe/Rome";
public bool HasDbHost => !string.IsNullOrWhiteSpace(DbHost);
public bool HasDbPassword => !string.IsNullOrEmpty(DbPassword);
public bool HasUiPassword => !string.IsNullOrEmpty(UiPassword);
public DbConfig ToDbConfig() => new(DbHost, DbPort, DbUser, DbPassword ?? "", DbName);
/// <summary>Legge l'ambiente e gli argomenti (<c>--config cartella</c> solo per lo sviluppo).</summary>
public static EnvConfig Read(Func<string, string?> env, string[] args)
{
var rawHost = env("DB_HOST")?.Trim();
var (host, portInHost) = SplitHost(rawHost);
var port = portInHost
?? (int.TryParse(env("DB_PORT"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var p) && p is > 0 and < 65536 ? p : 5432);
var httpPort = int.TryParse(env("PORT"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var hp) && hp is > 0 and < 65536 ? hp : 8080;
var configDir = "/config";
for (var i = 0; i < args.Length - 1; i++)
{
if (args[i] == "--config") configDir = Path.GetFullPath(args[i + 1]);
}
return new EnvConfig
{
DbHostRaw = rawHost,
DbHost = host,
DbPort = port,
DbUser = NonEmpty(env("DB_USER")) ?? "admin",
DbName = NonEmpty(env("DB_NAME")) ?? "autobidder",
DbPassword = env("DB_PASSWORD"),
UiPassword = env("UI_PASSWORD"),
HttpPort = httpPort,
ConfigDir = configDir,
TimeZone = NonEmpty(env("TZ")) ?? "Europe/Rome"
};
}
/// <summary>
/// <c>192.168.30.23</c> oppure <c>192.168.30.23:5432</c>. Un indirizzo IPv6 va scritto fra
/// quadre (<c>[::1]:5432</c>).
/// </summary>
public static (string Host, int? Port) SplitHost(string? raw)
{
if (string.IsNullOrWhiteSpace(raw)) return ("", null);
var text = raw.Trim();
if (text.StartsWith('['))
{
var close = text.IndexOf(']');
if (close > 0)
{
var h = text[1..close];
var rest = text[(close + 1)..];
return rest.StartsWith(':') && int.TryParse(rest[1..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var pp) ? (h, pp) : (h, null);
}
}
var colon = text.LastIndexOf(':');
if (colon > 0 && text.IndexOf(':') == colon &&
int.TryParse(text[(colon + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536)
{
return (text[..colon], port);
}
return (text, null);
}
private static string? NonEmpty(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
}
@@ -0,0 +1,149 @@
using System.Net.Sockets;
using BidooBidBot.Data;
using Npgsql;
namespace BidooBidBot.Config;
/// <summary>Una riga della schermata d'errore di configurazione.</summary>
/// <param name="Title">Cosa si verifica, in chiaro.</param>
/// <param name="Detail">I valori in uso (mai una password).</param>
/// <param name="Error">L'errore testuale, se la verifica non passa.</param>
public sealed record CheckItem(string Key, bool Ok, string Title, string? Detail, string? Error, string? Hint = null);
/// <summary>Esito di un giro di verifiche all'avvio.</summary>
public sealed class StartupReport
{
public List<CheckItem> Items { get; } = new();
public int Attempt { get; init; }
public DateTimeOffset At { get; init; } = DateTimeOffset.Now;
public bool AllOk => Items.All(i => i.Ok);
public CheckItem? FirstProblem => Items.FirstOrDefault(i => !i.Ok);
}
/// <summary>
/// Le verifiche all'avvio, nell'ordine della specifica (§10.3): variabili obbligatorie,
/// cartella <c>/config</c>, connessione a PostgreSQL, database (creato se manca e l'utente
/// può), migrazioni, partizioni. Se qualcosa non va il bot non parte: la schermata d'errore
/// mostra questo rapporto e si riprova ogni 30 secondi.
/// </summary>
public static class StartupCheck
{
public static async Task<(StartupReport Report, Db? Db)> RunAsync(EnvConfig env, ConfigPaths paths, int attempt, CancellationToken ct)
{
var report = new StartupReport { Attempt = attempt };
var dbDetail = env.HasDbHost ? $"{env.DbHost}:{env.DbPort} · utente {env.DbUser} · database {env.DbName}" : null;
report.Items.Add(env.HasDbHost
? new CheckItem("db_host", true, "Indirizzo del database impostato (DB_HOST)", dbDetail, null)
: new CheckItem("db_host", false, "Indirizzo del database mancante (DB_HOST)", null,
"La variabile DB_HOST è vuota.", "Nel template di bidoo-bidbot scrivi DB_HOST, per esempio 192.168.30.23:5432."));
report.Items.Add(env.HasDbPassword
? new CheckItem("db_password", true, "Password del database impostata (DB_PASSWORD)", null, null)
: new CheckItem("db_password", false, "Password del database mancante (DB_PASSWORD)", null,
"La variabile DB_PASSWORD è vuota.", "Nel template di bidoo-bidbot scrivi la password dell'utente PostgreSQL."));
report.Items.Add(env.HasUiPassword
? new CheckItem("ui_password", true, "Password dell'interfaccia impostata (UI_PASSWORD)", null, null)
: new CheckItem("ui_password", false, "Password dell'interfaccia mancante (UI_PASSWORD)", null,
"La variabile UI_PASSWORD è vuota: l'interfaccia comanda puntate vere e non può restare aperta.",
"Nel template di bidoo-bidbot scrivi una password in UI_PASSWORD."));
var (writable, writeError) = paths.CheckWritable();
var who = OperatingSystem.IsWindows() ? "" : $", utente {Environment.GetEnvironmentVariable("PUID") ?? "?"}:{Environment.GetEnvironmentVariable("PGID") ?? "?"}";
report.Items.Add(writable
? new CheckItem("config", true, "Cartella /config scrivibile", $"{paths.Root}{who}", null)
: new CheckItem("config", false, "Cartella /config non scrivibile", $"{paths.Root}{who}", writeError,
"Controlla il percorso della cartella dati nel template e i permessi (PUID/PGID)."));
if (!env.HasDbHost || !env.HasDbPassword)
{
report.Items.Add(new CheckItem("database", false, "Database non verificato", dbDetail,
"Mancano indirizzo o password del database.", null));
return (report, null);
}
Db? db = null;
try
{
var cfg = env.ToDbConfig();
await EnsureDatabaseAsync(cfg, ct).ConfigureAwait(false);
db = new Db(cfg);
report.Items.Add(new CheckItem("database", true, "Database raggiungibile", dbDetail, null));
}
catch (Exception ex)
{
if (db != null) await db.DisposeAsync().ConfigureAwait(false);
report.Items.Add(new CheckItem("database", false, "Database non raggiungibile", dbDetail,
Explain(ex, env), "Su Unraid: Docker ▸ postgresql18 ▸ avvia; poi controlla porta e password nel template di bidoo-bidbot."));
return (report, null);
}
try
{
var applied = await Migrations.ApplyAsync(db.Writer, ct).ConfigureAwait(false);
var version = await Migrations.CurrentVersionAsync(db).ConfigureAwait(false);
report.Items.Add(new CheckItem("migrations", true, "Schema del database aggiornato",
applied.Count > 0 ? $"versione {version}, applicate ora: {string.Join(", ", applied.Select(a => a.Name))}" : $"versione {version}", null));
await Partitions.EnsureAsync(db, DateTime.UtcNow).ConfigureAwait(false);
}
catch (Exception ex)
{
report.Items.Add(new CheckItem("migrations", false, "Migrazione dello schema non riuscita", dbDetail,
$"Npgsql: {ex.Message}", "Il database non è stato toccato oltre la migrazione fallita: annota l'errore e segnalalo."));
await db.DisposeAsync().ConfigureAwait(false);
return (report, null);
}
return (report, db);
}
/// <summary>
/// Si collega al database; se non esiste e l'utente ha il permesso lo crea (il container
/// di Alberto ha POSTGRES_DB=autobidder, quindi di solito c'è già).
/// </summary>
private static async Task EnsureDatabaseAsync(DbConfig cfg, CancellationToken ct)
{
try
{
await using var conn = new NpgsqlConnection(cfg.Builder().ConnectionString);
await conn.OpenAsync(ct).ConfigureAwait(false);
}
catch (PostgresException ex) when (ex.SqlState == "3D000")
{
await using var admin = new NpgsqlConnection(cfg.Builder("postgres").ConnectionString);
await admin.OpenAsync(ct).ConfigureAwait(false);
var safeName = cfg.Database.Replace("\"", "\"\"", StringComparison.Ordinal);
await using var create = new NpgsqlCommand($"CREATE DATABASE \"{safeName}\"", admin);
await create.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
}
/// <summary>L'errore di Npgsql con una frase che dice cosa controllare.</summary>
public static string Explain(Exception ex, EnvConfig env)
{
var where = $"{env.DbHost}:{env.DbPort}";
return ex switch
{
PostgresException { SqlState: "28P01" } => $"Npgsql: password sbagliata per l'utente {env.DbUser}",
PostgresException { SqlState: "28000" } => $"Npgsql: l'utente {env.DbUser} non può collegarsi ({ex.Message})",
PostgresException { SqlState: "3D000" } => $"Npgsql: il database {env.DbName} non esiste e l'utente non può crearlo",
PostgresException { SqlState: "42501" } => $"Npgsql: permesso negato ({ex.Message})",
_ when HasSocketError(ex, SocketError.ConnectionRefused) => $"Npgsql: connection refused ({where}) - il container PostgreSQL è spento o la porta è diversa",
_ when HasSocketError(ex, SocketError.HostNotFound) || HasSocketError(ex, SocketError.NoData) => $"Npgsql: indirizzo {env.DbHost} sconosciuto",
_ when ex is TimeoutException || ex.InnerException is TimeoutException || ex.Message.Contains("Timeout", StringComparison.OrdinalIgnoreCase)
=> $"Npgsql: nessuna risposta da {where} entro 5 secondi - indirizzo sbagliato o rete non raggiungibile",
_ => $"Npgsql: {ex.Message}"
};
}
private static bool HasSocketError(Exception? ex, SocketError code)
{
for (var e = ex; e != null; e = e.InnerException)
if (e is SocketException s && s.SocketErrorCode == code) return true;
return false;
}
}
+200
View File
@@ -0,0 +1,200 @@
using System.Data.Common;
using Npgsql;
using NpgsqlTypes;
namespace BidooBidBot.Data;
/// <summary>Parametri di connessione, dalle variabili d'ambiente (specifica §10.1).</summary>
public sealed record DbConfig(string Host, int Port, string User, string Password, string Database)
{
/// <summary>Descrizione senza segreti, per la schermata d'errore e il registro.</summary>
public string Describe() => $"{Host}:{Port} utente {User} database {Database}";
public NpgsqlConnectionStringBuilder Builder(string? database = null, int commandTimeoutSeconds = 30) => new()
{
Host = Host,
Port = Port,
Username = User,
Password = Password,
Database = database ?? Database,
Timeout = 5,
CommandTimeout = commandTimeoutSeconds,
Pooling = true,
MaxPoolSize = 20,
ApplicationName = "bidoo-bidbot",
IncludeErrorDetail = false
};
}
/// <summary>Un parametro da passare come <c>jsonb</c>: il testo è già JSON.</summary>
public readonly record struct Jsonb(string? Json);
/// <summary>
/// Accesso a PostgreSQL con SQL scritto a mano e parametri posizionali (<c>$1, $2…</c>).
///
/// <para>Due sorgenti di connessioni: una per le scritture (la usa solo
/// <see cref="WriteQueue"/>, più le migrazioni e la manutenzione) e una per le letture
/// dell'interfaccia, con un tempo massimo breve, così una pagina lenta non trattiene le
/// connessioni che servono alla coda.</para>
/// </summary>
public sealed class Db : IAsyncDisposable
{
public DbConfig Config { get; }
public NpgsqlDataSource Writer { get; }
public NpgsqlDataSource Reader { get; }
public Db(DbConfig config)
{
Config = config;
Writer = NpgsqlDataSource.Create(config.Builder(commandTimeoutSeconds: 120));
Reader = NpgsqlDataSource.Create(config.Builder(commandTimeoutSeconds: 15));
}
public static NpgsqlCommand Command(NpgsqlConnection connection, string sql, IReadOnlyList<object?> args)
{
var cmd = new NpgsqlCommand(sql, connection);
foreach (var arg in args) cmd.Parameters.Add(Parameter(arg));
return cmd;
}
public static NpgsqlBatchCommand BatchCommand(string sql, IReadOnlyList<object?> args)
{
var cmd = new NpgsqlBatchCommand(sql);
foreach (var arg in args) cmd.Parameters.Add(Parameter(arg));
return cmd;
}
/// <summary>
/// Un parametro posizionale. Null diventa NULL senza tipo (PostgreSQL lo ricava dal
/// contesto); le date devono essere UTC, <see cref="Jsonb"/> diventa jsonb.
/// </summary>
public static NpgsqlParameter Parameter(object? value) => value switch
{
null => new NpgsqlParameter { Value = DBNull.Value },
Jsonb j => new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.Jsonb, Value = (object?)j.Json ?? DBNull.Value },
DateTime d => new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.TimestampTz, Value = d.Kind == DateTimeKind.Utc ? d : d.ToUniversalTime() },
DateTimeOffset o => new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.TimestampTz, Value = o.UtcDateTime },
_ => new NpgsqlParameter { Value = value }
};
/// <summary>Righe di una lettura, già trasformate. Usa la sorgente delle letture.</summary>
public async Task<List<T>> QueryAsync<T>(string sql, Func<DbDataReader, T> map, params object?[] args)
{
await using var conn = await Reader.OpenConnectionAsync().ConfigureAwait(false);
await using var cmd = Command(conn, sql, args);
await using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false);
var list = new List<T>();
while (await reader.ReadAsync().ConfigureAwait(false)) list.Add(map(reader));
return list;
}
public async Task<T?> QueryOneAsync<T>(string sql, Func<DbDataReader, T> map, params object?[] args) where T : class
{
var rows = await QueryAsync(sql, map, args).ConfigureAwait(false);
return rows.Count > 0 ? rows[0] : null;
}
/// <summary>Il primo valore della prima riga, convertito; default se non c'è o è NULL.</summary>
public async Task<T?> ScalarAsync<T>(string sql, params object?[] args)
{
await using var conn = await Reader.OpenConnectionAsync().ConfigureAwait(false);
await using var cmd = Command(conn, sql, args);
var value = await cmd.ExecuteScalarAsync().ConfigureAwait(false);
return value is null or DBNull ? default : (T)Convert.ChangeType(value, Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T), System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>
/// Una scrittura diretta, fuori dalla coda. Solo per migrazioni, manutenzione e
/// operazioni lunghe chieste dall'utente: il motore scrive sempre attraverso la coda.
/// </summary>
public async Task<int> ExecuteAsync(string sql, params object?[] args)
{
await using var conn = await Writer.OpenConnectionAsync().ConfigureAwait(false);
await using var cmd = Command(conn, sql, args);
return await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
}
public async ValueTask DisposeAsync()
{
await Writer.DisposeAsync().ConfigureAwait(false);
await Reader.DisposeAsync().ConfigureAwait(false);
}
}
/// <summary>Letture comode e tolleranti ai NULL dalle righe di <see cref="DbDataReader"/>.</summary>
public static class RowExtensions
{
public static string Str(this DbDataReader r, string name)
{
var i = r.GetOrdinal(name);
return r.IsDBNull(i) ? "" : Convert.ToString(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture) ?? "";
}
public static string? StrOrNull(this DbDataReader r, string name)
{
var i = r.GetOrdinal(name);
return r.IsDBNull(i) ? null : Convert.ToString(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture);
}
public static double Dbl(this DbDataReader r, string name) => r.DblOrNull(name) ?? 0;
public static double? DblOrNull(this DbDataReader r, string name)
{
var i = r.GetOrdinal(name);
return r.IsDBNull(i) ? null : Convert.ToDouble(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture);
}
public static int Int(this DbDataReader r, string name) => r.IntOrNull(name) ?? 0;
public static int? IntOrNull(this DbDataReader r, string name)
{
var i = r.GetOrdinal(name);
return r.IsDBNull(i) ? null : Convert.ToInt32(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture);
}
public static long Long(this DbDataReader r, string name) => r.LongOrNull(name) ?? 0;
public static long? LongOrNull(this DbDataReader r, string name)
{
var i = r.GetOrdinal(name);
return r.IsDBNull(i) ? null : Convert.ToInt64(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture);
}
public static bool Bool(this DbDataReader r, string name)
{
var i = r.GetOrdinal(name);
return !r.IsDBNull(i) && Convert.ToBoolean(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture);
}
public static bool? BoolOrNull(this DbDataReader r, string name)
{
var i = r.GetOrdinal(name);
return r.IsDBNull(i) ? null : Convert.ToBoolean(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>Un timestamptz come istante UTC; null se NULL.</summary>
public static DateTime? Date(this DbDataReader r, string name)
{
var i = r.GetOrdinal(name);
if (r.IsDBNull(i)) return null;
var v = r.GetValue(i);
return v switch
{
DateTime d => d.Kind == DateTimeKind.Utc ? d : DateTime.SpecifyKind(d, DateTimeKind.Utc),
DateTimeOffset o => o.UtcDateTime,
_ => null
};
}
/// <summary>Tutte le colonne della riga in un dizionario: per le pagine che mostrano righe intere.</summary>
public static Dictionary<string, object?> ToDictionary(this DbDataReader r)
{
var d = new Dictionary<string, object?>(r.FieldCount, StringComparer.Ordinal);
for (var i = 0; i < r.FieldCount; i++)
{
var v = r.IsDBNull(i) ? null : r.GetValue(i);
d[r.GetName(i)] = v is decimal m ? (double)m : v;
}
return d;
}
}
@@ -0,0 +1,85 @@
using System.Collections.Concurrent;
namespace BidooBidBot.Data;
/// <summary>
/// Documenti chiave → JSON: i modelli appresi (<c>ml/*</c>), le aste in elenco
/// (<c>monitor/auctions</c>), l'HALT (<c>risk/halt</c>). Letture sincrone da una copia in
/// memoria, scritture accodate: nessuno dei chiamanti (motore, apprendimento) aspetta il
/// database.
/// </summary>
public interface IDocumentStore
{
string? Get(string key);
void Set(string key, string json);
void Delete(string key);
void DeletePrefix(string prefix);
IReadOnlyList<string> Keys(string prefix);
}
/// <summary>Documenti su PostgreSQL (tabella <c>documents</c>), caricati tutti all'avvio.</summary>
public sealed class DocumentStore : IDocumentStore
{
private readonly ConcurrentDictionary<string, string> _cache = new(StringComparer.Ordinal);
private readonly WriteQueue _queue;
public DocumentStore(WriteQueue queue) => _queue = queue;
/// <summary>Legge tutti i documenti in memoria. Sono pochi: i modelli pesano qualche centinaio di KB.</summary>
public async Task LoadAsync(Db db)
{
var rows = await db.QueryAsync("SELECT key, value::text AS value FROM documents",
r => (Key: r.Str("key"), Value: r.Str("value"))).ConfigureAwait(false);
_cache.Clear();
foreach (var (key, value) in rows) _cache[key] = value;
}
public string? Get(string key) => _cache.TryGetValue(key, out var v) ? v : null;
public void Set(string key, string json)
{
_cache[key] = json;
_queue.Enqueue(
"INSERT INTO documents(key, value, updated_at) VALUES($1, $2, now()) " +
"ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
key, new Jsonb(json));
}
public void Delete(string key)
{
_cache.TryRemove(key, out _);
_queue.Enqueue("DELETE FROM documents WHERE key = $1", key);
}
public void DeletePrefix(string prefix)
{
foreach (var k in _cache.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList())
_cache.TryRemove(k, out _);
var pattern = prefix.Replace("\\", "\\\\", StringComparison.Ordinal)
.Replace("%", "\\%", StringComparison.Ordinal)
.Replace("_", "\\_", StringComparison.Ordinal) + "%";
_queue.Enqueue("DELETE FROM documents WHERE key LIKE $1", pattern);
}
public IReadOnlyList<string> Keys(string prefix) =>
_cache.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).OrderBy(k => k, StringComparer.Ordinal).ToList();
}
/// <summary>Documenti in memoria soltanto: test e simulatore.</summary>
public sealed class MemoryDocumentStore : IDocumentStore
{
private readonly ConcurrentDictionary<string, string> _docs = new(StringComparer.Ordinal);
public string? Get(string key) => _docs.TryGetValue(key, out var v) ? v : null;
public void Set(string key, string json) => _docs[key] = json;
public void Delete(string key) => _docs.TryRemove(key, out _);
public void DeletePrefix(string prefix)
{
foreach (var k in _docs.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList())
_docs.TryRemove(k, out _);
}
public IReadOnlyList<string> Keys(string prefix) =>
_docs.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).OrderBy(k => k, StringComparer.Ordinal).ToList();
}
+147
View File
@@ -0,0 +1,147 @@
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using Npgsql;
namespace BidooBidBot.Data;
/// <summary>
/// Le migrazioni SQL incorporate nel binario (<c>Data/Migrations/NNNN_nome.sql</c>),
/// applicate in ordine, una transazione per file, registrate in <c>schema_migrations</c>.
/// Sempre additive. Una migrazione fallita ferma l'avvio e porta alla schermata d'errore.
/// </summary>
public static partial class Migrations
{
public sealed record Script(int Version, string Name, string Sql);
/// <summary>Gli script incorporati, in ordine di versione.</summary>
public static IReadOnlyList<Script> Embedded()
{
var asm = typeof(Migrations).Assembly;
var list = new List<Script>();
foreach (var res in asm.GetManifestResourceNames())
{
var m = ResourceName().Match(res);
if (!m.Success) continue;
using var stream = asm.GetManifestResourceStream(res)!;
using var reader = new StreamReader(stream);
list.Add(new Script(int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture), m.Groups[2].Value, reader.ReadToEnd()));
}
return list.OrderBy(s => s.Version).ToList();
}
/// <summary>Applica le migrazioni mancanti. Restituisce quelle applicate adesso.</summary>
public static async Task<IReadOnlyList<Script>> ApplyAsync(NpgsqlDataSource dataSource, CancellationToken ct = default)
{
await using var conn = await dataSource.OpenConnectionAsync(ct).ConfigureAwait(false);
await using (var create = new NpgsqlCommand(
"CREATE TABLE IF NOT EXISTS schema_migrations (version int PRIMARY KEY, name text NOT NULL DEFAULT '', applied_at timestamptz NOT NULL DEFAULT now())",
conn))
{
await create.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
var applied = new HashSet<int>();
await using (var read = new NpgsqlCommand("SELECT version FROM schema_migrations", conn))
await using (var reader = await read.ExecuteReaderAsync(ct).ConfigureAwait(false))
{
while (await reader.ReadAsync(ct).ConfigureAwait(false)) applied.Add(reader.GetInt32(0));
}
var done = new List<Script>();
foreach (var script in Embedded())
{
if (applied.Contains(script.Version)) continue;
await using var tx = await conn.BeginTransactionAsync(ct).ConfigureAwait(false);
await using (var cmd = new NpgsqlCommand(script.Sql, conn, tx))
{
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
await using (var mark = new NpgsqlCommand("INSERT INTO schema_migrations(version, name) VALUES($1, $2)", conn, tx))
{
mark.Parameters.Add(new NpgsqlParameter { Value = script.Version });
mark.Parameters.Add(new NpgsqlParameter { Value = script.Name });
await mark.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
await tx.CommitAsync(ct).ConfigureAwait(false);
done.Add(script);
}
return done;
}
/// <summary>La versione più alta applicata, per la schermata Impostazioni e /salute.</summary>
public static async Task<int> CurrentVersionAsync(Db db) =>
await db.ScalarAsync<int?>("SELECT MAX(version) FROM schema_migrations").ConfigureAwait(false) ?? 0;
[GeneratedRegex(@"^Migrations\.(\d{4})_([A-Za-z0-9_\-]+)\.sql$")]
private static partial Regex ResourceName();
}
/// <summary>
/// Le partizioni mensili di <c>bids</c>, <c>resets</c> e <c>bot_decisions</c>. Il programma
/// crea quella del mese corrente e del prossimo all'avvio, e ogni giorno dal 25 in poi
/// quella del mese dopo: una riga senza partizione verrebbe rifiutata.
/// </summary>
public static class Partitions
{
public static readonly string[] Tables = { "bids", "resets", "bot_decisions" };
public static string NameFor(string table, DateTime month) =>
$"{table}_{month.Year:D4}_{month.Month:D2}";
/// <summary>Crea (se mancano) le partizioni del mese di <paramref name="today"/> e del successivo.</summary>
public static async Task<int> EnsureAsync(Db db, DateTime today)
{
var created = 0;
var first = new DateTime(today.Year, today.Month, 1, 0, 0, 0, DateTimeKind.Utc);
foreach (var month in new[] { first, first.AddMonths(1) })
{
foreach (var table in Tables)
{
var name = NameFor(table, month);
var exists = await db.ScalarAsync<bool>("SELECT to_regclass($1) IS NOT NULL", name).ConfigureAwait(false);
if (exists) continue;
var from = month.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
var to = month.AddMonths(1).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
await db.ExecuteAsync(
$"CREATE TABLE IF NOT EXISTS {name} PARTITION OF {table} FOR VALUES FROM ('{from} 00:00:00+00') TO ('{to} 00:00:00+00')")
.ConfigureAwait(false);
created++;
}
}
return created;
}
/// <summary>Una partizione esistente con il mese che copre.</summary>
public sealed record Info(string Table, string Name, DateTime Month, long Bytes);
/// <summary>Le partizioni di una tabella, dalla più vecchia.</summary>
public static async Task<IReadOnlyList<Info>> ListAsync(Db db, string table)
{
var rows = await db.QueryAsync(
"SELECT c.relname AS name, pg_total_relation_size(c.oid) AS bytes " +
"FROM pg_inherits i JOIN pg_class c ON c.oid = i.inhrelid JOIN pg_class p ON p.oid = i.inhparent " +
"WHERE p.relname = $1",
r => (Name: r.Str("name"), Bytes: r.Long("bytes")), table).ConfigureAwait(false);
var list = new List<Info>();
foreach (var (name, bytes) in rows)
{
var tail = name[(table.Length + 1)..];
if (tail.Length == 7 &&
int.TryParse(tail[..4], NumberStyles.None, CultureInfo.InvariantCulture, out var y) &&
int.TryParse(tail[5..], NumberStyles.None, CultureInfo.InvariantCulture, out var m) && m is >= 1 and <= 12)
{
list.Add(new Info(table, name, new DateTime(y, m, 1, 0, 0, 0, DateTimeKind.Utc), bytes));
}
}
return list.OrderBy(p => p.Month).ToList();
}
}
@@ -0,0 +1,290 @@
-- Bidoo BidBot, schema iniziale.
--
-- Nel database sta solo ciò che serve allo storico e al miglioramento del modello: il
-- motivo di ogni tabella è scritto in docs/ARCHITETTURA.md. Registri, diagnostica di rete e
-- stato dell'interfaccia NON stanno qui (memoria o file in /config).
--
-- Migrazioni solo additive: un file nuovo per ogni cambio, mai riscrivere una tabella.
-- bids, resets e bot_decisions sono partizionate per mese su created_at; le partizioni le
-- crea il programma (all'avvio e il giorno 25 per il mese dopo). Gli indici dichiarati sulla
-- tabella madre valgono per tutte le partizioni, anche quelle future.
CREATE TABLE IF NOT EXISTS settings (
id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1),
value jsonb NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Documenti chiave -> JSON: modelli appresi (ml/*), aste in elenco (monitor/auctions), HALT.
CREATE TABLE IF NOT EXISTS documents (
key text PRIMARY KEY,
value jsonb NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Un prodotto: ciò che le aste hanno in comune.
CREATE TABLE IF NOT EXISTS items (
item_id bigserial PRIMARY KEY,
product_key text NOT NULL UNIQUE,
bidoo_product_id text,
title text NOT NULL DEFAULT '',
category text,
image_url text,
retail_price_bidoo numeric(10,2),
market_price_est numeric(10,2),
market_price_source text,
shipping numeric(10,2),
first_seen_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Un'asta: una riga sola, dall'aggancio alla chiusura. Le colonne del riepilogo restano
-- NULL finché l'asta è in corso.
CREATE TABLE IF NOT EXISTS auctions (
auction_id text PRIMARY KEY,
item_id bigint REFERENCES items(item_id),
product_key text NOT NULL DEFAULT '',
name text NOT NULL DEFAULT '',
url text NOT NULL DEFAULT '',
type text NOT NULL DEFAULT 'normal',
status text NOT NULL DEFAULT 'open',
me text,
app_version text,
added_at timestamptz NOT NULL DEFAULT now(),
first_seen_at timestamptz NOT NULL DEFAULT now(),
opened_at timestamptz,
closed_at timestamptz,
end_time timestamptz,
final_price numeric(10,2),
winner_user text,
won_by_me boolean NOT NULL DEFAULT false,
outcome text,
final_status text,
mode_at_close text,
bid_increment numeric(10,2) NOT NULL DEFAULT 0.01,
bid_fee numeric(10,4),
shipping numeric(10,2),
transaction_fee numeric(10,2),
buy_now_price numeric(10,2),
market_value numeric(10,2),
has_win_limit boolean NOT NULL DEFAULT false,
win_limit text,
my_bids int NOT NULL DEFAULT 0,
my_bids_cost numeric(10,2),
winner_bids_paid int,
winner_bids_free int,
resets int NOT NULL DEFAULT 0,
distinct_bidders int NOT NULL DEFAULT 0,
total_observed_bids int NOT NULL DEFAULT 0,
top_bidder_share double precision,
observed_from_start boolean NOT NULL DEFAULT false,
observed_to_end boolean NOT NULL DEFAULT false,
observed_minutes double precision,
avg_ping_ms double precision,
p95_ping_ms double precision,
p99_ping_ms double precision,
polls int NOT NULL DEFAULT 0,
poll_errors int NOT NULL DEFAULT 0,
configured_lead_ms int,
lead_is_manual boolean NOT NULL DEFAULT false,
timer_expired int NOT NULL DEFAULT 0,
successful_bids int NOT NULL DEFAULT 0,
failed_bids int NOT NULL DEFAULT 0,
price_velocity_per_minute double precision,
price_series jsonb,
bids_by_user jsonb,
config jsonb,
abandon_reason text,
learned_at timestamptz,
loss_reason text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_auctions_end ON auctions (end_time);
CREATE INDEX IF NOT EXISTS ix_auctions_product ON auctions (product_key);
CREATE INDEX IF NOT EXISTS ix_auctions_pending ON auctions (end_time) WHERE outcome IS NOT NULL AND learned_at IS NULL;
-- Ogni puntata di chiunque, come la riporta Bidoo. Il prezzo dopo la puntata la identifica
-- dentro l'asta (ogni puntata alza il prezzo di un centesimo): i doppioni li evita il
-- registratore, perché su una tabella partizionata l'unicità dovrebbe includere created_at.
CREATE TABLE IF NOT EXISTS bids (
bid_id bigserial,
auction_id text NOT NULL,
username text NOT NULL,
price_after numeric(10,2) NOT NULL,
bid_type text NOT NULL DEFAULT '',
is_mine boolean NOT NULL DEFAULT false,
server_ts bigint,
seen_t double precision,
local_ts timestamptz,
timer_before double precision,
rtt_ms int,
clock_offset_ms int,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (bid_id, created_at)
) PARTITION BY RANGE (created_at);
CREATE INDEX IF NOT EXISTS ix_bids_auction_ts ON bids (auction_id, server_ts);
CREATE INDEX IF NOT EXISTS ix_bids_auction_price ON bids (auction_id, price_after);
-- Un reset del timer: chiude un ciclo, di cui si sa fin dove è sceso il cronometro.
CREATE TABLE IF NOT EXISTS resets (
reset_id bigserial,
auction_id text NOT NULL,
t double precision NOT NULL,
local_ts timestamptz,
reset_count int,
price numeric(10,2),
bidder text,
min_timer double precision,
cycle_seconds double precision,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (reset_id, created_at)
) PARTITION BY RANGE (created_at);
CREATE INDEX IF NOT EXISTS ix_resets_auction_t ON resets (auction_id, t);
-- Le nostre puntate: anticipo voluto e ottenuto, chi ha risposto e dopo quanto.
CREATE TABLE IF NOT EXISTS my_bids (
id bigserial PRIMARY KEY,
auction_id text NOT NULL REFERENCES auctions(auction_id) ON DELETE CASCADE,
t double precision NOT NULL,
local_ts timestamptz,
price numeric(10,2),
planned_lead_ms int,
actual_lead_ms double precision,
wait_error_ms double precision,
ping_ms int,
rtt_ms int,
success boolean NOT NULL DEFAULT false,
error text,
bids_used int,
remaining_bids int,
remaining_paid int,
remaining_free int,
decision_id bigint,
answered_after_s double precision,
answered_by text,
answered_type text,
unanswered boolean,
p_win double precision,
kind text,
manual boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_my_bids_auction ON my_bids (auction_id, t);
-- Ogni decisione del modello, in Osserva (shadow) come dal vivo, con le variabili complete
-- in state: è la materia del CSV dei dati del modello.
CREATE TABLE IF NOT EXISTS bot_decisions (
decision_id bigint NOT NULL,
auction_id text NOT NULL,
ts timestamptz NOT NULL,
t double precision,
price numeric(10,2),
timer double precision,
kind text,
action text NOT NULL DEFAULT 'NO-OP',
p_model double precision,
p_bandit double precision,
own_bid_factor double precision,
p_win double precision,
ev double precision,
bid_cost double precision,
value double precision,
outcome text,
reason_detail text,
state jsonb,
context_key text,
champion text,
model_version text,
alt_action text,
lead_ms int,
shadow boolean NOT NULL DEFAULT true,
executed boolean NOT NULL DEFAULT false,
has_my_bid boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (decision_id, created_at)
) PARTITION BY RANGE (created_at);
CREATE INDEX IF NOT EXISTS ix_decisions_auction_ts ON bot_decisions (auction_id, ts);
CREATE INDEX IF NOT EXISTS ix_decisions_ts ON bot_decisions (ts);
-- Previsione dell'asta e, alla chiusura, la realtà con gli errori.
CREATE TABLE IF NOT EXISTS auction_forecasts (
id bigserial PRIMARY KEY,
auction_id text NOT NULL REFERENCES auctions(auction_id) ON DELETE CASCADE,
ts timestamptz NOT NULL,
is_initial boolean NOT NULL DEFAULT false,
price_at double precision,
forecast_close double precision,
forecast_close_p10 double precision,
forecast_close_p90 double precision,
forecast_winner_bids double precision,
forecast_minutes double precision,
p_win_if_enter double precision,
ev_if_enter double precision,
basis jsonb,
actual_close double precision,
actual_winner_bids int,
actual_minutes double precision,
error_close double precision,
in_interval boolean,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_forecasts_auction ON auction_forecasts (auction_id, ts);
CREATE INDEX IF NOT EXISTS ix_forecasts_ts ON auction_forecasts (ts);
-- Chi punta: aggregato asta per asta alla chiusura.
CREATE TABLE IF NOT EXISTS bidders (
username text PRIMARY KEY,
first_seen timestamptz,
last_seen timestamptz,
n_auctions int NOT NULL DEFAULT 0,
n_bids int NOT NULL DEFAULT 0,
n_auto int NOT NULL DEFAULT 0,
n_manual int NOT NULL DEFAULT 0,
win_count int NOT NULL DEFAULT 0,
aggressiveness_score double precision,
profile_class text
);
-- Uscite ed entrate in euro per il gestore del rischio, e gli HALT.
CREATE TABLE IF NOT EXISTS risk_ledger (
id bigserial PRIMARY KEY,
ts timestamptz NOT NULL,
kind text NOT NULL,
amount_euro numeric(10,2) NOT NULL,
auction_id text,
note text
);
CREATE INDEX IF NOT EXISTS ix_ledger_ts ON risk_ledger (ts);
-- Scheda prodotto: paletti propri e valore reale scelti dall'utente, stellina «segui».
CREATE TABLE IF NOT EXISTS products (
product_key text PRIMARY KEY,
item_id bigint REFERENCES items(item_id),
bidoo_product_id int,
display_name text NOT NULL DEFAULT '',
max_price numeric(10,2),
max_bids int,
market_value numeric(10,2),
horizon_minutes int,
followed boolean NOT NULL DEFAULT false,
auto_state text,
quiet_hours boolean,
auto_added_count int NOT NULL DEFAULT 0,
added_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Aste già proposte dalla sorveglianza e aste tolte a mano: non tornano più da sole.
CREATE TABLE IF NOT EXISTS watched_products (
product_key text PRIMARY KEY,
proposed_auction_ids jsonb NOT NULL DEFAULT '[]',
removed_auction_ids jsonb NOT NULL DEFAULT '[]',
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Statistiche per prodotto ricalcolate a ogni asta chiusa.
CREATE TABLE IF NOT EXISTS product_stats (
product_key text PRIMARY KEY,
value jsonb NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
+300
View File
@@ -0,0 +1,300 @@
using System.Net.Sockets;
using BidooBidBot.Logging;
using Npgsql;
namespace BidooBidBot.Data;
/// <summary>Che cosa si può sacrificare per primo quando la coda è piena.</summary>
public enum WriteKind
{
Normal,
/// <summary>Righe di <c>bids</c>: le prime a essere scartate se il database resta giù a lungo.</summary>
Bid
}
/// <summary>
/// La coda di scrittura verso PostgreSQL: tutto ciò che il programma scrive passa di qui.
/// Il motore accoda e prosegue; un solo consumatore scrive a lotti (ogni 200 ms o 500
/// righe) in una transazione con un solo viaggio di rete.
///
/// <para><b>Database assente.</b> Un errore di connessione non perde nulla: il lotto torna
/// in testa e si riprova. La coda accumula fino a <see cref="Capacity"/> righe, poi scarta
/// le righe di <c>bids</c> più vecchie e lo dice. Da quanto il database manca lo dice
/// <see cref="DownSince"/>: chi supervisiona decide (60 s → tutte le aste in Osserva,
/// 10 minuti → motore fermo e schermata d'errore).</para>
///
/// <para><b>Istruzione sbagliata.</b> Un errore SQL non deve bloccare la coda per sempre:
/// il lotto si rifà riga per riga, la riga colpevole si scarta e finisce nel registro.</para>
/// </summary>
public sealed class WriteQueue : IAsyncDisposable
{
private sealed class Item
{
public required IReadOnlyList<(string Sql, object?[] Args)> Ops { get; init; }
public WriteKind Kind { get; init; }
public TaskCompletionSource<bool>? Done { get; init; }
}
private readonly NpgsqlDataSource? _dataSource;
private readonly AppLog? _log;
private readonly object _sync = new();
private readonly LinkedList<Item> _items = new();
private readonly SemaphoreSlim _signal = new(0, int.MaxValue);
private readonly CancellationTokenSource _stop = new();
private readonly Task _loop;
private int _rows;
private long _written;
private long _dropped;
private long _failed;
private DateTimeOffset _lastDropWarning = DateTimeOffset.MinValue;
private DateTimeOffset? _downSince;
public int Capacity { get; set; } = 100_000;
public int BatchRows { get; set; } = 500;
public TimeSpan FlushInterval { get; set; } = TimeSpan.FromMilliseconds(200);
/// <summary>Righe in attesa di essere scritte.</summary>
public int Pending { get { lock (_sync) return _rows; } }
public long Written => Interlocked.Read(ref _written);
public long Dropped => Interlocked.Read(ref _dropped);
public long Failed => Interlocked.Read(ref _failed);
/// <summary>Da quando il database non accetta scritture; null se va tutto bene.</summary>
public DateTimeOffset? DownSince { get { lock (_sync) return _downSince; } }
public string? LastError { get; private set; }
/// <summary>
/// Una coda senza database (<paramref name="dataSource"/> null) accumula e basta: serve
/// ai test e al simulatore, dove niente deve finire nell'archivio vero.
/// </summary>
public WriteQueue(NpgsqlDataSource? dataSource, AppLog? log = null)
{
_dataSource = dataSource;
_log = log;
_loop = dataSource == null ? Task.CompletedTask : Task.Run(LoopAsync);
}
public void Enqueue(string sql, params object?[] args) =>
Add(new Item { Ops = new[] { (sql, args) }, Kind = WriteKind.Normal });
public void EnqueueBid(string sql, params object?[] args) =>
Add(new Item { Ops = new[] { (sql, args) }, Kind = WriteKind.Bid });
/// <summary>Più istruzioni che devono finire nella stessa transazione.</summary>
public void EnqueueGroup(IReadOnlyList<(string Sql, object?[] Args)> ops)
{
if (ops.Count > 0) Add(new Item { Ops = ops, Kind = WriteKind.Normal });
}
/// <summary>Accoda e aspetta che sia sul disco: per le poche scritture che l'utente attende (impostazioni).</summary>
public Task<bool> EnqueueAndWaitAsync(IReadOnlyList<(string Sql, object?[] Args)> ops, TimeSpan timeout)
{
if (_dataSource == null) return Task.FromResult(true);
var done = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
Add(new Item { Ops = ops, Kind = WriteKind.Normal, Done = done });
return done.Task.WaitAsync(timeout).ContinueWith(t => t.IsCompletedSuccessfully && t.Result, TaskScheduler.Default);
}
/// <summary>Aspetta che tutto ciò che è in coda adesso sia scritto (spegnimento, test).</summary>
public Task<bool> FlushAsync(TimeSpan timeout) =>
EnqueueAndWaitAsync(Array.Empty<(string, object?[])>(), timeout);
private void Add(Item item)
{
var warn = false;
lock (_sync)
{
_items.AddLast(item);
_rows += item.Ops.Count;
if (_rows > Capacity)
{
// Prima le righe di bids più vecchie, poi (solo se non ce ne sono) le altre.
var node = _items.First;
while (_rows > Capacity && node != null)
{
var next = node.Next;
if (node.Value.Kind == WriteKind.Bid && node.Value.Done == null) Drop(node);
node = next;
}
node = _items.First;
while (_rows > Capacity && node != null)
{
var next = node.Next;
if (node.Value.Done == null) Drop(node);
node = next;
}
if (DateTimeOffset.UtcNow - _lastDropWarning > TimeSpan.FromMinutes(1))
{
_lastDropWarning = DateTimeOffset.UtcNow;
warn = true;
}
}
}
if (warn)
_log?.Warn("DB", $"Coda di scrittura piena ({Capacity:N0} righe): scartate le puntate osservate più vecchie, {Dropped:N0} righe perse finora");
_signal.Release();
}
private void Drop(LinkedListNode<Item> node)
{
_items.Remove(node);
_rows -= node.Value.Ops.Count;
Interlocked.Add(ref _dropped, node.Value.Ops.Count);
}
private List<Item> TakeBatch()
{
var batch = new List<Item>();
lock (_sync)
{
var rows = 0;
while (_items.First != null && (rows == 0 || rows + _items.First.Value.Ops.Count <= BatchRows))
{
var item = _items.First.Value;
_items.RemoveFirst();
_rows -= item.Ops.Count;
rows += item.Ops.Count;
batch.Add(item);
}
}
return batch;
}
private void PutBack(List<Item> batch)
{
lock (_sync)
{
for (var i = batch.Count - 1; i >= 0; i--)
{
_items.AddFirst(batch[i]);
_rows += batch[i].Ops.Count;
}
}
}
private async Task LoopAsync()
{
var ct = _stop.Token;
var backoff = TimeSpan.FromSeconds(1);
while (true)
{
try { await _signal.WaitAsync(FlushInterval, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { /* allo spegnimento si svuota comunque */ }
while (true)
{
var batch = TakeBatch();
if (batch.Count == 0) break;
try
{
await WriteAsync(batch).ConfigureAwait(false);
Complete(batch, true);
lock (_sync) _downSince = null;
backoff = TimeSpan.FromSeconds(1);
}
catch (Exception ex) when (IsConnectivity(ex))
{
PutBack(batch);
LastError = ex.Message;
bool first;
lock (_sync) { first = _downSince == null; _downSince ??= DateTimeOffset.UtcNow; }
if (first) _log?.Error("DB", $"Database non raggiungibile, le scritture restano in coda: {ex.Message}");
if (ct.IsCancellationRequested) return; // spegnimento a database giù: resta in coda, si perde
try { await Task.Delay(backoff, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
backoff = TimeSpan.FromSeconds(Math.Min(10, backoff.TotalSeconds * 2));
break;
}
catch (Exception ex)
{
// Un'istruzione sbagliata nel lotto: si rifà una per una.
LastError = ex.Message;
await WriteOneByOneAsync(batch).ConfigureAwait(false);
}
}
if (ct.IsCancellationRequested && Pending == 0) return;
}
}
private async Task WriteAsync(List<Item> batch)
{
var commands = 0;
foreach (var item in batch) commands += item.Ops.Count;
if (commands == 0) return;
await using var conn = await _dataSource!.OpenConnectionAsync().ConfigureAwait(false);
await using var tx = await conn.BeginTransactionAsync().ConfigureAwait(false);
await using (var npgBatch = new NpgsqlBatch(conn, tx))
{
foreach (var item in batch)
foreach (var (sql, args) in item.Ops)
npgBatch.BatchCommands.Add(Db.BatchCommand(sql, args));
await npgBatch.ExecuteNonQueryAsync().ConfigureAwait(false);
}
await tx.CommitAsync().ConfigureAwait(false);
Interlocked.Add(ref _written, commands);
}
private async Task WriteOneByOneAsync(List<Item> batch)
{
foreach (var item in batch)
{
try
{
await WriteAsync(new List<Item> { item }).ConfigureAwait(false);
item.Done?.TrySetResult(true);
}
catch (Exception ex) when (IsConnectivity(ex))
{
// Il database è caduto a metà: il resto torna in coda.
PutBack(batch.SkipWhile(i => !ReferenceEquals(i, item)).ToList());
return;
}
catch (Exception ex)
{
Interlocked.Add(ref _failed, item.Ops.Count);
var sql = item.Ops.Count > 0 ? item.Ops[0].Sql : "";
var head = sql.Length > 80 ? sql[..80] + "..." : sql;
_log?.Error("DB", $"Scrittura scartata ({ex.Message}): {head}");
item.Done?.TrySetResult(false);
}
}
}
private static void Complete(List<Item> batch, bool ok)
{
foreach (var item in batch) item.Done?.TrySetResult(ok);
}
/// <summary>Errori che dicono «il database non c'è», non «l'istruzione è sbagliata».</summary>
public static bool IsConnectivity(Exception ex) => ex switch
{
NpgsqlException { IsTransient: true } => true,
PostgresException => false,
NpgsqlException n when n.InnerException is SocketException or IOException or TimeoutException => true,
SocketException or IOException or TimeoutException => true,
_ => ex.InnerException != null && IsConnectivity(ex.InnerException)
};
public async ValueTask DisposeAsync()
{
await _stop.CancelAsync().ConfigureAwait(false);
_signal.Release();
try { await _loop.WaitAsync(TimeSpan.FromSeconds(8)).ConfigureAwait(false); }
catch { /* spegnimento best-effort */ }
_stop.Dispose();
}
}
@@ -0,0 +1,19 @@
using BidooBidBot.Web;
namespace BidooBidBot.Host;
public sealed partial class Bot
{
public WebSocketHub Hub { get; } = new();
/// <summary>Avvia i servizi dopo impostazioni e documenti. Cresce milestone dopo milestone.</summary>
private Task StartServicesAsync(CancellationToken ct) => Task.CompletedTask;
private Task StopServicesAsync() => Task.CompletedTask;
private void OnDatabaseDown(TimeSpan elapsed) =>
Log.Error("DB", $"Database non raggiungibile da {elapsed.TotalSeconds:N0} s");
/// <summary>Le voci di /salute oltre al database.</summary>
public IEnumerable<KeyValuePair<string, object?>> HealthDetails() => Array.Empty<KeyValuePair<string, object?>>();
}
+118
View File
@@ -0,0 +1,118 @@
using BidooBidBot.Config;
using BidooBidBot.Data;
using BidooBidBot.Logging;
using BidooBidBot.Settings;
namespace BidooBidBot.Host;
/// <summary>
/// I servizi del bot in funzione: nasce quando le verifiche d'avvio passano e muore allo
/// spegnimento o dopo 10 minuti di database assente. È la radice di composizione: qui si
/// vede chi dipende da chi.
/// </summary>
public sealed partial class Bot : IAsyncDisposable
{
private readonly CancellationTokenSource _life = new();
public BotHost Host { get; }
public Db Db { get; }
public WriteQueue Queue { get; }
public DocumentStore Documents { get; }
public SettingsStore Settings { get; }
public AppLog Log => Host.Log;
public ConfigPaths Paths => Host.Paths;
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
/// <summary>Si spegne tutto: il token dei lavori di fondo.</summary>
public CancellationToken Lifetime => _life.Token;
private Bot(BotHost host, Db db)
{
Host = host;
Db = db;
Queue = new WriteQueue(db.Writer, host.Log);
Documents = new DocumentStore(Queue);
Settings = new SettingsStore(Queue, host.Log);
}
public static async Task<Bot> StartAsync(BotHost host, Db db, CancellationToken ct)
{
var bot = new Bot(host, db);
try
{
host.SetStartingStep("impostazioni e documenti");
await bot.Settings.LoadAsync(db).ConfigureAwait(false);
await bot.Documents.LoadAsync(db).ConfigureAwait(false);
bot.ApplyLogSettings(bot.Settings.Current);
bot.Settings.Changed += bot.ApplyLogSettings;
await bot.StartServicesAsync(ct).ConfigureAwait(false);
host.Log.Info("AVVIO", $"{AppInfo.Name} {AppInfo.Version} pronto: database {db.Config.Describe()}, " +
$"modalità {(bot.Settings.Current.LiveBiddingEnabled ? "DAL VIVO" : "OSSERVA")}");
return bot;
}
catch
{
await bot.DisposeAsync().ConfigureAwait(false);
throw;
}
}
private void ApplyLogSettings(AppSettings s)
{
Log.MinLevel = AppLog.ParseLevel(s.MinLogLevel);
Log.Capacity = s.MaxGlobalLogLines;
Log.WriteToFile = s.WriteAppLog;
Telegram.TelegramCache.Write(Paths, s);
}
/// <summary>
/// Resta qui finché il processo non si spegne o il database non manca da più di dieci
/// minuti. Dopo un minuto di database assente tutte le aste passano in Osserva.
/// </summary>
public async Task<string> WaitForStopAsync(CancellationToken ct)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _life.Token);
var observeForced = false;
while (!linked.IsCancellationRequested)
{
try { await Task.Delay(TimeSpan.FromSeconds(5), linked.Token).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
var down = Queue.DownSince;
if (down == null)
{
observeForced = false;
continue;
}
var elapsed = DateTimeOffset.UtcNow - down.Value;
if (elapsed > TimeSpan.FromSeconds(60) && !observeForced)
{
observeForced = true;
OnDatabaseDown(elapsed);
}
if (elapsed > TimeSpan.FromMinutes(10))
return $"database non raggiungibile da {elapsed.TotalMinutes:N0} minuti";
}
return "spegnimento";
}
public async ValueTask DisposeAsync()
{
if (!_life.IsCancellationRequested) await _life.CancelAsync().ConfigureAwait(false);
try { await StopServicesAsync().ConfigureAwait(false); }
catch (Exception ex) { Log.Error("AVVIO", $"Spegnimento dei servizi incompleto: {ex.Message}"); }
await Queue.FlushAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
await Queue.DisposeAsync().ConfigureAwait(false);
await Db.DisposeAsync().ConfigureAwait(false);
_life.Dispose();
}
}
+191
View File
@@ -0,0 +1,191 @@
using BidooBidBot.Config;
using BidooBidBot.Data;
using BidooBidBot.Logging;
using BidooBidBot.Web;
namespace BidooBidBot.Host;
public enum HostState
{
/// <summary>Verifiche in corso (primo avvio o nuovo tentativo).</summary>
Checking,
/// <summary>Configurazione o database non a posto: solo la schermata d'errore.</summary>
ConfigError,
/// <summary>Verifiche passate, servizi in partenza.</summary>
Starting,
Running,
Stopping
}
/// <summary>
/// Il ciclo di vita del processo (specifica §10.3). Il server web parte subito e mostra,
/// secondo lo stato, la schermata d'errore oppure l'applicazione. Le verifiche si ripetono
/// ogni 30 secondi (o subito con «Riprova adesso»): all'accensione di Unraid il bot può
/// partire prima del container PostgreSQL, e deve aspettarlo invece di morire.
///
/// <para>Anche a metà esecuzione: se il database manca da più di 10 minuti il motore si
/// ferma, i servizi si chiudono e si torna qui, alla schermata d'errore.</para>
/// </summary>
public sealed class BotHost : IAsyncDisposable
{
/// <summary>
/// Con la configurazione sbagliata: uscire con codice d'errore invece di riprovare (D2).
/// Di fabbrica si riprova, perché regge l'ordine di avvio dei container su Unraid.
/// </summary>
public static readonly bool ExitOnConfigError = false;
public static readonly TimeSpan RetryInterval = TimeSpan.FromSeconds(30);
private readonly SemaphoreSlim _retrySignal = new(0, 1);
private volatile HostState _state = HostState.Checking;
public EnvConfig Env { get; }
public ConfigPaths Paths { get; }
public AppLog Log { get; }
public FileLog? FileLog { get; }
/// <summary>Accesso all'interfaccia; null se UI_PASSWORD manca (e allora c'è la schermata d'errore).</summary>
public UiAuth? Auth { get; private set; }
public HostState State => _state;
public StartupReport? LastReport { get; private set; }
public DateTimeOffset NextRetryAt { get; private set; }
public string StartingStep { get; private set; } = "verifiche";
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
/// <summary>I servizi in funzione; null fuori dallo stato Running.</summary>
public Bot? Bot { get; private set; }
/// <summary>Chiamata quando il processo deve uscire (errore di configurazione con uscita chiesta).</summary>
public int? ExitCode { get; private set; }
public BotHost(EnvConfig env, ConfigPaths paths, AppLog log, FileLog? fileLog)
{
Env = env;
Paths = paths;
Log = log;
FileLog = fileLog;
if (env.HasUiPassword)
{
try { Auth = new UiAuth(env.UiPassword!, UiAuth.LoadOrCreateKey(Path.Combine(paths.Session, "interfaccia.key"))); }
catch (Exception ex) { log.Error("ACCESSO", $"Chiave dei cookie dell'interfaccia non disponibile: {ex.Message}"); }
}
}
/// <summary>«Riprova adesso» dalla schermata d'errore.</summary>
public void RequestRetry()
{
try { _retrySignal.Release(); }
catch (SemaphoreFullException) { /* già chiesto */ }
}
public void SetStartingStep(string step) => StartingStep = step;
public async Task RunAsync(CancellationToken ct)
{
var attempt = 0;
var outageNotified = false;
while (!ct.IsCancellationRequested)
{
attempt++;
_state = HostState.Checking;
StartingStep = "verifiche della configurazione";
var (report, db) = await StartupCheck.RunAsync(Env, Paths, attempt, ct).ConfigureAwait(false);
// La password dell'interfaccia manca: anche con il database a posto non si parte.
if (report.AllOk && Auth == null)
{
report.Items.Add(new CheckItem("ui_key", false, "Accesso all'interfaccia non disponibile", Paths.Session,
"La chiave dei cookie non si può scrivere nella cartella della sessione.", null));
}
LastReport = report;
if (!report.AllOk || db == null)
{
if (db != null) await db.DisposeAsync().ConfigureAwait(false);
_state = HostState.ConfigError;
var problem = report.FirstProblem;
if (attempt == 1 || attempt % 10 == 0)
Log.Error("AVVIO", $"Il bot non può partire: {problem?.Title} ({problem?.Error}). Nuovo tentativo ogni {RetryInterval.TotalSeconds:N0} s");
if (!outageNotified && problem?.Key == "database")
{
outageNotified = true;
Telegram.TelegramCache.TrySendOffline(Paths, Log,
"Bidoo BidBot: database non raggiungibile",
$"{problem.Error}. Il motore è fermo; il bot riprova ogni 30 secondi.");
}
if (ExitOnConfigError)
{
ExitCode = 2;
return;
}
NextRetryAt = DateTimeOffset.UtcNow + RetryInterval;
try { await _retrySignal.WaitAsync(RetryInterval, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
continue;
}
_state = HostState.Starting;
Bot? bot = null;
try
{
bot = await Bot.StartAsync(this, db, ct).ConfigureAwait(false);
Bot = bot;
_state = HostState.Running;
outageNotified = false;
attempt = 0;
}
catch (OperationCanceledException)
{
if (bot != null) await bot.DisposeAsync().ConfigureAwait(false);
else await db.DisposeAsync().ConfigureAwait(false);
return;
}
catch (Exception ex)
{
Log.Error("AVVIO", $"Avvio dei servizi non riuscito: {ex.Message}");
if (bot != null) await bot.DisposeAsync().ConfigureAwait(false);
else await db.DisposeAsync().ConfigureAwait(false);
var failed = new StartupReport { Attempt = attempt };
failed.Items.AddRange(report.Items);
failed.Items.Add(new CheckItem("startup", false, "Avvio dei servizi non riuscito", null, ex.Message, null));
LastReport = failed;
_state = HostState.ConfigError;
NextRetryAt = DateTimeOffset.UtcNow + RetryInterval;
try { await _retrySignal.WaitAsync(RetryInterval, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
continue;
}
// In funzione finché non si spegne il processo o il database manca da troppo.
var reason = await bot.WaitForStopAsync(ct).ConfigureAwait(false);
_state = HostState.Stopping;
Bot = null;
await bot.DisposeAsync().ConfigureAwait(false);
if (ct.IsCancellationRequested) return;
Log.Error("AVVIO", $"Motore fermato: {reason}. Torno alle verifiche della configurazione");
}
}
public async ValueTask DisposeAsync()
{
var bot = Bot;
Bot = null;
if (bot != null) await bot.DisposeAsync().ConfigureAwait(false);
}
}
+114
View File
@@ -0,0 +1,114 @@
using System.Globalization;
namespace BidooBidBot.Logging;
public enum LogLevel
{
Debug = 0,
Info = 1,
Success = 2,
Warning = 3,
Error = 4
}
/// <summary>Una riga del registro applicativo.</summary>
/// <param name="Tag">Il prefisso fra quadre, senza quadre: PUNTATA, FINE, SESSIONE...</param>
public sealed record LogEntry(long Id, DateTimeOffset Ts, LogLevel Level, string Tag, string Message, string? AuctionId)
{
/// <summary>La riga come sta sul file e a video: <c>[TAG] messaggio</c>.</summary>
public string Text => Tag.Length > 0 ? $"[{Tag}] {Message}" : Message;
}
/// <summary>
/// Il registro applicativo: una riga per evento, prefisso fra quadre, tutto da
/// <see cref="LogText.Clean"/>. Vive in memoria (anello per l'interfaccia) e su file
/// (<c>app-AAAA-MM-GG.log</c>); non va nel database.
///
/// <para>Chi ascolta (il WebSocket) riceve la riga con un evento: l'ascoltatore deve
/// accodare e tornare subito, perché l'evento parte dal thread di chi scrive.</para>
/// </summary>
public sealed class AppLog
{
private readonly FileLog? _file;
private readonly object _sync = new();
private readonly LinkedList<LogEntry> _ring = new();
private long _nextId;
/// <summary>Righe tenute in memoria per l'interfaccia (impostazione MaxGlobalLogLines).</summary>
public int Capacity { get; set; } = 1000;
/// <summary>Sotto questo livello la riga non si scrive affatto.</summary>
public LogLevel MinLevel { get; set; } = LogLevel.Info;
/// <summary>Scrivere anche su file (impostazione WriteAppLog).</summary>
public bool WriteToFile { get; set; } = true;
/// <summary>Ripetere le righe sull'uscita standard, per <c>docker logs</c>.</summary>
public bool EchoToConsole { get; set; }
public event Action<LogEntry>? Entry;
public AppLog(FileLog? file) => _file = file;
public void Write(LogLevel level, string tag, string message, string? auctionId = null)
{
if (level < MinLevel) return;
var entry = new LogEntry(Interlocked.Increment(ref _nextId), DateTimeOffset.Now, level,
LogText.Clean(tag).ToUpperInvariant(), LogText.Clean(message), auctionId);
lock (_sync)
{
_ring.AddLast(entry);
while (_ring.Count > Math.Max(50, Capacity)) _ring.RemoveFirst();
}
var local = entry.Ts.LocalDateTime;
var line = $"{local.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)} {LevelCode(level)} {entry.Text}";
if (WriteToFile && _file != null) _file.Write("app", local, line);
if (EchoToConsole)
{
if (_file != null) _file.Write(FileLog.ConsoleKind, local, line);
else Console.Out.WriteLine(line);
}
try { Entry?.Invoke(entry); }
catch { /* un ascoltatore rotto non deve fermare chi scrive */ }
}
public void Debug(string tag, string message, string? auctionId = null) => Write(LogLevel.Debug, tag, message, auctionId);
public void Info(string tag, string message, string? auctionId = null) => Write(LogLevel.Info, tag, message, auctionId);
public void Success(string tag, string message, string? auctionId = null) => Write(LogLevel.Success, tag, message, auctionId);
public void Warn(string tag, string message, string? auctionId = null) => Write(LogLevel.Warning, tag, message, auctionId);
public void Error(string tag, string message, string? auctionId = null) => Write(LogLevel.Error, tag, message, auctionId);
/// <summary>Le ultime righe, dalla più vecchia alla più recente.</summary>
public IReadOnlyList<LogEntry> Snapshot(int max = 0)
{
lock (_sync)
{
var skip = max > 0 && _ring.Count > max ? _ring.Count - max : 0;
return _ring.Skip(skip).ToList();
}
}
/// <summary>Livello dal nome usato nelle impostazioni («Normal» è il vecchio nome di Info).</summary>
public static LogLevel ParseLevel(string? name) => (name ?? "").Trim().ToLowerInvariant() switch
{
"debug" or "trace" => LogLevel.Debug,
"warning" or "warn" => LogLevel.Warning,
"error" or "erroronly" => LogLevel.Error,
_ => LogLevel.Info
};
public static string LevelCode(LogLevel level) => level switch
{
LogLevel.Debug => "DBG ",
LogLevel.Success => "OK ",
LogLevel.Warning => "WARN",
LogLevel.Error => "ERR ",
_ => "INFO"
};
}
+106
View File
@@ -0,0 +1,106 @@
using System.Globalization;
using System.Text;
using System.Threading.Channels;
namespace BidooBidBot.Logging;
/// <summary>
/// Scrittura dei registri su file, un file per giorno e per tipo
/// (<c>app-AAAA-MM-GG.log</c>, <c>aste-AAAA-MM-GG.log</c>) in <c>/config/registri</c>.
///
/// <para>Nessuna scrittura sincrona: chi registra accoda e prosegue, un solo consumatore
/// scrive in fondo. Il motore non aspetta mai il disco. Con la coda piena (20.000 righe) le
/// più vecchie si perdono: meglio un registro incompleto che la memoria esaurita durante
/// un'asta.</para>
/// </summary>
public sealed class FileLog : IAsyncDisposable
{
private readonly string _folder;
private readonly Channel<(string Kind, DateTime Day, string Line)> _queue;
private readonly Task _writer;
private readonly Dictionary<string, (DateTime Day, StreamWriter Writer)> _open = new(StringComparer.Ordinal);
public FileLog(string folder)
{
_folder = folder;
Directory.CreateDirectory(folder);
_queue = Channel.CreateBounded<(string, DateTime, string)>(new BoundedChannelOptions(20_000)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
SingleWriter = false
});
_writer = Task.Run(WriteLoopAsync);
}
public string Folder => _folder;
/// <summary>Il «tipo» che va sull'uscita standard invece che su file.</summary>
public const string ConsoleKind = "console";
/// <summary>Accoda una riga già pulita. Non blocca mai.</summary>
public void Write(string kind, DateTime localTime, string line) =>
_queue.Writer.TryWrite((kind, localTime.Date, line));
/// <summary>Il percorso del file di un giorno, per leggerlo o esportarlo.</summary>
public string PathFor(string kind, DateTime day) =>
System.IO.Path.Combine(_folder, $"{kind}-{day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.log");
private async Task WriteLoopAsync()
{
var reader = _queue.Reader;
try
{
while (await reader.WaitToReadAsync().ConfigureAwait(false))
{
while (reader.TryRead(out var item))
{
try
{
// «console» è l'uscita standard (docker logs): scritta anche lei qui,
// in fondo, così chi registra non aspetta mai il terminale.
if (item.Kind == ConsoleKind) Console.Out.WriteLine(item.Line);
else WriterFor(item.Kind, item.Day).WriteLine(item.Line);
}
catch { /* disco pieno o cartella sparita: si riprova alla riga dopo */ }
}
foreach (var (_, w) in _open.Values)
{
try { w.Flush(); } catch { }
}
}
}
finally
{
foreach (var (_, w) in _open.Values)
{
try { w.Dispose(); } catch { }
}
_open.Clear();
}
}
private StreamWriter WriterFor(string kind, DateTime day)
{
if (_open.TryGetValue(kind, out var current) && current.Day == day) return current.Writer;
if (current.Writer != null)
{
try { current.Writer.Dispose(); } catch { }
}
Directory.CreateDirectory(_folder);
var stream = new FileStream(PathFor(kind, day), FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
var writer = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = false };
_open[kind] = (day, writer);
return writer;
}
public async ValueTask DisposeAsync()
{
_queue.Writer.TryComplete();
try { await _writer.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); }
catch { /* chiusura best-effort */ }
}
}
@@ -0,0 +1,73 @@
using System.Text;
namespace BidooBidBot.Logging;
/// <summary>
/// Ripulisce una riga di registro: niente emoji, niente simboli tipografici, niente a capo.
/// Tutto ciò che finisce in un registro passa di qui, così la regola vale ovunque senza
/// doverla ricordare in ogni punto che scrive. Portato 1:1 dal legacy.
/// </summary>
public static class LogText
{
public static string Clean(string? message)
{
if (string.IsNullOrEmpty(message)) return "";
var sb = new StringBuilder(message.Length);
var previousSpace = false;
for (var i = 0; i < message.Length; i++)
{
var ch = message[i];
// Coppie surrogate: emoji e simboli fuori dal piano base. Si tolgono.
if (char.IsHighSurrogate(ch)) { i++; continue; }
if (char.IsLowSurrogate(ch)) continue;
string? replacement = ch switch
{
'\r' or '\n' or '\t' => " ",
'→' or '➔' or '⇒' => "->",
'←' => "<-",
'—' or '–' or '‒' => "-",
'…' => "...",
'≤' => "<=",
'≥' => ">=",
'×' => "x",
'−' => "-",
'•' or '·' or '●' or '○' => "-",
'✓' or '✔' or '✅' => "",
'⛔' or '❌' or '✖' or '⚠' or '⚡' or '⭐' or '❗' => "",
'️' => "",
'«' or '»' or '“' or '”' => "\"",
'‘' or '’' => "'",
'€' => "EUR",
' ' or ' ' => " ",
_ => null
};
if (replacement == null)
{
// Altri simboli fuori dall'alfabeto (frecce, dingbat, area privata).
if (ch >= '←' && ch <= '⯿' || ch >= '' && ch <= '') continue;
sb.Append(ch);
previousSpace = ch == ' ';
continue;
}
if (replacement == " ")
{
if (!previousSpace && sb.Length > 0) { sb.Append(' '); previousSpace = true; }
continue;
}
sb.Append(replacement);
previousSpace = false;
}
// Doppi spazi lasciati dai simboli tolti.
var text = sb.ToString();
while (text.Contains(" ", StringComparison.Ordinal)) text = text.Replace(" ", " ", StringComparison.Ordinal);
return text.Trim();
}
}
+79
View File
@@ -0,0 +1,79 @@
using System.Globalization;
using System.Runtime;
using BidooBidBot;
using BidooBidBot.Config;
using BidooBidBot.Host;
using BidooBidBot.Logging;
using BidooBidBot.Web;
// ── Sonda del HEALTHCHECK di Docker: nell'immagine non c'è curl ────────────────────
if (args.Contains("--salute"))
{
var port = Environment.GetEnvironmentVariable("PORT") is { Length: > 0 } p ? p : "8080";
try
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(8) };
using var response = await http.GetAsync($"http://127.0.0.1:{port}/salute");
return response.IsSuccessStatusCode ? 0 : 1;
}
catch
{
return 1;
}
}
// ── Numeri e date all'italiana, fuso del container ─────────────────────────────────
CultureInfo.DefaultThreadCurrentCulture = AppInfo.Italian;
CultureInfo.DefaultThreadCurrentUICulture = AppInfo.Italian;
CultureInfo.CurrentCulture = AppInfo.Italian;
CultureInfo.CurrentUICulture = AppInfo.Italian;
GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
var env = EnvConfig.Read(Environment.GetEnvironmentVariable, args);
try { AppInfo.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(env.TimeZone); }
catch { AppInfo.TimeZone = TimeZoneInfo.Local; }
var paths = new ConfigPaths(env.ConfigDir);
FileLog? fileLog = null;
try
{
paths.EnsureAll();
fileLog = new FileLog(paths.Logs);
File.WriteAllText(paths.VersionFile, AppInfo.Version + Environment.NewLine);
}
catch
{
// /config non scrivibile: lo dirà la schermata d'errore; il registro resta in memoria.
}
var log = new AppLog(fileLog) { EchoToConsole = true };
log.Info("AVVIO", $"{AppInfo.Name} {AppInfo.Version}, .NET {Environment.Version}, {Environment.OSVersion}, " +
$"cartella dati {paths.Root}, interfaccia sulla porta {env.HttpPort}");
await using var host = new BotHost(env, paths, log, fileLog);
var app = WebServer.Build(host);
using var shutdown = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); };
AppDomain.CurrentDomain.ProcessExit += (_, _) => { try { shutdown.Cancel(); } catch (ObjectDisposedException) { } };
await app.StartAsync(shutdown.Token);
log.Info("AVVIO", $"Interfaccia in ascolto su http://0.0.0.0:{env.HttpPort}");
try
{
await host.RunAsync(shutdown.Token);
}
finally
{
// Spegnimento ordinato entro 10 s (specifica §10.2): svuota la coda, chiude i motori,
// salva i modelli. Poi il web, poi i registri.
log.Info("AVVIO", "Spegnimento in corso");
using var grace = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try { await host.DisposeAsync().AsTask().WaitAsync(grace.Token); } catch { }
try { await app.StopAsync(grace.Token); } catch { }
log.Info("AVVIO", "Spento");
if (fileLog != null) await fileLog.DisposeAsync();
}
return host.ExitCode ?? 0;
@@ -0,0 +1,192 @@
namespace BidooBidBot.Settings;
/// <summary>
/// Tutte le impostazioni del bot, con i valori di fabbrica del legacy (specifica,
/// Appendice F). Si salvano in una riga <c>jsonb</c> della tabella <c>settings</c> e valgono
/// subito, senza riavvio: il motore rilegge <see cref="SettingsStore.Current"/> a ogni ciclo.
///
/// <para>Tutti i paletti dell'utente sono a zero di fabbrica, cioè nessun limite. Il
/// modello è l'unico decisore; i paletti sono solo quello che l'utente vuole garantirsi.</para>
///
/// <para>I nomi delle proprietà sono le chiavi JSON (e le chiavi dei messaggi
/// <c>settings.save</c>): cambiarne uno vuol dire scrivere una migrazione in
/// <see cref="SettingsStore.Migrate"/>.</para>
/// </summary>
public sealed class AppSettings
{
/// <summary>Versione dello schema delle impostazioni, per le migrazioni una tantum.</summary>
public int SettingsSchemaVersion { get; set; }
// ── Paletti dell'utente (0 = nessun limite) ──────────────────────────
/// <summary>Prezzo massimo per le aste nuove, se il prodotto non ne ha uno suo.</summary>
public double DefaultMaxPrice { get; set; }
/// <summary>Puntate massime per le aste nuove, se il prodotto non ne ha uno suo.</summary>
public int DefaultMaxClicks { get; set; }
/// <summary>Tetto di puntate del motore su una singola asta in questa sessione.</summary>
public int MaxBidsPerAuction { get; set; }
/// <summary>Tetto di puntate del motore in tutta la sessione (dall'avvio del processo).</summary>
public int MaxBidsPerSession { get; set; }
/// <summary>Sotto questo saldo (pagate + gratis) il motore non punta.</summary>
public int MinimumRemainingBids { get; set; }
/// <summary>Sospendere le puntate nella fascia oraria. Di fabbrica spento (il legacy aveva 0-10).</summary>
public bool QuietHoursEnabled { get; set; }
public int QuietHoursStart { get; set; }
public int QuietHoursEnd { get; set; } = 10;
// ── Gestione del rischio (0 = nessun limite) ─────────────────────────
public double DailyBudgetEuro { get; set; }
public double DailyStopLossEuro { get; set; }
public double MaxDrawdownEuro { get; set; }
public int MaxConcurrentActiveAuctions { get; set; }
// ── Modalità ─────────────────────────────────────────────────────────
/// <summary>
/// Puntate dal vivo. Spento = OSSERVA: il bot decide e registra ma non punta mai.
/// Si accende solo con la conferma in due passi (interruttore + parola DAL VIVO).
/// </summary>
public bool LiveBiddingEnabled { get; set; }
/// <summary>Costo di una puntata a pagamento; quello che entra nel valore atteso è scalato per la quota di pagate.</summary>
public double AverageBidCostEuro { get; set; } = 0.20;
public double TransactionFeeEuro { get; set; } = 1.00;
/// <summary>Considerare il «Compralo Ora» come copertura (solo con valore reale scritto dall'utente).</summary>
public bool BuyNowHedgeEnabled { get; set; } = true;
/// <summary>Spento, il motore punta entro i paletti senza consultare il modello.</summary>
public bool LearningEnabled { get; set; } = true;
// ── Apprendimento ────────────────────────────────────────────────────
public int LearningMinAuctions { get; set; } = 300;
public int ExplorationBidsPerDay { get; set; } = 20;
public int LearningBootstrapSecondsPerStart { get; set; } = 120;
public bool AdaptiveLeadEnabled { get; set; } = true;
public int LeadMinMs { get; set; } = 300;
public int LeadMaxMs { get; set; } = 1500;
/// <summary>Anticipo fisso quando l'adattivo è spento (e punto di partenza senza misure).</summary>
public int DefaultBidBeforeDeadlineMs { get; set; } = 500;
/// <summary>La previsione dell'asta si rifà ogni tanti rilanci...</summary>
public int ForecastRefreshBids { get; set; } = 25;
/// <summary>...o ogni tanti minuti, il primo che arriva.</summary>
public int ForecastRefreshMinutes { get; set; } = 5;
// ── Motore e rete ────────────────────────────────────────────────────
/// <summary>Tetto di richieste al secondo verso Bidoo (0 = nessuno). Non vale per bid.php.</summary>
public double MaxRequestsPerSecond { get; set; } = 40;
/// <summary>Cadenza del polling con più di 60 s sul cronometro.</summary>
public int PollFarMs { get; set; } = 2000;
/// <summary>Cadenza fra 10 e 60 s.</summary>
public int PollMidMs { get; set; } = 900;
/// <summary>Cadenza sotto i 10 s.</summary>
public int PollNearMs { get; set; } = 400;
/// <summary>Cadenza nella finestra critica (sotto i 4 s, solo aste in Attiva).</summary>
public int PollCriticalMs { get; set; } = 220;
/// <summary>Attesa di precisione (sonno fino a 4 ms, poi attesa attiva). Spenta = solo sonno.</summary>
public bool PrecisionTimerEnabled { get; set; } = true;
public bool ScheduledAuctionBackoffEnabled { get; set; } = true;
public int ScheduledPollFarSeconds { get; set; } = 1200;
public int ScheduledPollMidSeconds { get; set; } = 120;
public int ScheduledPollWakeSeconds { get; set; } = 120;
public bool ShowLateBidWarning { get; set; } = true;
// ── Aste ─────────────────────────────────────────────────────────────
/// <summary>Modo delle aste in elenco al riavvio del bot: Ferma, Osserva o Attiva.</summary>
public string DefaultStartAuctionsOnLoad { get; set; } = "Ferma";
/// <summary>Modo iniziale proposto per un'asta aggiunta a mano.</summary>
public string DefaultNewAuctionState { get; set; } = "Osserva";
/// <summary>Al riavvio ogni asta riprende il suo modo, invece di <see cref="DefaultStartAuctionsOnLoad"/>.</summary>
public bool RememberAuctionStates { get; set; }
public bool AutoRemoveFinished { get; set; } = true;
public bool AutoRemoveKeepWithMyBids { get; set; } = true;
public bool AutoRemoveKeepWon { get; set; } = true;
public bool AutoRemoveKeepEndedWhileActive { get; set; } = true;
public int MaxBidHistoryEntries { get; set; } = 20;
public int MaxLogLinesPerAuction { get; set; } = 500;
public int MaxGlobalLogLines { get; set; } = 1000;
public string MinLogLevel { get; set; } = "Normal";
/// <summary>Colonna «Previsione» nella griglia delle aste (D14: spenta, solo pannello).</summary>
public bool ShowForecastColumn { get; set; }
// ── Catalogo ─────────────────────────────────────────────────────────
public int CatalogCacheSeconds { get; set; } = 60;
public int CatalogMaxAuctions { get; set; } = 500;
public bool CatalogAutoRefresh { get; set; }
public bool CatalogShowImages { get; set; }
// ── Prodotti seguiti ─────────────────────────────────────────────────
public bool AutoAddProductsEnabled { get; set; } = true;
public int AutoAddScanSeconds { get; set; } = 90;
public int AutoAddScanMaxAuctions { get; set; } = 2500;
public string AutoAddNewAuctionState { get; set; } = "Osserva";
public int AutoAddMaxAuctions { get; set; } = 20;
public int AutoAddMaxStartMinutes { get; set; } = 60;
public bool AutoAddOnlyNotStarted { get; set; }
// ── Limiti consigliati per prodotto (solo consiglio, mai applicati da soli) ─
/// <summary>Quota di chiusure passate che il prezzo massimo consigliato copre.</summary>
public int SuggestedCoveragePercent { get; set; } = 85;
/// <summary>Quanto oltre il valore reale può arrivare il costo totale consigliato.</summary>
public int SuggestedValueTolerancePercent { get; set; } = 10;
/// <summary>Percentile delle chiusure sotto il quale l'asta non si chiude quasi mai (solo spiegazione).</summary>
public int SuggestedMinPercentile { get; set; } = 10;
// ── Telegram ─────────────────────────────────────────────────────────
public string TelegramBotToken { get; set; } = "";
public string TelegramChatId { get; set; } = "";
public bool TelegramNotifyWin { get; set; } = true;
public bool TelegramNotifyLoss { get; set; }
public bool TelegramNotifySession { get; set; } = true;
public bool TelegramNotifyRisk { get; set; } = true;
/// <summary>Riepilogo periodico in minuti; 0 = mai.</summary>
public int TelegramSummaryMinutes { get; set; } = 60;
/// <summary>Comandi in ingresso (/stato, /halt, /riprendi, /osserva) dal solo chat id configurato.</summary>
public bool TelegramCommandsEnabled { get; set; }
// ── Dati e conservazione ─────────────────────────────────────────────
public double DataCapGb { get; set; } = 50;
public int LogRetentionDays { get; set; } = 90;
public int BackupRetentionDays { get; set; } = 14;
public bool WriteAppLog { get; set; } = true;
public bool RecordAuctions { get; set; } = true;
public int ExportMaxRows { get; set; } = 5000;
// ── Aspetto (predefiniti per un browser nuovo: ogni browser ricorda le sue scelte) ─
public bool DarkMode { get; set; } = true;
public bool NavCollapsed { get; set; }
}
@@ -0,0 +1,297 @@
using System.Globalization;
using System.Reflection;
using System.Text.Json;
using BidooBidBot.Data;
using BidooBidBot.Logging;
namespace BidooBidBot.Settings;
/// <summary>
/// Le impostazioni in una riga <c>settings.value jsonb</c>, con una copia in memoria letta
/// senza lucchetto (il motore la legge a ogni ciclo di ogni asta). Ogni salvataggio vale
/// subito e scrive nel registro «[IMPOSTAZIONI] campo: prima -> dopo».
/// </summary>
public sealed class SettingsStore
{
/// <summary>Schema corrente. Alzarlo fa girare <see cref="Migrate"/> una volta sola.</summary>
public const int CurrentSchema = 1;
/// <summary>La parola da scrivere per accendere le puntate dal vivo.</summary>
public const string LiveConfirmationWord = "DAL VIVO";
private static readonly JsonSerializerOptions Json = new() { WriteIndented = false };
private static readonly PropertyInfo[] Properties = typeof(AppSettings)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && p.CanWrite)
.ToArray();
private volatile AppSettings _current = Normalize(new AppSettings { SettingsSchemaVersion = CurrentSchema });
private readonly WriteQueue? _queue;
private readonly AppLog? _log;
private readonly SemaphoreSlim _saveGate = new(1, 1);
public SettingsStore(WriteQueue? queue, AppLog? log)
{
_queue = queue;
_log = log;
}
/// <summary>Le impostazioni in vigore. Non modificarle: sono condivise; si salva con <see cref="SaveAsync"/>.</summary>
public AppSettings Current => _current;
/// <summary>Scatta dopo ogni salvataggio riuscito, con le impostazioni nuove.</summary>
public event Action<AppSettings>? Changed;
/// <summary>Legge la riga delle impostazioni; se non c'è la crea con i valori di fabbrica.</summary>
public async Task LoadAsync(Db db)
{
var json = await db.ScalarAsync<string>("SELECT value::text FROM settings WHERE id = 1").ConfigureAwait(false);
if (json == null)
{
var fresh = Normalize(new AppSettings { SettingsSchemaVersion = CurrentSchema });
await db.ExecuteAsync("INSERT INTO settings(id, value) VALUES(1, $1) ON CONFLICT(id) DO NOTHING",
new Jsonb(JsonSerializer.Serialize(fresh, Json))).ConfigureAwait(false);
_current = fresh;
return;
}
var loaded = Parse(json);
if (Migrate(loaded))
{
await db.ExecuteAsync("UPDATE settings SET value = $1, updated_at = now() WHERE id = 1",
new Jsonb(JsonSerializer.Serialize(loaded, Json))).ConfigureAwait(false);
}
_current = Normalize(loaded);
}
/// <summary>Solo per test e simulatore: impostazioni in memoria.</summary>
public void SetForTests(AppSettings settings) => _current = Normalize(settings);
public static AppSettings Parse(string json)
{
try { return JsonSerializer.Deserialize<AppSettings>(json, Json) ?? new AppSettings(); }
catch (JsonException) { return new AppSettings(); }
}
/// <summary>
/// Porta avanti una riga scritta da una versione precedente. Restituisce true se
/// qualcosa è cambiato. Si tocca solo ciò che era un valore di fabbrica sbagliato, mai
/// una scelta dell'utente.
/// </summary>
public static bool Migrate(AppSettings s)
{
if (s.SettingsSchemaVersion >= CurrentSchema) return false;
// Schema 0 -> 1: nomi dei modi dal legacy (inglese) all'italiano.
s.DefaultStartAuctionsOnLoad = NormalizeMode(s.DefaultStartAuctionsOnLoad, "Ferma");
s.DefaultNewAuctionState = NormalizeMode(s.DefaultNewAuctionState, "Osserva");
s.AutoAddNewAuctionState = NormalizeMode(s.AutoAddNewAuctionState, "Osserva");
s.SettingsSchemaVersion = CurrentSchema;
return true;
}
/// <summary>Riporta ogni valore nel suo intervallo sensato. Non si fida di ciò che arriva dall'interfaccia.</summary>
public static AppSettings Normalize(AppSettings s)
{
s.DefaultMaxPrice = Math.Max(0, s.DefaultMaxPrice);
s.DefaultMaxClicks = Math.Max(0, s.DefaultMaxClicks);
s.MaxBidsPerAuction = Math.Max(0, s.MaxBidsPerAuction);
s.MaxBidsPerSession = Math.Max(0, s.MaxBidsPerSession);
s.MinimumRemainingBids = Math.Max(0, s.MinimumRemainingBids);
s.QuietHoursStart = ((s.QuietHoursStart % 24) + 24) % 24;
s.QuietHoursEnd = ((s.QuietHoursEnd % 24) + 24) % 24;
s.DailyBudgetEuro = Math.Max(0, s.DailyBudgetEuro);
s.DailyStopLossEuro = Math.Max(0, s.DailyStopLossEuro);
s.MaxDrawdownEuro = Math.Max(0, s.MaxDrawdownEuro);
s.MaxConcurrentActiveAuctions = Math.Max(0, s.MaxConcurrentActiveAuctions);
s.AverageBidCostEuro = Math.Clamp(s.AverageBidCostEuro, 0.01, 10);
s.TransactionFeeEuro = Math.Clamp(s.TransactionFeeEuro, 0, 100);
s.LearningMinAuctions = Math.Max(1, s.LearningMinAuctions);
s.ExplorationBidsPerDay = Math.Max(0, s.ExplorationBidsPerDay);
s.LearningBootstrapSecondsPerStart = Math.Clamp(s.LearningBootstrapSecondsPerStart, 10, 3600);
s.LeadMinMs = Math.Clamp(s.LeadMinMs, 100, 5000);
s.LeadMaxMs = Math.Clamp(s.LeadMaxMs, s.LeadMinMs, 5000);
s.DefaultBidBeforeDeadlineMs = Math.Clamp(s.DefaultBidBeforeDeadlineMs, 50, 5000);
s.ForecastRefreshBids = Math.Max(1, s.ForecastRefreshBids);
s.ForecastRefreshMinutes = Math.Max(1, s.ForecastRefreshMinutes);
s.MaxRequestsPerSecond = Math.Clamp(s.MaxRequestsPerSecond, 0, 1000);
s.PollFarMs = Math.Clamp(s.PollFarMs, 200, 60_000);
s.PollMidMs = Math.Clamp(s.PollMidMs, 150, 30_000);
s.PollNearMs = Math.Clamp(s.PollNearMs, 100, 10_000);
s.PollCriticalMs = Math.Clamp(s.PollCriticalMs, 50, 5_000);
s.ScheduledPollFarSeconds = Math.Clamp(s.ScheduledPollFarSeconds, 60, 7200);
s.ScheduledPollMidSeconds = Math.Clamp(s.ScheduledPollMidSeconds, 30, 3600);
s.ScheduledPollWakeSeconds = Math.Clamp(s.ScheduledPollWakeSeconds, 30, 3600);
s.DefaultStartAuctionsOnLoad = NormalizeMode(s.DefaultStartAuctionsOnLoad, "Ferma");
s.DefaultNewAuctionState = NormalizeMode(s.DefaultNewAuctionState, "Osserva");
s.AutoAddNewAuctionState = NormalizeMode(s.AutoAddNewAuctionState, "Osserva");
s.MaxBidHistoryEntries = Math.Clamp(s.MaxBidHistoryEntries, 1, 50);
s.MaxLogLinesPerAuction = Math.Clamp(s.MaxLogLinesPerAuction, 50, 5000);
s.MaxGlobalLogLines = Math.Clamp(s.MaxGlobalLogLines, 100, 20_000);
s.MinLogLevel = string.IsNullOrWhiteSpace(s.MinLogLevel) ? "Normal" : s.MinLogLevel.Trim();
s.CatalogCacheSeconds = Math.Clamp(s.CatalogCacheSeconds, 0, 3600);
s.CatalogMaxAuctions = Math.Clamp(s.CatalogMaxAuctions, 50, 5000);
s.AutoAddScanSeconds = Math.Clamp(s.AutoAddScanSeconds, 30, 3600);
s.AutoAddScanMaxAuctions = Math.Clamp(s.AutoAddScanMaxAuctions, 50, 10_000);
s.AutoAddMaxAuctions = Math.Max(0, s.AutoAddMaxAuctions);
s.AutoAddMaxStartMinutes = Math.Max(0, s.AutoAddMaxStartMinutes);
s.SuggestedCoveragePercent = Math.Clamp(s.SuggestedCoveragePercent, 50, 99);
s.SuggestedValueTolerancePercent = Math.Clamp(s.SuggestedValueTolerancePercent, 0, 100);
s.SuggestedMinPercentile = Math.Clamp(s.SuggestedMinPercentile, 0, 50);
s.TelegramBotToken = (s.TelegramBotToken ?? "").Trim();
s.TelegramChatId = (s.TelegramChatId ?? "").Trim();
s.TelegramSummaryMinutes = Math.Clamp(s.TelegramSummaryMinutes, 0, 24 * 60);
s.DataCapGb = Math.Clamp(s.DataCapGb, 1, 10_000);
s.LogRetentionDays = Math.Clamp(s.LogRetentionDays, 0, 3650);
s.BackupRetentionDays = Math.Clamp(s.BackupRetentionDays, 1, 365);
s.ExportMaxRows = Math.Clamp(s.ExportMaxRows, 100, 1_000_000);
return s;
}
/// <summary>«Watch», «osserva», «Paused» → «Osserva»; lo stesso per gli altri due modi.</summary>
public static string NormalizeMode(string? mode, string fallback) => (mode ?? "").Trim().ToLowerInvariant() switch
{
"attiva" or "active" or "attivo" => "Attiva",
"osserva" or "watch" or "paused" or "pausa" => "Osserva",
"ferma" or "stopped" or "stop" or "fermo" => "Ferma",
_ => fallback
};
public static AppSettings Clone(AppSettings s) =>
JsonSerializer.Deserialize<AppSettings>(JsonSerializer.Serialize(s, Json), Json)!;
/// <summary>Esito di un salvataggio: le differenze applicate, oppure l'errore.</summary>
public sealed record SaveResult(bool Ok, string? Error, IReadOnlyList<string> Changes, AppSettings Settings);
/// <summary>
/// Applica una modifica parziale (<c>{"DailyBudgetEuro": 15}</c>), la salva e la rende
/// subito valida. Accendere le puntate dal vivo richiede la parola
/// <see cref="LiveConfirmationWord"/> in <paramref name="liveConfirmation"/>.
/// </summary>
public async Task<SaveResult> SaveAsync(IReadOnlyDictionary<string, JsonElement> patch, string? liveConfirmation)
{
await _saveGate.WaitAsync().ConfigureAwait(false);
try
{
var before = _current;
var next = Clone(before);
foreach (var (key, value) in patch)
{
var prop = Properties.FirstOrDefault(p => string.Equals(p.Name, key, StringComparison.OrdinalIgnoreCase));
if (prop == null || prop.Name == nameof(AppSettings.SettingsSchemaVersion))
return new SaveResult(false, $"impostazione sconosciuta: {key}", Array.Empty<string>(), before);
// Il segreto torna dall'interfaccia mascherato: vuol dire «lascialo com'è».
if (IsSecret(prop.Name) && value.ValueKind == JsonValueKind.String && value.GetString() == MaskedSecret)
continue;
try
{
var converted = value.Deserialize(prop.PropertyType, Json);
if (converted == null && prop.PropertyType.IsValueType)
return new SaveResult(false, $"valore mancante per {prop.Name}", Array.Empty<string>(), before);
prop.SetValue(next, converted);
}
catch (JsonException)
{
return new SaveResult(false, $"valore non valido per {prop.Name}: {value.GetRawText()}", Array.Empty<string>(), before);
}
}
Normalize(next);
if (next.LiveBiddingEnabled && !before.LiveBiddingEnabled &&
!string.Equals(liveConfirmation?.Trim(), LiveConfirmationWord, StringComparison.Ordinal))
{
return new SaveResult(false, $"per accendere le puntate dal vivo scrivi {LiveConfirmationWord}", Array.Empty<string>(), before);
}
var changes = Diff(before, next);
if (changes.Count == 0) return new SaveResult(true, null, changes, before);
if (_queue != null)
{
var ok = await _queue.EnqueueAndWaitAsync(new[]
{
("INSERT INTO settings(id, value, updated_at) VALUES(1, $1, now()) " +
"ON CONFLICT(id) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
new object?[] { new Jsonb(JsonSerializer.Serialize(next, Json)) })
}, TimeSpan.FromSeconds(10)).ConfigureAwait(false);
if (!ok) return new SaveResult(false, "il database non ha confermato il salvataggio: riprova", Array.Empty<string>(), before);
}
_current = next;
foreach (var line in changes) _log?.Info("IMPOSTAZIONI", line);
try { Changed?.Invoke(next); }
catch (Exception ex) { _log?.Warn("IMPOSTAZIONI", $"Applicazione a caldo incompleta: {ex.Message}"); }
return new SaveResult(true, null, changes, next);
}
finally
{
_saveGate.Release();
}
}
/// <summary>Le differenze come righe «campo: prima -> dopo», con i segreti nascosti.</summary>
public static List<string> Diff(AppSettings a, AppSettings b)
{
var list = new List<string>();
foreach (var p in Properties)
{
var va = p.GetValue(a);
var vb = p.GetValue(b);
if (Equals(va, vb)) continue;
if (IsSecret(p.Name))
{
list.Add($"{p.Name}: {(string.IsNullOrEmpty(vb as string) ? "tolto" : "cambiato")}");
continue;
}
list.Add($"{p.Name}: {Show(va)} -> {Show(vb)}");
}
return list;
}
/// <summary>Le impostazioni da mandare all'interfaccia: i segreti diventano «impostato sì/no».</summary>
public static Dictionary<string, object?> ForDisplay(AppSettings s)
{
var d = new Dictionary<string, object?>(StringComparer.Ordinal);
foreach (var p in Properties)
{
var v = p.GetValue(s);
d[p.Name] = IsSecret(p.Name) ? (string.IsNullOrEmpty(v as string) ? "" : MaskedSecret) : v;
}
return d;
}
public static bool IsSecret(string name) => name.Contains("Token", StringComparison.OrdinalIgnoreCase);
/// <summary>Come appare un segreto impostato nell'interfaccia.</summary>
public const string MaskedSecret = "********";
private static string Show(object? v) => v switch
{
null => "vuoto",
bool b => b ? "sì" : "no",
double d => d.ToString("0.##", CultureInfo.GetCultureInfo("it-IT")),
string s when s.Length == 0 => "vuoto",
_ => Convert.ToString(v, CultureInfo.GetCultureInfo("it-IT")) ?? ""
};
}
@@ -0,0 +1,75 @@
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace BidooBidBot.Telegram;
/// <summary>
/// Le due chiamate della Bot API di Telegram che servono, con <see cref="HttpClient"/> e
/// nient'altro: <c>sendMessage</c> e <c>getUpdates</c> (polling lungo, per i comandi).
/// Il token finisce solo nell'indirizzo della richiesta, mai in un registro.
/// </summary>
public static class TelegramApi
{
public const string BaseUrl = "https://api.telegram.org";
/// <summary>Manda un messaggio di testo semplice. True se Telegram risponde «ok».</summary>
public static async Task<bool> SendAsync(HttpClient http, string token, string chatId, string text, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync(
$"{BaseUrl}/bot{token}/sendMessage",
new SendMessage(chatId, text, true),
ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode) return false;
var body = await response.Content.ReadFromJsonAsync<OkResponse>(cancellationToken: ct).ConfigureAwait(false);
return body?.Ok == true;
}
/// <summary>Un messaggio arrivato al bot.</summary>
public sealed record Update(long UpdateId, string? ChatId, string? Text);
/// <summary>I messaggi nuovi dopo <paramref name="offset"/>, aspettando fino a <paramref name="timeoutSeconds"/>.</summary>
public static async Task<IReadOnlyList<Update>> GetUpdatesAsync(HttpClient http, string token, long offset, int timeoutSeconds, CancellationToken ct)
{
using var response = await http.GetAsync(
$"{BaseUrl}/bot{token}/getUpdates?offset={offset}&timeout={timeoutSeconds}&allowed_updates=%5B%22message%22%5D",
ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode) return Array.Empty<Update>();
using var doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false), cancellationToken: ct).ConfigureAwait(false);
return ParseUpdates(doc.RootElement);
}
/// <summary>Legge la risposta di getUpdates. Pura: sta sotto test.</summary>
public static IReadOnlyList<Update> ParseUpdates(JsonElement root)
{
var list = new List<Update>();
if (!root.TryGetProperty("ok", out var ok) || ok.ValueKind != JsonValueKind.True) return list;
if (!root.TryGetProperty("result", out var result) || result.ValueKind != JsonValueKind.Array) return list;
foreach (var u in result.EnumerateArray())
{
if (!u.TryGetProperty("update_id", out var idEl) || !idEl.TryGetInt64(out var id)) continue;
string? chat = null, text = null;
if (u.TryGetProperty("message", out var msg) && msg.ValueKind == JsonValueKind.Object)
{
if (msg.TryGetProperty("chat", out var c) && c.TryGetProperty("id", out var cid))
chat = cid.ValueKind == JsonValueKind.Number ? cid.GetInt64().ToString(System.Globalization.CultureInfo.InvariantCulture) : cid.GetString();
if (msg.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String)
text = t.GetString();
}
list.Add(new Update(id, chat, text));
}
return list;
}
private sealed record SendMessage(
[property: JsonPropertyName("chat_id")] string ChatId,
[property: JsonPropertyName("text")] string Text,
[property: JsonPropertyName("disable_web_page_preview")] bool DisablePreview);
private sealed record OkResponse([property: JsonPropertyName("ok")] bool Ok);
}
@@ -0,0 +1,56 @@
using System.Text.Json;
using BidooBidBot.Config;
using BidooBidBot.Logging;
using BidooBidBot.Settings;
namespace BidooBidBot.Telegram;
/// <summary>
/// Copia delle sole impostazioni di Telegram in <c>/config/cache/telegram.json</c>
/// (permessi 0600), riscritta a ogni salvataggio. Serve a un caso solo: avvisare che il
/// database non risponde, quando le impostazioni vere (che stanno nel database) non si
/// possono leggere.
/// </summary>
public static class TelegramCache
{
private sealed record Snapshot(string Token, string ChatId);
private static string FileFor(ConfigPaths paths) => Path.Combine(paths.Cache, "telegram.json");
public static void Write(ConfigPaths paths, AppSettings settings)
{
try
{
Directory.CreateDirectory(paths.Cache);
var file = FileFor(paths);
if (string.IsNullOrEmpty(settings.TelegramBotToken) || string.IsNullOrEmpty(settings.TelegramChatId))
{
if (File.Exists(file)) File.Delete(file);
return;
}
File.WriteAllText(file, JsonSerializer.Serialize(new Snapshot(settings.TelegramBotToken, settings.TelegramChatId)));
ConfigPaths.RestrictToOwner(file);
}
catch { /* la copia è un di più: senza, l'avviso a database fermo non parte */ }
}
/// <summary>Manda un messaggio usando la copia su file, senza aspettare l'esito oltre qualche secondo.</summary>
public static void TrySendOffline(ConfigPaths paths, AppLog log, string title, string body)
{
try
{
var file = FileFor(paths);
if (!File.Exists(file)) return;
var snap = JsonSerializer.Deserialize<Snapshot>(File.ReadAllText(file));
if (snap == null || string.IsNullOrEmpty(snap.Token) || string.IsNullOrEmpty(snap.ChatId)) return;
_ = Task.Run(async () =>
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
var ok = await TelegramApi.SendAsync(http, snap.Token, snap.ChatId, TelegramFormat.Message(title, body), CancellationToken.None).ConfigureAwait(false);
if (ok) log.Info("TELEGRAM", $"Avviso inviato a database fermo: {title}");
});
}
catch { /* niente da fare */ }
}
}
@@ -0,0 +1,69 @@
using System.Globalization;
using System.Text;
using BidooBidBot.Logging;
namespace BidooBidBot.Telegram;
/// <summary>
/// Il formato dei messaggi: prima riga breve come una notifica del telefono, poi i
/// dettagli. Testo semplice (niente Markdown: un nome di prodotto con un asterisco
/// romperebbe il messaggio). Classe pura, sotto test.
/// </summary>
public static class TelegramFormat
{
private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT");
public const int MaxLength = 4000;
public static string Message(string title, string? body)
{
var text = string.IsNullOrWhiteSpace(body) ? LogText.Clean(title) : LogText.Clean(title) + "\n" + body.Trim();
return text.Length <= MaxLength ? text : text[..(MaxLength - 3)] + "...";
}
public static string Euro(double value) => value.ToString("0.00", It) + " €";
public static string Won(string name, double price, int myBids, double realCost, double? value)
{
var body = new StringBuilder();
body.Append($"Aggiudicata a {Euro(price)} con {myBids} puntate tue.");
body.Append($"\nCosto reale: {Euro(realCost)}");
if (value is > 0) body.Append($" su un valore di {Euro(value.Value)}");
body.Append(".\nRicordati di confermare l'acquisto su Bidoo.");
return Message($"Asta vinta: {name}", body.ToString());
}
public static string Lost(string name, double price, string winner, int myBids, string? reason) =>
Message($"Asta persa: {name}",
$"Chiusa a {Euro(price)}, vinta da {winner}. Tue puntate: {myBids}." +
(string.IsNullOrWhiteSpace(reason) ? "" : $"\nPerché: {reason}"));
public static string SessionExpired(string? user, string detail) =>
Message("Sessione Bidoo scaduta",
$"{(string.IsNullOrEmpty(user) ? "" : $"Utente {user}. ")}{detail}\nTutte le aste sono passate in Osserva. Rifai l'accesso da «Accesso a Bidoo».");
public static string Halt(string reason, bool automatic) =>
Message(automatic ? "HALT automatico: puntate ferme" : "HALT: puntate ferme",
$"{reason}\nSi toglie da Impostazioni ▸ Gestione del rischio.");
public static string Resume() => Message("HALT tolto: le puntate riprendono", "Le aste in Attiva tornano a puntare secondo il modello.");
/// <summary>Il riepilogo periodico.</summary>
public sealed record Summary(
int AuctionsListed, int AuctionsActive, int? RemainingBids, double SpentToday, double NetToday,
double? RoiShadow7d, double? RoiLive7d, int? PingMs, bool Live, bool Halted);
public static string SummaryText(Summary s)
{
var mode = s.Halted ? "HALT" : s.Live ? "DAL VIVO" : "OSSERVA";
var sb = new StringBuilder();
sb.Append($"{s.AuctionsListed} aste in elenco, {s.AuctionsActive} attive.");
if (s.RemainingBids is { } b) sb.Append($"\nPuntate residue: {b.ToString("N0", It)}.");
sb.Append($"\nOggi: spesi {Euro(s.SpentToday)}, saldo {Euro(s.NetToday)}.");
sb.Append($"\nROI per puntata 7 giorni: Osserva {Roi(s.RoiShadow7d)}, dal vivo {Roi(s.RoiLive7d)}.");
if (s.PingMs is { } p) sb.Append($"\nPing {p} ms.");
return Message($"Bidoo BidBot, modalità {mode}", sb.ToString());
}
private static string Roi(double? v) => v is { } x ? x.ToString("+0.00;-0.00", It) + " €" : "n.d.";
}
+47
View File
@@ -0,0 +1,47 @@
using System.Text.RegularExpressions;
using BidooBidBot.Host;
using Microsoft.AspNetCore.Http;
namespace BidooBidBot.Web;
/// <summary>
/// Scaricamento dei file prodotti dal bot: esportazioni CSV (<c>/config/esportazioni</c>) e
/// registri giornalieri (<c>/config/registri</c>). Solo nomi semplici: niente percorsi,
/// niente «..».
/// </summary>
public static partial class Downloads
{
public static Task ServeExportAsync(BotHost host, HttpContext ctx, string name) =>
ServeAsync(ctx, host.Paths.Exports, name, "text/csv; charset=utf-8");
public static Task ServeLogAsync(BotHost host, HttpContext ctx, string name) =>
ServeAsync(ctx, host.Paths.Logs, name, "text/plain; charset=utf-8");
private static async Task ServeAsync(HttpContext ctx, string folder, string name, string contentType)
{
name = Uri.UnescapeDataString(name);
if (!SafeName().IsMatch(name))
{
ctx.Response.StatusCode = 400;
return;
}
var file = Path.Combine(folder, name);
if (!File.Exists(file))
{
ctx.Response.StatusCode = 404;
return;
}
if (name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) contentType = "text/plain; charset=utf-8";
if (name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) contentType = "application/zip";
ctx.Response.ContentType = contentType;
ctx.Response.Headers.ContentDisposition = $"attachment; filename=\"{name}\"";
ctx.Response.Headers.CacheControl = "no-store";
await ctx.Response.SendFileAsync(file).ConfigureAwait(false);
}
[GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9_\-\.]{0,120}\.(csv|txt|log|zip)$")]
private static partial Regex SafeName();
}
+61
View File
@@ -0,0 +1,61 @@
using System.Text.Json;
using BidooBidBot.Host;
using Microsoft.AspNetCore.Http;
namespace BidooBidBot.Web;
/// <summary>
/// <c>GET /salute</c>: lo stato del processo in JSON, senza segreti. Risponde 200 solo con
/// configurazione e database a posto; altrimenti 503 con il dettaglio, così il container
/// risulta «non sano» in Unraid. È pubblico: lo interroga il HEALTHCHECK di Docker.
/// </summary>
public static class Health
{
private static readonly JsonSerializerOptions Json = new() { WriteIndented = true };
public static async Task WriteAsync(BotHost host, HttpContext ctx)
{
var (ok, body) = Build(host);
ctx.Response.StatusCode = ok ? 200 : 503;
ctx.Response.ContentType = "application/json; charset=utf-8";
ctx.Response.Headers.CacheControl = "no-store";
await ctx.Response.WriteAsync(JsonSerializer.Serialize(body, Json)).ConfigureAwait(false);
}
public static (bool Ok, Dictionary<string, object?> Body) Build(BotHost host)
{
var body = new Dictionary<string, object?>
{
["versione"] = AppInfo.Version,
["avviatoIl"] = host.StartedAt,
};
var bot = host.Bot;
if (host.State != HostState.Running || bot == null)
{
body["stato"] = host.State == HostState.ConfigError ? "errore" : "avvio";
var problem = host.LastReport?.FirstProblem;
if (problem != null)
{
body["problema"] = problem.Title;
body["dettaglio"] = problem.Error;
}
return (false, body);
}
var down = bot.Queue.DownSince;
body["stato"] = down == null ? "ok" : "database-assente";
body["database"] = new Dictionary<string, object?>
{
["stato"] = down == null ? "ok" : "non raggiungibile",
["assenteDa"] = down,
["codaRighe"] = bot.Queue.Pending,
["righeScritte"] = bot.Queue.Written,
["righeScartate"] = bot.Queue.Dropped,
["ultimoErrore"] = bot.Queue.LastError
};
foreach (var (key, value) in bot.HealthDetails()) body[key] = value;
return (down == null, body);
}
}
+129
View File
@@ -0,0 +1,129 @@
using System.Net;
using System.Text;
using BidooBidBot.Config;
namespace BidooBidBot.Web;
/// <summary>
/// Le tre pagine che il server compone da sé, perché devono funzionare anche quando il
/// resto non c'è: l'accesso all'interfaccia (mockup 00), la schermata d'errore di
/// configurazione (mockup 09) e «avvio in corso». Tutto il resto è l'applicazione a pagina
/// unica in <c>wwwroot</c>.
/// </summary>
public static class Pages
{
private static string E(string? s) => WebUtility.HtmlEncode(s ?? "");
private static string Head(string title) => $$"""
<!doctype html>
<html lang="it" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{E(title)}}</title>
<link rel="icon" href="/img/icona.svg" type="image/svg+xml">
<link rel="stylesheet" href="/css/tokens.css">
<link rel="stylesheet" href="/css/app.css">
<script>try{var t=localStorage.getItem('bidbot.theme');if(t)document.documentElement.dataset.theme=t;}catch(e){}</script>
</head>
""";
/// <summary>La pagina di accesso: un solo campo, la versione, l'errore in chiaro.</summary>
public static string Login(string version, string? error, int waitSeconds)
{
var sb = new StringBuilder();
sb.Append(Head("Bidoo BidBot - accesso"));
sb.Append($$"""
<body class="fullpage">
<main class="box" role="main">
<h1><span class="logo" aria-hidden="true">B</span>Bidoo BidBot<span class="v" title="Versione del programma">{{E(version)}}</span></h1>
<p class="lead">Inserisci la password dell'interfaccia (quella impostata in <code>UI_PASSWORD</code> nel container).</p>
<form method="post" action="/accesso" autocomplete="off">
<input type="password" name="password" autofocus required aria-label="Password dell'interfaccia"
title="La password scritta nella variabile UI_PASSWORD del container" {{(waitSeconds > 0 ? "disabled" : "")}}>
<button class="btn primary wide" type="submit" title="Entra nell'interfaccia del bot" {{(waitSeconds > 0 ? "disabled" : "")}}>Entra</button>
</form>
""");
if (!string.IsNullOrEmpty(error))
sb.Append($"""<p class="form-error" role="alert">{E(error)}</p>""");
sb.Append("""
<p class="help">Password sbagliata: dopo 5 tentativi l'attesa cresce. La sessione dura 30 giorni su questo browser.</p>
</main>
""");
if (waitSeconds > 0)
sb.Append($"<script>setTimeout(function(){{location.href='/accesso';}},{waitSeconds * 1000 + 500});</script>");
sb.Append("</body></html>");
return sb.ToString();
}
/// <summary>
/// La schermata d'errore di configurazione: cosa manca o non risponde, con i valori in
/// uso (mai le password), l'errore testuale, il prossimo tentativo, «Riprova adesso» e
/// le istruzioni per Unraid. Nient'altro dell'interfaccia è raggiungibile.
/// </summary>
public static string ConfigError(string version, StartupReport report, int nextRetrySeconds)
{
var sb = new StringBuilder();
sb.Append(Head("Bidoo BidBot - errore di configurazione"));
sb.Append($$"""
<body class="fullpage">
<main class="box err" role="main">
<h1><span class="sq" aria-hidden="true"></span>Bidoo BidBot non può partire
<span class="v" title="Versione, numero del tentativo e secondi al prossimo">{{E(version)}} · tentativo {{report.Attempt}} · prossimo fra <span id="next">{{nextRetrySeconds}}</span> s</span></h1>
""");
foreach (var item in report.Items)
{
var cls = item.Ok ? "err-item ok" : "err-item";
var mark = item.Ok ? "&#10003;" : "&#10005;";
sb.Append($"""<div class="{cls}"><span class="mark" aria-hidden="true">{mark}</span><div>""");
sb.Append($"<b>{E(item.Title)}</b>");
if (!string.IsNullOrEmpty(item.Detail)) sb.Append($" <span class=\"detail\">{FormatDetail(item.Detail)}</span>");
if (!item.Ok && !string.IsNullOrEmpty(item.Error)) sb.Append($"<div class=\"mono\">{E(item.Error)}</div>");
sb.Append("</div></div>");
}
var hint = report.FirstProblem?.Hint
?? "Su Unraid: Docker ▸ postgresql18 ▸ avvia; poi controlla porta e password nel template di bidoo-bidbot.";
sb.Append($$"""
<p>Finché l'errore resta, il motore è fermo: nessuna asta seguita, nessuna puntata. Il bot riprova da solo ogni 30 secondi.</p>
<div class="row">
<form method="post" action="/riprova"><button class="btn primary" type="submit" title="Ripete subito tutte le verifiche invece di aspettare il prossimo tentativo">Riprova adesso</button></form>
<span class="help">{{E(hint)}}</span>
</div>
</main>
<script>
(function(){
var n=document.getElementById('next'),s={{nextRetrySeconds}};
setInterval(function(){ if(s>0){s--; n.textContent=s;} },1000);
setInterval(function(){
fetch('/salute',{cache:'no-store'}).then(function(r){ if(r.ok) location.href='/'; }).catch(function(){});
},3000);
})();
</script>
</body></html>
""");
return sb.ToString();
}
/// <summary>Tra le verifiche riuscite e il motore pronto passa qualche secondo.</summary>
public static string Starting(string version, string step) =>
Head("Bidoo BidBot - avvio") + $$"""
<body class="fullpage">
<main class="box" role="main">
<h1><span class="logo" aria-hidden="true">B</span>Bidoo BidBot<span class="v">{{E(version)}}</span></h1>
<p class="lead">Avvio in corso: {{E(step)}}</p>
<p class="help">La pagina si ricarica da sola appena il bot è pronto.</p>
</main>
<script>setInterval(function(){fetch('/salute',{cache:'no-store'}).then(function(r){if(r.ok)location.href='/';}).catch(function(){});},1500);</script>
</body></html>
""";
/// <summary>I valori «chiave valore · chiave valore» con i valori in codice, come nel mockup.</summary>
private static string FormatDetail(string detail) => E(detail);
}
+141
View File
@@ -0,0 +1,141 @@
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
using BidooBidBot.Config;
namespace BidooBidBot.Web;
/// <summary>
/// Accesso all'interfaccia con la password di <c>UI_PASSWORD</c> (specifica §11).
///
/// <list type="bullet">
/// <item>La password si confronta a tempo costante con quella dell'ambiente: niente hash
/// su disco, la fonte è la variabile.</item>
/// <item>Il cookie di sessione è firmato (HMAC-SHA256) con una chiave generata al primo
/// avvio in <c>/config/sessione/interfaccia.key</c>, mescolata con la password: cambiare
/// <c>UI_PASSWORD</c> fa uscire tutti i browser.</item>
/// <item>Dura 30 giorni e si rinnova a ogni uso (al massimo una volta al giorno).</item>
/// <item>Dopo 5 tentativi sbagliati dallo stesso indirizzo l'attesa cresce: 2, 4, 8… s.</item>
/// </list>
/// </summary>
public sealed class UiAuth
{
public const string CookieName = "bidbot_sessione";
public static readonly TimeSpan Lifetime = TimeSpan.FromDays(30);
private static readonly TimeSpan RenewAfter = TimeSpan.FromDays(1);
private const int FreeAttempts = 5;
private readonly byte[] _passwordHash;
private readonly byte[] _macKey;
private readonly ConcurrentDictionary<string, (int Failures, DateTimeOffset LockedUntil)> _attempts = new(StringComparer.Ordinal);
public UiAuth(string password, byte[] fileKey)
{
_passwordHash = SHA256.HashData(Encoding.UTF8.GetBytes(password));
_macKey = HMACSHA256.HashData(fileKey, Encoding.UTF8.GetBytes("interfaccia:" + password));
}
/// <summary>La chiave dei cookie: letta dal file, o generata e scritta con permessi 0600.</summary>
public static byte[] LoadOrCreateKey(string path)
{
try
{
if (File.Exists(path))
{
var existing = File.ReadAllBytes(path);
if (existing.Length >= 32) return existing;
}
}
catch { /* chiave illeggibile: se ne fa una nuova, i browser dovranno rientrare */ }
var key = RandomNumberGenerator.GetBytes(32);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, key);
ConfigPaths.RestrictToOwner(path);
return key;
}
/// <summary>Confronto a tempo costante: gli hash hanno la stessa lunghezza qualunque sia la password tentata.</summary>
public bool CheckPassword(string? attempt)
{
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(attempt ?? ""));
return CryptographicOperations.FixedTimeEquals(hash, _passwordHash);
}
/// <summary>Un cookie nuovo: istante di emissione, scadenza, casuale, firma.</summary>
public string IssueToken(DateTimeOffset now)
{
var payload = $"{now.ToUnixTimeSeconds()}.{now.Add(Lifetime).ToUnixTimeSeconds()}.{Convert.ToHexString(RandomNumberGenerator.GetBytes(8))}";
return Base64Url(Encoding.ASCII.GetBytes(payload)) + "." + Base64Url(Sign(payload));
}
public readonly record struct TokenCheck(bool Valid, bool ShouldRenew);
public TokenCheck Validate(string? token, DateTimeOffset now)
{
if (string.IsNullOrEmpty(token)) return default;
var dot = token.LastIndexOf('.');
if (dot <= 0) return default;
byte[] payloadBytes, signature;
try
{
payloadBytes = FromBase64Url(token[..dot]);
signature = FromBase64Url(token[(dot + 1)..]);
}
catch (FormatException) { return default; }
var payload = Encoding.ASCII.GetString(payloadBytes);
if (!CryptographicOperations.FixedTimeEquals(Sign(payload), signature)) return default;
var parts = payload.Split('.');
if (parts.Length != 3 || !long.TryParse(parts[0], out var issued) || !long.TryParse(parts[1], out var expires))
return default;
var nowSec = now.ToUnixTimeSeconds();
if (nowSec >= expires) return default;
return new TokenCheck(true, nowSec - issued > (long)RenewAfter.TotalSeconds);
}
/// <summary>Quanto deve ancora aspettare questo indirizzo prima di riprovare. Zero = può.</summary>
public TimeSpan LockedFor(string client, DateTimeOffset now) =>
_attempts.TryGetValue(client, out var a) && a.LockedUntil > now ? a.LockedUntil - now : TimeSpan.Zero;
/// <summary>Un tentativo sbagliato. Restituisce l'attesa imposta da adesso (zero nei primi cinque).</summary>
public TimeSpan RecordFailure(string client, DateTimeOffset now)
{
var entry = _attempts.AddOrUpdate(client,
_ => (1, DateTimeOffset.MinValue),
(_, old) => (old.Failures + 1, old.LockedUntil));
if (entry.Failures < FreeAttempts) return TimeSpan.Zero;
var exponent = Math.Min(entry.Failures - FreeAttempts, 10);
var wait = TimeSpan.FromSeconds(2 << exponent); // 2, 4, 8, ... fino a ~34 minuti
_attempts[client] = (entry.Failures, now.Add(wait));
return wait;
}
public int Failures(string client) => _attempts.TryGetValue(client, out var a) ? a.Failures : 0;
public void RecordSuccess(string client) => _attempts.TryRemove(client, out _);
private byte[] Sign(string payload) => HMACSHA256.HashData(_macKey, Encoding.ASCII.GetBytes(payload));
private static string Base64Url(byte[] data) =>
Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static byte[] FromBase64Url(string text)
{
var s = text.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 2: s += "=="; break;
case 3: s += "="; break;
case 1: throw new FormatException();
}
return Convert.FromBase64String(s);
}
}
+232
View File
@@ -0,0 +1,232 @@
using System.Net;
using System.Text.Json;
using BidooBidBot.Host;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BidooBidBot.Web;
/// <summary>
/// Kestrel sulla porta dell'interfaccia (8080). Parte prima di tutto il resto, perché deve
/// poter mostrare la schermata d'errore quando il bot non può partire; in quello stato
/// risponde solo con quella su ogni percorso, e <c>/salute</c> dà 503.
///
/// <para>A bot in funzione: <c>/accesso</c> e i fogli di stile sono pubblici, tutto il resto
/// (pagina, moduli JS, WebSocket, esportazioni) chiede il cookie dell'interfaccia.</para>
/// </summary>
public static class WebServer
{
public static WebApplication Build(BotHost host)
{
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions
{
ContentRootPath = AppContext.BaseDirectory,
WebRootPath = Path.Combine(AppContext.BaseDirectory, "wwwroot"),
Args = Array.Empty<string>()
});
builder.Logging.ClearProviders();
builder.WebHost.ConfigureKestrel(o =>
{
o.ListenAnyIP(host.Env.HttpPort);
o.AddServerHeader = false;
o.Limits.MaxRequestBodySize = 2 * 1024 * 1024;
});
builder.Services.AddRouting();
var app = builder.Build();
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20) });
app.Use((ctx, next) => Gate(host, ctx, next));
var files = new PhysicalFileProvider(app.Environment.WebRootPath);
app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = files });
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = files,
OnPrepareResponse = c =>
{
// L'interfaccia cambia con la versione: niente cache lunga su pagina e moduli.
c.Context.Response.Headers.CacheControl = "no-cache";
}
});
return app;
}
/// <summary>
/// Il cancello unico: stato del processo, poi autenticazione, poi i percorsi del server.
/// </summary>
private static async Task Gate(BotHost host, HttpContext ctx, Func<Task> next)
{
var path = ctx.Request.Path.Value ?? "/";
var method = ctx.Request.Method;
if (path == "/salute")
{
await Health.WriteAsync(host, ctx).ConfigureAwait(false);
return;
}
// Fogli di stile e icona servono anche alle pagine d'errore e d'accesso.
if (IsPublicAsset(path))
{
await next().ConfigureAwait(false);
return;
}
if (host.State != HostState.Running || host.Bot == null)
{
if (path == "/riprova" && HttpMethods.IsPost(method))
{
host.RequestRetry();
ctx.Response.Redirect("/");
return;
}
ctx.Response.StatusCode = 503;
ctx.Response.ContentType = "text/html; charset=utf-8";
ctx.Response.Headers.CacheControl = "no-store";
var html = host.State == HostState.ConfigError && host.LastReport != null
? Pages.ConfigError(AppInfo.Version, host.LastReport,
Math.Max(0, (int)Math.Ceiling((host.NextRetryAt - DateTimeOffset.UtcNow).TotalSeconds)))
: Pages.Starting(AppInfo.Version, host.StartingStep);
await ctx.Response.WriteAsync(html).ConfigureAwait(false);
return;
}
var auth = host.Auth!;
var client = ClientKey(ctx);
if (path == "/accesso")
{
if (HttpMethods.IsPost(method)) await LoginAsync(host, auth, ctx, client).ConfigureAwait(false);
else await LoginPageAsync(auth, ctx, client, null).ConfigureAwait(false);
return;
}
var check = auth.Validate(ctx.Request.Cookies[UiAuth.CookieName], DateTimeOffset.UtcNow);
if (!check.Valid)
{
if (path.StartsWith("/ws", StringComparison.Ordinal) || path.StartsWith("/api", StringComparison.Ordinal))
{
ctx.Response.StatusCode = 401;
return;
}
ctx.Response.Redirect("/accesso");
return;
}
if (check.ShouldRenew) SetCookie(ctx, auth.IssueToken(DateTimeOffset.UtcNow));
if (path == "/esci")
{
ctx.Response.Cookies.Delete(UiAuth.CookieName);
host.Log.Info("ACCESSO", $"Uscita dall'interfaccia da {client}");
ctx.Response.Redirect("/accesso");
return;
}
if (path == "/ws")
{
if (!ctx.WebSockets.IsWebSocketRequest)
{
ctx.Response.StatusCode = 400;
return;
}
await host.Bot.Hub.AcceptAsync(ctx).ConfigureAwait(false);
return;
}
if (path.StartsWith("/esportazioni/", StringComparison.Ordinal))
{
await Downloads.ServeExportAsync(host, ctx, path["/esportazioni/".Length..]).ConfigureAwait(false);
return;
}
if (path.StartsWith("/registri/", StringComparison.Ordinal))
{
await Downloads.ServeLogAsync(host, ctx, path["/registri/".Length..]).ConfigureAwait(false);
return;
}
await next().ConfigureAwait(false);
}
private static bool IsPublicAsset(string path) =>
path.StartsWith("/css/", StringComparison.Ordinal) ||
path.StartsWith("/img/", StringComparison.Ordinal) ||
path == "/favicon.ico";
private static async Task LoginPageAsync(UiAuth auth, HttpContext ctx, string client, string? error)
{
var wait = auth.LockedFor(client, DateTimeOffset.UtcNow);
if (wait > TimeSpan.Zero && error == null)
error = $"Troppi tentativi sbagliati: riprova fra {Math.Ceiling(wait.TotalSeconds):N0} secondi.";
ctx.Response.ContentType = "text/html; charset=utf-8";
ctx.Response.Headers.CacheControl = "no-store";
await ctx.Response.WriteAsync(Pages.Login(AppInfo.Version, error, (int)Math.Ceiling(wait.TotalSeconds))).ConfigureAwait(false);
}
private static async Task LoginAsync(BotHost host, UiAuth auth, HttpContext ctx, string client)
{
var now = DateTimeOffset.UtcNow;
var wait = auth.LockedFor(client, now);
if (wait > TimeSpan.Zero)
{
await LoginPageAsync(auth, ctx, client, null).ConfigureAwait(false);
return;
}
string? password = null;
if (ctx.Request.HasFormContentType)
{
var form = await ctx.Request.ReadFormAsync().ConfigureAwait(false);
password = form["password"].ToString();
}
if (auth.CheckPassword(password))
{
auth.RecordSuccess(client);
SetCookie(ctx, auth.IssueToken(now));
host.Log.Info("ACCESSO", $"Accesso all'interfaccia da {client}");
ctx.Response.Redirect("/");
return;
}
var lockFor = auth.RecordFailure(client, now);
var failures = auth.Failures(client);
host.Log.Warn("ACCESSO", $"Password dell'interfaccia sbagliata da {client} ({failures} di fila)" +
(lockFor > TimeSpan.Zero ? $", attesa {lockFor.TotalSeconds:N0} s" : ""));
var error = lockFor > TimeSpan.Zero
? $"Password sbagliata. Troppi tentativi: riprova fra {lockFor.TotalSeconds:N0} secondi."
: "Password sbagliata.";
ctx.Response.StatusCode = 401;
await LoginPageAsync(auth, ctx, client, error).ConfigureAwait(false);
}
private static void SetCookie(HttpContext ctx, string token) =>
ctx.Response.Cookies.Append(UiAuth.CookieName, token, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = ctx.Request.IsHttps,
MaxAge = UiAuth.Lifetime,
Path = "/"
});
/// <summary>
/// Chi sta chiedendo, per contare i tentativi. Solo l'indirizzo della connessione:
/// fidarsi di X-Forwarded-For permetterebbe di aggirare l'attesa cambiando l'intestazione.
/// Dietro un proxy i tentativi si contano tutti insieme, che è il lato prudente.
/// </summary>
private static string ClientKey(HttpContext ctx) =>
ctx.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
}
@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Http;
namespace BidooBidBot.Web;
/// <summary>Segnaposto fino a M6: il protocollo WebSocket completo arriva con l'interfaccia.</summary>
public sealed class WebSocketHub
{
public async Task AcceptAsync(HttpContext ctx)
{
using var socket = await ctx.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
await socket.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "non ancora disponibile", CancellationToken.None).ConfigureAwait(false);
}
}
+360
View File
@@ -0,0 +1,360 @@
/*
Bidoo BidBot — componenti dell'interfaccia. Solo token di tokens.css, niente colori
scritti qui. Densità compatta; layout fluido (grid/flex con 1fr, nessuna larghezza fissa
nelle colonne della griglia); le maniglie cambiano solo grid-template-columns/rows.
*/
*, *::before, *::after { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font: var(--fs)/1.35 var(--font);
font-variant-numeric: tabular-nums;
}
a { color: var(--accent); }
code { font-family: var(--mono); font-size: .95em; background: var(--surface-2); border: 1px solid var(--line); border-radius: 3px; padding: 0 4px; }
b, strong { font-weight: 600; }
button, input, select, textarea { font: inherit; color: inherit; }
button { cursor: pointer; }
button:disabled { cursor: not-allowed; opacity: .55; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
[hidden] { display: none !important; }
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-thumb { background: var(--surface-3); border-radius: 6px; border: 2px solid var(--bg); }
::-webkit-scrollbar-track { background: transparent; }
.muted { color: var(--muted); }
.faint { color: var(--faint); }
.small { font-size: var(--fs-small); color: var(--muted); }
.help { color: var(--faint); font-size: var(--fs-small); }
.right, .num { text-align: right; }
.nowrap { white-space: nowrap; }
.ok { color: var(--ok); }
.warn { color: var(--warn); }
.bad { color: var(--bad); }
.gold, .me, .won { color: var(--gold); font-weight: 600; }
.pos { color: var(--ok); }
.neg { color: var(--bad); }
.spacer { flex: 1; }
/* ── bottoni e campi ─────────────────────────────────────────────────── */
.btn {
display: inline-flex; align-items: center; gap: 6px;
padding: 6px 11px; border-radius: var(--r);
border: 1px solid var(--line); background: var(--surface-2); color: var(--text);
white-space: nowrap; line-height: 1.2;
}
.btn:hover:not(:disabled) { background: var(--surface-3); }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
.btn.danger { background: var(--bad); border-color: var(--bad); color: #fff; font-weight: 600; }
.btn.ghost { background: transparent; }
.btn.wide { width: 100%; justify-content: center; padding: 9px; }
.btn .ic { font-size: 12px; }
input.txt, select.txt, textarea.txt, .field input, .field select {
background: var(--surface-2); border: 1px solid var(--line); color: var(--text);
border-radius: var(--r); padding: 5px 8px; min-width: 0;
}
input.txt:focus, select.txt:focus, .field input:focus, .field select:focus { border-color: var(--accent); outline: none; }
input[type="number"] { -moz-appearance: textfield; }
input[type="number"]::-webkit-inner-spin-button { opacity: .4; }
/* interruttore: checkbox con aspetto a levetta */
.switch { position: relative; display: inline-block; width: 34px; height: 18px; flex: none; }
.switch input { position: absolute; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: pointer; z-index: 1; }
.switch span { position: absolute; inset: 0; border-radius: 9px; background: var(--line); transition: background .15s; }
.switch span::after { content: ""; position: absolute; left: 2px; top: 2px; width: 14px; height: 14px; border-radius: 50%; background: #fff; transition: transform .15s; }
.switch input:checked + span { background: var(--accent); }
.switch input:checked + span::after { transform: translateX(16px); }
.switch input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 1px; }
.chip {
display: inline-flex; align-items: center; gap: 5px; padding: 3px 8px; min-width: 0;
border-radius: 999px; background: var(--surface-2); border: 1px solid var(--line);
color: var(--muted); white-space: nowrap; font-size: var(--fs-small);
}
.chip b { color: var(--text); font-weight: 600; }
.chip small { color: var(--faint); font-size: var(--fs-tiny); }
.chip.live { border-color: var(--bad); color: var(--bad); background: var(--bad-soft); }
.chip.live b { color: var(--bad); }
.chip.shadow { border-color: var(--accent); color: var(--accent); }
.chip.shadow b { color: var(--accent); }
.chip.sim { border-color: var(--warn); color: var(--warn); }
.chip.clickable { cursor: pointer; }
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--ok); display: inline-block; flex: none; }
.dot.warn { background: var(--warn); }
.dot.bad { background: var(--bad); }
.dot.off { background: var(--faint); }
.dot.accent { background: var(--accent); }
.badge { display: inline-block; padding: 2px 7px; border-radius: 4px; font-size: var(--fs-tiny); font-weight: 600; letter-spacing: .1px; white-space: nowrap; }
.b-lead { background: var(--ok-soft); color: var(--ok); }
.b-active { background: var(--accent-soft); color: var(--accent); }
.b-watch { background: var(--muted-soft); color: var(--muted); }
.b-stop { background: var(--muted-soft); color: var(--faint); }
.b-won { background: var(--gold-soft); color: var(--gold); }
.b-lost { background: var(--bad-soft); color: var(--bad); }
.b-pause { background: var(--warn-soft); color: var(--warn); }
.b-sched { background: var(--muted-soft); color: var(--muted); }
.pill { padding: 2px 8px; border-radius: 999px; font-size: var(--fs-tiny); font-weight: 600; white-space: nowrap; }
.pill.ok { background: var(--ok-soft); color: var(--ok); }
.pill.warn { background: var(--warn-soft); color: var(--warn); }
.pill.bad { background: var(--bad-soft); color: var(--bad); }
.pill.info { background: var(--accent-soft); color: var(--accent); }
.pill.muted { background: var(--muted-soft); color: var(--muted); }
.banner { padding: 10px 14px; border-radius: var(--r); border: 1px solid var(--warn); background: var(--warn-soft); color: var(--warn); display: flex; gap: 12px; align-items: center; }
.banner.bad { border-color: var(--bad); background: var(--bad-soft); color: var(--bad); }
.banner.info { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
.banner.ok { border-color: var(--ok); background: var(--ok-soft); color: var(--ok); }
.banner .btn { margin-left: auto; }
/* ── pagine intere: accesso, errore, avvio ───────────────────────────── */
body.fullpage { display: grid; place-items: center; min-height: 100vh; padding: 16px; }
.box {
width: min(440px, 100%); background: var(--surface); border: 1px solid var(--line);
border-radius: var(--r-lg); padding: 26px 28px; display: flex; flex-direction: column; gap: 12px;
}
.box h1 { margin: 0; font-size: 18px; font-weight: 600; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.box .v { color: var(--faint); font-size: var(--fs-small); font-weight: 400; margin-left: auto; }
.box .lead { margin: 0; color: var(--muted); }
.box form { display: flex; flex-direction: column; gap: 10px; }
.box input[type="password"] { width: 100%; background: var(--surface-2); border: 1px solid var(--line); border-radius: var(--r); padding: 9px 10px; }
.box .form-error { margin: 0; color: var(--bad); }
.box .help { margin: 0; }
.box.err { width: min(720px, 100%); }
.box .row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
.logo { width: 22px; height: 22px; border-radius: 5px; background: var(--accent); display: grid; place-items: center; color: var(--accent-ink); font-weight: 800; font-size: 12px; flex: none; }
.sq { width: 16px; height: 16px; background: var(--bad); border-radius: 2px; flex: none; }
.err-item { display: grid; grid-template-columns: 22px 1fr; gap: 10px; padding: 10px 12px; border-radius: var(--r); border: 1px solid var(--bad); background: var(--bad-soft); }
.err-item.ok { border-color: var(--ok); background: var(--ok-soft); }
.err-item .mark { color: var(--bad); font-weight: 700; }
.err-item.ok .mark { color: var(--ok); }
.err-item .detail { color: var(--muted); }
.mono { font-family: var(--mono); font-size: var(--fs-small); color: var(--muted); background: var(--bg); border: 1px solid var(--line); border-radius: 4px; padding: 8px 10px; white-space: pre-wrap; margin-top: 6px; }
/* ── struttura dell'applicazione ─────────────────────────────────────── */
.app {
display: grid;
grid-template-columns: var(--nav-w) minmax(0, 1fr);
grid-template-rows: var(--topbar-h) minmax(0, 1fr);
height: 100vh; overflow: hidden;
}
.app.narrow { grid-template-columns: var(--nav-w-narrow) minmax(0, 1fr); }
.topbar {
grid-column: 1 / 3; display: flex; align-items: center; gap: 6px; padding: 0 12px;
overflow: hidden; background: var(--surface); border-bottom: 1px solid var(--line); min-width: 0;
}
.brand { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 14px; margin-right: 6px; white-space: nowrap; }
.topbar .chips { display: flex; align-items: center; gap: 6px; min-width: 0; overflow: hidden; }
.halt-btn { flex: none; background: var(--bad); color: #fff; border: 0; border-radius: var(--r); padding: 6px 12px; font-weight: 700; letter-spacing: .2px; }
.halt-btn.on { background: transparent; color: var(--bad); border: 1px solid var(--bad); }
.icon-btn { flex: none; width: 30px; height: 30px; border-radius: var(--r); border: 1px solid var(--line); background: var(--surface-2); color: var(--muted); display: grid; place-items: center; font-size: 14px; padding: 0; }
.icon-btn:hover { color: var(--text); background: var(--surface-3); }
.nav { background: var(--surface); border-right: 1px solid var(--line); padding: 10px 8px; display: flex; flex-direction: column; gap: 2px; min-height: 0; overflow: auto; }
.nav a { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: var(--r); color: var(--muted); text-decoration: none; white-space: nowrap; }
.nav a:hover { color: var(--text); background: var(--surface-2); }
.nav a.on { background: var(--surface-3); color: var(--text); font-weight: 600; }
.nav .ic { width: 18px; text-align: center; font-size: 14px; flex: none; }
.nav .sep { flex: 1; }
.nav .collapse { color: var(--faint); font-size: var(--fs-small); padding: 8px 10px; background: none; border: 0; text-align: left; display: flex; gap: 10px; align-items: center; }
.app.narrow .nav .lbl { display: none; }
.app.narrow .nav a, .app.narrow .nav .collapse { justify-content: center; }
.main { display: grid; grid-template-rows: minmax(0, 1fr) auto auto; min-width: 0; min-height: 0; overflow: hidden; }
.main.log-collapsed .bottom-log { display: none; }
.page-host { min-height: 0; min-width: 0; overflow: hidden; display: flex; flex-direction: column; }
.page-host > section { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.toolbar { display: flex; align-items: center; gap: 8px; padding: 10px 14px; border-bottom: 1px solid var(--line); background: var(--surface); flex-wrap: wrap; min-width: 0; }
.toolbar h1 { font-size: 15px; font-weight: 600; margin: 0 8px 0 0; white-space: nowrap; }
.toolbar .counter { color: var(--muted); white-space: nowrap; }
.toolbar .counter b { color: var(--text); }
.toolbar .counter.won b { color: var(--gold); }
.toolbar .sub { color: var(--muted); font-size: var(--fs-small); }
/* due colonne ridimensionabili: elenco | maniglia | pannello */
.split { display: grid; grid-template-columns: minmax(480px, 1fr) 6px var(--panel-w, 400px); flex: 1; min-height: 0; }
.split.collapsed { grid-template-columns: minmax(0, 1fr) 6px 0; }
.split.collapsed > .panel { display: none; }
.split > .content { overflow: auto; min-width: 0; min-height: 0; position: relative; }
.vsplit { cursor: col-resize; background: var(--surface); border-left: 1px solid var(--line); border-right: 1px solid var(--line); position: relative; }
.vsplit::after { content: ""; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 2px; height: 28px; background: var(--faint); border-radius: 2px; }
.vsplit button { position: absolute; top: 6px; left: -8px; width: 20px; height: 20px; padding: 0; border-radius: 50%; border: 1px solid var(--line); background: var(--surface-2); color: var(--muted); font-size: 10px; z-index: 2; }
.hsplit { height: 6px; cursor: row-resize; background: var(--surface); border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); position: relative; }
.hsplit::after { content: ""; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 28px; height: 2px; background: var(--faint); border-radius: 2px; }
body.dragging, body.dragging * { user-select: none !important; cursor: inherit; }
/* registro in basso */
.bottom-log { background: var(--surface); padding: 6px 14px; font-size: var(--fs-small); color: var(--muted); height: var(--log-h, 96px); overflow: auto; line-height: 1.55; }
.bottom-log .ttl { color: var(--text); font-weight: 600; margin-right: 8px; cursor: pointer; }
.bottom-log .ttl:hover { text-decoration: underline; }
.bottom-log .line { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bottom-log .line .ts { color: var(--faint); margin-right: 6px; }
.bottom-log .lv-warn { color: var(--warn); }
.bottom-log .lv-err { color: var(--bad); }
.bottom-log .lv-ok { color: var(--ok); }
/* ── tabelle ─────────────────────────────────────────────────────────── */
table.grid { border-collapse: separate; border-spacing: 0; width: 100%; }
table.grid th {
position: sticky; top: 0; z-index: 1; background: var(--surface); color: var(--muted);
font-weight: 600; text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line);
font-size: var(--fs-small); white-space: nowrap; user-select: none;
}
table.grid th.sortable { cursor: pointer; }
table.grid th.sorted-asc::after { content: " \25B4"; color: var(--accent); }
table.grid th.sorted-desc::after { content: " \25BE"; color: var(--accent); }
table.grid td { padding: 7px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; vertical-align: middle; }
table.grid tbody tr { cursor: default; }
table.grid tbody tr:hover td { background: var(--surface-2); }
table.grid tbody tr.sel td { background: var(--surface-3); }
table.grid td.num, table.grid th.num { text-align: right; }
table.grid td.wrap { white-space: normal; }
table.grid td.ell { max-width: 0; overflow: hidden; text-overflow: ellipsis; }
table.grid .spacer-row td { padding: 0; border: 0; }
.empty { padding: 30px 14px; color: var(--muted); text-align: center; }
.timer { display: flex; flex-direction: column; gap: 3px; min-width: 86px; }
.timer .t { font-weight: 600; }
.timer .t.warn { color: var(--warn); }
.timer .t.bad { color: var(--bad); }
.bar { height: 3px; border-radius: 2px; background: var(--line); overflow: hidden; }
.bar i { display: block; height: 100%; background: var(--ok); width: 0; }
.bar i.warn { background: var(--warn); }
.bar i.bad { background: var(--bad); }
.ping { color: var(--ok); }
.ping.warn { color: var(--warn); }
.ping.bad { color: var(--bad); }
.acts { display: flex; gap: 4px; }
.acts button { width: 24px; height: 24px; padding: 0; border-radius: 4px; border: 1px solid var(--line); background: var(--surface-2); display: grid; place-items: center; font-size: 11px; color: var(--muted); }
.acts button:hover { color: var(--text); background: var(--surface-3); }
.acts button.on { border-color: var(--accent); color: var(--accent); }
.acts button.fire { color: var(--gold); }
.star { background: none; border: 0; padding: 0 2px; font-size: 14px; color: var(--faint); }
.star.on { color: var(--gold); }
/* ── pannello dettagli ───────────────────────────────────────────────── */
.panel { background: var(--surface); display: flex; flex-direction: column; min-height: 0; min-width: 0; }
.panel .head { padding: 10px 14px; border-bottom: 1px solid var(--line); }
.panel .head h2 { margin: 0; font-size: 14px; font-weight: 600; overflow-wrap: anywhere; }
.panel .head small { color: var(--muted); }
.tabs { display: flex; gap: 2px; padding: 6px 8px 0; border-bottom: 1px solid var(--line); overflow-x: auto; flex: none; }
.tabs button { padding: 7px 9px; color: var(--muted); border: 0; border-bottom: 2px solid transparent; background: none; white-space: nowrap; }
.tabs button.on { color: var(--text); border-color: var(--accent); font-weight: 600; }
.panel .body { padding: 12px 14px; overflow: auto; display: flex; flex-direction: column; gap: 12px; min-height: 0; flex: 1; }
.panel .placeholder { color: var(--muted); padding: 24px 14px; }
.kv { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 10px; font-size: 12.5px; margin: 0; }
.kv dt { color: var(--muted); margin: 0; }
.kv dd { margin: 0; text-align: right; font-weight: 600; }
.field { display: grid; grid-template-columns: minmax(0, 1fr) 130px; align-items: center; gap: 8px; }
.field label { color: var(--muted); }
.field input, .field select { text-align: right; width: 100%; }
.field.wide { grid-template-columns: minmax(0, 1fr) minmax(0, 220px); }
.card { background: var(--surface-2); border: 1px solid var(--line); border-radius: var(--r); padding: 10px 12px; }
.card h3 { margin: 0 0 6px; font-size: 12.5px; font-weight: 600; color: var(--muted); }
.verdict { padding: 8px 10px; border-radius: var(--r); border: 1px solid var(--muted); color: var(--muted); background: var(--muted-soft); }
.verdict.yes { border-color: var(--ok); color: var(--ok); background: var(--ok-soft); }
.verdict.no { border-color: var(--bad); color: var(--bad); background: var(--bad-soft); }
.verdict.explore { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
.log { font-size: var(--fs-small); line-height: 1.5; color: var(--muted); white-space: pre-wrap; font-family: var(--font); }
.log b { color: var(--text); font-weight: 600; }
.log .cnt { color: var(--faint); }
.product { display: grid; grid-template-columns: 108px minmax(0, 1fr); gap: 12px; align-items: start; }
.product .img { width: 108px; height: 108px; border-radius: var(--r); background: var(--surface-3); display: grid; place-items: center; color: var(--faint); font-size: var(--fs-tiny); text-align: center; overflow: hidden; }
.product .img img { width: 100%; height: 100%; object-fit: contain; background: #fff; }
/* ── pagine generiche ────────────────────────────────────────────────── */
.page { padding: 14px; overflow: auto; display: flex; flex-direction: column; gap: 14px; min-height: 0; flex: 1; }
.grid2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
.grid3 { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; }
.grid4 { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; }
.stat { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); padding: 12px 14px; min-width: 0; }
.stat .v { font-size: 22px; font-weight: 600; margin: 2px 0; }
.stat .l { color: var(--muted); font-size: var(--fs-small); }
.stat .s { color: var(--muted); font-size: var(--fs-small); }
.section { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); min-width: 0; display: flex; flex-direction: column; }
.section > h2 { margin: 0; padding: 10px 14px; font-size: 13.5px; font-weight: 600; border-bottom: 1px solid var(--line); display: flex; gap: 8px; align-items: center; }
.section > .in { padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
.section > .table-wrap { overflow: auto; max-height: 420px; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.settings-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; align-items: start; }
.settings-grid .field { grid-template-columns: minmax(0, 1fr) minmax(110px, 170px); }
.settings-grid .field.toggle-row { grid-template-columns: minmax(0, 1fr) auto; }
.weights { display: flex; flex-direction: column; gap: 5px; font-size: var(--fs-small); }
.weights .w { display: grid; grid-template-columns: minmax(0, 1fr) minmax(60px, 160px) 48px; gap: 8px; align-items: center; }
.weights .w .bar { height: 6px; }
.weights .w .bar i { background: var(--accent); }
.weights .w .bar i.neg { background: var(--bad); }
.hist { height: 60px; display: flex; align-items: flex-end; gap: 2px; }
.hist i { display: block; flex: 1; background: var(--accent); opacity: .8; border-radius: 1px; min-height: 1px; }
/* browser del bot (screencast) */
.browser { background: var(--browser-bg); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; display: flex; flex-direction: column; min-height: 0; }
.browser .url { display: flex; gap: 8px; align-items: center; padding: 7px 10px; background: var(--surface-2); border-bottom: 1px solid var(--line); color: var(--muted); font-size: var(--fs-small); }
.browser .url span.addr { flex: 1; background: var(--bg); border: 1px solid var(--line); border-radius: 4px; padding: 4px 8px; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.browser .view { position: relative; flex: 1; min-height: 300px; display: grid; place-items: center; outline: none; }
.browser .view canvas { max-width: 100%; max-height: 100%; cursor: pointer; display: block; }
.browser .view .idle { color: var(--muted); padding: 30px; text-align: center; }
/* ── dialoghi e avvisi ───────────────────────────────────────────────── */
.modal-back { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); display: grid; place-items: center; z-index: 50; padding: 16px; }
.modal { width: min(520px, 100%); max-height: calc(100vh - 32px); overflow: auto; background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-lg); box-shadow: 0 10px 40px var(--shadow); display: flex; flex-direction: column; }
.modal header { padding: 14px 16px; border-bottom: 1px solid var(--line); font-weight: 600; font-size: 14px; }
.modal .content { padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; }
.modal footer { padding: 12px 16px; border-top: 1px solid var(--line); display: flex; gap: 8px; justify-content: flex-end; }
.modal .field { grid-template-columns: minmax(0, 1fr) minmax(0, 220px); }
.toasts { position: fixed; right: 16px; bottom: 16px; display: flex; flex-direction: column; gap: 8px; z-index: 60; max-width: min(420px, calc(100vw - 32px)); }
.toast { background: var(--surface); border: 1px solid var(--line); border-left: 4px solid var(--accent); border-radius: var(--r); padding: 10px 12px; box-shadow: 0 6px 24px var(--shadow); }
.toast.ok { border-left-color: var(--ok); }
.toast.warn { border-left-color: var(--warn); }
.toast.bad { border-left-color: var(--bad); }
.conn-lost { position: fixed; top: calc(var(--topbar-h) + 8px); left: 50%; transform: translateX(-50%); z-index: 40; }
/* catalogo: categorie a sinistra */
.catalog { display: grid; grid-template-columns: 220px minmax(0, 1fr); flex: 1; min-height: 0; }
.catalog .cats { border-right: 1px solid var(--line); overflow: auto; padding: 8px; background: var(--surface); }
.catalog .cats button { display: block; width: 100%; text-align: left; padding: 6px 10px; border: 0; background: none; border-radius: var(--r); color: var(--muted); }
.catalog .cats button.on { background: var(--surface-3); color: var(--text); font-weight: 600; }
.catalog .list { overflow: auto; min-width: 0; }
.thumb { width: 40px; height: 40px; object-fit: contain; background: #fff; border-radius: 4px; }
/* ── finestre strette ────────────────────────────────────────────────── */
@media (max-width: 1100px) {
.app { grid-template-columns: var(--nav-w-narrow) minmax(0, 1fr); }
.app .nav .lbl { display: none; }
.app .nav a, .app .nav .collapse { justify-content: center; }
.topbar .opt { display: none; }
.toolbar .counter { display: none; }
.split { grid-template-columns: minmax(0, 1fr) 6px 0; position: relative; }
.split > .panel {
position: absolute; top: 0; right: 0; bottom: 0; width: min(var(--panel-w, 400px), 92%);
border-left: 1px solid var(--line); box-shadow: -10px 0 30px var(--shadow); z-index: 5;
}
.split:not(.drawer-open) > .panel { display: none; }
.settings-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.grid4 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.grid3 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 720px) {
.settings-grid, .grid2, .grid3, .grid4 { grid-template-columns: minmax(0, 1fr); }
.catalog { grid-template-columns: minmax(0, 1fr); }
.catalog .cats { display: none; }
.topbar .brand span.name { display: none; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { transition: none !important; animation: none !important; }
}
@@ -0,0 +1,75 @@
/*
Bidoo BidBot — token dell'interfaccia (unica origine dei colori).
Nati dai token semantici di docs/mockup/mock.css. Il colore ha significato:
neutro = secondario, accento = primario, verde/ambra/rosso = ok/attenzione/pericolo,
oro = asta vinta o «sono io». Tema scuro predefinito; chiaro con gli stessi nomi.
*/
:root,
:root[data-theme="dark"] {
color-scheme: dark;
--bg: #151920;
--surface: #1c2129;
--surface-2: #232a34;
--surface-3: #2a323d;
--line: #2c3441;
--text: #e6eaf1;
--muted: #93a0b4;
--faint: #5f6b7d;
--accent: #5b9cff;
--accent-ink: #0b1d3a;
--ok: #3ecf8e;
--warn: #f2b640;
--bad: #f15b50;
--gold: #e5b94e;
--shadow: rgba(0, 0, 0, .45);
--ok-soft: rgba(62, 207, 142, .16);
--warn-soft: rgba(242, 182, 64, .16);
--bad-soft: rgba(241, 91, 80, .14);
--accent-soft: rgba(91, 156, 255, .16);
--gold-soft: rgba(229, 185, 78, .18);
--muted-soft: rgba(147, 160, 180, .16);
--browser-bg: #0e1116;
}
:root[data-theme="light"] {
color-scheme: light;
--bg: #eef1f5;
--surface: #ffffff;
--surface-2: #f4f6f9;
--surface-3: #e9edf3;
--line: #d7dde6;
--text: #1b2230;
--muted: #5b6778;
--faint: #9aa5b5;
--accent: #2f6fe4;
--accent-ink: #ffffff;
--ok: #1f9d63;
--warn: #c98a10;
--bad: #d63b31;
--gold: #b8891a;
--shadow: rgba(20, 30, 50, .18);
--ok-soft: rgba(31, 157, 99, .14);
--warn-soft: rgba(201, 138, 16, .14);
--bad-soft: rgba(214, 59, 49, .12);
--accent-soft: rgba(47, 111, 228, .12);
--gold-soft: rgba(184, 137, 26, .16);
--muted-soft: rgba(91, 103, 120, .12);
--browser-bg: #dfe3ea;
}
:root {
--font: "Segoe UI", system-ui, "Liberation Sans", Arial, sans-serif;
--mono: ui-monospace, "Cascadia Mono", "Liberation Mono", monospace;
--r: 6px;
--r-lg: 8px;
--fs: 13px;
--fs-small: 12px;
--fs-tiny: 11px;
--topbar-h: 46px;
--nav-w: 212px;
--nav-w-narrow: 56px;
}
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" role="img" aria-label="Bidoo BidBot">
<rect width="128" height="128" rx="26" fill="#5b9cff"/>
<text x="64" y="90" text-anchor="middle" font-family="Segoe UI, Liberation Sans, Arial, sans-serif" font-size="78" font-weight="800" fill="#0b1d3a">B</text>
</svg>

After

Width:  |  Height:  |  Size: 324 B

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<RootNamespace>BidooBidBot.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\BidooBidBot\BidooBidBot.csproj" />
</ItemGroup>
<ItemGroup>
<!-- Risposte registrate dal sito vero: i parser si provano su quelle. -->
<None Include="Fixtures\**\*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -0,0 +1,123 @@
using System.Text.Json;
using BidooBidBot.Data;
using BidooBidBot.Settings;
using Xunit;
namespace BidooBidBot.Tests;
/// <summary>Migrazioni, partizioni, coda di scrittura, documenti e impostazioni su PostgreSQL 18.</summary>
[Collection("Database")]
public class DatabaseTests
{
private readonly DatabaseFixture _fx;
public DatabaseTests(DatabaseFixture fx) => _fx = fx;
[DbFact]
public async Task Le_migrazioni_sono_applicate_una_volta_sola()
{
var again = await Migrations.ApplyAsync(_fx.Db!.Writer);
Assert.Empty(again);
Assert.True(await Migrations.CurrentVersionAsync(_fx.Db) >= 1);
// Nessuna delle tabelle che la specifica esclude.
foreach (var t in new[] { "polls", "auction_log", "network_metrics", "app_sessions", "maintenance_log" })
Assert.False(await _fx.Db.ScalarAsync<bool>("SELECT to_regclass($1) IS NOT NULL", t));
}
[DbFact]
public async Task Le_partizioni_del_mese_e_del_successivo_esistono()
{
var created = await Partitions.EnsureAsync(_fx.Db!, new DateTime(2031, 12, 5));
Assert.Equal(6, created); // dicembre 2031 e gennaio 2032, per tre tabelle
Assert.Equal(0, await Partitions.EnsureAsync(_fx.Db!, new DateTime(2031, 12, 20)));
var list = await Partitions.ListAsync(_fx.Db!, "bids");
Assert.Contains(list, p => p.Name == "bids_2032_01" && p.Month == new DateTime(2032, 1, 1));
}
[DbFact]
public async Task La_coda_scrive_a_lotti_e_svuota_allo_spegnimento()
{
await _fx.TruncateAsync();
await using (var queue = new WriteQueue(_fx.Db!.Writer) { BatchRows = 50 })
{
for (var i = 0; i < 230; i++)
queue.EnqueueBid("INSERT INTO bids(auction_id, username, price_after, bid_type) VALUES($1, $2, $3, $4)",
"a1", $"u{i % 7}", 0.01 * (i + 1), "Auto");
Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20)));
Assert.Equal(230, queue.Written);
}
Assert.Equal(230L, await _fx.Db.ScalarAsync<long>("SELECT COUNT(*) FROM bids WHERE auction_id = 'a1'"));
}
[DbFact]
public async Task Un_istruzione_sbagliata_non_blocca_le_altre()
{
await _fx.TruncateAsync();
await using var queue = new WriteQueue(_fx.Db!.Writer);
queue.Enqueue("INSERT INTO risk_ledger(ts, kind, amount_euro) VALUES(now(), 'bid', -0.2)");
queue.Enqueue("INSERT INTO tabella_che_non_esiste(x) VALUES(1)");
queue.Enqueue("INSERT INTO risk_ledger(ts, kind, amount_euro) VALUES(now(), 'bid', -0.2)");
Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20)));
Assert.Equal(1, queue.Failed);
Assert.Equal(2L, await _fx.Db.ScalarAsync<long>("SELECT COUNT(*) FROM risk_ledger"));
}
[DbFact]
public async Task I_documenti_si_rileggono_dopo_il_riavvio()
{
await _fx.TruncateAsync();
await using (var queue = new WriteQueue(_fx.Db!.Writer))
{
var docs = new DocumentStore(queue);
docs.Set("ml/prova", """{"a":1}""");
docs.Set("ml/altro", """{"b":2}""");
docs.Set("risk/halt", """{"reason":"x"}""");
docs.DeletePrefix("ml/");
docs.Set("ml/nuovo", """{"c":3}""");
await queue.FlushAsync(TimeSpan.FromSeconds(20));
}
await using var q2 = new WriteQueue(_fx.Db.Writer);
var reloaded = new DocumentStore(q2);
await reloaded.LoadAsync(_fx.Db);
Assert.Null(reloaded.Get("ml/prova"));
Assert.NotNull(reloaded.Get("ml/nuovo"));
Assert.Contains("reason", reloaded.Get("risk/halt"));
}
[DbFact]
public async Task Le_impostazioni_nascono_di_fabbrica_e_sopravvivono_al_riavvio()
{
await _fx.TruncateAsync();
await using var queue = new WriteQueue(_fx.Db!.Writer);
var store = new SettingsStore(queue, null);
await store.LoadAsync(_fx.Db);
Assert.Equal(300, store.Current.LearningMinAuctions);
var patch = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>("""{"DataCapGb": 20}""")!;
Assert.True((await store.SaveAsync(patch, null)).Ok);
var again = new SettingsStore(queue, null);
await again.LoadAsync(_fx.Db);
Assert.Equal(20, again.Current.DataCapGb);
}
}
public class WriteQueueCapacityTests
{
[Fact]
public void A_coda_piena_si_scartano_prima_le_puntate_osservate()
{
var queue = new WriteQueue(null) { Capacity = 10 };
for (var i = 0; i < 8; i++) queue.EnqueueBid("INSERT bid", i);
for (var i = 0; i < 5; i++) queue.Enqueue("INSERT altro", i);
Assert.Equal(10, queue.Pending);
Assert.Equal(3, queue.Dropped);
}
}
@@ -0,0 +1,301 @@
using System.Text.Json;
using BidooBidBot.Config;
using BidooBidBot.Logging;
using BidooBidBot.Settings;
using BidooBidBot.Web;
using Xunit;
namespace BidooBidBot.Tests;
/// <summary>Niente simboli né emoji nei registri (portati dal legacy).</summary>
public class LogTextTests
{
[Theory]
[InlineData("✓ Convenienza OK → tutto ok — bene… ≤ 3 × 2 €", "Convenienza OK -> tutto ok - bene... <= 3 x 2 EUR")]
[InlineData("🔥 avvio motore ⚡", "avvio motore")]
[InlineData("riga uno\r\nriga due\tfine", "riga uno riga due fine")]
[InlineData("«virgolette» e “altre”", "\"virgolette\" e \"altre\"")]
[InlineData("", "")]
public void Il_testo_esce_in_chiaro(string dentro, string fuori)
{
Assert.Equal(fuori, LogText.Clean(dentro));
}
[Fact]
public void Il_registro_applicativo_tiene_il_tag_e_rispetta_il_livello()
{
var log = new AppLog(null) { MinLevel = LogLevel.Info, Capacity = 50 };
LogEntry? seen = null;
log.Entry += e => seen = e;
log.Debug("PUNTATA", "non si vede");
Assert.Null(seen);
log.Info("puntata", "Buono → 4,12 €");
Assert.NotNull(seen);
Assert.Equal("PUNTATA", seen!.Tag);
Assert.Equal("[PUNTATA] Buono -> 4,12 EUR", seen.Text);
Assert.Single(log.Snapshot());
}
[Fact]
public void L_anello_in_memoria_ha_un_tetto()
{
var log = new AppLog(null) { Capacity = 60 };
for (var i = 0; i < 200; i++) log.Info("X", $"riga {i}");
var rows = log.Snapshot();
Assert.Equal(60, rows.Count);
Assert.Equal("riga 199", rows[^1].Message);
}
[Fact]
public async Task Il_file_giornaliero_riceve_le_righe()
{
using var dir = new TempDir();
var file = new FileLog(dir.Path);
var log = new AppLog(file);
log.Info("AVVIO", "prova");
await file.DisposeAsync();
var text = File.ReadAllText(file.PathFor("app", DateTime.Now));
Assert.Contains("[AVVIO] prova", text);
}
}
public class EnvConfigTests
{
[Theory]
[InlineData("192.168.30.23", "192.168.30.23", null)]
[InlineData("192.168.30.23:5433", "192.168.30.23", 5433)]
[InlineData("postgres:5432", "postgres", 5432)]
[InlineData("[::1]:5432", "::1", 5432)]
[InlineData(" ", "", null)]
public void DB_HOST_accetta_anche_la_porta(string raw, string host, int? port)
{
var (h, p) = EnvConfig.SplitHost(raw);
Assert.Equal(host, h);
Assert.Equal(port, p);
}
[Fact]
public void Predefiniti_e_porta_separata()
{
var env = new Dictionary<string, string?> { ["DB_HOST"] = "db", ["DB_PORT"] = "6000", ["DB_PASSWORD"] = "x" };
var cfg = EnvConfig.Read(k => env.GetValueOrDefault(k), Array.Empty<string>());
Assert.Equal("db", cfg.DbHost);
Assert.Equal(6000, cfg.DbPort);
Assert.Equal("admin", cfg.DbUser);
Assert.Equal("autobidder", cfg.DbName);
Assert.Equal(8080, cfg.HttpPort);
Assert.False(cfg.HasUiPassword);
Assert.Equal("/config", cfg.ConfigDir);
Assert.DoesNotContain("x", cfg.ToDbConfig().Describe());
}
}
/// <summary>Avvio senza variabili: schermata d'errore, niente database (ConfigErrorTests della specifica).</summary>
public class ConfigErrorTests
{
[Fact]
public async Task Senza_variabili_il_rapporto_dice_cosa_manca()
{
using var dir = new TempDir();
var env = EnvConfig.Read(_ => null, new[] { "--config", dir.Path });
var (report, db) = await StartupCheck.RunAsync(env, new ConfigPaths(dir.Path), 1, CancellationToken.None);
Assert.Null(db);
Assert.False(report.AllOk);
Assert.Contains(report.Items, i => i.Key == "db_host" && !i.Ok);
Assert.Contains(report.Items, i => i.Key == "db_password" && !i.Ok);
Assert.Contains(report.Items, i => i.Key == "ui_password" && !i.Ok);
Assert.Contains(report.Items, i => i.Key == "config" && i.Ok);
}
[Fact]
public async Task Database_irraggiungibile_da_un_errore_leggibile()
{
using var dir = new TempDir();
var vars = new Dictionary<string, string?> { ["DB_HOST"] = "127.0.0.1:1", ["DB_PASSWORD"] = "segreta", ["UI_PASSWORD"] = "x" };
var env = EnvConfig.Read(k => vars.GetValueOrDefault(k), new[] { "--config", dir.Path });
var (report, db) = await StartupCheck.RunAsync(env, new ConfigPaths(dir.Path), 1, CancellationToken.None);
Assert.Null(db);
var item = Assert.Single(report.Items, i => i.Key == "database");
Assert.False(item.Ok);
Assert.StartsWith("Npgsql:", item.Error);
Assert.DoesNotContain("segreta", item.Error + item.Detail);
var html = Pages.ConfigError("1.0.0", report, 30);
Assert.Contains("Bidoo BidBot non può partire", html);
Assert.Contains("Riprova adesso", html);
Assert.DoesNotContain("segreta", html);
}
}
public class UiAuthTests
{
private static UiAuth Make(string password = "giusta") => new(password, new byte[32]);
[Fact]
public void Solo_la_password_giusta_passa()
{
var auth = Make();
Assert.True(auth.CheckPassword("giusta"));
Assert.False(auth.CheckPassword("Giusta"));
Assert.False(auth.CheckPassword(""));
Assert.False(auth.CheckPassword(null));
}
[Fact]
public void Il_cookie_vale_30_giorni_e_poi_scade()
{
var auth = Make();
var now = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero);
var token = auth.IssueToken(now);
Assert.True(auth.Validate(token, now.AddDays(29)).Valid);
Assert.False(auth.Validate(token, now.AddDays(31)).Valid);
Assert.True(auth.Validate(token, now.AddDays(2)).ShouldRenew);
Assert.False(auth.Validate(token, now.AddHours(2)).ShouldRenew);
}
[Fact]
public void Un_cookie_alterato_o_di_un_altra_password_non_vale()
{
var now = DateTimeOffset.UtcNow;
var token = Make().IssueToken(now);
Assert.False(Make("altra").Validate(token, now).Valid);
Assert.False(Make().Validate(token[..^2] + "AA", now).Valid);
Assert.False(Make().Validate("spazzatura", now).Valid);
Assert.False(Make().Validate(null, now).Valid);
}
[Fact]
public void Dopo_cinque_tentativi_l_attesa_cresce()
{
var auth = Make();
var now = DateTimeOffset.UtcNow;
for (var i = 0; i < 4; i++) Assert.Equal(TimeSpan.Zero, auth.RecordFailure("1.2.3.4", now));
Assert.Equal(TimeSpan.FromSeconds(2), auth.RecordFailure("1.2.3.4", now));
Assert.Equal(TimeSpan.FromSeconds(4), auth.RecordFailure("1.2.3.4", now));
Assert.Equal(TimeSpan.FromSeconds(8), auth.RecordFailure("1.2.3.4", now));
Assert.True(auth.LockedFor("1.2.3.4", now) > TimeSpan.Zero);
Assert.Equal(TimeSpan.Zero, auth.LockedFor("5.6.7.8", now));
auth.RecordSuccess("1.2.3.4");
Assert.Equal(TimeSpan.Zero, auth.LockedFor("1.2.3.4", now));
}
[Fact]
public void La_chiave_si_crea_una_volta_e_si_rilegge()
{
using var dir = new TempDir();
var file = Path.Combine(dir.Path, "sessione", "interfaccia.key");
var a = UiAuth.LoadOrCreateKey(file);
var b = UiAuth.LoadOrCreateKey(file);
Assert.Equal(32, a.Length);
Assert.Equal(a, b);
}
}
/// <summary>Impostazioni: valori di fabbrica, migrazione, conferma DAL VIVO, segreti (SettingsMigrationTests).</summary>
public class SettingsTests
{
private static Dictionary<string, JsonElement> Patch(string json) =>
JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json)!;
[Fact]
public void I_paletti_di_fabbrica_sono_tutti_a_zero()
{
var s = new AppSettings();
Assert.Equal(0, s.DefaultMaxPrice);
Assert.Equal(0, s.MaxBidsPerAuction);
Assert.Equal(0, s.MinimumRemainingBids);
Assert.Equal(0, s.DailyBudgetEuro);
Assert.False(s.QuietHoursEnabled);
Assert.False(s.LiveBiddingEnabled);
Assert.Equal(300, s.LearningMinAuctions);
Assert.Equal(50, s.DataCapGb);
Assert.Equal("Osserva", s.AutoAddNewAuctionState);
}
[Fact]
public void La_migrazione_porta_i_modi_in_italiano()
{
var s = new AppSettings { SettingsSchemaVersion = 0, AutoAddNewAuctionState = "Watch", DefaultStartAuctionsOnLoad = "Stopped", DefaultNewAuctionState = "Active" };
Assert.True(SettingsStore.Migrate(s));
Assert.Equal("Osserva", s.AutoAddNewAuctionState);
Assert.Equal("Ferma", s.DefaultStartAuctionsOnLoad);
Assert.Equal("Attiva", s.DefaultNewAuctionState);
Assert.False(SettingsStore.Migrate(s));
}
[Fact]
public void I_valori_fuori_scala_si_riportano_nei_limiti()
{
var s = SettingsStore.Normalize(new AppSettings { LeadMinMs = 10, LeadMaxMs = 5, QuietHoursStart = 25, DataCapGb = 0, PollCriticalMs = 1 });
Assert.Equal(100, s.LeadMinMs);
Assert.Equal(100, s.LeadMaxMs);
Assert.Equal(1, s.QuietHoursStart);
Assert.Equal(1, s.DataCapGb);
Assert.Equal(50, s.PollCriticalMs);
}
[Fact]
public async Task Il_salvataggio_vale_subito_e_si_scrive_nel_registro()
{
var log = new AppLog(null);
var store = new SettingsStore(null, log);
var result = await store.SaveAsync(Patch("""{"DailyBudgetEuro": 15, "MaxBidsPerAuction": 25}"""), null);
Assert.True(result.Ok);
Assert.Equal(15, store.Current.DailyBudgetEuro);
Assert.Equal(2, result.Changes.Count);
Assert.Contains(log.Snapshot(), e => e.Tag == "IMPOSTAZIONI" && e.Message.StartsWith("DailyBudgetEuro: 0 -> 15"));
}
[Fact]
public async Task Per_puntare_dal_vivo_serve_la_parola()
{
var store = new SettingsStore(null, null);
var denied = await store.SaveAsync(Patch("""{"LiveBiddingEnabled": true}"""), "si");
Assert.False(denied.Ok);
Assert.False(store.Current.LiveBiddingEnabled);
var ok = await store.SaveAsync(Patch("""{"LiveBiddingEnabled": true}"""), "DAL VIVO");
Assert.True(ok.Ok);
Assert.True(store.Current.LiveBiddingEnabled);
// Spegnere non chiede conferme.
var off = await store.SaveAsync(Patch("""{"LiveBiddingEnabled": false}"""), null);
Assert.True(off.Ok);
Assert.False(store.Current.LiveBiddingEnabled);
}
[Fact]
public async Task I_segreti_non_finiscono_nel_registro_e_tornano_mascherati()
{
var log = new AppLog(null);
var store = new SettingsStore(null, log);
await store.SaveAsync(Patch("""{"TelegramBotToken": "123:segretissimo"}"""), null);
Assert.DoesNotContain(log.Snapshot(), e => e.Message.Contains("segretissimo"));
Assert.Equal(SettingsStore.MaskedSecret, SettingsStore.ForDisplay(store.Current)["TelegramBotToken"]);
// Il valore mascherato che torna dall'interfaccia lascia il segreto com'era.
await store.SaveAsync(Patch("""{"TelegramBotToken": "********", "TelegramChatId": "42"}"""), null);
Assert.Equal("123:segretissimo", store.Current.TelegramBotToken);
}
[Fact]
public async Task Una_chiave_sconosciuta_o_un_tipo_sbagliato_non_si_salvano()
{
var store = new SettingsStore(null, null);
Assert.False((await store.SaveAsync(Patch("""{"NonEsiste": 1}"""), null)).Ok);
Assert.False((await store.SaveAsync(Patch("""{"DailyBudgetEuro": "tanto"}"""), null)).Ok);
Assert.Equal(0, store.Current.DailyBudgetEuro);
}
}
@@ -0,0 +1,105 @@
using System.Globalization;
using System.Runtime.CompilerServices;
using BidooBidBot.Data;
using Npgsql;
using Xunit;
namespace BidooBidBot.Tests;
/// <summary>Numeri all'italiana anche nei test: i messaggi del bot si leggono così.</summary>
internal static class TestCulture
{
[ModuleInitializer]
internal static void Init()
{
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("it-IT");
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("it-IT");
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("it-IT");
}
}
/// <summary>
/// Il PostgreSQL dei test, da <c>TEST_DB_HOST</c> (più <c>TEST_DB_USER</c>,
/// <c>TEST_DB_PASSWORD</c>, <c>TEST_DB_NAME</c>). Senza la variabile i test su database
/// saltano: in locale basta il compose di <c>tools/dev</c>, nel workflow c'è il servizio.
/// </summary>
public static class TestDb
{
public static string? Host => Environment.GetEnvironmentVariable("TEST_DB_HOST") is { Length: > 0 } h ? h : null;
public static DbConfig Config => new(
Host ?? "localhost",
5432,
Environment.GetEnvironmentVariable("TEST_DB_USER") ?? "admin",
Environment.GetEnvironmentVariable("TEST_DB_PASSWORD") ?? "dev",
Environment.GetEnvironmentVariable("TEST_DB_NAME") ?? "bidbot_test");
}
/// <summary>Un test su PostgreSQL: salta se <c>TEST_DB_HOST</c> non è impostata.</summary>
public sealed class DbFactAttribute : FactAttribute
{
public DbFactAttribute()
{
if (TestDb.Host == null) Skip = "TEST_DB_HOST non impostata: test su PostgreSQL saltato";
}
}
/// <summary>
/// Database di prova pulito, una volta per esecuzione: si cancella e si ricrea, poi si
/// applicano le migrazioni. I test della collezione «Database» girano uno alla volta.
/// </summary>
public sealed class DatabaseFixture : IAsyncLifetime
{
public Db? Db { get; private set; }
public async Task InitializeAsync()
{
if (TestDb.Host == null) return;
var cfg = TestDb.Config;
await using (var admin = new NpgsqlConnection(cfg.Builder("postgres").ConnectionString))
{
await admin.OpenAsync();
var name = cfg.Database.Replace("\"", "\"\"", StringComparison.Ordinal);
await using (var drop = new NpgsqlCommand($"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", admin))
await drop.ExecuteNonQueryAsync();
await using (var create = new NpgsqlCommand($"CREATE DATABASE \"{name}\"", admin))
await create.ExecuteNonQueryAsync();
}
Db = new Db(cfg);
await Migrations.ApplyAsync(Db.Writer);
await Partitions.EnsureAsync(Db, DateTime.UtcNow);
}
public async Task DisposeAsync()
{
if (Db != null) await Db.DisposeAsync();
}
/// <summary>Svuota le tabelle fra un test e l'altro (le partizioni restano).</summary>
public async Task TruncateAsync()
{
await Db!.ExecuteAsync(
"TRUNCATE settings, documents, items, auctions, bids, resets, my_bids, bot_decisions, auction_forecasts, " +
"bidders, risk_ledger, products, watched_products, product_stats RESTART IDENTITY CASCADE");
}
}
[CollectionDefinition("Database")]
public sealed class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{
}
/// <summary>Cartella temporanea che si cancella da sola: i test non scrivono mai altrove.</summary>
public sealed class TempDir : IDisposable
{
public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "bidbot-test-" + Guid.NewGuid().ToString("N")[..10]);
public TempDir() => Directory.CreateDirectory(Path);
public void Dispose()
{
try { Directory.Delete(Path, true); } catch { }
}
}
+72
View File
@@ -0,0 +1,72 @@
# Sviluppo locale di Bidoo BidBot: PostgreSQL 18 come su Unraid, e il bot dal Dockerfile.
#
# docker compose -f tools/dev/docker-compose.yml up -d postgres # solo il database
# docker compose -f tools/dev/docker-compose.yml up -d --build # database + bot
# docker compose -f tools/dev/docker-compose.yml --profile simulatore up -d --build
#
# Il bot legge /config da tools/dev/config (ignorata da git). Interfaccia: http://localhost:8080,
# password «dev». Fuori da Docker: DB_HOST=localhost DB_PASSWORD=dev UI_PASSWORD=dev
# dotnet run --project src/BidooBidBot -- --config tools/dev/config
name: bidoo-bidbot-dev
services:
postgres:
image: postgres:18
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: dev
POSTGRES_DB: autobidder
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U admin -d autobidder"]
interval: 5s
retries: 20
bot:
build:
context: ../..
dockerfile: docker/Dockerfile
args:
VERSION: dev
depends_on:
postgres:
condition: service_healthy
environment:
DB_HOST: postgres:5432
DB_PASSWORD: dev
UI_PASSWORD: dev
TZ: Europe/Rome
PUID: "1000"
PGID: "1000"
ports:
- "8080:8080"
volumes:
- ./config:/config
# Lo stesso bot, senza sessione Bidoo: parte in modalità simulatore (banner in alto).
bot-simulatore:
profiles: ["simulatore"]
build:
context: ../..
dockerfile: docker/Dockerfile
args:
VERSION: dev
depends_on:
postgres:
condition: service_healthy
environment:
DB_HOST: postgres:5432
DB_NAME: bidbot_simulatore
DB_PASSWORD: dev
UI_PASSWORD: dev
TZ: Europe/Rome
ports:
- "8081:8080"
volumes:
- ./config-simulatore:/config
volumes:
pgdata:
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0"?>
<Container version="2">
<Name>bidoo-bidbot</Name>
<Repository>192.168.30.23:3000/alby96/bidoo-bidbot:latest</Repository>
<Registry>http://192.168.30.23:3000/Alby96/-/packages/container/bidoo-bidbot</Registry>
<Network>bridge</Network>
<MyIP/>
<Shell>bash</Shell>
<Privileged>false</Privileged>
<Support>http://192.168.30.23:3000/Alby96/bidoo-bidbot/issues</Support>
<Project>http://192.168.30.23:3000/Alby96/bidoo-bidbot</Project>
<Overview>Bidoo BidBot: segue le aste al centesimo di Bidoo, decide con un modello appreso se puntare e punta negli ultimi millisecondi. Parte in modalita' OSSERVA (nessuna puntata reale). Richiede il container PostgreSQL (postgresql18) e una password per l'interfaccia. Interfaccia web sulla porta 8080, notifiche Telegram. Registry in HTTP: aggiungi --insecure-registry 192.168.30.23:3000 in DOCKER_OPTS (/boot/config/docker.cfg). Uso personale: rispetta i Termini di Bidoo, un solo account.</Overview>
<Category>Tools: Productivity:</Category>
<WebUI>http://[IP]:[PORT:8080]/</WebUI>
<TemplateURL>http://192.168.30.23:3000/Alby96/bidoo-bidbot/raw/branch/main/unraid/bidoo-bidbot.xml</TemplateURL>
<Icon>http://192.168.30.23:3000/Alby96/bidoo-bidbot/raw/branch/main/docs/icona.png</Icon>
<ExtraParams>--memory=1g --restart=unless-stopped --stop-timeout 15</ExtraParams>
<PostArgs/>
<CPUset/>
<DateInstalled/>
<DonateText/>
<DonateLink/>
<Requires>Il container PostgreSQL (postgresql18, utente admin, database autobidder) raggiungibile dal bot.</Requires>
<Config Name="Interfaccia web" Target="8080" Default="8080" Mode="tcp" Description="Porta dell'interfaccia" Type="Port" Display="always" Required="true" Mask="false">8080</Config>
<Config Name="Cartella dati (/config)" Target="/config" Default="/mnt/user/appdata/bidoo-bidbot" Mode="rw" Description="Sessione, riferimenti, registri, esportazioni, profilo browser, backup" Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/bidoo-bidbot</Config>
<Config Name="DB_HOST" Target="DB_HOST" Default="192.168.30.23:5432" Mode="" Description="Indirizzo del container PostgreSQL (IP o nome, con :porta se non e' 5432)" Type="Variable" Display="always" Required="true" Mask="false">192.168.30.23:5432</Config>
<Config Name="DB_PASSWORD" Target="DB_PASSWORD" Default="" Mode="" Description="Password dell'utente PostgreSQL" Type="Variable" Display="always" Required="true" Mask="true"></Config>
<Config Name="UI_PASSWORD" Target="UI_PASSWORD" Default="" Mode="" Description="Password per entrare nell'interfaccia web (comanda puntate vere)" Type="Variable" Display="always" Required="true" Mask="true"></Config>
<Config Name="DB_USER" Target="DB_USER" Default="admin" Mode="" Description="Utente PostgreSQL" Type="Variable" Display="advanced" Required="false" Mask="false">admin</Config>
<Config Name="DB_NAME" Target="DB_NAME" Default="autobidder" Mode="" Description="Nome del database (creato se manca e l'utente puo')" Type="Variable" Display="advanced" Required="false" Mask="false">autobidder</Config>
<Config Name="TZ" Target="TZ" Default="Europe/Rome" Mode="" Description="Fuso orario" Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
<Config Name="PUID" Target="PUID" Default="99" Mode="" Description="Utente per i file in /config" Type="Variable" Display="advanced" Required="false" Mask="false">99</Config>
<Config Name="PGID" Target="PGID" Default="100" Mode="" Description="Gruppo per i file in /config" Type="Variable" Display="advanced" Required="false" Mask="false">100</Config>
</Container>