Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
992467ff04 | ||
|
|
cf6d0536aa | ||
|
|
101dcbb152 | ||
|
|
f9d71559e8 | ||
|
|
53ca01b7c3 | ||
|
|
ffb67c9135 |
No files matched your search
@@ -6,6 +6,7 @@
|
||||
artifacts/
|
||||
TestResults/
|
||||
docs/
|
||||
!docs/design/logo/
|
||||
**/*.md
|
||||
.env
|
||||
.env.*
|
||||
@@ -24,3 +24,7 @@ csharp_using_directive_placement = outside_namespace:warning
|
||||
dotnet_style_qualification_for_field = false:warning
|
||||
dotnet_style_qualification_for_property = false:warning
|
||||
dotnet_style_qualification_for_method = false:warning
|
||||
|
||||
# Tests: literal arrays in assertions read better than static fields.
|
||||
[tests/**.cs]
|
||||
dotnet_diagnostic.CA1861.severity = none
|
||||
@@ -5,3 +5,4 @@
|
||||
Dockerfile text eol=lf
|
||||
*.png binary
|
||||
*.ico binary
|
||||
*.ttf binary
|
||||
@@ -32,6 +32,7 @@ jobs:
|
||||
ANUBIS_TEST_DB: ${{ matrix.db }}
|
||||
ANUBIS_TEST_PG_HOST: postgres
|
||||
ANUBIS_TEST_PG_PORT: "5432"
|
||||
ANUBIS_TEST_PG_PASSWORD: anubis-ci
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
|
||||
DOTNET_NOLOGO: "1"
|
||||
TESTINGPLATFORM_TELEMETRY_OPTOUT: "1"
|
||||
|
||||
@@ -11,15 +11,17 @@ Bot di trading personale: azioni USA su Alpaca, crypto spot su OKX Europe, senza
|
||||
|
||||
## Comandi
|
||||
|
||||
Da `tools/Anubis.Tasks`, tramite `./tasks.ps1 <comando>` (Windows) o `sh ./tasks.sh <comando>` (Linux). Niente `make`.
|
||||
Dalla radice del repository: `./tasks.ps1 <comando>` (Windows) o `sh ./tasks.sh <comando>` (Linux); il codice sta in `tools/Anubis.Tasks`. Niente `make`.
|
||||
- `check`: ripristino con `--locked-mode`, `dotnet format --verify-no-changes`, build Release con gli analizzatori, test. Va verde prima di ogni commit.
|
||||
- `test`: solo i test; il motore viene da `ANUBIS_TEST_DB` (`sqlite` o `postgres`). Esclude la categoria `LiveDemo`.
|
||||
- `dev`: il server con `dotnet watch` su http://localhost:5000 (o `--urls`).
|
||||
- `dev`: il server con `dotnet watch` su http://localhost:8787 (o `--urls`). Fuori da Docker usa la configurazione desktop e la cartella dei dati dell'utente (`%APPDATA%\Anubis`): per provare senza toccarla c'è `seed-demo`.
|
||||
- `build`: l'immagine Docker `gitea.encke-hake.ts.net/balbosoft/anubis:dev`.
|
||||
- `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker.
|
||||
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
||||
- `seed-demo` (Fase 1), `desktop-win` (Fase 10): non ancora disponibili.
|
||||
- `docker compose up --build`: l'applicazione su http://localhost:8787, `/health` risponde `ok`.
|
||||
- `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso.
|
||||
- `screenshots`: fotografa Panoramica, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati.
|
||||
- `desktop-win` (Fase 10): non ancora disponibile.
|
||||
- `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose.
|
||||
|
||||
Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR 0004) e presente in `Directory.Packages.props` e nel file di blocco. Una sua dipendenza di terze parti va aggiunta all'elenco del test e a `docs/API-NOTES.md` (ADR 0006).
|
||||
|
||||
@@ -42,6 +44,7 @@ Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR
|
||||
- `docs/SPEC.md` — specifica completa
|
||||
- `docs/adr/0003-csharp-dotnet.md` — stack, struttura del repository, strumenti
|
||||
- `docs/adr/0004-componenti-esterni.md` — pacchetti ammessi e come chiederne altri
|
||||
- `docs/adr/0007-scelte-fase-1.md` — schema per i due motori, interfaccia statica, immagine Docker
|
||||
- `docs/design/` — screen di riferimento (SPEC 13.1); `docs/design/logo/` — logo
|
||||
- `docs/ROADMAP.md` — fasi, issue, criteri di accettazione
|
||||
- `docs/STATE.md` — stato corrente
|
||||
|
||||
@@ -9,4 +9,11 @@
|
||||
<PackageVersion Include="MSTest.TestAdapter" Version="4.5.2" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Databases (ADR 0003): ADO.NET drivers for PostgreSQL and SQLite. -->
|
||||
<PackageVersion Include="Npgsql" Version="10.0.3" />
|
||||
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.14" />
|
||||
<!-- Desktop secret key on Windows (DPAPI, SPEC 15.6). -->
|
||||
<PackageVersion Include="System.Security.Cryptography.ProtectedData" Version="10.0.14" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,5 +1,5 @@
|
||||
# Anubis image (ADR 0003). Phase 0: minimal server with /health.
|
||||
# Phase 1 adds the entrypoint (PUID/PGID, data folder) and the HEALTHCHECK (issue #16).
|
||||
# Anubis image (ADR 0003, SPEC 15.2). Build from the repository root:
|
||||
# docker build -f deploy/docker/Dockerfile -t gitea.encke-hake.ts.net/balbosoft/anubis:dev .
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
@@ -9,14 +9,24 @@ COPY src/Anubis.Server/Anubis.Server.csproj src/Anubis.Server/packages.lock.json
|
||||
RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode
|
||||
COPY src/Anubis/ src/Anubis/
|
||||
COPY src/Anubis.Server/ src/Anubis.Server/
|
||||
# The logo is embedded from docs/design/logo, its only source (ADR 0005).
|
||||
COPY docs/design/logo/ docs/design/logo/
|
||||
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
||||
WORKDIR /app
|
||||
COPY --from=build /app ./
|
||||
ENV ASPNETCORE_HTTP_PORTS=8787 \
|
||||
TZ=Europe/Rome
|
||||
COPY --chmod=755 deploy/docker/entrypoint.sh /usr/local/bin/anubis-entrypoint
|
||||
# The port comes from PORT (8787 by default), read by the app; the base image's own port setting is cleared.
|
||||
ENV ANUBIS_PLATFORM=docker \
|
||||
ASPNETCORE_HTTP_PORTS= \
|
||||
TZ=Europe/Rome \
|
||||
PUID=99 \
|
||||
PGID=100
|
||||
EXPOSE 8787
|
||||
VOLUME /data
|
||||
USER $APP_UID
|
||||
ENTRYPOINT ["dotnet", "Anubis.Server.dll"]
|
||||
# Starts as root only to give /data to PUID:PGID, then runs the app as that user (entrypoint.sh).
|
||||
# Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down) counts as unhealthy.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
CMD ["bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/${PORT:-8787} && printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"]
|
||||
ENTRYPOINT ["anubis-entrypoint"]
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
# Container start (SPEC 15.2, issue #16). As root: prepare /data for PUID:PGID (99:100 on Unraid), then drop to that
|
||||
# user with setpriv, which is part of the base image (no gosu). Started as another user (docker run --user): go straight on.
|
||||
set -eu
|
||||
|
||||
app="/app/Anubis.Server.dll"
|
||||
|
||||
if [ "$(id -u)" != "0" ]; then
|
||||
exec dotnet "$app" "$@"
|
||||
fi
|
||||
|
||||
uid="${PUID:-99}"
|
||||
gid="${PGID:-100}"
|
||||
case "$uid$gid" in
|
||||
*[!0-9]*|"")
|
||||
echo "PUID e PGID devono essere numeri (adesso: PUID=$uid PGID=$gid)." >&2
|
||||
exit 64
|
||||
;;
|
||||
esac
|
||||
|
||||
mkdir -p /data
|
||||
for folder in db models research import backups logs web-keys; do
|
||||
mkdir -p "/data/$folder"
|
||||
done
|
||||
# Only what does not already belong to PUID:PGID, so a large data folder does not slow every start.
|
||||
find /data -xdev \( ! -user "$uid" -o ! -group "$gid" \) -exec chown -h "$uid:$gid" {} +
|
||||
chmod 700 /data
|
||||
|
||||
export HOME=/tmp
|
||||
exec setpriv --reuid="$uid" --regid="$gid" --clear-groups -- dotnet "$app" "$@"
|
||||
@@ -1,5 +1,6 @@
|
||||
# Development only (SPEC 3): the app plus a local PostgreSQL. Never used in production.
|
||||
# Start: docker compose up --build Health: curl http://localhost:8787/health
|
||||
# First access at http://localhost:8787 with ANUBIS_ADMIN_PASSWORD, then choose a new password.
|
||||
services:
|
||||
anubis:
|
||||
build:
|
||||
@@ -15,6 +16,9 @@ services:
|
||||
ANUBIS_DB_NAME: anubis
|
||||
ANUBIS_DB_USER: anubis
|
||||
ANUBIS_DB_PASSWORD: ${ANUBIS_DB_PASSWORD:-anubis-dev}
|
||||
# Development values only: a real installation chooses its own (deploy/unraid/anubis.xml).
|
||||
ANUBIS_SECRET_KEY: ${ANUBIS_SECRET_KEY:-dev-only-secret-key-change-me-0123456789}
|
||||
ANUBIS_ADMIN_PASSWORD: ${ANUBIS_ADMIN_PASSWORD:-dev-only-change-me}
|
||||
ANUBIS_ALLOW_LIVE: "0"
|
||||
TZ: Europe/Rome
|
||||
volumes:
|
||||
|
||||
+10
-2
@@ -170,7 +170,7 @@ Ultime versioni stabili lette dall'API di NuGet il 10 novembre 2026. Quelle già
|
||||
| `Microsoft.NET.Test.Sdk` | 18.11.0 | MIT | Fase 0 | https://www.nuget.org/packages/Microsoft.NET.Test.Sdk |
|
||||
| `Microsoft.Data.Sqlite` | 10.0.14 | MIT | Fase 1 | https://www.nuget.org/packages/Microsoft.Data.Sqlite/10.0.14 |
|
||||
| `Npgsql` | 10.0.3 | PostgreSQL License | Fase 1 | https://www.nuget.org/packages/Npgsql/10.0.3 |
|
||||
| `System.Security.Cryptography.ProtectedData` | 10.0.14 | MIT | Fase 10 | https://www.nuget.org/packages/System.Security.Cryptography.ProtectedData/10.0.14 |
|
||||
| `System.Security.Cryptography.ProtectedData` | 10.0.14 | MIT | Fase 1 (la custodia della chiave dei segreti su desktop nasce con lo strato di piattaforma) | https://www.nuget.org/packages/System.Security.Cryptography.ProtectedData/10.0.14 |
|
||||
| `Microsoft.Web.WebView2` | 1.0.4314.35 | Licenza Microsoft di tipo BSD | Fase 10 | https://www.nuget.org/packages/Microsoft.Web.WebView2/1.0.4314.35 |
|
||||
| `Microsoft.ML`, `Microsoft.ML.LightGbm`, `Microsoft.ML.FastTree` | 5.0.1 | MIT | Fase 8 | https://www.nuget.org/packages/Microsoft.ML/5.0.1 |
|
||||
| `Microsoft.ML.OnnxRuntime` | 1.31.1 (librerie native per linux-x64 e win-x64) | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.OnnxRuntime/1.31.1 |
|
||||
@@ -202,7 +202,7 @@ Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del tes
|
||||
|
||||
| Dipendenza | Di chi, licenza | Arriva con | Fase | Nota |
|
||||
|---|---|---|---|---|
|
||||
| `SQLitePCLRaw.bundle_e_sqlite3`, `SQLitePCLRaw.core` 2.1.13 | Eric Sink, Apache-2.0 | `Microsoft.Data.Sqlite` | 1 | Contiene la libreria nativa di SQLite. |
|
||||
| `SQLitePCLRaw.bundle_e_sqlite3`, `SQLitePCLRaw.core`, `SQLitePCLRaw.lib.e_sqlite3`, `SQLitePCLRaw.provider.e_sqlite3` 2.1.13 | Eric Sink, Apache-2.0 | `Microsoft.Data.Sqlite` | 1 (in uso) | Contengono la libreria nativa di SQLite e il suo caricatore. Sono nell'elenco del test dalla Fase 1. |
|
||||
| `Newtonsoft.Json` 13.0.3 | James Newton-King, MIT | `Microsoft.ML`, LightGbm, FastTree | 8 | — |
|
||||
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | 8 | Libreria nativa; in Docker serve `libgomp1`. |
|
||||
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 | — |
|
||||
@@ -213,3 +213,11 @@ Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del tes
|
||||
- `mcr.microsoft.com/dotnet/sdk:10.0` (SDK 10.0.403) e `mcr.microsoft.com/dotnet/aspnet:10.0` (runtime 10.0.14) esistono. Dal .NET 10 il tag `10.0` usa **Ubuntu 24.04 "noble"**, non Debian. Non esiste un tag Debian stabile.
|
||||
- `libgomp1` non è nelle immagini, ma si installa da Ubuntu "main" con `apt-get install -y --no-install-recommends libgomp1`. Si aggiunge nella Fase 8, insieme a LightGBM.
|
||||
- Fonti: https://mcr.microsoft.com/v2/dotnet/aspnet/tags/list · https://github.com/dotnet/dotnet-docker/blob/main/manifest.json · https://packages.ubuntu.com/noble/libgomp1
|
||||
|
||||
## Carattere
|
||||
|
||||
- **Instrument Sans**, di Rodrigo Fuenzalida e Jordan Egstad, licenza SIL OFL 1.1 (ammesso dall'ADR 0004). Scaricato il 10/11/2026 con il permesso dell'utente, dalla raccolta ufficiale di Google Fonts.
|
||||
- File: `InstrumentSans[wdth,wght].ttf`, 194.336 byte, SHA-256 `b24f1812584816958afcf22e22d08e44318c5e51651e25d2438efdde389b33b1`. È un solo file variabile con pesi da 400 a 700. Nel repository si chiama `src/Anubis.Server/Assets/InstrumentSans.ttf`.
|
||||
- La licenza è accanto al file, in `InstrumentSans-OFL.txt`, e l'applicazione la serve su `/assets/InstrumentSans-OFL.txt`.
|
||||
- La versione corsiva non è inclusa: l'interfaccia quasi non la usa, e il browser la ricava dal carattere normale.
|
||||
- Fonte: https://github.com/google/fonts/tree/main/ofl/instrumentsans
|
||||
+21
-21
@@ -53,30 +53,30 @@ Le basi su cui si appoggia tutto: piattaforma, database, sicurezza, guscio dell'
|
||||
|
||||
**Lavori**
|
||||
|
||||
- [ ] [#7](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/7) Strato di piattaforma: configurazione d'avvio Docker e desktop, cartella dei dati, identità dell'installazione
|
||||
- [ ] [#8](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/8) Database portabile PostgreSQL/SQLite: tipi, accesso ADO.NET, migrazioni SQL
|
||||
- [ ] [#9](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/9) Esportazione e importazione indipendenti dal motore; salvataggi notturni e prima delle migrazioni
|
||||
- [ ] [#10](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/10) Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni, segreti, registri strutturati
|
||||
- [ ] [#11](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/11) Accesso e sicurezza: PBKDF2, sessioni, CSRF, limite tentativi, TOTP
|
||||
- [ ] [#12](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/12) Scheletro delle API REST e del WebSocket
|
||||
- [ ] [#13](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/13) Guscio dell'interfaccia: menu, barra superiore, temi, token grafici, formati italiani
|
||||
- [ ] [#14](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/14) Schermate di servizio: accesso, primo avvio (Docker e desktop), pagina d'errore del database, prima parte di Impostazioni
|
||||
- [ ] [#15](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/15) Modalità dimostrativa con i dati dell'appendice F (`tasks seed-demo`)
|
||||
- [ ] [#16](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/16) Dockerfile definitivo con entrypoint (PUID/PGID, cartella dati, healthcheck)
|
||||
- [ ] [#17](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/17) Chiusura della fase, revisione indipendente e tag `fase-1`
|
||||
- [x] [#7](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/7) Strato di piattaforma: configurazione d'avvio Docker e desktop, cartella dei dati, identità dell'installazione
|
||||
- [x] [#8](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/8) Database portabile PostgreSQL/SQLite: tipi, accesso ADO.NET, migrazioni SQL
|
||||
- [x] [#9](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/9) Esportazione e importazione indipendenti dal motore; salvataggi notturni e prima delle migrazioni
|
||||
- [x] [#10](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/10) Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni, segreti, registri strutturati
|
||||
- [x] [#11](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/11) Accesso e sicurezza: PBKDF2, sessioni, CSRF, limite tentativi, TOTP
|
||||
- [x] [#12](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/12) Scheletro delle API REST e del WebSocket
|
||||
- [x] [#13](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/13) Guscio dell'interfaccia: menu, barra superiore, temi, token grafici, formati italiani
|
||||
- [x] [#14](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/14) Schermate di servizio: accesso, primo avvio (Docker e desktop), pagina d'errore del database, prima parte di Impostazioni
|
||||
- [x] [#15](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/15) Modalità dimostrativa con i dati dell'appendice F (`tasks seed-demo`)
|
||||
- [x] [#16](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/16) Dockerfile definitivo con entrypoint (PUID/PGID, cartella dati, healthcheck)
|
||||
- [x] [#17](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/17) Chiusura della fase, revisione indipendente e tag `fase-1`
|
||||
|
||||
**Criteri di accettazione**
|
||||
|
||||
- [ ] Accesso funzionante
|
||||
- [ ] Il guscio corrisponde ai mockup per menu e barra superiore a 1440 px e per barra superiore e barra in basso a 390 px (screenshot allegati)
|
||||
- [ ] I formati numerici superano i test
|
||||
- [ ] L'immagine si costruisce e parte con `ANUBIS_DB_ENGINE=sqlite` e con `postgres`
|
||||
- [ ] Con una configurazione mancante o sbagliata compare la pagina d'errore e non nasce alcun altro database
|
||||
- [ ] Staccando il database compare la pagina d'errore e al ritorno l'applicazione riprende da sola
|
||||
- [ ] La stessa batteria di test passa su entrambi i motori
|
||||
- [ ] Un archivio esportato da un motore e importato nell'altro dà gli stessi conteggi
|
||||
- [ ] Con la configurazione desktop il server parte da una cartella dei dati vuota e la chiave dei segreti non finisce in `config.toml`
|
||||
- [ ] La modalità dimostrativa non tocca il database configurato (test)
|
||||
- [x] Accesso funzionante
|
||||
- [x] Il guscio corrisponde ai mockup per menu e barra superiore a 1440 px e per barra superiore e barra in basso a 390 px (screenshot allegati)
|
||||
- [x] I formati numerici superano i test
|
||||
- [x] L'immagine si costruisce e parte con `ANUBIS_DB_ENGINE=sqlite` e con `postgres`
|
||||
- [x] Con una configurazione mancante o sbagliata compare la pagina d'errore e non nasce alcun altro database
|
||||
- [x] Staccando il database compare la pagina d'errore e al ritorno l'applicazione riprende da sola
|
||||
- [x] La stessa batteria di test passa su entrambi i motori
|
||||
- [x] Un archivio esportato da un motore e importato nell'altro dà gli stessi conteggi
|
||||
- [x] Con la configurazione desktop il server parte da una cartella dei dati vuota e la chiave dei segreti non finisce in `config.toml`
|
||||
- [x] La modalità dimostrativa non tocca il database configurato (test)
|
||||
|
||||
## Fase 2 — Dati di mercato
|
||||
|
||||
|
||||
+16
-3
@@ -4,7 +4,7 @@ Aggiornato: 2026-11-10
|
||||
|
||||
## Fase corrente
|
||||
|
||||
**Fase 0 — Preparazione: completata.** La prossima è la Fase 1 (Fondamenta), da iniziare con il via dell'utente.
|
||||
**Fase 1 — Fondamenta: completata.** La prossima è la Fase 2 (Dati di mercato), da iniziare con il via dell'utente.
|
||||
|
||||
## Fatto
|
||||
|
||||
@@ -34,6 +34,17 @@ Aggiornato: 2026-11-10
|
||||
- `/health`.
|
||||
- Applicazione minima con `GET /health`, `Dockerfile` e `docker-compose.yml` con PostgreSQL 18.
|
||||
- CI in `.gitea/workflows/ci.yml`: test su SQLite e PostgreSQL, poi l'immagine. Solo passi `run:`.
|
||||
- **Fase 1** (scelte nell'ADR 0007):
|
||||
- Piattaforma: configurazione d'avvio Docker (variabili) e desktop (`config.toml`), cartella dei dati, identità dell'installazione con impronta del database, custodia della chiave dei segreti (DPAPI su Windows).
|
||||
- Database portabile su PostgreSQL e SQLite con ADO.NET: un solo schema con tipi per motore, migrazioni SQL numerate con salvataggio prima, esportazione e importazione tra motori con controllo di conteggi e totali (`Anubis.Server db export|import`), salvataggi notturni (ne tiene 14).
|
||||
- Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni con registro delle modifiche, segreti cifrati AES-GCM, registri JSON con i segreti oscurati, formati italiani.
|
||||
- Accesso: password PBKDF2, sessioni, CSRF, limite ai tentativi, secondo fattore TOTP facoltativo.
|
||||
- Server: avvio a stati (configurazione, primo avvio, database assente, schema, identità, pronto), pagina d'errore con riprova automatica, API REST e WebSocket dello stato.
|
||||
- Interfaccia: guscio di menu, barra superiore e barra in basso come nei mockup, temi chiaro e scuro, Panoramica, Diario, Rischio, Impostazioni (aspetto, sicurezza, sistema); le altre voci arrivano con le loro fasi.
|
||||
- Modalità dimostrativa (`tasks seed-demo`) con i dati dell'appendice F, in un database a parte.
|
||||
- Immagine Docker definitiva: `PUID`/`PGID`, controllo di salute, l'applicazione non gira come root. Provata con SQLite, PostgreSQL, configurazione sbagliata e database staccato.
|
||||
- `tasks screenshots` per confrontare le schermate con i mockup.
|
||||
- Dopo la chiusura, con il permesso dell'utente: carattere Instrument Sans incluso nell'applicazione (ADR 0007, punto 5).
|
||||
|
||||
## In corso
|
||||
|
||||
@@ -41,11 +52,13 @@ Nulla.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, accesso, guscio dell'interfaccia.
|
||||
Fase 2, dati di mercato: storico e dati dal vivo, controlli di qualità, cambi del giorno. Servono le chiavi del conto paper di Alpaca (vedi sotto); senza, la parte azionaria si prova su dati sintetici.
|
||||
|
||||
## Da sapere
|
||||
|
||||
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
|
||||
- La modalità dimostrativa mostra solo le parti già costruite: conti, posizioni, strategie e notizie della Panoramica arrivano con le loro fasi.
|
||||
- `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`.
|
||||
- Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14).
|
||||
- OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3).
|
||||
- Gitea ha un esecutore delle Actions attivo: la CI gira a ogni push (prima esecuzione: run 169 del branch `fase-0`, test verdi su SQLite e PostgreSQL). `tasks ci` resta per provarla in locale.
|
||||
@@ -55,7 +68,7 @@ Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, acc
|
||||
|
||||
| Cosa | Da quando serve | Senza |
|
||||
|---|---|---|
|
||||
| Via libera per la Fase 1 | Subito | Non si parte |
|
||||
| Via libera per la Fase 2 | Subito | Non si parte |
|
||||
| Chiavi del conto paper di Alpaca | Fase 2 (dati azionari) | La parte azionaria si prova su dati sintetici; criteri in attesa |
|
||||
| Chiavi demo di OKX Europe | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criteri in attesa |
|
||||
| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 0004 — Nessun SDK o componente esterno senza il permesso dell'utente
|
||||
|
||||
Data: 2026-11-09 · Stato: accettata · Precisata dall'ADR 0006 (MSTest tramite i suoi pacchetti di base; `libgomp1` nella Fase 8)
|
||||
Data: 2026-11-09 · Stato: accettata · Precisata dagli ADR 0006 (MSTest tramite i suoi pacchetti di base; `libgomp1` nella Fase 8) e 0007 (`ProtectedData` dalla Fase 1; Instrument Sans scaricato il 10/11/2026)
|
||||
|
||||
## Contesto
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# 0007 — Scelte della Fase 1: database portabile, interfaccia, immagine Docker
|
||||
|
||||
Data: 2026-11-10 · Stato: accettata · Precisa gli ADR 0003, 0004 e 0006, senza aggiungere componenti esterni
|
||||
|
||||
## Contesto
|
||||
|
||||
La Fase 1 costruisce le fondamenta: piattaforma, database su due motori, accesso, guscio dell'interfaccia, modalità dimostrativa e immagine Docker. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
|
||||
|
||||
## Decisione
|
||||
|
||||
**1. Un solo schema per i due motori.**
|
||||
- Le migrazioni sono file SQL numerati (`src/Anubis/Db/Migrations`). Lo stesso testo gira su PostgreSQL e SQLite. Le parole tra graffe diventano i tipi del motore:
|
||||
|
||||
| Segno | PostgreSQL | SQLite |
|
||||
|---|---|---|
|
||||
| `{money}` | `NUMERIC(38,18)` | `TEXT` in forma canonica, arrotondato a 18 decimali |
|
||||
| `{timestamp}` | `TIMESTAMPTZ` | `TEXT` ISO 8601 in UTC |
|
||||
| `{uuid}` | `UUID` | `TEXT` |
|
||||
| `{bool}`, `{bytes}`, `{json}`, `{float}` | `BOOLEAN`, `BYTEA`, `JSON`, `DOUBLE PRECISION` | `INTEGER`, `BLOB`, `TEXT`, `REAL` |
|
||||
|
||||
- Su SQLite le tabelle sono `STRICT` e il database lavora con WAL, `synchronous=FULL` e chiavi esterne attive.
|
||||
- Il denaro passa sempre come `decimal` e non è mai `REAL`. `{float}` serve solo a misure che non sono importi.
|
||||
- Lo schema 1 contiene le tabelle che servono adesso e quelle contabili che la modalità dimostrativa riempie (conti, ordini, eseguiti, lotti, liquidità, posizioni, patrimonio, diario, rischio). Le tabelle delle fasi successive (barre, notizie, modelli, prove storiche, segnali) arrivano ciascuna con la propria migrazione.
|
||||
- Prima di ogni migrazione si fa un salvataggio.
|
||||
- I limiti di SQLite restano quelli della specifica: un solo processo scrive, e il file deve stare su un disco locale.
|
||||
|
||||
**2. Il database non si ricrea da solo.**
|
||||
- Un file SQLite già visto che sparisce, mentre l'applicazione gira, è un errore. Non si crea un database nuovo e vuoto al suo posto: compare la pagina d'errore finché il file non torna.
|
||||
- All'avvio il file si crea solo se nella cartella dei dati manca `installation.json`, cioè alla prima installazione.
|
||||
|
||||
**3. Password con PBKDF2, secondo fattore senza codice QR.**
|
||||
- Le password si cifrano con PBKDF2-SHA512 (ADR 0003).
|
||||
- Per il secondo fattore l'interfaccia mostra la chiave in base32 e l'indirizzo `otpauth://`. Non disegna un codice QR, che richiederebbe una libreria esterna o un generatore scritto in casa. Le app di autenticazione accettano la chiave scritta a mano.
|
||||
- La chiave in prova resta sul server, legata alla sessione, per 15 minuti. Non passa mai nell'indirizzo della pagina.
|
||||
|
||||
**4. Interfaccia con rendering statico.**
|
||||
- Le pagine Blazor sono generate sul server e arrivano come HTML semplice. Niente modalità interattiva e niente `blazor.web.js`: per questo il progetto del server imposta `RequiresAspNetWebAssets=false`, e il pacchetto `Microsoft.AspNetCore.App.Internal.Assets` non entra.
|
||||
- I pulsanti sono moduli HTML che inviano ad `/azioni/*`, con il gettone CSRF. La risposta riporta alla pagina (post/redirect/get). Gli errori tornano come codici brevi, mai con i valori scritti dall'utente.
|
||||
- Lo stato dal vivo (bot, freschezza dei dati) arriva da un WebSocket su `/ws`, letto da un piccolo `app.js`.
|
||||
- Fogli di stile, script e logo sono risorse incluse nella DLL. Il logo arriva solo da `docs/design/logo` (ADR 0005).
|
||||
- Le chiavi dei gettoni dei moduli stanno in `web-keys/`, nella cartella dei dati, così un riavvio non rompe le pagine aperte. Sono salvate senza cifratura, ma la cartella dei dati è leggibile solo dall'utente dell'applicazione.
|
||||
|
||||
**5. Instrument Sans incluso nell'applicazione.**
|
||||
- L'ADR 0004 ammette Instrument Sans. L'utente ha dato il permesso di scaricarlo il 10/11/2026, dopo la chiusura della fase. Fino ad allora l'interfaccia usava i caratteri di sistema.
|
||||
- Il file sta in `src/Anubis.Server/Assets/`, con accanto la sua licenza. L'applicazione lo serve da sé e non lo carica mai da internet. Provenienza e impronta sono in `docs/API-NOTES.md`.
|
||||
- C'è un solo file variabile, solo in versione normale. Se il file non arriva, il foglio di stile ripiega sui caratteri di sistema.
|
||||
- Instrument Sans è un po' più largo del carattere di sistema. Nella barra superiore etichette e pulsanti passano a 13 px, come nel mockup, così la riga con la data resta intera a 1440 px.
|
||||
|
||||
**6. Modalità dimostrativa.**
|
||||
- `--demo` crea una cartella dei dati nuova in quella temporanea, con un database SQLite proprio, e non legge mai la configurazione vera.
|
||||
- La modalità dimostrativa:
|
||||
- usa un orologio fermo al 9 ottobre 2026, 08:21;
|
||||
- risponde solo dal computer stesso;
|
||||
- accede da sola;
|
||||
- tiene la chiave dei segreti in un file della propria cartella, per non toccare il portachiavi di Windows.
|
||||
- Carica i dati dell'appendice F solo nelle tabelle che esistono già. Strategie, notizie e apprendimento compaiono quando arrivano le loro fasi.
|
||||
- Gli importi in dollari si mostrano solo qui, con il cambio dei dati d'esempio. Nell'uso vero restano in euro finché la Fase 2 non porta i cambi del giorno.
|
||||
|
||||
**7. Custodia della chiave su desktop dalla Fase 1.** `System.Security.Cryptography.ProtectedData` (già nell'ADR 0004) entra adesso e non nella Fase 10: la chiave dei segreti va custodita da quando nasce lo strato di piattaforma.
|
||||
|
||||
**8. Immagine Docker.**
|
||||
- Il container parte come root solo per preparare `/data` e darla a `PUID:PGID` (99:100 su Unraid). Poi l'applicazione gira con quell'utente tramite `setpriv`, che è già nell'immagine di base. Niente `gosu`.
|
||||
- Il controllo di salute usa `/dev/tcp` di bash su `/health`, perché nell'immagine non ci sono `curl` né `wget`. Un 503 (database che non risponde) conta come container non sano.
|
||||
- `libgomp1` resta rimandata alla Fase 8 (ADR 0006).
|
||||
|
||||
**9. Fotografie con il browser già installato.**
|
||||
- `tasks screenshots` usa Edge o Chrome già presenti sul computer e li guida con il protocollo DevTools, attraverso il `ClientWebSocket` di .NET. Niente Playwright (ADR 0004).
|
||||
- Il protocollo serve per fissare la larghezza esatta: una finestra senza schermo non scende sotto i 500 pixel circa, troppi per il telefono a 390.
|
||||
|
||||
**10. Correzioni della revisione indipendente.**
|
||||
- **Indirizzo di ritorno.** Dopo l'accesso si torna solo a un percorso del sito. Sono esclusi i percorsi con barre rovesciate o caratteri di controllo, perché il browser li toglie e `/␉/altro.sito` diventerebbe `//altro.sito`.
|
||||
- **Solo dal computer.** Desktop e modalità dimostrativa controllano due cose: l'indirizzo di chi chiama e il nome con cui chiama. Sono ammessi solo `localhost`, `127.0.0.1` e `[::1]`. Così una pagina web che fa puntare il proprio nome a 127.0.0.1 (DNS rebinding) non arriva alla procedura guidata né alle scelte della pagina d'errore.
|
||||
- **Limite ai tentativi.**
|
||||
- Ogni tentativo si conta prima di controllare la password, così tentativi in parallelo non passano tutti.
|
||||
- Lo stesso limite vale per la password della configurazione d'avvio chiesta dalla pagina d'errore.
|
||||
- **Secondo fattore.**
|
||||
- Ogni codice vale una volta sola. Il registro sta in memoria: un riavvio lo azzera, ma il codice scade comunque entro 90 secondi.
|
||||
- Per disattivare il secondo fattore servono la password e un codice.
|
||||
- **Pagina d'errore e ciclo d'avvio.**
|
||||
- Una scelta (ripristina, importa, comincia da capo, usa questo) tiene fermo il ciclo d'avvio finché non ha finito, rinnovo dell'identità compreso.
|
||||
- L'identità si controlla prima di migrare. Un database che appartiene a un'altra installazione non viene toccato. Uno vuoto resta vuoto, quindi accoglie anche un salvataggio con uno schema più vecchio.
|
||||
- Dopo un ripristino, un'importazione o "usa questo database", il bot riparte con "Ferma tutto" acceso (SPEC 15.1), qualunque cosa dicesse l'archivio.
|
||||
- Un archivio rovinato dà un messaggio sulla pagina, non un errore del server.
|
||||
- La scelta azzera lo stato dell'applicazione prima di lasciare ripartire il ciclo d'avvio. Prima lo faceva dopo, e il ciclo poteva ripartire nel frattempo: l'applicazione risultava pronta ma senza servizi. Il difetto è emerso nella CI su Linux.
|
||||
- **File SQLite che sparisce durante l'apertura.**
|
||||
- Controllare che il file esista non basta: può sparire tra il controllo e l'apertura, e un'apertura che può creare il file metterebbe al suo posto un database vuoto.
|
||||
- Dopo la prima apertura riuscita, il file si apre solo se c'è già.
|
||||
- **Pagine che leggono prima di disegnare.**
|
||||
- Con il rendering statico Blazor disegna una prima volta mentre `OnInitializedAsync` aspetta ancora.
|
||||
- Con SQLite le letture finiscono subito e il difetto non si vede. Con PostgreSQL la pagina si rompe.
|
||||
- I componenti che leggono dati ereditano da `LoadedComponent` (o `LoadedLayout`): prima leggono, poi disegnano una volta sola.
|
||||
- I test del server ora girano anche su PostgreSQL.
|
||||
- **Docker con SQLite e `/data` non collegata.**
|
||||
- Docker crea un volume anonimo senza `installation.json`, quindi parte un'installazione nuova e vuota. Non si può distinguere da una prima installazione vera.
|
||||
- Il manuale (Fase 9) dirà di controllare la riga "Cartella dei dati" in Impostazioni.
|
||||
|
||||
## Alternative scartate
|
||||
|
||||
- **Tipi diversi per motore scritti a mano in due serie di migrazioni.** Raddoppia il lavoro e lascia divergere i due schemi.
|
||||
- **Blazor interattivo sul server (SignalR).** Una connessione sempre aperta per ogni pagina, più JavaScript del framework, e pagine che smettono di funzionare quando la connessione cade. I moduli semplici funzionano anche senza script.
|
||||
- **Un generatore di codici QR scritto in casa.** È molto codice per un passo che si fa una volta sola.
|
||||
- **Chiedere il pacchetto Playwright.** Il browser già installato fa lo stesso lavoro.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Ogni fase che aggiunge tabelle scrive una nuova migrazione con gli stessi segni, e la prova su entrambi i motori.
|
||||
- Chi apre la modalità dimostrativa vede solo le parti costruite fino a quella fase.
|
||||
- Il WebSocket dello stato non si chiude quando si esce: manda solo lo stato del bot e la freschezza dei dati, e si chiude alla prima riconnessione. Da rivedere quando porterà dati più ricchi.
|
||||
@@ -2,8 +2,87 @@
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||
},
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,87 @@
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||
},
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Anubis.Server</RootNamespace>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
<!-- Static rendering only: no blazor.web.js, so no Microsoft.AspNetCore.App.Internal.Assets package (ADR 0007). -->
|
||||
<RequiresAspNetWebAssets>false</RequiresAspNetWebAssets>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Anubis\Anubis.csproj" />
|
||||
@@ -9,4 +11,10 @@
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Anubis.Tests" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Style and scripts served from the assembly: no static web assets pipeline, no files to lose (ADR 0007). -->
|
||||
<EmbeddedResource Include="Assets\*" LogicalName="Anubis.Server.Assets.%(Filename)%(Extension)" />
|
||||
<!-- The logo comes only from docs/design/logo (ADR 0005). -->
|
||||
<EmbeddedResource Include="..\..\docs\design\logo\*.svg;..\..\docs\design\logo\*.png;..\..\docs\design\logo\*.ico" LogicalName="Anubis.Server.Brand.%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,490 @@
|
||||
using Anubis.Access;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Demo;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
public enum HostMode
|
||||
{
|
||||
Starting,
|
||||
|
||||
/// <summary>The startup configuration is missing or wrong: the error page lists what to fix.</summary>
|
||||
ConfigProblem,
|
||||
|
||||
/// <summary>Desktop without config.toml, or without a user yet: the first-run wizard.</summary>
|
||||
FirstRun,
|
||||
|
||||
/// <summary>The configured database does not answer: error page, retry, never another database (trap 20).</summary>
|
||||
DatabaseUnavailable,
|
||||
|
||||
/// <summary>The database schema is newer than this version or was altered.</summary>
|
||||
SchemaProblem,
|
||||
|
||||
/// <summary>Database and data folder do not belong together (SPEC 15.1): the user chooses.</summary>
|
||||
IdentityProblem,
|
||||
|
||||
Ready,
|
||||
}
|
||||
|
||||
public sealed record HostStatus(HostMode Mode, string? Detail, IdentityCheck? Identity, DateTimeOffset Since, int Attempts);
|
||||
|
||||
/// <summary>Published on the bus whenever the host changes mode.</summary>
|
||||
internal sealed record HostChanged(HostMode Mode);
|
||||
|
||||
/// <summary>Everything that needs the database, built once it is reachable and the installation checks out.</summary>
|
||||
internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler);
|
||||
|
||||
/// <summary>
|
||||
/// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured
|
||||
/// database and nothing else, migrates it after a backup, checks the installation identity, then runs. While anything
|
||||
/// is wrong the interface shows the error page and the host retries by itself; when the database comes back the
|
||||
/// application resumes without a restart.
|
||||
/// </summary>
|
||||
internal sealed partial class AnubisHost(
|
||||
ServerOptions options,
|
||||
StartupConfig initialConfig,
|
||||
IReadOnlyDictionary<string, string?> environment,
|
||||
IClock clock,
|
||||
EventBus bus,
|
||||
ILogger<AnubisHost> logger,
|
||||
ServerOverrides? overrides = null) : BackgroundService
|
||||
{
|
||||
private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5);
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
// One step of the loop or one error-page choice at a time: a restore must not race the start that would follow it.
|
||||
private readonly SemaphoreSlim _exclusive = new(1, 1);
|
||||
private TaskCompletionSource _wake = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private Database? _db;
|
||||
private Task? _schedulerLoop;
|
||||
private CancellationTokenSource? _schedulerStop;
|
||||
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
|
||||
private volatile AppServices? _services;
|
||||
|
||||
public StartupConfig Config { get; private set; } = initialConfig;
|
||||
|
||||
public bool IsDemo => options.Demo;
|
||||
|
||||
public HostStatus Status => _status;
|
||||
|
||||
/// <summary>The running services; null until the first successful start.</summary>
|
||||
public AppServices? Services => _status.Mode == HostMode.Ready ? _services : null;
|
||||
|
||||
/// <summary>Desktop first run: the password chosen in the wizard, used once the database is ready.</summary>
|
||||
public string? PendingPassword { get; set; }
|
||||
|
||||
public int PasswordIterations => overrides?.PasswordIterations ?? Passwords.DefaultIterations;
|
||||
|
||||
/// <summary>Asks the loop to check again now (after the wizard or an error-page choice).</summary>
|
||||
public void Wake()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_wake.TrySetResult();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits until the host reaches <paramref name="mode"/>; for tests and the CLI.</summary>
|
||||
public async Task WaitForAsync(HostMode mode, TimeSpan timeout)
|
||||
{
|
||||
using var cts = new CancellationTokenSource(timeout);
|
||||
while (_status.Mode != mode)
|
||||
{
|
||||
await Task.Delay(20, cts.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Last time the database answered: the "Dati aggiornati" of the top bar.</summary>
|
||||
public DateTimeOffset? LastCheckUtc { get; private set; }
|
||||
|
||||
/// <summary>The scheduler loop is alive (health check).</summary>
|
||||
public bool SchedulerRunning => _schedulerLoop is { IsCompleted: false };
|
||||
|
||||
/// <summary>The database even when not ready (error-page choices need it to restore or import).</summary>
|
||||
internal Database? Database => _db;
|
||||
|
||||
/// <summary>Holds the loop still while an error-page choice works on the database.</summary>
|
||||
internal async Task<IDisposable> ExclusiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _exclusive.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new Releaser(_exclusive);
|
||||
}
|
||||
|
||||
private sealed class Releaser(SemaphoreSlim semaphore) : IDisposable
|
||||
{
|
||||
private int _released;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0)
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
base.Dispose();
|
||||
_exclusive.Dispose();
|
||||
_schedulerStop?.Dispose();
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (options.Demo)
|
||||
{
|
||||
LogDemo(logger, Config.Data.Root);
|
||||
}
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
Task wake;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_wake.Task.IsCompleted)
|
||||
{
|
||||
_wake = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
|
||||
wake = _wake.Task;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using (await ExclusiveAsync(stoppingToken).ConfigureAwait(false))
|
||||
{
|
||||
await StepAsync(stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogStepFailed(logger, ex);
|
||||
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||
}
|
||||
|
||||
await Task.WhenAny(wake, Task.Delay(_interval, stoppingToken)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await StopSchedulerAsync().ConfigureAwait(false);
|
||||
if (_db is not null)
|
||||
{
|
||||
await _db.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StepAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Desktop: the wizard may have written config.toml, or the user fixed it by hand.
|
||||
if (Config.Platform == PlatformKind.Desktop && !options.Demo && !Config.IsComplete)
|
||||
{
|
||||
Config = options.LoadConfig(environment);
|
||||
}
|
||||
|
||||
if (Config.NeedsFirstRun)
|
||||
{
|
||||
SetStatus(HostMode.FirstRun, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Config.IsComplete)
|
||||
{
|
||||
SetStatus(HostMode.ConfigProblem, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_services is not null)
|
||||
{
|
||||
await CheckRunningAsync(cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
Config.Data.Ensure();
|
||||
|
||||
// A data folder that belongs to an installation never gets a new empty SQLite file by itself (trap 20).
|
||||
_db ??= Database.Open(Config.Db!, allowCreate: !File.Exists(Config.Data.InstallationFile));
|
||||
try
|
||||
{
|
||||
await _db.PingAsync(cancellationToken).ConfigureAwait(false);
|
||||
LastCheckUtc = clock.UtcNow;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||
if (Config.Db!.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
// Reopen next time: the file may come back, or the folder may be released.
|
||||
await _db.DisposeAsync().ConfigureAwait(false);
|
||||
_db = null;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Identity first, migration after: a database that belongs elsewhere is never written to, and an empty one stays
|
||||
// empty, so a backup taken with an older schema can still be restored into it.
|
||||
var backups = new Backups(Config.Data, clock);
|
||||
IdentityCheck identity;
|
||||
try
|
||||
{
|
||||
var schema = await Migrations.StatusAsync(_db, cancellationToken).ConfigureAwait(false);
|
||||
if (schema.IsEmpty && File.Exists(Config.Data.InstallationFile))
|
||||
{
|
||||
identity = new IdentityCheck(IdentityVerdict.EmptyDatabase, Installation.ReadFile(Config.Data), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (schema.IsEmpty)
|
||||
{
|
||||
await MigrateAsync(backups, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
identity = await Installation.CheckAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||
if (identity.CanStart)
|
||||
{
|
||||
await MigrateAsync(backups, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SchemaException ex)
|
||||
{
|
||||
SetStatus(HostMode.SchemaProblem, ex.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!identity.CanStart)
|
||||
{
|
||||
SetStatus(HostMode.IdentityProblem, null, identity);
|
||||
return;
|
||||
}
|
||||
|
||||
var key = Config.SecretKey.GetOrCreateKey();
|
||||
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
|
||||
var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys);
|
||||
var access = new AccessStore(_db, clock, secrets, PasswordIterations);
|
||||
if (options.Demo && identity.Verdict == IdentityVerdict.Created)
|
||||
{
|
||||
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!await EnsureUserAsync(access, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
SetStatus(HostMode.FirstRun, null);
|
||||
return;
|
||||
}
|
||||
|
||||
var scheduler = new Scheduler(clock, bus);
|
||||
_services = new AppServices(_db, settings, secrets, access, backups, scheduler);
|
||||
StartScheduler(scheduler, backups);
|
||||
SetStatus(HostMode.Ready, null);
|
||||
}
|
||||
|
||||
private async Task MigrateAsync(Backups backups, CancellationToken cancellationToken)
|
||||
{
|
||||
var applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, "prima-della-migrazione", ct), cancellationToken).ConfigureAwait(false);
|
||||
if (applied > 0)
|
||||
{
|
||||
LogMigrated(logger, applied, Migrations.Latest);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> EnsureUserAsync(AccessStore access, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await access.HasUserAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (options.Demo)
|
||||
{
|
||||
// The demo signs in by itself (see SessionAuthentication); the password exists only to fill the table.
|
||||
await access.EnsureUserAsync(Ids.NewToken(), mustChange: false, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Config.Platform == PlatformKind.Docker && Config.AdminPassword is { } initial)
|
||||
{
|
||||
await access.EnsureUserAsync(initial, mustChange: true, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (PendingPassword is { } chosen)
|
||||
{
|
||||
await access.EnsureUserAsync(chosen, mustChange: false, cancellationToken).ConfigureAwait(false);
|
||||
PendingPassword = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// While running: the database is checked every few seconds. If it stops answering, the error page shows and the
|
||||
// engine waits; when it answers again the installation is checked again (it might be another copy) and the
|
||||
// application resumes by itself.
|
||||
private async Task CheckRunningAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _db!.PingAsync(cancellationToken).ConfigureAwait(false);
|
||||
LastCheckUtc = clock.UtcNow;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
if (_status.Mode != HostMode.DatabaseUnavailable)
|
||||
{
|
||||
LogLost(logger, Redactor.Redact(ex.Message));
|
||||
}
|
||||
|
||||
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||
return;
|
||||
}
|
||||
|
||||
if (_status.Mode == HostMode.Ready)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var identity = await Installation.CheckAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||
if (!identity.CanStart)
|
||||
{
|
||||
await StopSchedulerAsync().ConfigureAwait(false);
|
||||
_services = null;
|
||||
SetStatus(HostMode.IdentityProblem, null, identity);
|
||||
return;
|
||||
}
|
||||
|
||||
LogBack(logger);
|
||||
SetStatus(HostMode.Ready, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After an error-page choice changed the database: forget the services so the next step starts over. Called while
|
||||
/// the choice still holds <see cref="ExclusiveAsync"/>.
|
||||
/// </summary>
|
||||
internal async Task ResetAsync()
|
||||
{
|
||||
await StopSchedulerAsync().ConfigureAwait(false);
|
||||
_services = null;
|
||||
SetStatus(HostMode.Starting, null);
|
||||
Wake();
|
||||
}
|
||||
|
||||
private void StartScheduler(Scheduler scheduler, Backups backups)
|
||||
{
|
||||
scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
|
||||
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
|
||||
{ MaxLateness = TimeSpan.FromHours(2) });
|
||||
_schedulerStop = new CancellationTokenSource();
|
||||
var token = _schedulerStop.Token;
|
||||
_schedulerLoop = Task.Run(async () =>
|
||||
{
|
||||
using var runs = bus.Subscribe<JobRun>();
|
||||
var recorder = RecordJobsAsync(runs, token);
|
||||
try
|
||||
{
|
||||
await scheduler.RunAsync(token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
|
||||
await recorder.ConfigureAwait(false);
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
|
||||
// The jobs table keeps the outcome of the last run of each job (Diario e sistema, SPEC 13.6).
|
||||
private async Task RecordJobsAsync(EventSubscription<JobRun> runs, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var run in runs.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
await _db!.WriteAsync(async s =>
|
||||
{
|
||||
var description = _services?.Scheduler.Upcoming(100).FirstOrDefault(u => u.Name == run.Name)?.Description ?? run.Name;
|
||||
var updated = await s.ExecuteAsync(
|
||||
"UPDATE jobs SET last_due_at = @d, last_started_at = @s, last_finished_at = @f, last_outcome = @o, last_error = @e, updated_at = @f WHERE name = @n",
|
||||
("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc), ("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error), ("n", run.Name)).ConfigureAwait(false);
|
||||
if (updated == 0)
|
||||
{
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO jobs (id, name, description, last_due_at, last_started_at, last_finished_at, last_outcome, last_error, created_at, updated_at) VALUES (@id, @n, @desc, @d, @s, @f, @o, @e, @f, @f)",
|
||||
("id", Ids.NewId(clock)), ("n", run.Name), ("desc", description), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
|
||||
("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error)).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogJobRecordFailed(logger, ex, run.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StopSchedulerAsync()
|
||||
{
|
||||
if (_schedulerStop is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _schedulerStop.CancelAsync().ConfigureAwait(false);
|
||||
if (_schedulerLoop is not null)
|
||||
{
|
||||
await _schedulerLoop.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_schedulerStop.Dispose();
|
||||
_schedulerStop = null;
|
||||
_schedulerLoop = null;
|
||||
}
|
||||
|
||||
// Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5).
|
||||
private static Dictionary<string, StartupOverride> StartupOverrides() => [];
|
||||
|
||||
private void SetStatus(HostMode mode, string? detail, IdentityCheck? identity = null)
|
||||
{
|
||||
var previous = _status;
|
||||
var attempts = previous.Mode == mode ? previous.Attempts + 1 : 1;
|
||||
var since = previous.Mode == mode ? previous.Since : clock.UtcNow;
|
||||
_status = new HostStatus(mode, detail, identity, since, attempts);
|
||||
if (previous.Mode != mode)
|
||||
{
|
||||
LogMode(logger, mode);
|
||||
bus.Publish(new HostChanged(mode));
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Mode: {Mode}")]
|
||||
private static partial void LogMode(ILogger logger, HostMode mode);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Demo mode: separate database in {Folder}")]
|
||||
private static partial void LogDemo(ILogger logger, string folder);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Applied {Count} migrations, schema version {Version}")]
|
||||
private static partial void LogMigrated(ILogger logger, int count, int version);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Database lost: {Reason}")]
|
||||
private static partial void LogLost(ILogger logger, string reason);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Database back: resuming")]
|
||||
private static partial void LogBack(ILogger logger);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Startup step failed")]
|
||||
private static partial void LogStepFailed(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not record the run of job {Job}")]
|
||||
private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
@@ -0,0 +1,373 @@
|
||||
/* Anubis — tokens of appendix C (SPEC), light and dark. ContrastTests reads this block: keep one token per line. */
|
||||
:root {
|
||||
--page: #f1f3f0;
|
||||
--surface: #fbfcfa;
|
||||
--surface-2: #e9ede8;
|
||||
--track: #dfe4de;
|
||||
--rule: #d9ded8;
|
||||
--rule-inner: #e3e7e2;
|
||||
--control: #8a948e;
|
||||
--text: #141a17;
|
||||
--text-2: #46504a;
|
||||
--text-3: #5f6963;
|
||||
--link: #1c5cab;
|
||||
--info-bg: #e3eefb;
|
||||
--gain: #0a6b55;
|
||||
--gain-bg: #dff2ea;
|
||||
--loss: #b42f1a;
|
||||
--loss-bg: #fbe5df;
|
||||
--attention: #7a5000;
|
||||
--attention-bg: #fbefcf;
|
||||
--s-crypto-trend: #2a78d6;
|
||||
--s-equity-momentum: #eb6834;
|
||||
--s-equity-meanrev: #4a3aa7;
|
||||
--bench: #8a948e;
|
||||
--cash: #c5cbc4;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
--page: #101412;
|
||||
--surface: #181d1a;
|
||||
--surface-2: #222924;
|
||||
--track: #2c342f;
|
||||
--rule: #2c342f;
|
||||
--rule-inner: #262d28;
|
||||
--control: #6c766f;
|
||||
--text: #f2f5f1;
|
||||
--text-2: #c3cbc4;
|
||||
--text-3: #9aa39c;
|
||||
--link: #86b6ef;
|
||||
--info-bg: #17304f;
|
||||
--gain: #4cc9a4;
|
||||
--gain-bg: #12372d;
|
||||
--loss: #ff8d78;
|
||||
--loss-bg: #45201a;
|
||||
--attention: #f2c14e;
|
||||
--attention-bg: #3d2f0c;
|
||||
--s-crypto-trend: #17a2b8;
|
||||
--s-equity-momentum: #d95926;
|
||||
--s-equity-meanrev: #9085e9;
|
||||
--bench: #6c766f;
|
||||
--cash: #3a433d;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
--page: #101412;
|
||||
--surface: #181d1a;
|
||||
--surface-2: #222924;
|
||||
--track: #2c342f;
|
||||
--rule: #2c342f;
|
||||
--rule-inner: #262d28;
|
||||
--control: #6c766f;
|
||||
--text: #f2f5f1;
|
||||
--text-2: #c3cbc4;
|
||||
--text-3: #9aa39c;
|
||||
--link: #86b6ef;
|
||||
--info-bg: #17304f;
|
||||
--gain: #4cc9a4;
|
||||
--gain-bg: #12372d;
|
||||
--loss: #ff8d78;
|
||||
--loss-bg: #45201a;
|
||||
--attention: #f2c14e;
|
||||
--attention-bg: #3d2f0c;
|
||||
--s-crypto-trend: #17a2b8;
|
||||
--s-equity-momentum: #d95926;
|
||||
--s-equity-meanrev: #9085e9;
|
||||
--bench: #6c766f;
|
||||
--cash: #3a433d;
|
||||
}
|
||||
}
|
||||
|
||||
/* Instrument Sans served by the app itself, never from the internet (ADR 0004, SIL OFL: assets/InstrumentSans-OFL.txt).
|
||||
One variable file covers weights 400 to 700; italics are drawn by the browser from it. */
|
||||
@font-face {
|
||||
font-family: "Instrument Sans";
|
||||
src: url("/assets/InstrumentSans.ttf") format("truetype");
|
||||
font-weight: 400 700;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
:root {
|
||||
--font: "Instrument Sans", "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif;
|
||||
color-scheme: light dark;
|
||||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
html { -webkit-text-size-adjust: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--page);
|
||||
color: var(--text);
|
||||
font-family: var(--font);
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
font-variant-numeric: proportional-nums;
|
||||
}
|
||||
a { color: var(--link); }
|
||||
h1, h2, h3 { margin: 0; font-weight: 650; }
|
||||
h1 { font-size: 22px; line-height: 28px; }
|
||||
h2 { font-size: 17px; line-height: 24px; }
|
||||
h3 { font-size: 14px; line-height: 20px; }
|
||||
p { margin: 0; }
|
||||
code { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12.5px; overflow-wrap: anywhere; }
|
||||
:focus-visible { outline: 2px solid var(--link); outline-offset: 2px; border-radius: 4px; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
.icon { flex: none; }
|
||||
.logo-dark { display: none; }
|
||||
:root[data-theme="dark"] .logo-light { display: none; }
|
||||
:root[data-theme="dark"] .logo-dark { display: inline; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) .logo-light { display: none; }
|
||||
:root:not([data-theme="light"]) .logo-dark { display: inline; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { transition: none !important; animation: none !important; scroll-behavior: auto !important; }
|
||||
}
|
||||
|
||||
/* ---- Shell ---- */
|
||||
.shell { display: grid; grid-template-columns: 220px minmax(0, 1fr); min-height: 100vh; }
|
||||
.sidebar {
|
||||
position: sticky; top: 0; height: 100vh; overflow-y: auto;
|
||||
background: var(--surface); border-right: 1px solid var(--rule);
|
||||
padding: 20px 12px 24px;
|
||||
}
|
||||
.brand { display: flex; align-items: center; justify-content: space-between; padding: 0 8px 0 10px; margin-bottom: 20px; min-height: 40px; }
|
||||
.brand-link { display: flex; align-items: center; gap: 14px; color: var(--text); text-decoration: none; font-size: 20px; font-weight: 650; }
|
||||
.icon-button {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px;
|
||||
border: 0; border-radius: 8px; background: transparent; color: var(--text-3); cursor: pointer;
|
||||
}
|
||||
.icon-button:hover { background: var(--surface-2); color: var(--text); }
|
||||
.when-closed { display: none; }
|
||||
.nav-group { list-style: none; margin: 0; padding: 0; }
|
||||
.nav-group + .nav-group { margin-top: 22px; }
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: 12px; min-height: 40px; padding: 8px 12px; margin-bottom: 2px;
|
||||
border-radius: 8px; color: var(--text-2); text-decoration: none; font-size: 14px;
|
||||
}
|
||||
.nav-item:hover { background: var(--surface-2); color: var(--text); }
|
||||
.nav-item.active { background: var(--surface-2); color: var(--text); font-weight: 600; }
|
||||
|
||||
:root[data-nav="collapsed"] .shell { grid-template-columns: 72px minmax(0, 1fr); }
|
||||
:root[data-nav="collapsed"] .brand { flex-direction: column; gap: 8px; padding: 0; }
|
||||
:root[data-nav="collapsed"] .brand-name,
|
||||
:root[data-nav="collapsed"] .nav-label { display: none; }
|
||||
:root[data-nav="collapsed"] .nav-item { justify-content: center; padding: 10px; }
|
||||
:root[data-nav="collapsed"] .when-open { display: none; }
|
||||
:root[data-nav="collapsed"] .when-closed { display: inline; }
|
||||
|
||||
.main { min-width: 0; display: flex; flex-direction: column; }
|
||||
.topbar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: nowrap;
|
||||
padding: 16px 32px; background: var(--surface); border-bottom: 1px solid var(--rule);
|
||||
}
|
||||
.topbar-title { min-width: 0; flex: 1 1 auto; }
|
||||
.status-line { color: var(--text-3); font-size: 13px; line-height: 18px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.topbar-actions { display: flex; align-items: center; gap: 8px; flex: none; }
|
||||
@media (max-width: 1240px) {
|
||||
.topbar { flex-wrap: wrap; }
|
||||
.topbar-actions { flex-wrap: wrap; }
|
||||
}
|
||||
.topbar-actions form { margin: 0; }
|
||||
/* As in the mockup: one point smaller up here, so the date line keeps its full length at 1440 px. */
|
||||
.topbar-actions .pill, .topbar-actions .btn, .topbar-actions .currency select { font-size: 13px; }
|
||||
.phone-brand, .phone-bot, .mode-band, .bottombar { display: none; }
|
||||
|
||||
.pill {
|
||||
display: inline-flex; align-items: center; gap: 8px; height: 32px; padding: 0 12px;
|
||||
border-radius: 999px; font-size: 14px; font-weight: 550; white-space: nowrap;
|
||||
}
|
||||
.pill-bot { border: 1px solid var(--rule); background: var(--surface); color: var(--text); margin-right: 0; }
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--gain); flex: none; }
|
||||
[data-state="paused"] .dot { background: var(--attention); }
|
||||
[data-state="stopped"] .dot { background: var(--loss); }
|
||||
.pill-mode { background: var(--info-bg); color: var(--link); margin-right: 12px; }
|
||||
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 40px; padding: 0 16px;
|
||||
border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text);
|
||||
font: inherit; font-size: 14px; font-weight: 550; cursor: pointer; text-decoration: none; white-space: nowrap;
|
||||
}
|
||||
.btn:hover { background: var(--surface-2); }
|
||||
.btn:disabled { opacity: .55; cursor: not-allowed; }
|
||||
.btn-small { height: 32px; padding: 0 12px; }
|
||||
.btn-danger { border-color: var(--loss); color: var(--loss); }
|
||||
.btn-danger:hover { background: var(--loss-bg); }
|
||||
.btn-primary { background: var(--text); border-color: var(--text); color: var(--surface); }
|
||||
.btn-primary:hover { background: var(--text-2); }
|
||||
|
||||
.currency { position: relative; }
|
||||
.currency select, select, input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]) {
|
||||
height: 40px; border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text);
|
||||
font: inherit; font-size: 14px; padding: 0 12px;
|
||||
}
|
||||
.currency select { appearance: none; padding: 0 40px 0 16px; font-weight: 550; cursor: pointer; }
|
||||
.select-chevron { position: absolute; right: 14px; top: 12px; pointer-events: none; color: var(--text-2); }
|
||||
|
||||
.stale-notice {
|
||||
display: flex; align-items: center; gap: 10px; margin: 12px 32px 0; padding: 10px 12px; border-radius: 10px;
|
||||
background: var(--attention-bg); color: var(--attention); font-size: 13.5px;
|
||||
}
|
||||
.stale-notice[hidden] { display: none; }
|
||||
|
||||
.page { padding: 28px 32px 36px; display: flex; flex-direction: column; gap: 28px; flex: 1; }
|
||||
.page-footer { color: var(--text-3); font-size: 13px; line-height: 18px; }
|
||||
|
||||
/* ---- Components ---- */
|
||||
.panel { background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; padding: 20px 22px; }
|
||||
.panel > h2 { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
|
||||
.panel > h3, .panel h3 { margin: 20px 0 8px; }
|
||||
.note { color: var(--text-3); font-size: 13px; line-height: 18px; }
|
||||
.hint { color: var(--text-3); font-size: 13px; line-height: 18px; }
|
||||
.empty { display: flex; flex-direction: column; gap: 8px; color: var(--text-2); max-width: 70ch; }
|
||||
.empty-title { color: var(--text); font-weight: 600; font-size: 15px; }
|
||||
.notice {
|
||||
display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px; border-radius: 10px; font-size: 13.5px; line-height: 20px;
|
||||
}
|
||||
.notice .icon { margin-top: 2px; }
|
||||
.notice-loss { background: var(--loss-bg); color: var(--loss); }
|
||||
.notice-gain { background: var(--gain-bg); color: var(--gain); }
|
||||
.notice-attention { background: var(--attention-bg); color: var(--attention); }
|
||||
.badge { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 8px; font-size: 18px; line-height: 24px; font-weight: 600; }
|
||||
.badge-gain { background: var(--gain-bg); color: var(--gain); }
|
||||
.badge-loss { background: var(--loss-bg); color: var(--loss); }
|
||||
.gain { color: var(--gain); }
|
||||
.loss { color: var(--loss); }
|
||||
.arrow { flex: none; }
|
||||
|
||||
.table-wrap { overflow-x: auto; }
|
||||
.table { width: 100%; border-collapse: collapse; font-size: 13.5px; line-height: 20px; font-variant-numeric: tabular-nums; }
|
||||
.table th { text-align: left; font-size: 12.5px; font-weight: 500; color: var(--text-3); padding: 9px 12px 9px 0; border-bottom: 1px solid var(--rule-inner); }
|
||||
.table td { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule-inner); vertical-align: top; }
|
||||
.table .num { text-align: right; }
|
||||
.nowrap { white-space: nowrap; }
|
||||
|
||||
.facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 20px; margin: 0; }
|
||||
.facts dt { color: var(--text-3); }
|
||||
.facts dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.facts + .hint, .facts + h2, .facts + h3 { margin-top: 16px; }
|
||||
|
||||
.form { display: flex; flex-direction: column; gap: 8px; max-width: 420px; }
|
||||
.form label { font-weight: 550; margin-top: 6px; }
|
||||
.form .btn { align-self: flex-start; margin-top: 10px; }
|
||||
.form-inline { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 8px 0; }
|
||||
.form-inline label { min-width: 80px; font-weight: 550; }
|
||||
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.row > div { display: flex; flex-direction: column; gap: 8px; }
|
||||
.choice { display: flex; gap: 10px; align-items: flex-start; font-weight: 400 !important; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 10px; }
|
||||
.choice input { margin-top: 4px; }
|
||||
fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
|
||||
legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-weight: 650; margin-bottom: 8px; padding: 0; }
|
||||
.step { display: inline-flex; width: 26px; height: 26px; border-radius: 50%; background: var(--surface-2); align-items: center; justify-content: center; font-size: 14px; }
|
||||
.postgres-fields { display: flex; flex-direction: column; gap: 8px; margin-top: 4px; }
|
||||
.postgres-fields[hidden] { display: none; }
|
||||
.test-result:empty { display: none; }
|
||||
.steps { margin: 8px 0; padding-left: 20px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.secret { background: var(--surface-2); padding: 2px 6px; border-radius: 6px; }
|
||||
.tabs { display: flex; gap: 16px; flex-wrap: wrap; }
|
||||
.tabs a { color: var(--text-2); text-decoration: none; font-weight: 550; }
|
||||
.tabs a:hover { color: var(--text); text-decoration: underline; }
|
||||
.columns { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: start; }
|
||||
.more-list { list-style: none; margin: 0; padding: 0; }
|
||||
.more-list a { display: flex; align-items: center; gap: 12px; min-height: 48px; color: var(--text); text-decoration: none; border-bottom: 1px solid var(--rule-inner); }
|
||||
|
||||
/* ---- Panoramica ---- */
|
||||
.head-block { display: grid; grid-template-columns: 1.35fr 1fr; padding: 0; }
|
||||
.half { padding: 24px 28px; min-width: 0; }
|
||||
.half + .half { border-left: 1px solid var(--rule); }
|
||||
.half-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; min-height: 44px; }
|
||||
.half-head h2 { display: flex; align-items: center; gap: 12px; }
|
||||
.segmented { display: inline-flex; padding: 4px; border-radius: 10px; background: var(--surface-2); gap: 2px; }
|
||||
.segmented a { padding: 6px 14px; border-radius: 8px; color: var(--text-2); text-decoration: none; font-size: 14px; }
|
||||
.segmented a.on { background: var(--surface); color: var(--text); font-weight: 550; }
|
||||
.lead { color: var(--text-2); font-size: 17px; line-height: 24px; margin-top: 20px; }
|
||||
.big-result { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; margin-top: 4px; }
|
||||
.big-number { font-size: 60px; line-height: 60px; font-weight: 650; letter-spacing: -0.025em; }
|
||||
.half-past .note { margin-top: 10px; }
|
||||
.cells { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-top: 20px; padding: 16px 0; border-top: 1px solid var(--rule); border-bottom: 1px solid var(--rule); }
|
||||
.cell { display: flex; flex-direction: column; gap: 2px; }
|
||||
.cell-label { color: var(--text-3); font-size: 13px; }
|
||||
.cell-value { font-size: 18px; line-height: 24px; font-weight: 650; letter-spacing: -0.015em; }
|
||||
.cell-change { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 550; }
|
||||
.statement { font-size: 20px; line-height: 28px; font-weight: 650; margin: 20px 0 8px; }
|
||||
.list-title { color: var(--text-3); font-weight: 550; margin-top: 20px !important; padding-bottom: 8px; border-bottom: 1px solid var(--rule); }
|
||||
.moves { list-style: none; margin: 0; padding: 0; }
|
||||
.moves li { display: grid; grid-template-columns: 72px minmax(0, 1fr); gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
|
||||
.move-time { font-weight: 650; font-variant-numeric: tabular-nums; }
|
||||
.moves-past .move-time { font-weight: 500; color: var(--text-3); }
|
||||
.more { display: inline-block; margin-top: 12px; }
|
||||
|
||||
.chart { margin: 20px 0 0; }
|
||||
.chart-box { position: relative; display: grid; grid-template-columns: 64px minmax(0, 1fr) 84px; height: 284px; }
|
||||
.chart-axis { position: relative; }
|
||||
.chart-axis span { position: absolute; left: 0; transform: translateY(-50%); color: var(--text-3); font-size: 13px; font-variant-numeric: tabular-nums; }
|
||||
.chart-plot { position: relative; }
|
||||
.chart-plot svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
|
||||
.chart .grid { stroke: var(--rule-inner); stroke-width: 1; }
|
||||
.chart .area { fill: var(--text); opacity: .05; }
|
||||
.chart .equity { fill: none; stroke: var(--text); stroke-width: 2; stroke-linejoin: round; }
|
||||
.chart .bench { fill: none; stroke: var(--bench); stroke-width: 2; stroke-linejoin: round; }
|
||||
.end-dot { position: absolute; width: 14px; height: 14px; margin: -7px 0 0 -7px; border-radius: 50%; background: var(--text); border: 2px solid var(--surface); }
|
||||
.end-dot.bench-dot { background: var(--bench); }
|
||||
.end-label { position: absolute; left: 100%; margin-left: 14px; transform: translateY(-50%); font-weight: 650; font-size: 13px; white-space: nowrap; }
|
||||
.end-label.bench-label { font-weight: 400; color: var(--text-3); }
|
||||
.legend { display: flex; gap: 20px; margin-top: 12px; color: var(--text-2); font-size: 13px; }
|
||||
.key { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.key::before { content: ""; width: 18px; height: 2px; background: var(--text); }
|
||||
.key-bench::before { background: var(--bench); }
|
||||
.chart-table { margin-top: 8px; font-size: 13px; }
|
||||
.chart-table summary { color: var(--link); cursor: pointer; }
|
||||
.chart-table .table-wrap { max-height: 280px; overflow: auto; margin-top: 8px; }
|
||||
|
||||
/* ---- Service pages ---- */
|
||||
.service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; }
|
||||
.service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; }
|
||||
.service-brand { display: flex; align-items: center; gap: 14px; font-size: 22px; font-weight: 650; margin-bottom: 8px; }
|
||||
.service-section { background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; padding: 20px 22px; display: flex; flex-direction: column; gap: 10px; }
|
||||
.service-section h2 { display: flex; align-items: center; gap: 10px; }
|
||||
.service-foot { color: var(--text-3); font-size: 13px; margin-top: 8px; }
|
||||
.problems td:first-child { white-space: nowrap; }
|
||||
|
||||
/* ---- Phone (SPEC 13.4, appendix C): 390 px and below the tablet width ---- */
|
||||
@media (max-width: 760px) {
|
||||
.shell { display: block; padding-bottom: 76px; }
|
||||
.sidebar { display: none; }
|
||||
.topbar { flex-wrap: nowrap; padding: 12px 16px; }
|
||||
.topbar h1, .status-line, .pill, .currency, .topbar-actions form:not(.stop-form) { display: none; }
|
||||
.topbar-title { display: flex; align-items: center; gap: 14px; }
|
||||
.phone-brand { display: flex; align-items: center; gap: 10px; color: var(--text); text-decoration: none; font-size: 18px; font-weight: 650; }
|
||||
.phone-bot { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 14px; }
|
||||
.btn-danger { height: 44px; }
|
||||
.mode-band { display: flex; align-items: center; gap: 10px; padding: 10px 16px; background: var(--info-bg); color: var(--link); font-weight: 550; font-size: 14px; }
|
||||
.stale-notice { margin: 12px 16px 0; }
|
||||
.page { padding: 16px; gap: 14px; }
|
||||
.panel { padding: 18px; }
|
||||
.head-block { grid-template-columns: 1fr; gap: 14px; padding: 0; background: none; border: 0; }
|
||||
.half { padding: 18px; background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; }
|
||||
.half + .half { border-left: 1px solid var(--rule); }
|
||||
.segmented, .cell-change, .cell-extra, .long, .chart-axis { display: none; }
|
||||
.lead { margin-top: 12px; }
|
||||
.big-result { gap: 12px; }
|
||||
.big-number { font-size: 46px; line-height: 48px; }
|
||||
.badge { font-size: 15px; padding: 4px 10px; }
|
||||
.cells { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.chart-box { grid-template-columns: minmax(0, 1fr) 80px; height: 200px; }
|
||||
.legend { flex-direction: column; gap: 4px; }
|
||||
.statement { font-size: 18px; line-height: 26px; margin-top: 12px; }
|
||||
.columns { grid-template-columns: 1fr; }
|
||||
.row { grid-template-columns: 1fr; }
|
||||
.facts { grid-template-columns: 1fr; gap: 2px; }
|
||||
.facts dd { margin-bottom: 8px; }
|
||||
.bottombar {
|
||||
display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; position: fixed; left: 0; right: 0; bottom: 0;
|
||||
padding: 6px 6px calc(6px + env(safe-area-inset-bottom)); background: var(--surface); border-top: 1px solid var(--rule); z-index: 10;
|
||||
}
|
||||
.bottom-item {
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; min-height: 52px;
|
||||
border-radius: 10px; color: var(--text-2); text-decoration: none; font-size: 11.5px; line-height: 14px;
|
||||
}
|
||||
.bottom-item.active { background: var(--surface-2); color: var(--text); font-weight: 650; }
|
||||
.nav-item, .btn, .more-list a { min-height: 44px; }
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Anubis: the few behaviours the server-rendered pages need. No libraries, no requests to other servers.
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// Collapsible menu, remembered on this device.
|
||||
var collapse = document.querySelector("[data-collapse]");
|
||||
if (collapse) {
|
||||
var sync = function () {
|
||||
var closed = document.documentElement.dataset.nav === "collapsed";
|
||||
collapse.setAttribute("aria-expanded", closed ? "false" : "true");
|
||||
collapse.setAttribute("aria-label", closed ? "Espandi il menu" : "Comprimi il menu");
|
||||
};
|
||||
sync();
|
||||
collapse.addEventListener("click", function () {
|
||||
var closed = document.documentElement.dataset.nav !== "collapsed";
|
||||
if (closed) {
|
||||
document.documentElement.dataset.nav = "collapsed";
|
||||
} else {
|
||||
delete document.documentElement.dataset.nav;
|
||||
}
|
||||
try { localStorage.setItem("anubis.nav", closed ? "collapsed" : "open"); } catch (e) { /* storage blocked */ }
|
||||
sync();
|
||||
});
|
||||
}
|
||||
|
||||
// Selects that apply at once (currency, theme).
|
||||
document.querySelectorAll("select[data-autosubmit]").forEach(function (select) {
|
||||
select.addEventListener("change", function () { select.form.submit(); });
|
||||
});
|
||||
|
||||
// Buttons that ask before acting ("Ferma tutto").
|
||||
document.querySelectorAll("[data-confirm]").forEach(function (button) {
|
||||
button.addEventListener("click", function (event) {
|
||||
if (!window.confirm(button.getAttribute("data-confirm"))) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// First run: PostgreSQL fields only when chosen; "Prova la connessione" without leaving the page.
|
||||
var wizard = document.querySelector("[data-wizard]");
|
||||
if (wizard) {
|
||||
var fields = wizard.querySelector("[data-postgres]");
|
||||
var engines = wizard.querySelectorAll("[data-engine]");
|
||||
var showFields = function () {
|
||||
if (!fields) { return; }
|
||||
var pg = wizard.querySelector("[data-engine]:checked");
|
||||
fields.hidden = !(pg && pg.value === "postgres");
|
||||
};
|
||||
engines.forEach(function (radio) { radio.addEventListener("change", showFields); });
|
||||
showFields();
|
||||
var test = wizard.querySelector("[data-test-connection]");
|
||||
var result = wizard.querySelector("[data-test-result]");
|
||||
if (test && result) {
|
||||
test.addEventListener("click", function (event) {
|
||||
event.preventDefault();
|
||||
result.textContent = "Provo…";
|
||||
fetch("/azioni/primo-avvio/prova", { method: "POST", body: new FormData(wizard), credentials: "same-origin" })
|
||||
.then(function (response) { return response.json(); })
|
||||
.then(function (answer) { result.textContent = answer.message; result.className = "test-result " + (answer.ok ? "gain" : "loss"); })
|
||||
.catch(function () { result.textContent = "Non riesco a fare la prova adesso. Riprova tra poco."; result.className = "test-result loss"; });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Live status over the WebSocket: bot state, freshness of the data, and a discreet notice when the link drops.
|
||||
var age = document.querySelector("[data-live='age']");
|
||||
if (!age || !("WebSocket" in window)) { return; }
|
||||
|
||||
var lastAge = Number(age.getAttribute("data-age")) || 0;
|
||||
var lastAt = Date.now();
|
||||
var lastMessage = Date.now();
|
||||
var connected = false;
|
||||
var retry = 1000;
|
||||
var stale = document.querySelector("[data-stale]");
|
||||
var staleText = document.querySelector("[data-stale-text]");
|
||||
|
||||
var ago = function (seconds) {
|
||||
seconds = Math.max(0, Math.floor(seconds));
|
||||
if (seconds < 60) { return seconds + (seconds === 1 ? " secondo fa" : " secondi fa"); }
|
||||
var minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) { return minutes + (minutes === 1 ? " minuto fa" : " minuti fa"); }
|
||||
var hours = Math.floor(minutes / 60);
|
||||
return hours + (hours === 1 ? " ora fa" : " ore fa");
|
||||
};
|
||||
|
||||
var tick = function () {
|
||||
var seconds = lastAge + (Date.now() - lastAt) / 1000;
|
||||
age.textContent = "Dati aggiornati " + ago(seconds);
|
||||
var silent = (Date.now() - lastMessage) / 1000;
|
||||
if (stale && (!connected || silent > 15)) {
|
||||
stale.hidden = false;
|
||||
staleText.textContent = "Collegamento interrotto: i dati sono fermi da " + ago(seconds).replace(" fa", "") + ". Riprovo da solo.";
|
||||
} else if (stale) {
|
||||
stale.hidden = true;
|
||||
}
|
||||
};
|
||||
|
||||
var apply = function (status) {
|
||||
lastAge = status.ageSeconds;
|
||||
lastAt = Date.now();
|
||||
document.querySelectorAll("[data-live='bot']").forEach(function (el) { el.setAttribute("data-state", status.bot); });
|
||||
document.querySelectorAll("[data-live='bot-label']").forEach(function (el) { el.textContent = status.botLabel; });
|
||||
document.querySelectorAll("[data-live='bot-short']").forEach(function (el) { el.textContent = status.botShort; });
|
||||
var now = document.querySelector("[data-live='now']");
|
||||
if (now) { now.textContent = status.now; }
|
||||
};
|
||||
|
||||
var connect = function () {
|
||||
var socket = new WebSocket((location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws");
|
||||
socket.onopen = function () { connected = true; retry = 1000; };
|
||||
socket.onmessage = function (event) {
|
||||
lastMessage = Date.now();
|
||||
try {
|
||||
var message = JSON.parse(event.data);
|
||||
if (message.type === "status") { apply(message.status); }
|
||||
} catch (e) { /* ignore a malformed message */ }
|
||||
};
|
||||
socket.onclose = function () {
|
||||
connected = false;
|
||||
setTimeout(connect, retry);
|
||||
retry = Math.min(retry * 2, 30000);
|
||||
};
|
||||
};
|
||||
|
||||
connect();
|
||||
setInterval(tick, 1000);
|
||||
})();
|
||||
@@ -0,0 +1,10 @@
|
||||
// Runs before the page paints: applies the remembered menu state so the menu does not jump (SPEC 13.4).
|
||||
(function () {
|
||||
try {
|
||||
if (localStorage.getItem("anubis.nav") === "collapsed") {
|
||||
document.documentElement.dataset.nav = "collapsed";
|
||||
}
|
||||
} catch (e) {
|
||||
// Storage blocked: the menu simply starts open.
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,12 @@
|
||||
@if (Docker)
|
||||
{
|
||||
<label for="@_id">Password della configurazione d'avvio (<code>ANUBIS_ADMIN_PASSWORD</code>)</label>
|
||||
<input id="@_id" name="password" type="password" autocomplete="off" required />
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly string _id = "admin-" + Guid.NewGuid().ToString("N")[..6];
|
||||
|
||||
[Parameter]
|
||||
public bool Docker { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
@inherits LoadedComponent
|
||||
@inject ShellData Shell
|
||||
<!DOCTYPE html>
|
||||
<html lang="it" data-theme="@_theme">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<link rel="stylesheet" href="/assets/app.css?v=@AnubisInfo.Version" />
|
||||
<script src="/assets/early.js?v=@AnubisInfo.Version"></script>
|
||||
<HeadOutlet />
|
||||
</head>
|
||||
<body>
|
||||
<Routes />
|
||||
<script src="/assets/app.js?v=@AnubisInfo.Version" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@code {
|
||||
private string? _theme;
|
||||
|
||||
protected override async Task LoadAsync()
|
||||
{
|
||||
var snapshot = await Shell.SnapshotAsync(CancellationToken.None);
|
||||
_theme = snapshot.Theme == "auto" ? null : snapshot.Theme;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
@* A small filled triangle: the direction is never told by colour alone (SPEC 13.2). *@
|
||||
<svg class="arrow" width="10" height="10" viewBox="0 0 10 10" aria-hidden="true" focusable="false">
|
||||
@if (Up)
|
||||
{
|
||||
<path d="M5 1.5 9.3 8.5H.7Z" fill="currentColor" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<path d="M5 8.5.7 1.5h8.6Z" fill="currentColor" />
|
||||
}
|
||||
</svg>
|
||||
|
||||
@code {
|
||||
[Parameter]
|
||||
public bool Up { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
@inject ShellData Shell
|
||||
|
||||
@* Equity against the "senza bot" comparison (SPEC 13.4): one scale, 2 px lines, faint grid, direct label on the last
|
||||
point, legend, and the same numbers in a table. Lines are SVG stretched to the box; texts and the end point are
|
||||
HTML placed in percent, so nothing gets distorted at any width. *@
|
||||
@if (Points.Count >= 2)
|
||||
{
|
||||
var values = Points.Select(p => Shell.Convert(p.Equity, Currency)).ToList();
|
||||
var bench = Points.Select(p => p.Benchmark is { } b ? Shell.Convert(b, Currency) : (decimal?)null).ToList();
|
||||
var all = values.Concat(bench.OfType<decimal>()).ToList();
|
||||
var (lo, hi, step) = Scale(all.Min(), all.Max());
|
||||
double X(int i) => i * 1000.0 / (Points.Count - 1);
|
||||
double Y(decimal v) => (double)((hi - v) / (hi - lo)) * 1000.0;
|
||||
string Line(IEnumerable<(int I, decimal V)> pts) => string.Join(" ", pts.Select(p => Fmt(X(p.I)) + "," + Fmt(Y(p.V))));
|
||||
var equityLine = Line(values.Select((v, i) => (i, v)));
|
||||
var benchLine = Line(bench.Select((v, i) => (i, v)).Where(p => p.v is not null).Select(p => (p.i, p.v!.Value)));
|
||||
var last = values[^1];
|
||||
<figure class="chart" aria-label="Patrimonio nel tempo, con il bot e senza">
|
||||
<div class="chart-box">
|
||||
<div class="chart-axis" aria-hidden="true">
|
||||
@for (var t = lo; t <= hi; t += step)
|
||||
{
|
||||
<span style="top:@Pct(Y(t) / 10)">@Format.Number(t)</span>
|
||||
}
|
||||
</div>
|
||||
<div class="chart-plot">
|
||||
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||
@for (var t = lo; t <= hi; t += step)
|
||||
{
|
||||
<line class="grid" x1="0" x2="1000" y1="@Fmt(Y(t))" y2="@Fmt(Y(t))" vector-effect="non-scaling-stroke" />
|
||||
}
|
||||
<polygon class="area" points="0,1000 @equityLine 1000,1000" />
|
||||
@if (benchLine.Length > 0)
|
||||
{
|
||||
<polyline class="bench" points="@benchLine" vector-effect="non-scaling-stroke" />
|
||||
}
|
||||
<polyline class="equity" points="@equityLine" vector-effect="non-scaling-stroke" />
|
||||
</svg>
|
||||
@if (bench[^1] is { } lastBench)
|
||||
{
|
||||
// Two labels never overlap: the lower one moves down when they are closer than one line.
|
||||
var gap = Math.Abs(Y(last) - Y(lastBench)) / 10;
|
||||
var benchTop = gap < 7 ? Y(last) / 10 + (Y(lastBench) >= Y(last) ? 7 : -7) : Y(lastBench) / 10;
|
||||
<span class="end-dot bench-dot" style="left:100%;top:@Pct(Y(lastBench) / 10)"></span>
|
||||
<span class="end-label bench-label" style="top:@Pct(benchTop)">@Shell.Money(Points[^1].Benchmark!.Value, Currency, decimals: 0)</span>
|
||||
}
|
||||
<span class="end-dot" style="left:100%;top:@Pct(Y(last) / 10)"></span>
|
||||
<span class="end-label" style="top:@Pct(Y(last) / 10)">@Shell.Money(Points[^1].Equity, Currency, decimals: 0)</span>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption class="legend">
|
||||
<span class="key key-equity">Con Anubis</span>
|
||||
@if (benchLine.Length > 0)
|
||||
{
|
||||
<span class="key key-bench">Senza bot: Bitcoin e S&P 500 comprati e tenuti</span>
|
||||
}
|
||||
</figcaption>
|
||||
<details class="chart-table">
|
||||
<summary>Vedi i numeri in una tabella</summary>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Giorno</th><th scope="col" class="num">Con il bot</th><th scope="col" class="num">Senza bot</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var p in Points.AsEnumerable().Reverse())
|
||||
{
|
||||
<tr><td>@Format.LongDate(p.Day)</td><td class="num">@Shell.Money(p.Equity, Currency)</td><td class="num">@(p.Benchmark is { } b ? Shell.Money(b, Currency) : "—")</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</figure>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<EquityPoint> Points { get; set; } = [];
|
||||
|
||||
[Parameter]
|
||||
public string Currency { get; set; } = "EUR";
|
||||
|
||||
private static string Fmt(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
private static string Pct(double v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||
|
||||
// Round steps (1, 2, 2.5, 3, 5 times a power of ten) giving three to five grid lines.
|
||||
internal static (decimal Lo, decimal Hi, decimal Step) Scale(decimal min, decimal max)
|
||||
{
|
||||
if (max <= min)
|
||||
{
|
||||
max = min + 1;
|
||||
}
|
||||
|
||||
var raw = (double)(max - min) / 4;
|
||||
var power = Math.Pow(10, Math.Floor(Math.Log10(raw)));
|
||||
var step = new[] { 1, 2, 2.5, 3, 5, 10 }.Select(m => m * power).First(s => s >= raw);
|
||||
var stepValue = (decimal)step;
|
||||
var lo = Math.Floor(min / stepValue) * stepValue;
|
||||
var hi = Math.Ceiling(max / stepValue) * stepValue;
|
||||
return (lo, hi == lo ? lo + stepValue : hi, stepValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
@* Line icons drawn for Anubis: 24 grid, stroke 2, round ends (appendix C). Decorative: the text next to them says it all. *@
|
||||
<svg class="icon @Class" width="@Size" height="@Size" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
|
||||
@switch (Name)
|
||||
{
|
||||
case "grid":
|
||||
<rect x="3.5" y="3.5" width="7" height="7" rx="1.5" /><rect x="13.5" y="3.5" width="7" height="7" rx="1.5" /><rect x="3.5" y="13.5" width="7" height="7" rx="1.5" /><rect x="13.5" y="13.5" width="7" height="7" rx="1.5" />
|
||||
break;
|
||||
case "card":
|
||||
<rect x="3" y="5.5" width="18" height="13" rx="2.5" /><path d="M3 10h18M16 14.5h2" />
|
||||
break;
|
||||
case "arrows":
|
||||
<path d="M5 8h14M15 4l4 4-4 4M19 16H5M9 12l-4 4 4 4" />
|
||||
break;
|
||||
case "layers":
|
||||
<path d="M12 3 3 8l9 5 9-5-9-5Z" /><path d="m3 12.5 9 5 9-5" /><path d="m3 16.5 9 5 9-5" />
|
||||
break;
|
||||
case "news":
|
||||
<rect x="3.5" y="4" width="17" height="16" rx="2.5" /><path d="M7.5 9h9M7.5 12.5h9M7.5 16h5" />
|
||||
break;
|
||||
case "network":
|
||||
<circle cx="5.5" cy="5.5" r="2.2" /><circle cx="18.5" cy="5.5" r="2.2" /><circle cx="12" cy="18.5" r="2.2" /><path d="M7.5 6.5 11 16.4M16.5 6.5 13 16.4M7.7 5.5h8.6" />
|
||||
break;
|
||||
case "shield":
|
||||
<path d="M12 3 5 6v5.5c0 4.4 3 8 7 9.5 4-1.5 7-5.1 7-9.5V6l-7-3Z" /><path d="m9 12 2.2 2.2L15.5 10" />
|
||||
break;
|
||||
case "list":
|
||||
<path d="M9 6h11M9 12h11M9 18h11" /><circle cx="4.5" cy="6" r="0.6" /><circle cx="4.5" cy="12" r="0.6" /><circle cx="4.5" cy="18" r="0.6" />
|
||||
break;
|
||||
case "flask":
|
||||
<path d="M9.5 3h5M10 3v6.2L4.8 18.3A1.8 1.8 0 0 0 6.4 21h11.2a1.8 1.8 0 0 0 1.6-2.7L14 9.2V3" /><path d="M7.3 15h9.4" />
|
||||
break;
|
||||
case "sliders":
|
||||
<path d="M4 7h9M17 7h3M4 17h3M11 17h9" /><circle cx="15" cy="7" r="2" /><circle cx="9" cy="17" r="2" />
|
||||
break;
|
||||
case "dots":
|
||||
<circle cx="5.5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="18.5" cy="12" r="1" />
|
||||
break;
|
||||
case "collapse":
|
||||
<path d="m11 17-5-5 5-5M18 17l-5-5 5-5" />
|
||||
break;
|
||||
case "expand":
|
||||
<path d="m13 17 5-5-5-5M6 17l5-5-5-5" />
|
||||
break;
|
||||
case "pause":
|
||||
<path d="M9.5 6v12M14.5 6v12" />
|
||||
break;
|
||||
case "play":
|
||||
<path d="M8 5.5v13l10-6.5-10-6.5Z" />
|
||||
break;
|
||||
case "stop":
|
||||
<path d="M8.3 3h7.4L21 8.3v7.4L15.7 21H8.3L3 15.7V8.3L8.3 3Z" /><rect x="9.5" y="9.5" width="5" height="5" rx="0.6" />
|
||||
break;
|
||||
case "chevron":
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
break;
|
||||
case "clock":
|
||||
<circle cx="12" cy="12" r="8.5" /><path d="M12 7.5V12l3 2" />
|
||||
break;
|
||||
case "half":
|
||||
<path d="M12 3.5a8.5 8.5 0 0 0 0 17Z" fill="currentColor" />
|
||||
break;
|
||||
case "next":
|
||||
<path d="M8 3.5h1a8.5 8.5 0 0 1 0 17H8Z" />
|
||||
break;
|
||||
case "alert":
|
||||
<path d="M12 4 2.8 19.5h18.4L12 4Z" /><path d="M12 10v4M12 17h.01" />
|
||||
break;
|
||||
case "info":
|
||||
<circle cx="12" cy="12" r="8.5" /><path d="M12 11v5M12 8h.01" />
|
||||
break;
|
||||
case "check":
|
||||
<circle cx="12" cy="12" r="8.5" /><path d="m8.5 12 2.4 2.4 4.6-4.8" />
|
||||
break;
|
||||
case "database":
|
||||
<ellipse cx="12" cy="6" rx="7.5" ry="2.8" /><path d="M4.5 6v12c0 1.5 3.4 2.8 7.5 2.8s7.5-1.3 7.5-2.8V6M4.5 12c0 1.5 3.4 2.8 7.5 2.8s7.5-1.3 7.5-2.8" />
|
||||
break;
|
||||
case "lock":
|
||||
<rect x="5" y="10.5" width="14" height="10" rx="2.2" /><path d="M8.5 10.5V7.8a3.5 3.5 0 0 1 7 0v2.7" />
|
||||
break;
|
||||
case "logout":
|
||||
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
|
||||
break;
|
||||
}
|
||||
</svg>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
[Parameter]
|
||||
public int Size { get; set; } = 20;
|
||||
|
||||
[Parameter]
|
||||
public string? Class { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
@inject AnubisHost Host
|
||||
@inject IClock Clock
|
||||
|
||||
@* SPEC 15.1: database and data folder disagree. The user chooses; Docker asks the startup password because users
|
||||
and sessions live in the database that is missing, desktop accepts choices only from the computer itself. *@
|
||||
@{
|
||||
var verdict = Status.Identity!.Verdict;
|
||||
var data = Host.Config.Data;
|
||||
var docker = Host.Config.Platform == PlatformKind.Docker;
|
||||
var canChoose = docker || Local;
|
||||
}
|
||||
|
||||
@switch (verdict)
|
||||
{
|
||||
case IdentityVerdict.EmptyDatabase:
|
||||
<p>Il database è vuoto, ma la cartella dei dati appartiene a un'installazione che esiste già. Il motore resta spento: se partisse, comincerebbe da zero e i conti risulterebbero diversi dal registro.</p>
|
||||
break;
|
||||
case IdentityVerdict.DifferentInstallation:
|
||||
<p>Il database appartiene a un'altra installazione di Anubis. Il motore resta spento: due registri sugli stessi conti produrrebbero ordini doppi.</p>
|
||||
break;
|
||||
case IdentityVerdict.StaleDatabase:
|
||||
<p>È il database di questa installazione, ma una copia più vecchia: dopo l'ultimo ripristino o spostamento ne è nata una più recente. Il motore resta spento per non lavorare su dati superati.</p>
|
||||
break;
|
||||
}
|
||||
|
||||
<dl class="facts">
|
||||
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||
<dt>Cartella dei dati</dt><dd>@data.Root</dd>
|
||||
@if (Status.Identity.File is { } file)
|
||||
{
|
||||
<dt>Installazione della cartella</dt><dd>@file.InstallationId.ToString("D")[..8], nata il @Format.ShortDate(file.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)</dd>
|
||||
}
|
||||
@if (Status.Identity.Row is { } row)
|
||||
{
|
||||
<dt>Installazione del database</dt><dd>@row.Id.ToString("D")[..8], nata il @Format.ShortDate(row.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)</dd>
|
||||
}
|
||||
</dl>
|
||||
|
||||
<p class="hint">La soluzione più sicura spesso è correggere la configurazione perché punti al database giusto. Altrimenti scegli qui sotto. Dopo un ripristino o un'importazione il bot riparte protetto: "Ferma tutto" acceso finché non confermi.</p>
|
||||
|
||||
@if (!canChoose)
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="lock" Size="16" />Queste scelte si fanno solo dal computer su cui gira Anubis.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (verdict == IdentityVerdict.EmptyDatabase)
|
||||
{
|
||||
var backups = new Backups(data, Clock).List();
|
||||
var imports = ServiceChoices.ImportFolders(data);
|
||||
<section class="service-section">
|
||||
<h2>Ripristina un salvataggio</h2>
|
||||
@if (backups.Count == 0)
|
||||
{
|
||||
<p class="hint">Nessun salvataggio nella cartella <code>@data.Backups</code>.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/servizio/ripristina" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="salvataggio">Salvataggio</label>
|
||||
<select id="salvataggio" name="salvataggio">
|
||||
@foreach (var backup in backups)
|
||||
{
|
||||
<option value="@backup.Name">@Format.ShortDate(backup.TakenAt, Clock.UtcNow, Host.Config.TimeZone) · @backup.Reason</option>
|
||||
}
|
||||
</select>
|
||||
<AdminPassword Docker="docker" />
|
||||
<button class="btn btn-primary" type="submit">Ripristina</button>
|
||||
</form>
|
||||
}
|
||||
</section>
|
||||
<section class="service-section">
|
||||
<h2>Importa un archivio</h2>
|
||||
@if (imports.Count == 0)
|
||||
{
|
||||
<p class="hint">Metti la cartella di un archivio esportato (con il suo <code>index.json</code>) dentro <code>@data.Import</code> e ricarica la pagina.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/servizio/importa" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="archivio">Archivio</label>
|
||||
<select id="archivio" name="archivio">
|
||||
@foreach (var folder in imports)
|
||||
{
|
||||
<option value="@Path.GetFileName(folder)">@Path.GetFileName(folder)</option>
|
||||
}
|
||||
</select>
|
||||
<AdminPassword Docker="docker" />
|
||||
<button class="btn btn-primary" type="submit">Importa</button>
|
||||
</form>
|
||||
}
|
||||
</section>
|
||||
<section class="service-section">
|
||||
<h2>Comincia da capo</h2>
|
||||
<p class="hint">Una nuova installazione in questo database vuoto. Il file d'identità della cartella viene messo da parte, non cancellato.</p>
|
||||
<form method="post" action="/azioni/servizio/da-capo" class="form">
|
||||
<AntiforgeryToken />
|
||||
<AdminPassword Docker="docker" />
|
||||
<button class="btn btn-danger" type="submit" data-confirm="Cominciare da capo con un database vuoto? Lo storico precedente resta nei salvataggi.">Comincia da capo</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
else
|
||||
{
|
||||
<section class="service-section">
|
||||
<h2>Usa comunque questo database</h2>
|
||||
<p class="hint">Diventa il database di questa installazione con una nuova impronta. Ogni altra copia non verrà più accettata. Il bot riparte protetto.</p>
|
||||
<form method="post" action="/azioni/servizio/usa-questo" class="form">
|
||||
<AntiforgeryToken />
|
||||
<AdminPassword Docker="docker" />
|
||||
<button class="btn btn-danger" type="submit" data-confirm="Usare questo database da ora in poi? Le altre copie non saranno più accettate.">Usa questo database</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
public HostStatus Status { get; set; } = null!;
|
||||
|
||||
[Parameter]
|
||||
public bool Local { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
@inherits LoadedLayout
|
||||
@inject ShellData Shell
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@* The shell of SPEC 13.4: menu on the left (collapsible, remembered), top bar with state and commands, on phones a
|
||||
bottom bar with five entries. Rendered on the server; app.js keeps state and freshness live over the WebSocket. *@
|
||||
<div class="shell" data-shell>
|
||||
<nav class="sidebar" aria-label="Menu principale">
|
||||
<div class="brand">
|
||||
<a class="brand-link" href="/">
|
||||
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="28" height="28" />
|
||||
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="28" height="28" />
|
||||
<span class="brand-name">Anubis</span>
|
||||
</a>
|
||||
<button type="button" class="icon-button collapse" data-collapse aria-label="Comprimi il menu" aria-expanded="true">
|
||||
<Icon Name="collapse" Class="when-open" /><Icon Name="expand" Class="when-closed" />
|
||||
</button>
|
||||
</div>
|
||||
@foreach (var group in Menu.Groups)
|
||||
{
|
||||
<ul class="nav-group">
|
||||
@foreach (var item in group)
|
||||
{
|
||||
<li>
|
||||
<a class="nav-item @(IsActive(item.Path) ? "active" : null)" href="@item.Path" aria-current="@(IsActive(item.Path) ? "page" : null)" title="@item.Label">
|
||||
<Icon Name="@item.Icon" /><span class="nav-label">@item.Label</span>
|
||||
</a>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</nav>
|
||||
|
||||
<div class="main">
|
||||
<header class="topbar">
|
||||
<div class="topbar-title">
|
||||
<a class="phone-brand" href="/">
|
||||
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="24" height="24" />
|
||||
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="24" height="24" />
|
||||
<span>Anubis</span>
|
||||
</a>
|
||||
<span class="phone-bot" data-live="bot" data-state="@_shell.Bot"><span class="dot"></span><span data-live="bot-short">@_shell.BotShort</span></span>
|
||||
<h1>@Menu.Title(_path)</h1>
|
||||
<p class="status-line">
|
||||
<span data-live="now">@_shell.Now</span>. <span data-live="age" data-age="@_shell.AgeSeconds">Dati aggiornati @Format.Ago(TimeSpan.FromSeconds(_shell.AgeSeconds))</span>.
|
||||
</p>
|
||||
</div>
|
||||
<div class="topbar-actions">
|
||||
<span class="pill pill-bot" data-live="bot" data-state="@_shell.Bot"><span class="dot"></span><span data-live="bot-label">@_shell.BotLabel</span></span>
|
||||
<span class="pill pill-mode"><Icon Name="flask" Size="16" />Simulazione: nessun soldo reale</span>
|
||||
<form class="currency" method="post" action="/azioni/impostazioni/appearance.currency">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="@_back" />
|
||||
<label class="sr-only" for="valuta">Valuta di visualizzazione</label>
|
||||
<select id="valuta" name="valore" data-autosubmit>
|
||||
<option value="EUR" selected="@(_shell.Currency == "EUR")">EUR</option>
|
||||
<option value="USD" selected="@(_shell.Currency == "USD")">USD</option>
|
||||
</select>
|
||||
<Icon Name="chevron" Size="16" Class="select-chevron" />
|
||||
<noscript><button class="btn btn-small" type="submit">Cambia</button></noscript>
|
||||
</form>
|
||||
@if (_shell.Bot == "paused")
|
||||
{
|
||||
<form method="post" action="/azioni/bot/riprendi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn" type="submit"><Icon Name="play" Size="18" />Riprendi</button></form>
|
||||
}
|
||||
else if (_shell.Bot == "active")
|
||||
{
|
||||
<form method="post" action="/azioni/bot/pausa"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn" type="submit"><Icon Name="pause" Size="18" />Metti in pausa</button></form>
|
||||
}
|
||||
<form class="stop-form" method="post" action="/azioni/bot/ferma"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn btn-danger" type="submit" data-confirm="Ferma tutto: il bot non apre né gestisce nuove operazioni finché non lo riattivi dalla pagina Rischio. Confermi?" disabled="@(_shell.Bot == "stopped")"><Icon Name="stop" Size="18" />Ferma tutto</button></form>
|
||||
</div>
|
||||
</header>
|
||||
<div class="mode-band"><Icon Name="flask" Size="16" />Simulazione: nessun soldo reale</div>
|
||||
<div class="stale-notice" data-stale hidden role="status"><Icon Name="alert" Size="16" /><span data-stale-text>Collegamento interrotto.</span></div>
|
||||
|
||||
<main class="page" id="contenuto">
|
||||
@Body
|
||||
<footer class="page-footer">
|
||||
@if (Shell.IsDemo)
|
||||
{
|
||||
<p>Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Anubis @AnubisInfo.Version</p>
|
||||
}
|
||||
</footer>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<nav class="bottombar" aria-label="Menu del telefono">
|
||||
@foreach (var item in Menu.Phone)
|
||||
{
|
||||
<a class="bottom-item @(IsActive(item.Path) ? "active" : null)" href="@item.Path" aria-current="@(IsActive(item.Path) ? "page" : null)">
|
||||
<Icon Name="@item.Icon" Size="22" /><span>@item.Label</span>
|
||||
</a>
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private ShellSnapshot _shell = null!;
|
||||
private string _path = "/";
|
||||
private string _back = "/";
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
protected override async Task LoadAsync()
|
||||
{
|
||||
_shell = await Shell.SnapshotAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
|
||||
var uri = new Uri(Navigation.Uri);
|
||||
_path = uri.AbsolutePath;
|
||||
_back = uri.PathAndQuery;
|
||||
}
|
||||
|
||||
private bool IsActive(string path) => path == "/" ? _path == "/" : _path.StartsWith(path, StringComparison.Ordinal);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
@inherits LayoutComponentBase
|
||||
@inject ShellData Shell
|
||||
|
||||
@* Pages outside the shell: sign-in, first run, first access, error page. *@
|
||||
<div class="service">
|
||||
<div class="service-box">
|
||||
<div class="service-brand">
|
||||
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="36" height="36" />
|
||||
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="36" height="36" />
|
||||
<span>Anubis</span>
|
||||
</div>
|
||||
@Body
|
||||
<p class="service-foot">Anubis @AnubisInfo.Version@(Shell.IsDemo ? " · modalità dimostrativa" : "")</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,49 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace Anubis.Server.Components;
|
||||
|
||||
/// <summary>
|
||||
/// A component that reads its data before drawing anything. With static rendering, a plain <c>OnInitializedAsync</c>
|
||||
/// that really waits (PostgreSQL does; SQLite answers at once) lets Blazor draw the component once with its fields
|
||||
/// still empty. Here the data are loaded first, then the component renders once.
|
||||
/// </summary>
|
||||
public abstract class LoadedComponent : ComponentBase
|
||||
{
|
||||
private bool _loaded;
|
||||
|
||||
public override async Task SetParametersAsync(ParameterView parameters)
|
||||
{
|
||||
parameters.SetParameterProperties(this);
|
||||
if (!_loaded)
|
||||
{
|
||||
_loaded = true;
|
||||
await LoadAsync().ConfigureAwait(true);
|
||||
}
|
||||
|
||||
await base.SetParametersAsync(ParameterView.Empty).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
/// <summary>Reads what the component shows. Parameters, cascading values and query values are already set.</summary>
|
||||
protected abstract Task LoadAsync();
|
||||
}
|
||||
|
||||
/// <summary>The same for the layout.</summary>
|
||||
public abstract class LoadedLayout : LayoutComponentBase
|
||||
{
|
||||
private bool _loaded;
|
||||
|
||||
public override async Task SetParametersAsync(ParameterView parameters)
|
||||
{
|
||||
parameters.SetParameterProperties(this);
|
||||
if (!_loaded)
|
||||
{
|
||||
_loaded = true;
|
||||
await LoadAsync().ConfigureAwait(true);
|
||||
}
|
||||
|
||||
await base.SetParametersAsync(ParameterView.Empty).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="LoadedComponent.LoadAsync"/>
|
||||
protected abstract Task LoadAsync();
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace Anubis.Server.Components;
|
||||
|
||||
internal sealed record MenuItem(string Path, string Label, string Icon, string Title);
|
||||
|
||||
/// <summary>The screens of SPEC 13.6 in the order of the mockups.</summary>
|
||||
internal static class Menu
|
||||
{
|
||||
public static readonly MenuItem Overview = new("/", "Panoramica", "grid", "Panoramica");
|
||||
public static readonly MenuItem Accounts = new("/conti", "Conti e posizioni", "card", "Conti e posizioni");
|
||||
public static readonly MenuItem Trades = new("/operazioni", "Operazioni", "arrows", "Operazioni");
|
||||
public static readonly MenuItem Strategies = new("/strategie", "Strategie", "layers", "Strategie");
|
||||
public static readonly MenuItem News = new("/notizie", "Notizie e mercato", "news", "Notizie e mercato");
|
||||
public static readonly MenuItem Learning = new("/apprendimento", "Apprendimento", "network", "Apprendimento");
|
||||
public static readonly MenuItem Risk = new("/rischio", "Rischio", "shield", "Rischio");
|
||||
public static readonly MenuItem Journal = new("/diario", "Diario e sistema", "list", "Diario e sistema");
|
||||
public static readonly MenuItem Lab = new("/laboratorio", "Laboratorio", "flask", "Laboratorio");
|
||||
public static readonly MenuItem Settings = new("/impostazioni", "Impostazioni", "sliders", "Impostazioni");
|
||||
public static readonly MenuItem More = new("/altro", "Altro", "dots", "Altro");
|
||||
|
||||
public static readonly IReadOnlyList<IReadOnlyList<MenuItem>> Groups =
|
||||
[
|
||||
[Overview, Accounts, Trades],
|
||||
[Strategies, News, Learning],
|
||||
[Risk, Journal, Lab, Settings],
|
||||
];
|
||||
|
||||
/// <summary>The bottom bar of the phone (SPEC 13.4).</summary>
|
||||
public static readonly IReadOnlyList<MenuItem> Phone =
|
||||
[
|
||||
Overview,
|
||||
Accounts with { Label = "Conti" },
|
||||
Journal with { Label = "Diario" },
|
||||
Risk,
|
||||
More,
|
||||
];
|
||||
|
||||
public static string Title(string path) =>
|
||||
Groups.SelectMany(g => g).Append(More).FirstOrDefault(i => i.Path == "/" ? path == "/" : path.StartsWith(i.Path, StringComparison.Ordinal))?.Title ?? "Anubis";
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
@page "/accesso"
|
||||
@layout ServiceLayout
|
||||
@attribute [AllowAnonymous]
|
||||
|
||||
<PageTitle>Accesso · Anubis</PageTitle>
|
||||
|
||||
<h1>Accedi</h1>
|
||||
@if (Message is { } message)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||
}
|
||||
<form method="post" action="/azioni/accesso" class="form">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="@(Ritorno is { } r && Forms.IsLocalPath(r) ? r : "/")" />
|
||||
<label for="password">Password</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" required autofocus />
|
||||
@if (Fattore == "1")
|
||||
{
|
||||
<label for="codice">Codice dell'app di autenticazione</label>
|
||||
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
||||
<p class="hint">Sei cifre, cambiano ogni 30 secondi. Scrivi di nuovo anche la password.</p>
|
||||
}
|
||||
<button class="btn btn-primary" type="submit">Accedi</button>
|
||||
</form>
|
||||
|
||||
@code {
|
||||
[SupplyParameterFromQuery(Name = "errore")]
|
||||
public string? Errore { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "minuti")]
|
||||
public string? Minuti { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "fattore")]
|
||||
public string? Fattore { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "ritorno")]
|
||||
public string? Ritorno { get; set; }
|
||||
|
||||
private string? Message => Errore switch
|
||||
{
|
||||
"password" => "Password sbagliata. Riprova: dopo 5 tentativi sbagliati l'accesso si blocca per 15 minuti.",
|
||||
"codice" => "Il codice non è giusto o è scaduto. Usa quello che l'app mostra adesso.",
|
||||
"attesa" => $"Troppi tentativi sbagliati. Riprova tra {Minuti ?? "15"} minuti.",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/altro"
|
||||
@inject ShellData Shell
|
||||
|
||||
<PageTitle>Altro · Anubis</PageTitle>
|
||||
|
||||
@* On the phone: the screens that do not fit the bottom bar, the pause and the currency (SPEC 13.4). *@
|
||||
<section class="panel">
|
||||
<ul class="more-list">
|
||||
@foreach (var item in Menu.Groups.SelectMany(g => g).Where(i => !Menu.Phone.Any(p => p.Path == i.Path)))
|
||||
{
|
||||
<li><a href="@item.Path"><Icon Name="@item.Icon" />@item.Label</a></li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<h2>Comandi</h2>
|
||||
<div class="form-inline">
|
||||
@if (_shell.Bot == "active")
|
||||
{
|
||||
<form method="post" action="/azioni/bot/pausa"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/altro" /><button class="btn" type="submit"><Icon Name="pause" Size="18" />Metti in pausa</button></form>
|
||||
}
|
||||
else if (_shell.Bot == "paused")
|
||||
{
|
||||
<form method="post" action="/azioni/bot/riprendi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/altro" /><button class="btn" type="submit"><Icon Name="play" Size="18" />Riprendi</button></form>
|
||||
}
|
||||
<form method="post" action="/azioni/impostazioni/appearance.currency">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/altro" />
|
||||
<input type="hidden" name="valore" value="@(_shell.Currency == "EUR" ? "USD" : "EUR")" />
|
||||
<button class="btn" type="submit">Mostra in @(_shell.Currency == "EUR" ? "dollari" : "euro")</button>
|
||||
</form>
|
||||
@if (!Shell.IsDemo)
|
||||
{
|
||||
<form method="post" action="/azioni/esci"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="logout" Size="18" />Esci</button></form>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private ShellSnapshot _shell = null!;
|
||||
|
||||
protected override async Task LoadAsync() => _shell = await Shell.SnapshotAsync(CancellationToken.None);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@page "/apprendimento"
|
||||
|
||||
<PageTitle>Apprendimento · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Il modello non è ancora in osservazione.">Comincia a imparare quando ci sono abbastanza segnali: qui vedrai quanti ne mancano e quanto è preciso su casi mai visti.</Pending>
|
||||
@@ -0,0 +1,5 @@
|
||||
@page "/conti"
|
||||
|
||||
<PageTitle>Conti e posizioni · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Nessun conto collegato.">Conti, posizioni e ordini arrivano con la contabilità: lì aggiungerai le chiavi dei conti di prova e vedrai patrimonio, liquidità e commissioni di ciascuno.</Pending>
|
||||
@@ -0,0 +1,90 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/diario"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
|
||||
<PageTitle>Diario e sistema · Anubis</PageTitle>
|
||||
|
||||
<div class="columns">
|
||||
<section class="panel">
|
||||
<h2>Diario</h2>
|
||||
@if (_entries.Count == 0)
|
||||
{
|
||||
<p class="note">Ancora nessuna voce.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Quando</th><th scope="col">Tipo</th><th scope="col">Voce</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var e in _entries)
|
||||
{
|
||||
<tr><td class="nowrap">@Format.ShortDate(e.At, Shell.Now, Shell.Zone)</td><td>@e.Kind</td><td>@e.Text</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
<section class="panel">
|
||||
<h2>Sistema</h2>
|
||||
<dl class="facts">
|
||||
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
|
||||
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop")</dd>
|
||||
<dt>Database</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite") · risponde</dd>
|
||||
<dt>In funzione da</dt><dd>@Format.Ago(Shell.Now - _since).Replace(" fa", "", StringComparison.Ordinal)</dd>
|
||||
</dl>
|
||||
<h3 class="list-title">Lavori in programma</h3>
|
||||
<ul class="moves">
|
||||
@foreach (var job in _upcoming)
|
||||
{
|
||||
<li><span class="move-time">@Format.ShortDate(job.DueUtc, Shell.Now, Shell.Zone)</span><span>@job.Description</span></li>
|
||||
}
|
||||
</ul>
|
||||
@if (_jobs.Count > 0)
|
||||
{
|
||||
<h3 class="list-title">Ultimi lavori</h3>
|
||||
<ul class="moves moves-past">
|
||||
@foreach (var job in _jobs)
|
||||
{
|
||||
<li><span class="move-time">@(job.Finished is { } f ? Format.ShortDate(f, Shell.Now, Shell.Zone) : "—")</span><span>@job.Description: @Outcome(job.Outcome)</span></li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private List<(DateTimeOffset At, string Kind, string Text)> _entries = [];
|
||||
private List<(string Description, DateTimeOffset? Finished, string? Outcome)> _jobs = [];
|
||||
private IReadOnlyList<UpcomingRun> _upcoming = [];
|
||||
private DateTimeOffset _since;
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
protected override async Task LoadAsync()
|
||||
{
|
||||
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||
var services = Host.Services!;
|
||||
(_entries, _jobs) = await services.Db.ReadAsync(async s =>
|
||||
{
|
||||
var entries = await s.QueryAsync("SELECT occurred_at, kind, message FROM journal ORDER BY occurred_at DESC LIMIT 200",
|
||||
r => (r.Moment("occurred_at"), r.Text("kind"), r.Text("message")));
|
||||
var jobs = await s.QueryAsync("SELECT description, last_finished_at, last_outcome FROM jobs ORDER BY last_finished_at DESC",
|
||||
r => (r.Text("description"), r.MomentOrNull("last_finished_at"), r.TextOrNull("last_outcome")));
|
||||
return (entries, jobs);
|
||||
}, ct);
|
||||
_upcoming = services.Scheduler.Upcoming(10);
|
||||
_since = Host.Status.Since;
|
||||
}
|
||||
|
||||
private static string Outcome(string? outcome) => outcome switch
|
||||
{
|
||||
"succeeded" => "fatto",
|
||||
"failed" => "non riuscito",
|
||||
"skipped" => "saltato, orario superato",
|
||||
_ => "in attesa",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/impostazioni"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
@inject SecondFactorDrafts Drafts
|
||||
|
||||
<PageTitle>Impostazioni · Anubis</PageTitle>
|
||||
|
||||
@* First part of SPEC 13.5: appearance, security, system. The other sections arrive with their phases. *@
|
||||
@if (Ok is { } ok)
|
||||
{
|
||||
<p class="notice notice-gain" role="status"><Icon Name="check" Size="16" />@(ok switch
|
||||
{
|
||||
"password" => "Password cambiata. Le altre sessioni sono state chiuse.",
|
||||
"due-fattori" => "Secondo fattore attivato.",
|
||||
"due-fattori-tolti" => "Secondo fattore disattivato.",
|
||||
"salvataggio" => "Salvataggio fatto.",
|
||||
_ => "Fatto.",
|
||||
})</p>
|
||||
}
|
||||
@if (ErrorText is { } error)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@error</p>
|
||||
}
|
||||
|
||||
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
||||
<a href="#aspetto">Aspetto</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
</nav>
|
||||
|
||||
<section class="panel" id="aspetto">
|
||||
<h2>Aspetto</h2>
|
||||
@foreach (var setting in _appearance)
|
||||
{
|
||||
var definition = SettingsStore.Definition(setting.Key);
|
||||
<form method="post" action="/azioni/impostazioni/@setting.Key" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni#aspetto" />
|
||||
<label for="@setting.Key">@definition.Label</label>
|
||||
<select id="@setting.Key" name="valore" disabled="@setting.ReadOnly" data-autosubmit>
|
||||
@foreach (var value in definition.Allowed!)
|
||||
{
|
||||
<option value="@value" selected="@(value == setting.Value)">@Label(value)</option>
|
||||
}
|
||||
</select>
|
||||
@if (setting.ReadOnly)
|
||||
{
|
||||
<span class="hint">Fissato da @setting.Source: si cambia lì.</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
}
|
||||
</form>
|
||||
}
|
||||
<p class="hint">Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.</p>
|
||||
</section>
|
||||
|
||||
<section class="panel" id="sicurezza">
|
||||
<h2>Sicurezza</h2>
|
||||
@if (Shell.IsDemo)
|
||||
{
|
||||
<p class="hint">Nella modalità dimostrativa password e secondo fattore non si cambiano.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<h3>Password</h3>
|
||||
<form method="post" action="/azioni/password" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="attuale">Password attuale</label>
|
||||
<input id="attuale" name="attuale" type="password" autocomplete="current-password" required />
|
||||
<label for="nuova">Nuova password</label>
|
||||
<input id="nuova" name="nuova" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||
<label for="conferma">Scrivila di nuovo</label>
|
||||
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||
<button class="btn" type="submit">Cambia password</button>
|
||||
</form>
|
||||
|
||||
<h3>Secondo fattore</h3>
|
||||
@if (_hasSecondFactor)
|
||||
{
|
||||
<p>Attivo: all'accesso chiedo anche il codice dell'app. Servirà anche per attivare i soldi veri.</p>
|
||||
<form method="post" action="/azioni/due-fattori/disattiva" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="password-2fa">Per disattivarlo: password</label>
|
||||
<input id="password-2fa" name="password" type="password" autocomplete="current-password" required />
|
||||
<label for="codice-2fa">Codice dell'app</label>
|
||||
<input id="codice-2fa" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
||||
<button class="btn" type="submit">Disattiva il secondo fattore</button>
|
||||
</form>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Facoltativo: un codice di sei cifre da un'app di autenticazione (per esempio quella del tuo gestore di password), oltre alla password.</p>
|
||||
<ol class="steps">
|
||||
<li>Nell'app scegli "aggiungi con chiave" e scrivi questa chiave: <code class="secret">@_draft</code></li>
|
||||
<li>Oppure, se l'app accetta un indirizzo, usa: <code class="secret">@_draftUri</code></li>
|
||||
<li>Scrivi qui il codice che l'app mostra.</li>
|
||||
</ol>
|
||||
<form method="post" action="/azioni/due-fattori/attiva" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="codice">Codice</label>
|
||||
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
||||
<button class="btn" type="submit">Attiva il secondo fattore</button>
|
||||
</form>
|
||||
}
|
||||
<form method="post" action="/azioni/esci" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="logout" Size="18" />Esci</button></form>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" id="sistema">
|
||||
<h2>Sistema</h2>
|
||||
<dl class="facts">
|
||||
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop (Windows)")</dd>
|
||||
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||
<dt>Cartella dei dati</dt><dd>@Host.Config.Data.Root</dd>
|
||||
<dt>Chiave dei segreti</dt><dd>@Host.Config.SecretKey.Description</dd>
|
||||
<dt>Fuso orario</dt><dd>@Host.Config.TimeZone.Id</dd>
|
||||
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
|
||||
</dl>
|
||||
<p class="hint">
|
||||
@if (Host.Config.Platform == PlatformKind.Docker)
|
||||
{
|
||||
@:Motore e connessione del database si cambiano solo nella configurazione del container.
|
||||
}
|
||||
else
|
||||
{
|
||||
@:Motore e connessione del database stanno in config.toml, nella cartella dei dati. Lo spostamento su un altro database arriva con l'applicazione desktop.
|
||||
}
|
||||
</p>
|
||||
|
||||
<h3>Salvataggi</h3>
|
||||
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
|
||||
<form method="post" action="/azioni/salvataggio" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="database" Size="18" />Salva adesso</button></form>
|
||||
@if (_backups.Count > 0)
|
||||
{
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Quando</th><th scope="col">Perché</th><th scope="col">Cartella</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var b in _backups)
|
||||
{
|
||||
<tr><td class="nowrap">@Format.ShortDate(b.TakenAt, Shell.Now, Shell.Zone)</td><td>@b.Reason</td><td><code>@b.Name</code></td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" id="modifiche">
|
||||
<h2>Registro delle modifiche</h2>
|
||||
@if (_history.Count == 0)
|
||||
{
|
||||
<p class="note">Nessuna modifica finora.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Quando</th><th scope="col">Voce</th><th scope="col">Prima</th><th scope="col">Dopo</th><th scope="col">Chi</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var h in _history)
|
||||
{
|
||||
<tr><td class="nowrap">@Format.ShortDate(h.At, Shell.Now, Shell.Zone)</td><td>@h.Key</td><td>@Label(h.OldValue)</td><td>@Label(h.NewValue)</td><td>@h.ChangedBy</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private readonly List<SettingValue> _appearance = [];
|
||||
private List<SettingChange> _history = [];
|
||||
private IReadOnlyList<BackupInfo> _backups = [];
|
||||
private bool _hasSecondFactor;
|
||||
private string? _draft;
|
||||
private string? _draftUri;
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "ok")]
|
||||
public string? Ok { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "errore")]
|
||||
public string? Errore { get; set; }
|
||||
|
||||
protected override async Task LoadAsync()
|
||||
{
|
||||
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||
var services = Host.Services!;
|
||||
_appearance.Add(await services.Settings.GetAsync(SettingsStore.Theme.Key, ct));
|
||||
_appearance.Add(await services.Settings.GetAsync(SettingsStore.Currency.Key, ct));
|
||||
_history = await services.Settings.HistoryAsync(null, 50, ct);
|
||||
_backups = services.Backups.List();
|
||||
var user = HttpContext!.User;
|
||||
_hasSecondFactor = CurrentUser.HasSecondFactor(user);
|
||||
if (!_hasSecondFactor && !Shell.IsDemo)
|
||||
{
|
||||
var secret = Drafts.For(CurrentUser.Session(user));
|
||||
_draft = Base32.Encode(secret);
|
||||
_draftUri = Totp.Uri("Anubis", AccessStore.AdminName, secret);
|
||||
}
|
||||
}
|
||||
|
||||
private string? ErrorText => Errore switch
|
||||
{
|
||||
"codice" => "Il codice non è giusto. Controlla l'ora del telefono e riprova con il codice che vedi adesso.",
|
||||
"segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.",
|
||||
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
|
||||
"impostazione" => "Questa impostazione non si può cambiare così.",
|
||||
"bot" => "Comando non ammesso nello stato attuale del bot.",
|
||||
_ => PasswordMessages.For(Errore),
|
||||
};
|
||||
|
||||
private static string Label(string? value) => value switch
|
||||
{
|
||||
null => "—",
|
||||
"auto" => "Come il sistema",
|
||||
"light" => "Chiaro",
|
||||
"dark" => "Scuro",
|
||||
"EUR" => "Euro (EUR)",
|
||||
"USD" => "Dollaro (USD)",
|
||||
"active" => "Attivo",
|
||||
"paused" => "In pausa",
|
||||
"stopped" => "Fermo",
|
||||
_ => value.Trim('"'),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@page "/laboratorio"
|
||||
|
||||
<PageTitle>Laboratorio · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Nessun test eseguito.">Il laboratorio dei test sul passato arriva con il motore dei backtest.</Pending>
|
||||
@@ -0,0 +1,5 @@
|
||||
@page "/notizie"
|
||||
|
||||
<PageTitle>Notizie e mercato · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Nessuna notizia letta finora.">La lettura delle notizie, l'umore del mercato e il calendario degli eventi arrivano in una fase successiva.</Pending>
|
||||
@@ -0,0 +1,5 @@
|
||||
@page "/operazioni"
|
||||
|
||||
<PageTitle>Operazioni · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Ancora nessuna operazione chiusa.">Quando il bot comincerà a lavorare, qui troverai ogni operazione con il suo risultato e il perché di ogni ingresso e uscita.</Pending>
|
||||
@@ -0,0 +1,134 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
|
||||
<PageTitle>Panoramica · Anubis</PageTitle>
|
||||
|
||||
@{
|
||||
var o = _overview;
|
||||
var c = _currency;
|
||||
}
|
||||
<section class="panel head-block" aria-label="Il punto della situazione">
|
||||
<div class="half half-past">
|
||||
<div class="half-head">
|
||||
<h2><Icon Name="half" Size="18" />Finora</h2>
|
||||
@if (o.HasData)
|
||||
{
|
||||
<nav class="segmented" aria-label="Periodo">
|
||||
@foreach (var (key, label) in Overview.Periods)
|
||||
{
|
||||
<a href="@(key == "avvio" ? "/" : "/?periodo=" + key)" class="@(key == _period ? "on" : null)" aria-current="@(key == _period ? "true" : null)">@label</a>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
</div>
|
||||
@if (!o.HasData)
|
||||
{
|
||||
<div class="empty">
|
||||
<p class="empty-title">Ancora nessun risultato da mostrare.</p>
|
||||
<p>Il patrimonio comincia a essere registrato quando colleghi un conto. Da quel giorno qui vedrai quanto stai guadagnando o perdendo, al netto dei costi, e il confronto con chi non usa il bot.</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
var gain = o.Result.Amount >= 0;
|
||||
<p class="lead">@(gain ? "Sei in profitto di" : "Sei in perdita di")</p>
|
||||
<div class="big-result">
|
||||
<span class="big-number">@Shell.Money(o.Result.Amount, c, withSign: true)</span>
|
||||
<span class="badge @(gain ? "badge-gain" : "badge-loss")"><Arrow Up="gain" />@Format.Percent(o.Result.Percent, 2, withSign: true)</span>
|
||||
</div>
|
||||
<p class="note">Dal @Format.LongDate(o.From), partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.</p>
|
||||
<div class="cells">
|
||||
@foreach (var (cell, i) in o.Cells.Select((x, i) => (x, i)))
|
||||
{
|
||||
var up = cell.Amount >= 0;
|
||||
var label = cell.Label.StartsWith("Ultimi ", StringComparison.Ordinal) ? cell.Label["Ultimi ".Length..] : cell.Label;
|
||||
<div class="cell @(i >= 3 ? "cell-extra" : null)">
|
||||
<span class="cell-label">@if (label != cell.Label) {<span class="long">Ultimi </span>}@label</span>
|
||||
<span class="cell-value">@Shell.Money(cell.Amount, c, withSign: true)</span>
|
||||
<span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Format.Percent(cell.Percent, 2, withSign: true)</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<EquityChart Points="o.Series" Currency="c" />
|
||||
}
|
||||
</div>
|
||||
<div class="half half-next">
|
||||
<div class="half-head">
|
||||
<h2><Icon Name="next" Size="18" />Adesso e dopo</h2>
|
||||
@if (_runningDays is { } days)
|
||||
{
|
||||
<span class="note">Attivo da @days giorni senza interruzioni</span>
|
||||
}
|
||||
</div>
|
||||
<p class="statement">@Statement(o)</p>
|
||||
<h3 class="list-title">Prossime mosse</h3>
|
||||
@if (o.Next.Count == 0)
|
||||
{
|
||||
<p class="note">Niente in programma.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="moves">
|
||||
@foreach (var move in o.Next)
|
||||
{
|
||||
<li><span class="move-time">@move.Time</span><span>@move.Text</span></li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<h3 class="list-title">Ultime azioni</h3>
|
||||
@if (o.Last.Count == 0)
|
||||
{
|
||||
<p class="note">Ancora nessuna voce nel diario.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="moves moves-past">
|
||||
@foreach (var action in o.Last)
|
||||
{
|
||||
<li><span class="move-time">@action.When</span><span>@action.Text</span></li>
|
||||
}
|
||||
</ul>
|
||||
<a class="more" href="/diario">Tutto il diario</a>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private Overview _overview = null!;
|
||||
private string _currency = "EUR";
|
||||
private string _period = "avvio";
|
||||
private int? _runningDays;
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "periodo")]
|
||||
public string? Periodo { get; set; }
|
||||
|
||||
protected override async Task LoadAsync()
|
||||
{
|
||||
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||
_period = Periodo is "30" or "7" or "oggi" ? Periodo : "avvio";
|
||||
var services = Host.Services!;
|
||||
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||
_overview = await Overview.LoadAsync(services, _period, Shell.Now, Shell.Zone, ct);
|
||||
using var aggregates = Shell.Aggregates();
|
||||
_runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32();
|
||||
}
|
||||
|
||||
private static string Statement(Overview o)
|
||||
{
|
||||
var orders = o.OpenOrders == 0 ? "Nessun ordine in corso." : o.OpenOrders == 1 ? "Un ordine in corso." : $"{o.OpenOrders} ordini in corso.";
|
||||
if (o.Positions == 0)
|
||||
{
|
||||
return "Nessuna posizione aperta. " + orders;
|
||||
}
|
||||
|
||||
var stops = o.PositionsWithoutStop == 0
|
||||
? (o.Positions == 1 ? "con il suo stop" : "ognuna con il suo stop")
|
||||
: $"{o.PositionsWithoutStop} senza stop";
|
||||
return o.Positions == 1 ? $"Sorveglio una posizione, {stops}. {orders}" : $"Sorveglio {o.Positions} posizioni, {stops}. {orders}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
@page "/primo-accesso"
|
||||
@layout ServiceLayout
|
||||
@inject AnubisHost Host
|
||||
|
||||
<PageTitle>Primo accesso · Anubis</PageTitle>
|
||||
|
||||
<h1>Benvenuto in Anubis</h1>
|
||||
<p>Prima di cominciare, due cose.</p>
|
||||
|
||||
<section class="service-section">
|
||||
<h2><Icon Name="database" Size="18" />Database</h2>
|
||||
<p>Scelto nella configurazione del container: qui si vede soltanto. Per cambiarlo si modifica il container (manuale, capitolo Installazione).</p>
|
||||
<dl class="facts">
|
||||
<dt>Motore</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite")</dd>
|
||||
<dt>Dove</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="service-section">
|
||||
<h2><Icon Name="lock" Size="18" />Scegli la tua password</h2>
|
||||
<p>La password iniziale del container vale solo per questo primo accesso. Scegline una nuova, di almeno @Passwords.MinimumLength caratteri.</p>
|
||||
@if (Message is { } message)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||
}
|
||||
<form method="post" action="/azioni/primo-accesso" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="attuale">Password iniziale</label>
|
||||
<input id="attuale" name="attuale" type="password" autocomplete="current-password" required />
|
||||
<label for="nuova">Nuova password</label>
|
||||
<input id="nuova" name="nuova" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||
<label for="conferma">Scrivila di nuovo</label>
|
||||
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||
<button class="btn btn-primary" type="submit">Salva e continua</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
@code {
|
||||
[SupplyParameterFromQuery(Name = "errore")]
|
||||
public string? Errore { get; set; }
|
||||
|
||||
private string? Message => PasswordMessages.For(Errore);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
@page "/primo-avvio"
|
||||
@layout ServiceLayout
|
||||
@attribute [AllowAnonymous]
|
||||
@inject AnubisHost Host
|
||||
|
||||
<PageTitle>Primo avvio · Anubis</PageTitle>
|
||||
|
||||
<h1>Primo avvio</h1>
|
||||
@if (!_local)
|
||||
{
|
||||
<p class="notice notice-attention" role="alert"><Icon Name="lock" Size="16" />La prima configurazione si fa solo dal computer su cui gira Anubis.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.</p>
|
||||
@if (Message is { } message)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||
}
|
||||
|
||||
<form method="post" action="/azioni/primo-avvio" class="form" data-wizard>
|
||||
<AntiforgeryToken />
|
||||
@if (!Host.Config.IsComplete)
|
||||
{
|
||||
<fieldset class="service-section">
|
||||
<legend><span class="step">1</span>Database</legend>
|
||||
<label class="choice">
|
||||
<input type="radio" name="motore" value="sqlite" checked data-engine />
|
||||
<span><strong>SQLite</strong> (consigliato): un file nella cartella dei dati, niente da installare.</span>
|
||||
</label>
|
||||
<label class="choice">
|
||||
<input type="radio" name="motore" value="postgres" data-engine />
|
||||
<span><strong>PostgreSQL</strong>: un server che hai già, con un database dedicato e vuoto.</span>
|
||||
</label>
|
||||
<div class="postgres-fields" data-postgres>
|
||||
<label for="host">Indirizzo del server</label>
|
||||
<input id="host" name="host" autocomplete="off" placeholder="192.168.1.10" />
|
||||
<div class="row">
|
||||
<div><label for="porta">Porta</label><input id="porta" name="porta" inputmode="numeric" value="5432" /></div>
|
||||
<div><label for="nome">Nome del database</label><input id="nome" name="nome" value="anubis" /></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div><label for="utente">Utente</label><input id="utente" name="utente" value="anubis" autocomplete="off" /></div>
|
||||
<div><label for="dbpassword">Password del database</label><input id="dbpassword" name="dbpassword" type="password" autocomplete="off" /></div>
|
||||
</div>
|
||||
<p class="hint">La password del database non va in <code>config.toml</code>: la custodisce Windows per il tuo utente.</p>
|
||||
<button class="btn" type="submit" formaction="/azioni/primo-avvio/prova" data-test-connection>Prova la connessione</button>
|
||||
<p class="test-result" data-test-result role="status"></p>
|
||||
</div>
|
||||
</fieldset>
|
||||
}
|
||||
<fieldset class="service-section">
|
||||
<legend><span class="step">@(Host.Config.IsComplete ? "1" : "2")</span>Password</legend>
|
||||
<p class="hint">Serve per entrare nell'interfaccia, anche da questo computer. Almeno @Passwords.MinimumLength caratteri.</p>
|
||||
<label for="password">Password</label>
|
||||
<input id="password" name="password" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||
<label for="conferma">Scrivila di nuovo</label>
|
||||
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
|
||||
</fieldset>
|
||||
<p class="hint">Anubis lavora solo quando il computer è acceso. Dopo un'assenza ricostruisce cosa è successo prima di riprendere.</p>
|
||||
<button class="btn btn-primary" type="submit">Crea l'installazione</button>
|
||||
</form>
|
||||
}
|
||||
|
||||
@code {
|
||||
private bool _local;
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "errore")]
|
||||
public string? Errore { get; set; }
|
||||
|
||||
protected override void OnInitialized() => _local = HttpContext is not null && CurrentUser.IsLocal(HttpContext);
|
||||
|
||||
private string? Message => Errore == "database"
|
||||
? "Non riesco a collegarmi al database con questi dati. Controlla indirizzo, porta, nome, utente e password, poi riprova."
|
||||
: PasswordMessages.For(Errore);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/rischio"
|
||||
@inject AnubisHost Host
|
||||
|
||||
<PageTitle>Rischio · Anubis</PageTitle>
|
||||
|
||||
<section class="panel">
|
||||
<h2><Icon Name="shield" Size="18" />Interruttore</h2>
|
||||
@if (_bot == "stopped")
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" />"Ferma tutto" è acceso: il bot non apre e non gestisce operazioni finché non lo riattivi.</p>
|
||||
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/rischio" />
|
||||
<button class="btn" type="submit" data-confirm="Riattivare il bot?">Riattiva il bot</button>
|
||||
</form>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.</p>
|
||||
}
|
||||
</section>
|
||||
<Pending Title="Limiti e scenari non sono ancora attivi.">Limiti di perdita, calo dal massimo, esposizione e scenari arrivano con le strategie e il controllo del rischio.</Pending>
|
||||
|
||||
@code {
|
||||
private string _bot = "active";
|
||||
|
||||
protected override async Task LoadAsync() =>
|
||||
_bot = (await Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
@page "/servizio"
|
||||
@layout ServiceLayout
|
||||
@attribute [AllowAnonymous]
|
||||
@inject AnubisHost Host
|
||||
@inject IClock Clock
|
||||
|
||||
@* The error page of SPEC 15.1: what is wrong, what to do, and the engine stays off. Never another database. *@
|
||||
<PageTitle>@ServiceText.Title(_status.Mode) · Anubis</PageTitle>
|
||||
@if (_refresh)
|
||||
{
|
||||
<HeadContent><meta http-equiv="refresh" content="5" /></HeadContent>
|
||||
}
|
||||
|
||||
<h1>@ServiceText.Title(_status.Mode)</h1>
|
||||
|
||||
@switch (_status.Mode)
|
||||
{
|
||||
case HostMode.Starting:
|
||||
<p>Controllo configurazione e database. Questa pagina si aggiorna da sola.</p>
|
||||
break;
|
||||
|
||||
case HostMode.ConfigProblem:
|
||||
<p>Il motore resta spento finché la configurazione non è completa. Non uso nessun altro database al posto di quello indicato.</p>
|
||||
<table class="table problems">
|
||||
<thead><tr><th scope="col">Voce</th><th scope="col">Cosa non va</th><th scope="col">Come rimediare</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var problem in Host.Config.Problems)
|
||||
{
|
||||
<tr><td><code>@problem.Setting</code></td><td>@problem.What</td><td>@problem.Remedy</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@if (Host.Config.Platform == PlatformKind.Docker)
|
||||
{
|
||||
<p class="hint">Le variabili si cambiano nella configurazione del container (su Unraid, nei campi del modello), poi si riavvia il container.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="hint">Il file è <code>@Host.Config.Data.ConfigFile</code>. Appena lo correggi riprovo da solo.</p>
|
||||
}
|
||||
break;
|
||||
|
||||
case HostMode.DatabaseUnavailable:
|
||||
<p>Il motore è fermo e aspetta il database. Non apro un altro database al suo posto: riprovo da solo ogni pochi secondi e riparto appena risponde.</p>
|
||||
<dl class="facts">
|
||||
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
|
||||
<dt>Risposta</dt><dd>@(_status.Detail ?? "nessuna")</dd>
|
||||
<dt>Tentativi</dt><dd>@_status.Attempts, dal @Format.ShortDate(_status.Since, Clock.UtcNow, Host.Config.TimeZone)</dd>
|
||||
</dl>
|
||||
<h2>Cosa controllare</h2>
|
||||
<ul class="steps">
|
||||
@if (Host.Config.Db?.Engine == DbEngine.Postgres)
|
||||
{
|
||||
<li>Che il server PostgreSQL sia acceso e raggiungibile da qui (indirizzo e porta).</li>
|
||||
<li>Che nome del database, utente e password siano quelli giusti.</li>
|
||||
<li>Che il database esista: lo crei tu una volta, Anubis non crea e non cancella database.</li>
|
||||
}
|
||||
else
|
||||
{
|
||||
<li>Che il file del database sia al suo posto e leggibile. Se l'hai spostato, rimettilo dov'era.</li>
|
||||
<li>Che il disco della cartella dei dati sia collegato e abbia spazio libero.</li>
|
||||
}
|
||||
</ul>
|
||||
break;
|
||||
|
||||
case HostMode.SchemaProblem:
|
||||
<p>@_status.Detail</p>
|
||||
<p>Per non rovinare i dati il motore resta spento. Aggiorna Anubis alla versione che ha creato questo database, oppure ripristina un salvataggio in un database vuoto.</p>
|
||||
break;
|
||||
|
||||
case HostMode.IdentityProblem:
|
||||
<IdentityChoices Status="_status" Local="_local" />
|
||||
break;
|
||||
|
||||
case HostMode.FirstRun:
|
||||
<p><a href="/primo-avvio">Apri la procedura di primo avvio</a>.</p>
|
||||
break;
|
||||
}
|
||||
|
||||
@if (Errore is { } errore)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@(errore switch
|
||||
{
|
||||
"password" => "Password della configurazione d'avvio sbagliata, oppure scelta fatta da un altro computer.",
|
||||
"importazione" => "Il ripristino non è riuscito e non ho cambiato nulla. Controlla l'archivio e riprova.",
|
||||
"attesa" => "Troppi tentativi sbagliati. Riprova tra 15 minuti.",
|
||||
_ => "Questa scelta non è disponibile adesso.",
|
||||
})</p>
|
||||
}
|
||||
|
||||
@code {
|
||||
private HostStatus _status = null!;
|
||||
private bool _refresh;
|
||||
private bool _local;
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "errore")]
|
||||
public string? Errore { get; set; }
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
_status = Host.Status;
|
||||
_refresh = _status.Mode is HostMode.Starting or HostMode.DatabaseUnavailable or HostMode.ConfigProblem;
|
||||
if (HttpContext is not null)
|
||||
{
|
||||
_local = CurrentUser.IsLocal(HttpContext);
|
||||
if (!HttpContext.Response.HasStarted)
|
||||
{
|
||||
HttpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
HttpContext.Response.Headers.CacheControl = "no-store";
|
||||
HttpContext.Response.Headers.RetryAfter = "5";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@page "/strategie"
|
||||
|
||||
<PageTitle>Strategie · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Le strategie non sono ancora attive.">Arrivano dopo il laboratorio: ognuna con la sua descrizione, i requisiti per passare allo stadio successivo e i risultati.</Pending>
|
||||
@@ -0,0 +1,13 @@
|
||||
@* A screen whose content arrives with a later phase: it says so plainly instead of showing invented numbers (SPEC 13.1). *@
|
||||
<section class="panel empty">
|
||||
<p class="empty-title">@Title</p>
|
||||
<p>@ChildContent</p>
|
||||
</section>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
public string Title { get; set; } = "";
|
||||
|
||||
[Parameter]
|
||||
public RenderFragment? ChildContent { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<Router AppAssembly="typeof(App).Assembly">
|
||||
<Found Context="routeData">
|
||||
<RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" />
|
||||
</Found>
|
||||
</Router>
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>Titles of the service page, also used in plain answers while the application is not ready.</summary>
|
||||
internal static class ServiceText
|
||||
{
|
||||
public static string Title(HostMode mode) => mode switch
|
||||
{
|
||||
HostMode.Starting => "Anubis si sta avviando",
|
||||
HostMode.ConfigProblem => "Manca qualcosa nella configurazione d'avvio",
|
||||
HostMode.FirstRun => "Anubis va configurato",
|
||||
HostMode.DatabaseUnavailable => "Il database non risponde",
|
||||
HostMode.SchemaProblem => "Il database non è compatibile con questa versione",
|
||||
HostMode.IdentityProblem => "Il database non è quello di questa installazione",
|
||||
_ => "Anubis",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Messages of the password forms.</summary>
|
||||
internal static class PasswordMessages
|
||||
{
|
||||
public static string? For(string? code) => code switch
|
||||
{
|
||||
"diverse" => "Le due password non coincidono. Scrivile di nuovo.",
|
||||
"corta" => $"La password è troppo corta: servono almeno {Access.Passwords.MinimumLength} caratteri.",
|
||||
"uguale" => "La nuova password deve essere diversa da quella iniziale.",
|
||||
"attuale" => "La password attuale non è giusta.",
|
||||
"demo" => "Nella modalità dimostrativa la password non si cambia.",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
@using System.Globalization
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.AspNetCore.Components
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Anubis
|
||||
@using Anubis.Access
|
||||
@using Anubis.Core
|
||||
@using Anubis.Db
|
||||
@using Anubis.Platform
|
||||
@using Anubis.Server
|
||||
@using Anubis.Server.Components
|
||||
@using Anubis.Server.Components.Layout
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Collections;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Command line export and import (SPEC 5.4), the way to change engine: with the server stopped, export from the old
|
||||
/// database, point the configuration to the new one, import. The import goes only into an empty database and renews
|
||||
/// the installation fingerprint, so the old copy is no longer accepted (SPEC 15.1).
|
||||
/// </summary>
|
||||
internal static class DatabaseCommand
|
||||
{
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null)
|
||||
{
|
||||
output ??= Console.Out;
|
||||
if (args.Length < 2 || args[0] is not ("export" or "import"))
|
||||
{
|
||||
await output.WriteLineAsync("Uso: anubis db export <cartella> | anubis db import <cartella> [--platform docker|desktop] [--data-dir <cartella>]").ConfigureAwait(false);
|
||||
return 2;
|
||||
}
|
||||
|
||||
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||
var options = ServerOptions.Parse(args[2..], environment);
|
||||
var config = options.LoadConfig(environment);
|
||||
if (!config.IsComplete)
|
||||
{
|
||||
await output.WriteLineAsync("La configurazione d'avvio non è completa:").ConfigureAwait(false);
|
||||
foreach (var problem in config.Problems)
|
||||
{
|
||||
await output.WriteLineAsync($"- {problem.Setting}: {problem.What} {problem.Remedy}").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
Redactor.Register(config.Db!.Password);
|
||||
var clock = new SystemClock();
|
||||
var folder = Path.GetFullPath(args[1]);
|
||||
try
|
||||
{
|
||||
await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import" && !File.Exists(config.Data.InstallationFile));
|
||||
if (args[0] == "export")
|
||||
{
|
||||
var index = await Archive.ExportAsync(db, folder, clock).ConfigureAwait(false);
|
||||
await output.WriteLineAsync($"Esportate {index.Tables.Sum(t => t.Count)} righe di {index.Tables.Count} tabelle in {folder}.").ConfigureAwait(false);
|
||||
return 0;
|
||||
}
|
||||
|
||||
config.Data.Ensure();
|
||||
var imported = await Archive.ImportAsync(db, folder, clock).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: !File.Exists(config.Data.InstallationFile)).ConfigureAwait(false);
|
||||
await output.WriteLineAsync($"Importate {imported.Tables.Sum(t => t.Count)} righe di {imported.Tables.Count} tabelle: conteggi e totali coincidono. " +
|
||||
"Al prossimo avvio il bot riparte protetto.").ConfigureAwait(false);
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidOperationException or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException)
|
||||
{
|
||||
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
using System.Net.WebSockets;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Anubis.Access;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>Answer of <c>GET /health</c>.</summary>
|
||||
internal sealed record HealthResponse(string Status, string Name, string Version, string? Mode = null, IReadOnlyDictionary<string, string>? Checks = null);
|
||||
|
||||
internal sealed record SettingBody(string Value);
|
||||
|
||||
/// <summary>
|
||||
/// The REST and WebSocket skeleton (issue #12) and the form actions of the service pages. The API answers JSON with
|
||||
/// Italian messages, needs a session, and every request that changes something carries the CSRF token in a header.
|
||||
/// </summary>
|
||||
internal static partial class Endpoints
|
||||
{
|
||||
public const string CsrfHeader = "X-Anubis-Csrf";
|
||||
|
||||
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public static void Map(WebApplication app)
|
||||
{
|
||||
app.MapGet("/health", HealthAsync).AllowAnonymous();
|
||||
app.MapGet("/brand/{file}", Brand).AllowAnonymous();
|
||||
app.MapGet("/assets/{file}", Asset).AllowAnonymous();
|
||||
app.MapGet("/favicon.ico", () => Brand("anubis.ico")).AllowAnonymous();
|
||||
|
||||
MapApi(app);
|
||||
app.Map("/ws", StatusSocketAsync).RequireAuthorization();
|
||||
Forms.Map(app);
|
||||
}
|
||||
|
||||
// Healthy only when the database answers and the scheduler loop is alive (SPEC 15.2); the body says why not.
|
||||
private static async Task<IResult> HealthAsync(AnubisHost host, CancellationToken cancellationToken)
|
||||
{
|
||||
var status = host.Status;
|
||||
var checks = new Dictionary<string, string>(StringComparer.Ordinal) { ["mode"] = status.Mode.ToString() };
|
||||
var healthy = status.Mode == HostMode.Ready;
|
||||
if (host.Services is { } services)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
await services.Db.PingAsync(timeout.Token).ConfigureAwait(false);
|
||||
checks["database"] = "ok";
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
checks["database"] = "non risponde";
|
||||
healthy = false;
|
||||
}
|
||||
|
||||
checks["scheduler"] = host.SchedulerRunning ? "ok" : "fermo";
|
||||
healthy &= host.SchedulerRunning;
|
||||
}
|
||||
|
||||
var body = new HealthResponse(healthy ? "ok" : "unavailable", AnubisInfo.Name, AnubisInfo.Version, status.Mode.ToString(), checks);
|
||||
return Results.Json(body, _json, statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
|
||||
}
|
||||
|
||||
// The logo comes only from docs/design/logo, embedded at build time (ADR 0005).
|
||||
private static IResult Brand(string file) => Embedded("Anubis.Server.Brand." + file, file);
|
||||
|
||||
private static IResult Asset(string file) => Embedded("Anubis.Server.Assets." + file, file);
|
||||
|
||||
private static IResult Embedded(string resource, string file)
|
||||
{
|
||||
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
|
||||
if (stream is null)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var type = Path.GetExtension(file) switch
|
||||
{
|
||||
".svg" => "image/svg+xml",
|
||||
".png" => "image/png",
|
||||
".ico" => "image/x-icon",
|
||||
".css" => "text/css; charset=utf-8",
|
||||
".js" => "text/javascript; charset=utf-8",
|
||||
".ttf" => "font/ttf",
|
||||
".txt" => "text/plain; charset=utf-8",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
return Results.Stream(stream, type);
|
||||
}
|
||||
|
||||
private static void MapApi(WebApplication app)
|
||||
{
|
||||
var api = app.MapGroup("/api").RequireAuthorization().AddEndpointFilter(CsrfFilterAsync);
|
||||
|
||||
api.MapGet("/antiforgery", (HttpContext context, IAntiforgery antiforgery) =>
|
||||
{
|
||||
var tokens = antiforgery.GetAndStoreTokens(context);
|
||||
return Results.Json(new { header = CsrfHeader, token = tokens.RequestToken }, _json);
|
||||
});
|
||||
|
||||
api.MapGet("/status", async (AnubisHost host, ShellData shell, CancellationToken ct) => Results.Json(await shell.SnapshotAsync(ct).ConfigureAwait(false), _json));
|
||||
|
||||
api.MapGet("/me", (HttpContext context) => Results.Json(new
|
||||
{
|
||||
username = context.User.Identity?.Name,
|
||||
mustChangePassword = CurrentUser.MustChangePassword(context.User),
|
||||
hasSecondFactor = CurrentUser.HasSecondFactor(context.User),
|
||||
}, _json));
|
||||
|
||||
api.MapGet("/settings", async (AnubisHost host, CancellationToken ct) =>
|
||||
{
|
||||
var services = host.Services!;
|
||||
var values = new List<SettingValue>();
|
||||
foreach (var definition in SettingsStore.All)
|
||||
{
|
||||
values.Add(await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return Results.Json(values, _json);
|
||||
});
|
||||
|
||||
api.MapPut("/settings/{key}", async (string key, SettingBody body, AnubisHost host, HttpContext context, CancellationToken ct) =>
|
||||
{
|
||||
if (key == SettingsStore.BotState.Key)
|
||||
{
|
||||
return Error(StatusCodes.Status400BadRequest, "usa_i_comandi", "Lo stato del bot si cambia con pausa, ripresa e Ferma tutto.");
|
||||
}
|
||||
|
||||
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
||||
});
|
||||
|
||||
api.MapGet("/settings/history", async (AnubisHost host, CancellationToken ct) =>
|
||||
Results.Json(await host.Services!.Settings.HistoryAsync(null, 100, ct).ConfigureAwait(false), _json));
|
||||
|
||||
// Only whether a secret is set and where it comes from: the value never leaves the server (SPEC 15.4).
|
||||
api.MapGet("/secrets/{name}", async (string name, AnubisHost host, CancellationToken ct) =>
|
||||
Results.Json(await host.Services!.Secrets.StatusAsync(name, ct).ConfigureAwait(false), _json));
|
||||
|
||||
api.MapPost("/bot/{command}", async (string command, AnubisHost host, HttpContext context, CancellationToken ct) =>
|
||||
{
|
||||
var (ok, message) = await BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
|
||||
return ok ? Results.Json(new { state = message }, _json) : Error(StatusCodes.Status409Conflict, "comando_non_ammesso", message);
|
||||
});
|
||||
|
||||
api.MapGet("/jobs", async (AnubisHost host, CancellationToken ct) =>
|
||||
{
|
||||
var services = host.Services!;
|
||||
var last = await services.Db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT name, description, last_due_at, last_finished_at, last_outcome, last_error FROM jobs ORDER BY name",
|
||||
r => new
|
||||
{
|
||||
name = r.Text("name"),
|
||||
description = r.Text("description"),
|
||||
lastDue = r.MomentOrNull("last_due_at"),
|
||||
lastFinished = r.MomentOrNull("last_finished_at"),
|
||||
outcome = r.TextOrNull("last_outcome"),
|
||||
error = r.TextOrNull("last_error")
|
||||
}), ct).ConfigureAwait(false);
|
||||
return Results.Json(new { upcoming = services.Scheduler.Upcoming(20), last }, _json);
|
||||
});
|
||||
}
|
||||
|
||||
internal static IResult Error(int status, string code, string message) => Results.Json(new ApiError(code, message), _json, statusCode: status);
|
||||
|
||||
private static async ValueTask<object?> CsrfFilterAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
|
||||
{
|
||||
var http = context.HttpContext;
|
||||
if (!HttpMethods.IsGet(http.Request.Method) && !HttpMethods.IsHead(http.Request.Method))
|
||||
{
|
||||
var antiforgery = http.RequestServices.GetRequiredService<IAntiforgery>();
|
||||
if (!await antiforgery.IsRequestValidAsync(http).ConfigureAwait(false))
|
||||
{
|
||||
return Error(StatusCodes.Status400BadRequest, "csrf", "Richiesta senza il gettone di sicurezza: ricarica la pagina e riprova.");
|
||||
}
|
||||
}
|
||||
|
||||
return await next(context).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<IResult> SetSettingAsync(AnubisHost host, string key, string value, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await host.Services!.Settings.SetAsync(key, value, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
return Results.NoContent();
|
||||
}
|
||||
catch (ReadOnlySettingException ex)
|
||||
{
|
||||
return Error(StatusCodes.Status409Conflict, "sola_lettura", ex.Message);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return Error(StatusCodes.Status400BadRequest, "valore_non_valido", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pause blocks new entries and keeps stops and exits; "Ferma tutto" is the switch of SPEC 9.3 (its full effect
|
||||
/// arrives with the engine). Resume works only from a pause, never after "Ferma tutto" (SPEC 14).
|
||||
/// </summary>
|
||||
internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var settings = host.Services!.Settings;
|
||||
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
|
||||
var target = command switch
|
||||
{
|
||||
"pause" or "pausa" when current == "active" => "paused",
|
||||
"resume" or "riprendi" when current == "paused" => "active",
|
||||
"stop" or "ferma" => "stopped",
|
||||
"restart" or "riattiva" when current == "stopped" => "active",
|
||||
_ => null,
|
||||
};
|
||||
if (target is null)
|
||||
{
|
||||
return (false, current == "stopped"
|
||||
? "Dopo \"Ferma tutto\" il bot non riprende da solo: riattivalo dalla pagina Rischio."
|
||||
: "Comando non ammesso nello stato attuale del bot.");
|
||||
}
|
||||
|
||||
await settings.SetAsync(SettingsStore.BotState.Key, target, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
return (true, target);
|
||||
}
|
||||
|
||||
// Live status (SPEC 13.4): one message on connect, one at every change and a heartbeat every few seconds, so the
|
||||
// page can tell how old its data are and warn when the link drops.
|
||||
private static async Task StatusSocketAsync(HttpContext context, AnubisHost host, ShellData shell, EventBus bus)
|
||||
{
|
||||
if (!context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
return;
|
||||
}
|
||||
|
||||
// Cross-site WebSocket hijacking: the page must come from this same server.
|
||||
var origin = context.Request.Headers.Origin.ToString();
|
||||
if (origin.Length > 0 && (!Uri.TryCreate(origin, UriKind.Absolute, out var originUri) ||
|
||||
!string.Equals(originUri.Authority, context.Request.Host.Value, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return;
|
||||
}
|
||||
|
||||
using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
|
||||
using var settings = bus.Subscribe<SettingChanged>(16);
|
||||
using var modes = bus.Subscribe<HostChanged>(16);
|
||||
var aborted = context.RequestAborted;
|
||||
var receive = DrainAsync(socket, aborted);
|
||||
try
|
||||
{
|
||||
while (socket.State == WebSocketState.Open && !aborted.IsCancellationRequested)
|
||||
{
|
||||
var snapshot = await shell.SnapshotAsync(aborted).ConfigureAwait(false);
|
||||
var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "status", status = snapshot }, _json);
|
||||
await socket.SendAsync(bytes, WebSocketMessageType.Text, true, aborted).ConfigureAwait(false);
|
||||
|
||||
using var wait = CancellationTokenSource.CreateLinkedTokenSource(aborted);
|
||||
wait.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var changed = Task.WhenAny(Next(settings, wait.Token), Next(modes, wait.Token));
|
||||
await Task.WhenAny(changed, receive, Task.Delay(Timeout.Infinite, wait.Token)).ConfigureAwait(false);
|
||||
|
||||
// Stop the reader that lost, or it would swallow the next event of its kind.
|
||||
await wait.CancelAsync().ConfigureAwait(false);
|
||||
if (receive.IsCompleted)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
||||
{
|
||||
}
|
||||
|
||||
// Answer the client's close, or start ours. Output only: the drain loop may still be receiving.
|
||||
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var closing = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, closing.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
await Task.WhenAny(receive, Task.Delay(TimeSpan.FromSeconds(2), CancellationToken.None)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task Next<T>(EventSubscription<T> subscription, CancellationToken cancellationToken)
|
||||
{
|
||||
await foreach (var _ in subscription.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task DrainAsync(WebSocket socket, CancellationToken cancellationToken)
|
||||
{
|
||||
var buffer = new byte[1024];
|
||||
try
|
||||
{
|
||||
while (socket.State == WebSocketState.Open)
|
||||
{
|
||||
var result = await socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Compares two secrets in constant time.</summary>
|
||||
internal static bool SameSecret(string? given, string? expected) =>
|
||||
given is not null && expected is not null &&
|
||||
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(given)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
using Anubis.Access;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Form actions of the pages: plain HTML forms with the CSRF field, answered with a redirect (post, redirect, get).
|
||||
/// Errors travel back as a short code in the address, never with the values typed in.
|
||||
/// </summary>
|
||||
internal static partial class Forms
|
||||
{
|
||||
public static void Map(WebApplication app)
|
||||
{
|
||||
var open = app.MapGroup("/azioni").AllowAnonymous();
|
||||
open.MapPost("/accesso", SignInAsync);
|
||||
open.MapPost("/primo-avvio/prova", TestDatabaseAsync);
|
||||
open.MapPost("/primo-avvio", FirstRunAsync);
|
||||
open.MapPost("/servizio/{choice}", ServiceChoiceAsync);
|
||||
|
||||
var signed = app.MapGroup("/azioni").RequireAuthorization();
|
||||
signed.MapPost("/esci", SignOutAsync);
|
||||
signed.MapPost("/primo-accesso", (IFormCollection form, AnubisHost host, StartupConfig config, HttpContext context, CancellationToken ct) =>
|
||||
ChangePasswordAsync(form, host, context, config.AdminPassword, "/primo-accesso", "/", ct));
|
||||
signed.MapPost("/password", (IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) =>
|
||||
ChangePasswordAsync(form, host, context, null, "/impostazioni", "/impostazioni", ct));
|
||||
signed.MapPost("/due-fattori/attiva", EnableSecondFactorAsync);
|
||||
signed.MapPost("/due-fattori/disattiva", DisableSecondFactorAsync);
|
||||
signed.MapPost("/impostazioni/{key}", SetSettingAsync);
|
||||
signed.MapPost("/bot/{command}", BotAsync);
|
||||
signed.MapPost("/salvataggio", BackupAsync);
|
||||
}
|
||||
|
||||
private static string Back(IFormCollection form, string fallback)
|
||||
{
|
||||
var back = form["ritorno"].ToString();
|
||||
|
||||
return IsLocalPath(back) ? back : fallback;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only paths of this site: "/x" yes; "//other.site", "https://..." no; no backslash and no control characters,
|
||||
/// which browsers drop or turn into "/" while reading an address ("/\t/other.site" becomes "//other.site").
|
||||
/// </summary>
|
||||
internal static bool IsLocalPath(string path) =>
|
||||
path.StartsWith('/') && !path.StartsWith("//", StringComparison.Ordinal) && !path.Any(c => char.IsControl(c) || c == '\\');
|
||||
|
||||
private static string With(string path, string key, string value)
|
||||
{
|
||||
var hash = path.IndexOf('#', StringComparison.Ordinal);
|
||||
var anchor = hash >= 0 ? path[hash..] : "";
|
||||
var bare = hash >= 0 ? path[..hash] : path;
|
||||
return bare + (bare.Contains('?', StringComparison.Ordinal) ? "&" : "?") + key + "=" + Uri.EscapeDataString(value) + anchor;
|
||||
}
|
||||
|
||||
private static async Task<IResult> SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var services = host.Services;
|
||||
if (services is null)
|
||||
{
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
|
||||
var back = Back(form, "/");
|
||||
var wait = limiter.Begin(address);
|
||||
if (wait > TimeSpan.Zero)
|
||||
{
|
||||
var minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes));
|
||||
return Results.Redirect(With(With("/accesso", "errore", "attesa"), "minuti", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
}
|
||||
|
||||
var code = form["codice"].ToString();
|
||||
var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct)
|
||||
.ConfigureAwait(false);
|
||||
switch (result)
|
||||
{
|
||||
case LoginResult.Ok:
|
||||
limiter.Succeeded(address);
|
||||
SessionAuthentication.WriteCookie(context, token!);
|
||||
return Results.Redirect(back);
|
||||
case LoginResult.SecondFactorNeeded:
|
||||
limiter.Forgive(address);
|
||||
return Results.Redirect(With(With("/accesso", "fattore", "1"), "ritorno", back));
|
||||
case LoginResult.WrongSecondFactor:
|
||||
return Results.Redirect(With(With(With("/accesso", "fattore", "1"), "errore", "codice"), "ritorno", back));
|
||||
default:
|
||||
return Results.Redirect(With(With("/accesso", "errore", "password"), "ritorno", back));
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<IResult> SignOutAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
if (context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token) && host.Services is { } services)
|
||||
{
|
||||
await services.Access.SignOutAsync(token, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
SessionAuthentication.ClearCookie(context);
|
||||
return Results.Redirect("/accesso");
|
||||
}
|
||||
|
||||
private static async Task<IResult> ChangePasswordAsync(IFormCollection form, AnubisHost host, HttpContext context, string? initial, string page, string done, CancellationToken ct)
|
||||
{
|
||||
if (host.IsDemo)
|
||||
{
|
||||
return Results.Redirect(With(page, "errore", "demo"));
|
||||
}
|
||||
|
||||
var replacement = form["nuova"].ToString();
|
||||
if (replacement != form["conferma"].ToString())
|
||||
{
|
||||
return Results.Redirect(With(page, "errore", "diverse"));
|
||||
}
|
||||
|
||||
if (Passwords.Problem(replacement, initial) is not null)
|
||||
{
|
||||
return Results.Redirect(With(page, "errore", replacement.Length < Passwords.MinimumLength ? "corta" : "uguale"));
|
||||
}
|
||||
|
||||
var ok = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct)
|
||||
.ConfigureAwait(false);
|
||||
return Results.Redirect(ok ? With(done, "ok", "password") : With(page, "errore", "attuale"));
|
||||
}
|
||||
|
||||
private static async Task<IResult> EnableSecondFactorAsync(IFormCollection form, AnubisHost host, SecondFactorDrafts drafts, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
// The secret shown on the page stays on the server, tied to this session: it never travels in a form or an address.
|
||||
var session = CurrentUser.Session(context.User);
|
||||
if (host.IsDemo || drafts.Peek(session) is not { } secret)
|
||||
{
|
||||
return Results.Redirect("/impostazioni?errore=segreto#sicurezza");
|
||||
}
|
||||
|
||||
var ok = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["codice"].ToString(), ct).ConfigureAwait(false);
|
||||
if (ok)
|
||||
{
|
||||
drafts.Remove(session);
|
||||
}
|
||||
|
||||
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori#sicurezza" : "/impostazioni?errore=codice#sicurezza");
|
||||
}
|
||||
|
||||
private static async Task<IResult> DisableSecondFactorAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var ok = !host.IsDemo && await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(), form["codice"].ToString(), ct).ConfigureAwait(false);
|
||||
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori-tolti#sicurezza" : "/impostazioni?errore=attuale#sicurezza");
|
||||
}
|
||||
|
||||
private static async Task<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var back = Back(form, "/impostazioni");
|
||||
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key)
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", "impostazione"));
|
||||
}
|
||||
|
||||
var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false);
|
||||
return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione"));
|
||||
}
|
||||
|
||||
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var back = Back(form, "/");
|
||||
var (ok, _) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
|
||||
return Results.Redirect(ok ? back : With(back, "errore", "bot"));
|
||||
}
|
||||
|
||||
private static async Task<IResult> BackupAsync(IFormCollection form, AnubisHost host, ILogger<AnubisHost> logger, CancellationToken ct)
|
||||
{
|
||||
var services = host.Services!;
|
||||
try
|
||||
{
|
||||
await services.Backups.TakeAsync(services.Db, "a-mano", ct).ConfigureAwait(false);
|
||||
return Results.Redirect("/impostazioni?ok=salvataggio#sistema");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException)
|
||||
{
|
||||
LogBackupFailed(logger, ex);
|
||||
return Results.Redirect("/impostazioni?errore=salvataggio#sistema");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Desktop first run (SPEC 15.6): only from the computer itself, only while the wizard is due. ----
|
||||
|
||||
private static DbSettings ReadDatabase(IFormCollection form, StartupConfig config)
|
||||
{
|
||||
if (form["motore"].ToString() != "postgres")
|
||||
{
|
||||
return new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = config.Data.SqliteFile };
|
||||
}
|
||||
|
||||
return new DbSettings
|
||||
{
|
||||
Engine = DbEngine.Postgres,
|
||||
Host = form["host"].ToString().Trim(),
|
||||
Port = int.TryParse(form["porta"].ToString(), out var port) && port is > 0 and < 65536 ? port : 5432,
|
||||
Database = string.IsNullOrWhiteSpace(form["nome"]) ? "anubis" : form["nome"].ToString().Trim(),
|
||||
User = string.IsNullOrWhiteSpace(form["utente"]) ? "anubis" : form["utente"].ToString().Trim(),
|
||||
Password = form["dbpassword"].ToString(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Opens the database without creating anything and asks it one question.</summary>
|
||||
private static async Task<string?> TryConnectAsync(DbSettings settings, CancellationToken ct)
|
||||
{
|
||||
if (settings.Engine == DbEngine.Postgres && string.IsNullOrWhiteSpace(settings.Host))
|
||||
{
|
||||
return "Manca l'indirizzo del server PostgreSQL.";
|
||||
}
|
||||
|
||||
Redactor.Register(settings.Password);
|
||||
try
|
||||
{
|
||||
await using var db = Database.Open(settings, allowCreate: settings.Engine == DbEngine.Sqlite);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(8));
|
||||
await db.PingAsync(timeout.Token).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return Redactor.Redact(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool WizardAllowed(AnubisHost host, HttpContext context) =>
|
||||
host.Status.Mode == HostMode.FirstRun && host.Config.Platform == PlatformKind.Desktop && CurrentUser.IsLocal(context);
|
||||
|
||||
private static async Task<IResult> TestDatabaseAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
if (!WizardAllowed(host, context))
|
||||
{
|
||||
return Endpoints.Error(StatusCodes.Status403Forbidden, "non_ammesso", "La procedura guidata si usa solo dal computer su cui gira Anubis, al primo avvio.");
|
||||
}
|
||||
|
||||
var problem = await TryConnectAsync(ReadDatabase(form, host.Config), ct).ConfigureAwait(false);
|
||||
return Results.Json(new { ok = problem is null, message = problem ?? "Connessione riuscita." });
|
||||
}
|
||||
|
||||
private static async Task<IResult> FirstRunAsync(IFormCollection form, AnubisHost host, HttpContext context, ILogger<AnubisHost> logger, CancellationToken ct)
|
||||
{
|
||||
if (!WizardAllowed(host, context))
|
||||
{
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
var password = form["password"].ToString();
|
||||
if (password != form["conferma"].ToString())
|
||||
{
|
||||
return Results.Redirect("/primo-avvio?errore=diverse");
|
||||
}
|
||||
|
||||
if (Passwords.Problem(password) is not null)
|
||||
{
|
||||
return Results.Redirect("/primo-avvio?errore=corta");
|
||||
}
|
||||
|
||||
var config = host.Config;
|
||||
if (!config.IsComplete)
|
||||
{
|
||||
var settings = ReadDatabase(form, config);
|
||||
if (await TryConnectAsync(settings, ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
return Results.Redirect("/primo-avvio?errore=database");
|
||||
}
|
||||
|
||||
// config.toml without the database password: that goes to the protected store (SPEC 15.6).
|
||||
DesktopPlatform.WriteConfig(config.Data, ProtectedSecretKey.DefaultStore(config.Data), settings, config.Port, allowNetwork: false);
|
||||
}
|
||||
|
||||
host.PendingPassword = password;
|
||||
host.Wake();
|
||||
try
|
||||
{
|
||||
await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(60)).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
LogFirstRunSlow(logger);
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
var (result, token) = await host.Services!.Access.SignInAsync(password, null, context.Request.Headers.UserAgent.ToString(),
|
||||
context.Connection.RemoteIpAddress?.ToString(), ct).ConfigureAwait(false);
|
||||
if (result == LoginResult.Ok)
|
||||
{
|
||||
SessionAuthentication.WriteCookie(context, token!);
|
||||
}
|
||||
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
// ---- Choices of the error page (SPEC 15.1): Docker asks the startup password, desktop only the computer itself. ----
|
||||
|
||||
private static async Task<IResult> ServiceChoiceAsync(string choice, IFormCollection form, AnubisHost host, IClock clock, LoginLimiter limiter,
|
||||
HttpContext context, ILogger<AnubisHost> logger, CancellationToken ct)
|
||||
{
|
||||
var config = host.Config;
|
||||
if (config.Platform == PlatformKind.Docker)
|
||||
{
|
||||
// The startup password, asked by a page anyone on the network can open: same attempt limit as the sign-in.
|
||||
var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto";
|
||||
if (limiter.Begin(address) > TimeSpan.Zero)
|
||||
{
|
||||
return Results.Redirect("/?errore=attesa");
|
||||
}
|
||||
|
||||
if (!Endpoints.SameSecret(form["password"].ToString(), config.AdminPassword))
|
||||
{
|
||||
LogChoiceRefused(logger, choice);
|
||||
return Results.Redirect("/?errore=password");
|
||||
}
|
||||
|
||||
limiter.Succeeded(address);
|
||||
}
|
||||
else if (!CurrentUser.IsLocal(context))
|
||||
{
|
||||
return Results.Redirect("/?errore=password");
|
||||
}
|
||||
|
||||
// The startup loop stays still until the choice is done and the installation renewed.
|
||||
using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false);
|
||||
var status = host.Status;
|
||||
var db = host.Database;
|
||||
if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null)
|
||||
{
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
var verdict = status.Identity.Verdict;
|
||||
try
|
||||
{
|
||||
switch (choice)
|
||||
{
|
||||
case "ripristina" when verdict == IdentityVerdict.EmptyDatabase:
|
||||
var backup = new Backups(config.Data, clock).List().FirstOrDefault(b => b.Name == form["salvataggio"].ToString());
|
||||
if (backup is null)
|
||||
{
|
||||
return Results.Redirect("/?errore=scelta");
|
||||
}
|
||||
|
||||
await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case "importa" when verdict == IdentityVerdict.EmptyDatabase:
|
||||
var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString());
|
||||
if (folder is null)
|
||||
{
|
||||
return Results.Redirect("/?errore=scelta");
|
||||
}
|
||||
|
||||
await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case "da-capo" when verdict == IdentityVerdict.EmptyDatabase:
|
||||
Installation.StartOver(config.Data, clock);
|
||||
break;
|
||||
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase:
|
||||
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: true, ct).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
return Results.Redirect("/?errore=scelta");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (IsArchiveProblem(ex))
|
||||
{
|
||||
LogChoiceFailed(logger, ex, choice);
|
||||
return Results.Redirect("/?errore=importazione");
|
||||
}
|
||||
|
||||
LogChoice(logger, choice);
|
||||
|
||||
// Reset while the loop is still held: released first, it could start the application again before the reset
|
||||
// and then lose the services it had just built while showing "ready".
|
||||
await host.ResetAsync().ConfigureAwait(false);
|
||||
exclusive.Dispose();
|
||||
await WaitBrieflyAsync(host).ConfigureAwait(false);
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
/// <summary>What a damaged or unsuitable archive throws: reported on the page, not as a crash.</summary>
|
||||
internal static bool IsArchiveProblem(Exception ex) =>
|
||||
ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException or FormatException or OverflowException
|
||||
or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException;
|
||||
|
||||
private static async Task WaitBrieflyAsync(AnubisHost host)
|
||||
{
|
||||
try
|
||||
{
|
||||
await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(10)).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Backup on request failed")]
|
||||
private static partial void LogBackupFailed(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "First run: the application is not ready after 60 seconds")]
|
||||
private static partial void LogFirstRunSlow(ILogger logger);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} confirmed")]
|
||||
private static partial void LogChoice(ILogger logger, string choice);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} refused: wrong startup password")]
|
||||
private static partial void LogChoiceRefused(ILogger logger, string choice);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Error page choice {Choice} failed")]
|
||||
private static partial void LogChoiceFailed(ILogger logger, Exception exception, string choice);
|
||||
}
|
||||
|
||||
/// <summary>Second-factor secrets being set up, one per session, kept for 15 minutes.</summary>
|
||||
internal sealed class SecondFactorDrafts(IClock clock)
|
||||
{
|
||||
private static readonly TimeSpan _life = TimeSpan.FromMinutes(15);
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<Guid, (byte[] Secret, DateTimeOffset Until)> _drafts = new();
|
||||
|
||||
/// <summary>The draft of this session, or a new one.</summary>
|
||||
public byte[] For(Guid session)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
foreach (var expired in _drafts.Where(d => d.Value.Until <= now).Select(d => d.Key).ToList())
|
||||
{
|
||||
_drafts.TryRemove(expired, out _);
|
||||
}
|
||||
|
||||
return _drafts.AddOrUpdate(session, _ => (Totp.NewSecret(), now + _life), (_, d) => d.Until > now ? d : (Totp.NewSecret(), now + _life)).Secret;
|
||||
}
|
||||
|
||||
public byte[]? Peek(Guid session) => _drafts.TryGetValue(session, out var d) && d.Until > clock.UtcNow ? d.Secret : null;
|
||||
|
||||
public void Remove(Guid session) => _drafts.TryRemove(session, out _);
|
||||
}
|
||||
|
||||
/// <summary>What the error page can offer.</summary>
|
||||
internal static class ServiceChoices
|
||||
{
|
||||
/// <summary>Archives under data/import, one folder each with its index.json.</summary>
|
||||
public static IReadOnlyList<string> ImportFolders(DataDirectory data) =>
|
||||
!Directory.Exists(data.Import)
|
||||
? []
|
||||
: Directory.EnumerateDirectories(data.Import).Where(d => File.Exists(Path.Combine(d, Archive.IndexFile))).Order(StringComparer.Ordinal).ToList();
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Structured logs (SPEC 2.2, issue #10): one JSON object per line on the console and in a daily file under
|
||||
/// data/logs, every text passed through the <see cref="Redactor"/> so no secret reaches a log. The last 14 files are kept.
|
||||
/// </summary>
|
||||
internal sealed class JsonLogProvider : ILoggerProvider
|
||||
{
|
||||
public const int KeepFiles = 14;
|
||||
|
||||
private readonly string? _folder;
|
||||
private readonly IClock _clock;
|
||||
private readonly bool _console;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly ConcurrentDictionary<string, JsonLogger> _loggers = new(StringComparer.Ordinal);
|
||||
private StreamWriter? _file;
|
||||
private string? _fileDay;
|
||||
|
||||
public JsonLogProvider(string? folder, IClock clock, bool console)
|
||||
{
|
||||
_folder = folder;
|
||||
_clock = clock;
|
||||
_console = console;
|
||||
}
|
||||
|
||||
public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, name => new JsonLogger(name, this));
|
||||
|
||||
internal void Write(string category, LogLevel level, EventId eventId, string message, Exception? exception)
|
||||
{
|
||||
var now = _clock.UtcNow;
|
||||
using var buffer = new MemoryStream();
|
||||
using (var json = new Utf8JsonWriter(buffer))
|
||||
{
|
||||
json.WriteStartObject();
|
||||
json.WriteString("at", now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture));
|
||||
json.WriteString("level", level.ToString().ToLowerInvariant());
|
||||
json.WriteString("category", category);
|
||||
if (eventId.Id != 0)
|
||||
{
|
||||
json.WriteNumber("event", eventId.Id);
|
||||
}
|
||||
|
||||
json.WriteString("message", Redactor.Redact(message));
|
||||
if (exception is not null)
|
||||
{
|
||||
json.WriteString("error", Redactor.Redact(exception.GetType().Name + ": " + exception.Message));
|
||||
json.WriteString("stack", Redactor.Redact(exception.StackTrace));
|
||||
}
|
||||
|
||||
json.WriteEndObject();
|
||||
}
|
||||
|
||||
var line = Encoding.UTF8.GetString(buffer.ToArray());
|
||||
lock (_gate)
|
||||
{
|
||||
if (_console)
|
||||
{
|
||||
Console.Out.WriteLine(line);
|
||||
}
|
||||
|
||||
WriteFile(now, line);
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteFile(DateTimeOffset now, string line)
|
||||
{
|
||||
if (_folder is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var day = now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
|
||||
if (_file is null || _fileDay != day)
|
||||
{
|
||||
_file?.Dispose();
|
||||
Directory.CreateDirectory(_folder);
|
||||
_file = new StreamWriter(new FileStream(Path.Combine(_folder, "anubis-" + day + ".log"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), new UTF8Encoding(false))
|
||||
{
|
||||
AutoFlush = true,
|
||||
};
|
||||
_fileDay = day;
|
||||
Prune();
|
||||
}
|
||||
|
||||
_file.WriteLine(line);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// A full or read-only disk must not stop the application: the console still has the line.
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private void Prune()
|
||||
{
|
||||
foreach (var old in Directory.EnumerateFiles(_folder!, "anubis-*.log").OrderDescending(StringComparer.Ordinal).Skip(KeepFiles))
|
||||
{
|
||||
File.Delete(old);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_file?.Dispose();
|
||||
_file = null;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class JsonLogger(string category, JsonLogProvider provider) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state)
|
||||
where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
provider.Write(category, logLevel, eventId, formatter(state, exception), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark);
|
||||
|
||||
internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent);
|
||||
|
||||
internal sealed record NextMove(string Time, string Text);
|
||||
|
||||
internal sealed record LastAction(string When, string Text);
|
||||
|
||||
/// <summary>The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database.</summary>
|
||||
internal sealed record Overview(
|
||||
IReadOnlyList<EquityPoint> Points,
|
||||
IReadOnlyList<EquityPoint> Series,
|
||||
PeriodResult Result,
|
||||
DateOnly From,
|
||||
decimal FromEquity,
|
||||
IReadOnlyList<PeriodResult> Cells,
|
||||
int Positions,
|
||||
int PositionsWithoutStop,
|
||||
int OpenOrders,
|
||||
IReadOnlyList<NextMove> Next,
|
||||
IReadOnlyList<LastAction> Last)
|
||||
{
|
||||
public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("30", "30 giorni"), ("7", "7 giorni"), ("oggi", "Oggi")];
|
||||
|
||||
public bool HasData => Points.Count > 0;
|
||||
|
||||
public static async Task<Overview> LoadAsync(AppServices services, string period, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken)
|
||||
{
|
||||
var (points, positions, withoutStop, orders, journal) = await services.Db.ReadAsync(async s =>
|
||||
{
|
||||
var p = await s.QueryAsync(
|
||||
"SELECT taken_at, equity, benchmark FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at",
|
||||
r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"))).ConfigureAwait(false);
|
||||
var count = await s.CountAsync("SELECT COUNT(*) FROM positions").ConfigureAwait(false);
|
||||
var noStop = await s.CountAsync("SELECT COUNT(*) FROM positions WHERE stop_price IS NULL").ConfigureAwait(false);
|
||||
var open = await s.CountAsync("SELECT COUNT(*) FROM orders WHERE status IN ('new', 'submitted', 'accepted', 'partially_filled')").ConfigureAwait(false);
|
||||
var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 4",
|
||||
r => (At: r.Moment("occurred_at"), Text: r.Text("message"))).ConfigureAwait(false);
|
||||
return (p, count, noStop, open, j);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// One point per day: the last snapshot of each local day.
|
||||
var daily = points
|
||||
.Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark))
|
||||
.GroupBy(p => p.Day)
|
||||
.Select(g => g.Last())
|
||||
.ToList();
|
||||
|
||||
var next = services.Scheduler.Upcoming(5)
|
||||
.Select(u => new NextMove(TimeZoneInfo.ConvertTime(u.DueUtc, zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture), u.Description))
|
||||
.ToList();
|
||||
var last = journal.Select(j => new LastAction(Format.ShortDate(j.At, now, zone), j.Text)).ToList();
|
||||
|
||||
if (daily.Count == 0)
|
||||
{
|
||||
return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last);
|
||||
}
|
||||
|
||||
var latest = daily[^1];
|
||||
EquityPoint Since(int days) => daily.LastOrDefault(p => p.Day <= latest.Day.AddDays(-days)) ?? daily[0];
|
||||
PeriodResult Between(string label, EquityPoint start) =>
|
||||
new(label, latest.Equity - start.Equity, start.Equity == 0 ? 0 : (latest.Equity - start.Equity) / start.Equity * 100m);
|
||||
|
||||
var start = period switch
|
||||
{
|
||||
"30" => Since(30),
|
||||
"7" => Since(7),
|
||||
"oggi" => Since(1),
|
||||
_ => daily[0],
|
||||
};
|
||||
var series = daily.Where(p => p.Day >= start.Day).ToList();
|
||||
var cells = new List<PeriodResult> { Between("Oggi", Since(1)), Between("Ultimi 7 giorni", Since(7)), Between("Ultimi 30 giorni", Since(30)) };
|
||||
if (daily[0].Benchmark is { } firstBenchmark && latest.Benchmark is { } lastBenchmark && firstBenchmark != 0)
|
||||
{
|
||||
cells.Add(new PeriodResult("Senza bot", lastBenchmark - firstBenchmark, (lastBenchmark - firstBenchmark) / firstBenchmark * 100m));
|
||||
}
|
||||
|
||||
return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
using Anubis.Server;
|
||||
|
||||
// "anubis db export <folder>" and "anubis db import <folder>" (SPEC 5.4) run with the engine stopped; anything else starts the server.
|
||||
if (args.Length >= 1 && args[0] == "db")
|
||||
{
|
||||
return await DatabaseCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var app = ServerApp.Build(args);
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
return 0;
|
||||
@@ -1,18 +1,245 @@
|
||||
using System.Collections;
|
||||
using Anubis.Access;
|
||||
using Anubis.Core;
|
||||
using Anubis.Demo;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Server.Components;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>Builds the web application. Kept apart from Program so tests can host it.</summary>
|
||||
internal static class ServerApp
|
||||
{
|
||||
public static WebApplication Build(string[] args)
|
||||
public static WebApplication Build(string[] args, ServerOverrides? overrides = null)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var app = builder.Build();
|
||||
var environment = overrides?.Environment ?? ReadEnvironment();
|
||||
var options = ServerOptions.Parse(args, environment);
|
||||
IClock clock = overrides?.Clock ?? (options.Demo ? new ManualClock(DemoMode.Now) : new Anubis.Core.SystemClock());
|
||||
|
||||
app.MapGet("/health", () => Results.Ok(new HealthResponse("ok", AnubisInfo.Name, AnubisInfo.Version)));
|
||||
// Demo mode never reads the configured database: it gets a brand-new folder of its own (trap 27).
|
||||
var config = options.Demo ? DemoMode.Config(DemoMode.CreateFolder(new Anubis.Core.SystemClock())) : options.LoadConfig(environment);
|
||||
RegisterSecrets(config);
|
||||
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
|
||||
{
|
||||
Args = options.AspNetArgs,
|
||||
ApplicationName = typeof(ServerApp).Assembly.GetName().Name,
|
||||
ContentRootPath = AppContext.BaseDirectory,
|
||||
});
|
||||
|
||||
if (!options.AspNetArgs.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
|
||||
{
|
||||
// Desktop and demo listen only on the computer itself unless the user allowed the home network (SPEC 15.6).
|
||||
var local = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
|
||||
builder.WebHost.UseUrls((local ? "http://127.0.0.1:" : "http://0.0.0.0:") + config.Port.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
builder.Logging.ClearProviders();
|
||||
// Created by the container so it is disposed with the application and releases the log file.
|
||||
builder.Services.AddSingleton<ILoggerProvider>(_ => new JsonLogProvider(config.Data.Logs, clock, console: true));
|
||||
builder.Logging.SetMinimumLevel(LogLevel.Information);
|
||||
builder.Logging.AddFilter("Microsoft", LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Information);
|
||||
// The form-token keys sit unencrypted in the data folder, which only the app's user can read (ADR 0007).
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore.DataProtection", LogLevel.Error);
|
||||
|
||||
var services = builder.Services;
|
||||
services.AddSingleton(options);
|
||||
services.AddSingleton(config);
|
||||
services.AddSingleton(environment);
|
||||
services.AddSingleton(clock);
|
||||
services.AddSingleton(overrides ?? new ServerOverrides());
|
||||
services.AddSingleton<EventBus>();
|
||||
services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService<EventBus>(),
|
||||
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides));
|
||||
services.AddHostedService(sp => sp.GetRequiredService<AnubisHost>());
|
||||
services.AddSingleton(new LoginLimiter(clock));
|
||||
services.AddSingleton<ShellData>();
|
||||
services.AddSingleton<SecondFactorDrafts>();
|
||||
|
||||
services.AddAuthentication(SessionAuthentication.SchemeName)
|
||||
.AddScheme<AuthenticationSchemeOptions, SessionAuthentication>(SessionAuthentication.SchemeName, null);
|
||||
services.AddAuthorization();
|
||||
services.AddAntiforgery(o =>
|
||||
{
|
||||
o.Cookie.Name = "anubis_csrf";
|
||||
o.Cookie.SameSite = SameSiteMode.Strict;
|
||||
o.Cookie.HttpOnly = true;
|
||||
o.HeaderName = Endpoints.CsrfHeader;
|
||||
o.FormFieldName = "__csrf";
|
||||
});
|
||||
// The keys behind the form tokens live in the data folder, so a restart or a new container keeps open pages working
|
||||
// (otherwise ASP.NET would use a home folder that in Docker belongs to root, or keys lost at every start).
|
||||
services.AddDataProtection()
|
||||
.SetApplicationName("Anubis")
|
||||
.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(config.Data.Root, "web-keys")));
|
||||
services.AddRazorComponents();
|
||||
|
||||
// Pages in Italian stay readable: letters with accents and the euro sign are written as they are.
|
||||
services.AddSingleton(System.Text.Encodings.Web.HtmlEncoder.Create(System.Text.Unicode.UnicodeRanges.All));
|
||||
|
||||
var app = builder.Build();
|
||||
var host = app.Services.GetRequiredService<AnubisHost>();
|
||||
|
||||
app.Use(SecurityHeaders);
|
||||
app.Use((context, next) => LocalOnly(context, next, options, config));
|
||||
app.Use((context, next) => Gate.InvokeAsync(context, next, host));
|
||||
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20) });
|
||||
app.UseRouting();
|
||||
app.UseAuthentication();
|
||||
app.Use(MustChangePassword);
|
||||
app.UseAuthorization();
|
||||
app.UseAntiforgery();
|
||||
|
||||
Endpoints.Map(app);
|
||||
app.MapRazorComponents<App>().RequireAuthorization();
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
private static Dictionary<string, string?> ReadEnvironment()
|
||||
{
|
||||
var result = new Dictionary<string, string?>(StringComparer.Ordinal);
|
||||
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
|
||||
{
|
||||
result[(string)entry.Key] = entry.Value as string;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Every secret the startup configuration knows is masked in logs and messages from the first line on.
|
||||
private static void RegisterSecrets(StartupConfig config)
|
||||
{
|
||||
Redactor.Register(config.Db?.Password);
|
||||
Redactor.Register(config.AdminPassword);
|
||||
foreach (var value in config.EnvironmentKeys.Values)
|
||||
{
|
||||
Redactor.Register(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static Task SecurityHeaders(HttpContext context, Func<Task> next)
|
||||
{
|
||||
var headers = context.Response.Headers;
|
||||
headers.XContentTypeOptions = "nosniff";
|
||||
headers.XFrameOptions = "DENY";
|
||||
headers["Referrer-Policy"] = "same-origin";
|
||||
headers.ContentSecurityPolicy = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " +
|
||||
"font-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'";
|
||||
return next();
|
||||
}
|
||||
|
||||
// Defence in depth: even if someone binds the server to every address, desktop and demo answer only the computer itself.
|
||||
private static Task LocalOnly(HttpContext context, Func<Task> next, ServerOptions options, StartupConfig config)
|
||||
{
|
||||
var localOnly = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
|
||||
if (localOnly && !CurrentUser.IsLocal(context))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return context.Response.WriteAsync("Anubis risponde solo dal computer su cui gira.");
|
||||
}
|
||||
|
||||
return next();
|
||||
}
|
||||
|
||||
// Docker: the initial password works once, then the interface asks for a new one before anything else (SPEC 13.1).
|
||||
private static Task MustChangePassword(HttpContext context, Func<Task> next)
|
||||
{
|
||||
if (context.User.Identity?.IsAuthenticated != true || !CurrentUser.MustChangePassword(context.User))
|
||||
{
|
||||
return next();
|
||||
}
|
||||
|
||||
var path = context.Request.Path;
|
||||
if (path.StartsWithSegments("/primo-accesso", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-accesso", StringComparison.Ordinal) ||
|
||||
path.StartsWithSegments("/azioni/esci", StringComparison.Ordinal) || Gate.IsAlwaysOpen(path))
|
||||
{
|
||||
return next();
|
||||
}
|
||||
|
||||
if (SessionAuthentication.IsApi(context.Request))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return context.Response.WriteAsJsonAsync(new ApiError("password_da_cambiare", "Scegli una nuova password prima di continuare."));
|
||||
}
|
||||
|
||||
context.Response.Redirect("/primo-accesso");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Answer of <c>GET /health</c>.</summary>
|
||||
internal sealed record HealthResponse(string Status, string Name, string Version);
|
||||
/// <summary>
|
||||
/// While the application is not ready, every page is the service page (error, first run): the engine does not start
|
||||
/// and no other database is ever opened (SPEC 15.1). Health, logo and style always answer.
|
||||
/// </summary>
|
||||
internal static class Gate
|
||||
{
|
||||
public static bool IsAlwaysOpen(PathString path) =>
|
||||
path.StartsWithSegments("/health", StringComparison.Ordinal) || path.StartsWithSegments("/assets", StringComparison.Ordinal) ||
|
||||
path.StartsWithSegments("/brand", StringComparison.Ordinal) || path == "/favicon.ico";
|
||||
|
||||
public static async Task InvokeAsync(HttpContext context, Func<Task> next, AnubisHost host)
|
||||
{
|
||||
var path = context.Request.Path;
|
||||
var mode = host.Status.Mode;
|
||||
if (IsAlwaysOpen(path))
|
||||
{
|
||||
await next().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode == HostMode.Ready)
|
||||
{
|
||||
if (path.StartsWithSegments("/servizio", StringComparison.Ordinal) || path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal))
|
||||
{
|
||||
context.Response.Redirect("/");
|
||||
return;
|
||||
}
|
||||
|
||||
await next().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var api = SessionAuthentication.IsApi(context.Request);
|
||||
if (mode == HostMode.FirstRun)
|
||||
{
|
||||
if (path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-avvio", StringComparison.Ordinal))
|
||||
{
|
||||
await next().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!api && HttpMethods.IsGet(context.Request.Method))
|
||||
{
|
||||
context.Response.Redirect("/primo-avvio");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (path.StartsWithSegments("/azioni/servizio", StringComparison.Ordinal))
|
||||
{
|
||||
await next().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (api)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
await context.Response.WriteAsJsonAsync(new ApiError("non_pronto", ServiceText.Title(mode))).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
await context.Response.WriteAsync(ServiceText.Title(mode)).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// The service page answers in place of whatever was asked, with 503 so nothing caches it.
|
||||
context.Request.Path = "/servizio";
|
||||
await next().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// What the server process was asked to be, from its arguments and environment: Docker or desktop, which data
|
||||
/// folder, demo mode. Tests pass a fake environment and clock through <see cref="ServerOverrides"/>.
|
||||
/// </summary>
|
||||
internal sealed record ServerOptions(PlatformKind Platform, string? DataDir, bool Demo, string[] AspNetArgs)
|
||||
{
|
||||
public static ServerOptions Parse(string[] args, IReadOnlyDictionary<string, string?> environment)
|
||||
{
|
||||
var rest = new List<string>();
|
||||
PlatformKind? platform = null;
|
||||
string? dataDir = null;
|
||||
var demo = false;
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
switch (args[i])
|
||||
{
|
||||
case "--platform" when i + 1 < args.Length:
|
||||
platform = args[++i].Equals("docker", StringComparison.OrdinalIgnoreCase) ? PlatformKind.Docker : PlatformKind.Desktop;
|
||||
break;
|
||||
case "--data-dir" when i + 1 < args.Length:
|
||||
dataDir = Path.GetFullPath(args[++i]);
|
||||
break;
|
||||
case "--demo":
|
||||
demo = true;
|
||||
break;
|
||||
default:
|
||||
rest.Add(args[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
platform ??= (environment.GetValueOrDefault("ANUBIS_PLATFORM") ?? "").ToLowerInvariant() switch
|
||||
{
|
||||
"docker" => PlatformKind.Docker,
|
||||
"desktop" => PlatformKind.Desktop,
|
||||
_ => environment.GetValueOrDefault("DOTNET_RUNNING_IN_CONTAINER") == "true" ? PlatformKind.Docker : PlatformKind.Desktop,
|
||||
};
|
||||
return new ServerOptions(platform.Value, dataDir, demo, [.. rest]);
|
||||
}
|
||||
|
||||
/// <summary>Reads the startup configuration of the chosen platform.</summary>
|
||||
public StartupConfig LoadConfig(IReadOnlyDictionary<string, string?> environment)
|
||||
{
|
||||
if (Platform == PlatformKind.Docker)
|
||||
{
|
||||
return DockerPlatform.Load(environment, DataDir ?? "/data");
|
||||
}
|
||||
|
||||
var data = DataDir is null ? DataDirectory.ForCurrentUser() : new DataDirectory(DataDir);
|
||||
return DesktopPlatform.Load(data, ProtectedSecretKey.DefaultStore(data));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Test hooks: a fake environment, a manual clock, a cheaper password hash.</summary>
|
||||
internal sealed record ServerOverrides
|
||||
{
|
||||
public IReadOnlyDictionary<string, string?>? Environment { get; init; }
|
||||
|
||||
public IClock? Clock { get; init; }
|
||||
|
||||
public int? PasswordIterations { get; init; }
|
||||
|
||||
/// <summary>How often the database is checked while running and retried while it is missing.</summary>
|
||||
public TimeSpan? DatabaseCheckInterval { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Anubis.Access;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Sign-in by session cookie (SPEC 15.4): the cookie holds a random token, the database only its hash. HttpOnly,
|
||||
/// SameSite=Strict, Secure when the request is HTTPS. In demo mode everyone on the computer itself is signed in.
|
||||
/// </summary>
|
||||
internal sealed class SessionAuthentication(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
AnubisHost host) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
public const string SchemeName = "anubis";
|
||||
public const string Cookie = "anubis_session";
|
||||
public const string SessionClaim = "anubis:session";
|
||||
public const string MustChangeClaim = "anubis:must_change";
|
||||
public const string SecondFactorClaim = "anubis:second_factor";
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var services = host.Services;
|
||||
if (services is null)
|
||||
{
|
||||
return AuthenticateResult.NoResult();
|
||||
}
|
||||
|
||||
if (host.IsDemo)
|
||||
{
|
||||
var user = await services.Access.GetUserAsync(Context.RequestAborted).ConfigureAwait(false);
|
||||
return user is null ? AuthenticateResult.NoResult() : Success(user, Guid.Empty);
|
||||
}
|
||||
|
||||
if (!Request.Cookies.TryGetValue(Cookie, out var token) || string.IsNullOrEmpty(token))
|
||||
{
|
||||
return AuthenticateResult.NoResult();
|
||||
}
|
||||
|
||||
var session = await services.Access.ValidateAsync(token, Context.RequestAborted).ConfigureAwait(false);
|
||||
return session is null ? AuthenticateResult.Fail("Sessione scaduta") : Success(session.User, session.Id);
|
||||
}
|
||||
|
||||
private static AuthenticateResult Success(User user, Guid session)
|
||||
{
|
||||
Claim[] claims =
|
||||
[
|
||||
new(ClaimTypes.NameIdentifier, user.Id.ToString("D")),
|
||||
new(ClaimTypes.Name, user.Username),
|
||||
new(SessionClaim, session.ToString("D")),
|
||||
new(MustChangeClaim, user.MustChangePassword ? "1" : "0"),
|
||||
new(SecondFactorClaim, user.HasSecondFactor ? "1" : "0"),
|
||||
];
|
||||
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName));
|
||||
return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName));
|
||||
}
|
||||
|
||||
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
if (IsApi(Request))
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return Response.WriteAsJsonAsync(new ApiError("non_autenticato", "Accedi di nuovo."));
|
||||
}
|
||||
|
||||
var back = Request.Path + Request.QueryString;
|
||||
Response.Redirect("/accesso" + (back == "/" ? "" : "?ritorno=" + Uri.EscapeDataString(back)));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
internal static bool IsApi(HttpRequest request) =>
|
||||
request.Path.StartsWithSegments("/api", StringComparison.Ordinal) || request.Path.StartsWithSegments("/ws", StringComparison.Ordinal);
|
||||
|
||||
public static void WriteCookie(HttpContext context, string token) =>
|
||||
context.Response.Cookies.Append(Cookie, token, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Secure = context.Request.IsHttps,
|
||||
Path = "/",
|
||||
MaxAge = AccessStore.MaxLifetime,
|
||||
IsEssential = true,
|
||||
});
|
||||
|
||||
public static void ClearCookie(HttpContext context) =>
|
||||
context.Response.Cookies.Delete(Cookie, new CookieOptions { Path = "/", HttpOnly = true, SameSite = SameSiteMode.Strict, Secure = context.Request.IsHttps });
|
||||
}
|
||||
|
||||
/// <summary>Who is signed in, read from the claims.</summary>
|
||||
internal static class CurrentUser
|
||||
{
|
||||
public static Guid Id(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!, CultureInfo.InvariantCulture);
|
||||
|
||||
public static Guid Session(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(SessionAuthentication.SessionClaim) ?? Guid.Empty.ToString(), CultureInfo.InvariantCulture);
|
||||
|
||||
public static bool MustChangePassword(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.MustChangeClaim) == "1";
|
||||
|
||||
public static bool HasSecondFactor(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.SecondFactorClaim) == "1";
|
||||
|
||||
/// <summary>
|
||||
/// The request comes from the computer the server runs on, addressed to it by a local name. The name matters too:
|
||||
/// a web page that points its own name at 127.0.0.1 (DNS rebinding) arrives from the loopback with a foreign Host.
|
||||
/// </summary>
|
||||
public static bool IsLocal(HttpContext context) =>
|
||||
context.Connection.RemoteIpAddress is { } address && IPAddress.IsLoopback(address) && IsLocalName(context.Request.Host.Host);
|
||||
|
||||
internal static bool IsLocalName(string host) =>
|
||||
host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host is "127.0.0.1" or "[::1]" or "::1";
|
||||
}
|
||||
|
||||
/// <summary>Error body of the API: a code for programs and a sentence for people.</summary>
|
||||
internal sealed record ApiError(string Code, string Message);
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Demo;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>What the top bar shows and the WebSocket sends: state of the bot, mode, currency, how fresh the data are.</summary>
|
||||
internal sealed record ShellSnapshot(
|
||||
string Mode,
|
||||
string Bot,
|
||||
string BotLabel,
|
||||
string BotShort,
|
||||
bool RealMoney,
|
||||
string Currency,
|
||||
string Theme,
|
||||
string Now,
|
||||
int AgeSeconds,
|
||||
bool Demo,
|
||||
string Version);
|
||||
|
||||
/// <summary>Reads the shell state once per request; also the money formatter with the chosen display currency.</summary>
|
||||
internal sealed class ShellData(AnubisHost host, IClock clock)
|
||||
{
|
||||
private decimal? _demoRate;
|
||||
private int? _demoAge;
|
||||
|
||||
public bool IsDemo => host.IsDemo;
|
||||
|
||||
public TimeZoneInfo Zone => host.Config.TimeZone;
|
||||
|
||||
public DateTimeOffset Now => clock.UtcNow;
|
||||
|
||||
public async Task<ShellSnapshot> SnapshotAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var services = host.Services;
|
||||
var bot = "active";
|
||||
var currency = "EUR";
|
||||
var theme = "auto";
|
||||
if (services is not null)
|
||||
{
|
||||
bot = (await services.Settings.GetAsync(Core.SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
|
||||
currency = (await services.Settings.GetAsync(Core.SettingsStore.Currency.Key, cancellationToken).ConfigureAwait(false)).Value;
|
||||
theme = (await services.Settings.GetAsync(Core.SettingsStore.Theme.Key, cancellationToken).ConfigureAwait(false)).Value;
|
||||
}
|
||||
|
||||
var (label, shortLabel) = bot switch
|
||||
{
|
||||
"paused" => ("Bot in pausa", "In pausa"),
|
||||
"stopped" => ("Bot fermo", "Fermo"),
|
||||
_ => ("Bot attivo", "Attivo"),
|
||||
};
|
||||
var age = DemoAge() ?? (host.LastCheckUtc is { } last ? (int)Math.Max(0, (clock.UtcNow - last).TotalSeconds) : 0);
|
||||
return new ShellSnapshot(host.Status.Mode.ToString(), bot, label, shortLabel, RealMoney: false, currency, theme,
|
||||
Format.LongDateTime(clock.UtcNow, Zone), age, host.IsDemo, AnubisInfo.Version);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An amount in euro shown in the display currency. Exchange rates arrive with the market data (phase 2): until
|
||||
/// then dollars appear only in demo mode, with the rate of appendix F, and otherwise amounts stay in euro.
|
||||
/// </summary>
|
||||
public string Money(decimal euro, string currency, bool withSign = false, int decimals = 2) =>
|
||||
Format.Money(Convert(euro, currency), Effective(currency), withSign, decimals);
|
||||
|
||||
public decimal Convert(decimal euro, string currency) => currency == "USD" && DemoRate() is { } rate ? euro * rate : euro;
|
||||
|
||||
/// <summary>The display currency that <see cref="Money"/> can honour.</summary>
|
||||
public string Effective(string currency) => currency == "USD" && DemoRate() is not null ? "USD" : "EUR";
|
||||
|
||||
private decimal? DemoRate()
|
||||
{
|
||||
if (!host.IsDemo)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (_demoRate is null && Aggregates() is { } doc)
|
||||
{
|
||||
_demoRate = decimal.Parse(doc.RootElement.GetProperty("cambio_eur_usd").GetString()!, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return _demoRate;
|
||||
}
|
||||
|
||||
private int? DemoAge()
|
||||
{
|
||||
if (!host.IsDemo)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (_demoAge is null && Aggregates() is { } doc)
|
||||
{
|
||||
_demoAge = doc.RootElement.GetProperty("dati_aggiornati_secondi").GetInt32();
|
||||
}
|
||||
|
||||
return _demoAge;
|
||||
}
|
||||
|
||||
/// <summary>The aggregates of appendix F; only in demo mode (SPEC 13.1).</summary>
|
||||
public JsonDocument? Aggregates() => host.IsDemo ? DemoMode.ReadAggregates(host.Config.Data) : null;
|
||||
|
||||
public PlatformKind Platform => host.Config.Platform;
|
||||
}
|
||||
@@ -2,8 +2,71 @@
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||
},
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w=="
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,87 @@
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||
},
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"anubis": {
|
||||
"type": "Project"
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
|
||||
namespace Anubis.Access;
|
||||
|
||||
public sealed record User(Guid Id, string Username, bool MustChangePassword, bool HasSecondFactor);
|
||||
|
||||
public sealed record SessionInfo(Guid Id, User User, DateTimeOffset CreatedAt, DateTimeOffset ExpiresAt);
|
||||
|
||||
public enum LoginResult
|
||||
{
|
||||
Ok,
|
||||
WrongPassword,
|
||||
SecondFactorNeeded,
|
||||
WrongSecondFactor,
|
||||
Locked,
|
||||
NoUser,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Limit on sign-in attempts (SPEC 15.4): after 5 failures from the same address in 15 minutes that address
|
||||
/// waits 15 minutes; after 20 failures overall, everyone waits. Kept in memory: a restart clears it, which
|
||||
/// costs an attacker a restart they cannot cause.
|
||||
/// </summary>
|
||||
public sealed class LoginLimiter(IClock clock)
|
||||
{
|
||||
public const int PerAddress = 5;
|
||||
public const int Overall = 20;
|
||||
public static readonly TimeSpan Window = TimeSpan.FromMinutes(15);
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<string, List<DateTimeOffset>> _failures = new(StringComparer.Ordinal);
|
||||
private readonly List<DateTimeOffset> _all = [];
|
||||
|
||||
/// <summary>How long <paramref name="address"/> must still wait, or zero.</summary>
|
||||
public TimeSpan Wait(string address)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
Trim(now);
|
||||
var mine = _failures.TryGetValue(address, out var list) ? list : [];
|
||||
var wait = TimeSpan.Zero;
|
||||
if (mine.Count >= PerAddress)
|
||||
{
|
||||
wait = mine[^PerAddress] + Window - now;
|
||||
}
|
||||
|
||||
if (_all.Count >= Overall)
|
||||
{
|
||||
var overall = _all[^Overall] + Window - now;
|
||||
wait = overall > wait ? overall : wait;
|
||||
}
|
||||
|
||||
return wait > TimeSpan.Zero ? wait : TimeSpan.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts an attempt: zero when it may go ahead, already counted as a failure, so parallel attempts cannot all slip
|
||||
/// through before the first one fails. A success clears it with <see cref="Succeeded"/>, a correct password still
|
||||
/// waiting for its code with <see cref="Forgive"/>.
|
||||
/// </summary>
|
||||
public TimeSpan Begin(string address)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var wait = Wait(address);
|
||||
if (wait == TimeSpan.Zero)
|
||||
{
|
||||
Failed(address);
|
||||
}
|
||||
|
||||
return wait;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Takes back the last attempt counted by <see cref="Begin"/>.</summary>
|
||||
public void Forgive(string address)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_failures.TryGetValue(address, out var list) && list.Count > 0)
|
||||
{
|
||||
var last = list[^1];
|
||||
list.RemoveAt(list.Count - 1);
|
||||
var index = _all.LastIndexOf(last);
|
||||
if (index >= 0)
|
||||
{
|
||||
_all.RemoveAt(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Failed(string address)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
if (!_failures.TryGetValue(address, out var list))
|
||||
{
|
||||
_failures[address] = list = [];
|
||||
}
|
||||
|
||||
list.Add(now);
|
||||
_all.Add(now);
|
||||
}
|
||||
}
|
||||
|
||||
public void Succeeded(string address)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_failures.Remove(address);
|
||||
}
|
||||
}
|
||||
|
||||
private void Trim(DateTimeOffset now)
|
||||
{
|
||||
_all.RemoveAll(t => t + Window <= now);
|
||||
foreach (var key in _failures.Keys.ToList())
|
||||
{
|
||||
_failures[key].RemoveAll(t => t + Window <= now);
|
||||
if (_failures[key].Count == 0)
|
||||
{
|
||||
_failures.Remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The single user of Anubis and their sessions (SPEC 15.4). Sessions are random tokens in an HttpOnly cookie;
|
||||
/// only their SHA-256 is stored, so a copy of the database does not let anyone in.
|
||||
/// </summary>
|
||||
public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, int iterations = Passwords.DefaultIterations)
|
||||
{
|
||||
public const string AdminName = "admin";
|
||||
public static readonly TimeSpan IdleTimeout = TimeSpan.FromHours(12);
|
||||
public static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(7);
|
||||
|
||||
// Each second-factor code works once (RFC 6238, 5.2): the last time step used, in memory.
|
||||
private readonly Lock _stepGate = new();
|
||||
private long _lastStep = long.MinValue;
|
||||
|
||||
private bool AcceptCode(ReadOnlySpan<byte> secret, string? code)
|
||||
{
|
||||
if (Totp.Match(secret, code, clock.UtcNow) is not { } step)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_stepGate)
|
||||
{
|
||||
if (step <= _lastStep)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_lastStep = step;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public Task<bool> HasUserAsync(CancellationToken cancellationToken = default) =>
|
||||
db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM users").ConfigureAwait(false) > 0, cancellationToken);
|
||||
|
||||
/// <summary>The single user, or null before the first run created it.</summary>
|
||||
public Task<User?> GetUserAsync(CancellationToken cancellationToken = default) =>
|
||||
db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, username, must_change_password, totp_secret FROM users WHERE username = @u",
|
||||
r => new User(r.Id("id"), r.Text("username"), r.Bool("must_change_password"), !r.IsNull("totp_secret")), ("u", AdminName)), cancellationToken);
|
||||
|
||||
/// <summary>Creates the user when there is none. In Docker the initial password must be changed at first sign-in.</summary>
|
||||
public async Task<bool> EnsureUserAsync(string password, bool mustChange, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var hash = Passwords.Hash(password, iterations);
|
||||
var now = clock.UtcNow;
|
||||
return await db.WriteAsync(async s =>
|
||||
{
|
||||
if (await s.CountAsync("SELECT COUNT(*) FROM users").ConfigureAwait(false) > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, @u, @h, @m, NULL, @t, @t)",
|
||||
cancellationToken, ("id", Ids.NewId(clock)), ("u", AdminName), ("h", hash), ("m", mustChange), ("t", now)).ConfigureAwait(false);
|
||||
return true;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<(LoginResult Result, string? Token)> SignInAsync(string password, string? code, string? userAgent, string? address, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, password_hash, totp_secret FROM users WHERE username = @u",
|
||||
r => (Id: r.Id("id"), Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("u", AdminName)), cancellationToken).ConfigureAwait(false);
|
||||
if (user == default)
|
||||
{
|
||||
return (LoginResult.NoUser, null);
|
||||
}
|
||||
|
||||
if (!Passwords.Verify(password, user.Hash))
|
||||
{
|
||||
return (LoginResult.WrongPassword, null);
|
||||
}
|
||||
|
||||
if (user.Totp is not null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
return (LoginResult.SecondFactorNeeded, null);
|
||||
}
|
||||
|
||||
var secret = Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp));
|
||||
if (!AcceptCode(secret, code))
|
||||
{
|
||||
return (LoginResult.WrongSecondFactor, null);
|
||||
}
|
||||
}
|
||||
|
||||
var token = Ids.NewToken();
|
||||
var now = clock.UtcNow;
|
||||
await db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO sessions (id, user_id, token_hash, user_agent, address, created_at, last_seen_at, expires_at) VALUES (@id, @u, @h, @ua, @a, @t, @t, @e)",
|
||||
cancellationToken, ("id", Ids.NewId(clock)), ("u", user.Id), ("h", HashToken(token)), ("ua", Truncate(userAgent, 300)), ("a", Truncate(address, 100)),
|
||||
("t", now), ("e", now + MaxLifetime)), cancellationToken).ConfigureAwait(false);
|
||||
return (LoginResult.Ok, token);
|
||||
}
|
||||
|
||||
/// <summary>The session behind a cookie token, or null when unknown, idle too long or expired.</summary>
|
||||
public async Task<SessionInfo?> ValidateAsync(string? token, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var now = clock.UtcNow;
|
||||
var found = await db.ReadAsync(s => s.FirstOrDefaultAsync(
|
||||
"SELECT s.id, s.created_at, s.last_seen_at, s.expires_at, u.id AS user_id, u.username, u.must_change_password, u.totp_secret FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = @h",
|
||||
r => new
|
||||
{
|
||||
Id = r.Id("id"),
|
||||
Created = r.Moment("created_at"),
|
||||
Seen = r.Moment("last_seen_at"),
|
||||
Expires = r.Moment("expires_at"),
|
||||
User = new User(r.Id("user_id"), r.Text("username"), r.Bool("must_change_password"), !r.IsNull("totp_secret")),
|
||||
}, ("h", HashToken(token))), cancellationToken).ConfigureAwait(false);
|
||||
if (found is null || now >= found.Expires || now - found.Seen >= IdleTimeout)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Refresh the idle timer at most once a minute, to keep writes rare.
|
||||
if (now - found.Seen > TimeSpan.FromMinutes(1))
|
||||
{
|
||||
await db.WriteAsync(s => s.ExecuteAsync("UPDATE sessions SET last_seen_at = @t WHERE id = @id", cancellationToken, ("t", now), ("id", found.Id)), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new SessionInfo(found.Id, found.User, found.Created, found.Expires);
|
||||
}
|
||||
|
||||
public Task SignOutAsync(string token, CancellationToken cancellationToken = default) =>
|
||||
db.WriteAsync(s => s.ExecuteAsync("DELETE FROM sessions WHERE token_hash = @h", cancellationToken, ("h", HashToken(token))), cancellationToken);
|
||||
|
||||
/// <summary>Changes the password and ends every other session.</summary>
|
||||
public async Task<bool> ChangePasswordAsync(Guid userId, string current, string replacement, Guid keepSession, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var hash = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash FROM users WHERE id = @id", r => r.Text("password_hash"), ("id", userId)), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (hash is null || !Passwords.Verify(current, hash))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var replacementHash = Passwords.Hash(replacement, iterations);
|
||||
var now = clock.UtcNow;
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE users SET password_hash = @h, must_change_password = @m, updated_at = @t WHERE id = @id", cancellationToken,
|
||||
("h", replacementHash), ("m", false), ("t", now), ("id", userId)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("DELETE FROM sessions WHERE user_id = @u AND id <> @keep", cancellationToken, ("u", userId), ("keep", keepSession)).ConfigureAwait(false);
|
||||
await LogAsync(s, "security.password", "cambiata", cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Turns on the second factor after the user proved the app produces valid codes.</summary>
|
||||
public async Task<bool> EnableSecondFactorAsync(Guid userId, byte[] secret, string code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(secret);
|
||||
if (!AcceptCode(secret, code))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var sealedSecret = secrets.Seal("totp:" + userId.ToString("D"), Convert.ToBase64String(secret));
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE users SET totp_secret = @s, updated_at = @t WHERE id = @id", cancellationToken,
|
||||
("s", sealedSecret), ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false);
|
||||
await LogAsync(s, "security.second_factor", "attivato", cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Turning the second factor off asks for both: the password and a code from the app.</summary>
|
||||
public async Task<bool> DisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash, totp_secret FROM users WHERE id = @id",
|
||||
r => (Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("id", userId)), cancellationToken).ConfigureAwait(false);
|
||||
if (user == default || !Passwords.Verify(password, user.Hash))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (user.Totp is not null && !AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + userId.ToString("D"), user.Totp)), code))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE users SET totp_secret = NULL, updated_at = @t WHERE id = @id", cancellationToken, ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false);
|
||||
await LogAsync(s, "security.second_factor", "disattivato", cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Task<int> LogAsync(DbSession s, string key, string what, CancellationToken cancellationToken) =>
|
||||
s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, NULL, @n, @by, @t)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("k", key), ("n", new DbJson(System.Text.Json.JsonSerializer.Serialize(what))), ("by", AdminName), ("t", clock.UtcNow));
|
||||
|
||||
private static string HashToken(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||
|
||||
private static string? Truncate(string? value, int length) => value is null || value.Length <= length ? value : value[..length];
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Anubis.Access;
|
||||
|
||||
/// <summary>
|
||||
/// Password hashes with PBKDF2-SHA512 (<see cref="Rfc2898DeriveBytes.Pbkdf2(string, byte[], int, HashAlgorithmName, int)"/>),
|
||||
/// in place of Argon2id (ADR 0003). Stored as <c>pbkdf2-sha512$iterations$salt$hash</c> so the cost can grow later.
|
||||
/// </summary>
|
||||
public static class Passwords
|
||||
{
|
||||
/// <summary>OWASP's figure for PBKDF2-HMAC-SHA512.</summary>
|
||||
public const int DefaultIterations = 210_000;
|
||||
|
||||
public const int MinimumLength = 10;
|
||||
|
||||
private const string Scheme = "pbkdf2-sha512";
|
||||
|
||||
public static string Hash(string password, int iterations = DefaultIterations)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(password);
|
||||
var salt = RandomNumberGenerator.GetBytes(16);
|
||||
var hash = Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA512, 64);
|
||||
return string.Join('$', Scheme, iterations.ToString(CultureInfo.InvariantCulture), Convert.ToBase64String(salt), Convert.ToBase64String(hash));
|
||||
}
|
||||
|
||||
/// <summary>Checks a password in constant time. A malformed stored hash never verifies.</summary>
|
||||
public static bool Verify(string password, string stored)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(password);
|
||||
ArgumentNullException.ThrowIfNull(stored);
|
||||
var parts = stored.Split('$');
|
||||
if (parts.Length != 4 || parts[0] != Scheme || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var iterations) || iterations < 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] salt;
|
||||
byte[] expected;
|
||||
try
|
||||
{
|
||||
salt = Convert.FromBase64String(parts[2]);
|
||||
expected = Convert.FromBase64String(parts[3]);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var actual = Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA512, expected.Length);
|
||||
return CryptographicOperations.FixedTimeEquals(actual, expected);
|
||||
}
|
||||
|
||||
/// <summary>What is wrong with a new password, in plain Italian, or null when it is acceptable.</summary>
|
||||
public static string? Problem(string? password, string? initialPassword = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(password) || password.Length < MinimumLength)
|
||||
{
|
||||
return $"La password deve avere almeno {MinimumLength} caratteri.";
|
||||
}
|
||||
|
||||
if (initialPassword is not null && password == initialPassword)
|
||||
{
|
||||
return "Scegli una password diversa da quella iniziale del container.";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Base32 without padding (RFC 4648), the format authenticator apps expect for TOTP secrets.</summary>
|
||||
public static class Base32
|
||||
{
|
||||
private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
|
||||
public static string Encode(ReadOnlySpan<byte> data)
|
||||
{
|
||||
var text = new StringBuilder((data.Length * 8 + 4) / 5);
|
||||
int buffer = 0, bits = 0;
|
||||
foreach (var b in data)
|
||||
{
|
||||
buffer = (buffer << 8) | b;
|
||||
bits += 8;
|
||||
while (bits >= 5)
|
||||
{
|
||||
text.Append(Alphabet[(buffer >> (bits - 5)) & 31]);
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
|
||||
if (bits > 0)
|
||||
{
|
||||
text.Append(Alphabet[(buffer << (5 - bits)) & 31]);
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
public static byte[] Decode(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var clean = text.Replace(" ", "", StringComparison.Ordinal).Replace("-", "", StringComparison.Ordinal).TrimEnd('=').ToUpperInvariant();
|
||||
var result = new List<byte>(clean.Length * 5 / 8);
|
||||
int buffer = 0, bits = 0;
|
||||
foreach (var c in clean)
|
||||
{
|
||||
var value = Alphabet.IndexOf(c, StringComparison.Ordinal);
|
||||
if (value < 0)
|
||||
{
|
||||
throw new FormatException("Carattere non valido nel codice: " + c);
|
||||
}
|
||||
|
||||
buffer = (buffer << 5) | value;
|
||||
bits += 5;
|
||||
if (bits >= 8)
|
||||
{
|
||||
result.Add((byte)(buffer >> (bits - 8)));
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
|
||||
return [.. result];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Time-based one-time passwords (RFC 6238), written in house and checked against the RFC's test vectors.
|
||||
/// Defaults are the ones every authenticator app uses: HMAC-SHA1, 6 digits, 30-second steps.
|
||||
/// </summary>
|
||||
public static class Totp
|
||||
{
|
||||
public static byte[] NewSecret() => RandomNumberGenerator.GetBytes(20);
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5350", Justification = "RFC 6238 and every authenticator app use HMAC-SHA1; HMAC keeps SHA-1 safe here.")]
|
||||
public static string Compute(ReadOnlySpan<byte> secret, DateTimeOffset at, int digits = 6, int stepSeconds = 30, string algorithm = "SHA1")
|
||||
{
|
||||
var counter = at.ToUnixTimeSeconds() / stepSeconds;
|
||||
Span<byte> message = stackalloc byte[8];
|
||||
for (var i = 7; i >= 0; i--)
|
||||
{
|
||||
message[i] = (byte)(counter & 0xff);
|
||||
counter >>= 8;
|
||||
}
|
||||
|
||||
byte[] hash = algorithm switch
|
||||
{
|
||||
"SHA1" => HMACSHA1.HashData(secret, message),
|
||||
"SHA256" => HMACSHA256.HashData(secret, message),
|
||||
"SHA512" => HMACSHA512.HashData(secret, message),
|
||||
_ => throw new ArgumentException("Unsupported algorithm " + algorithm, nameof(algorithm)),
|
||||
};
|
||||
var offset = hash[^1] & 0x0f;
|
||||
var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16) | (hash[offset + 2] << 8) | hash[offset + 3];
|
||||
var modulo = (int)Math.Pow(10, digits);
|
||||
return (binary % modulo).ToString(CultureInfo.InvariantCulture).PadLeft(digits, '0');
|
||||
}
|
||||
|
||||
/// <summary>Accepts the code of the current step and of one step before or after, for clocks a little apart.</summary>
|
||||
public static bool Verify(ReadOnlySpan<byte> secret, string? code, DateTimeOffset now) => Match(secret, code, now) is not null;
|
||||
|
||||
/// <summary>The time step the code belongs to (current, one before or one after), or null when it matches none.</summary>
|
||||
public static long? Match(ReadOnlySpan<byte> secret, string? code, DateTimeOffset now)
|
||||
{
|
||||
if (code is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
code = code.Replace(" ", "", StringComparison.Ordinal);
|
||||
if (code.Length != 6 || !code.All(char.IsAsciiDigit))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
long? matched = null;
|
||||
for (var step = -1; step <= 1; step++)
|
||||
{
|
||||
var at = now.AddSeconds(step * 30);
|
||||
var expected = Compute(secret, at);
|
||||
if (CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(code)))
|
||||
{
|
||||
matched = at.ToUnixTimeSeconds() / 30;
|
||||
}
|
||||
}
|
||||
|
||||
return matched;
|
||||
}
|
||||
|
||||
/// <summary>The address authenticator apps read (otpauth://), for manual entry or a QR code.</summary>
|
||||
public static string Uri(string issuer, string account, ReadOnlySpan<byte> secret) =>
|
||||
$"otpauth://totp/{System.Uri.EscapeDataString(issuer)}:{System.Uri.EscapeDataString(account)}?secret={Base32.Encode(secret)}&issuer={System.Uri.EscapeDataString(issuer)}&algorithm=SHA1&digits=6&period=30";
|
||||
}
|
||||
@@ -2,6 +2,15 @@
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Anubis</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Npgsql" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" />
|
||||
<PackageReference Include="System.Security.Cryptography.ProtectedData" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Db\Migrations\*.sql" LogicalName="Anubis.Db.Migrations.%(Filename)%(Extension)" />
|
||||
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Anubis.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>
|
||||
/// The only source of time in Anubis (SPEC 16, trap 12): no code reads the system clock directly,
|
||||
/// so tests and the demo mode can run at any moment.
|
||||
/// </summary>
|
||||
public interface IClock
|
||||
{
|
||||
DateTimeOffset UtcNow { get; }
|
||||
|
||||
/// <summary>Waits until the clock reaches <paramref name="dueUtc"/>. A manual clock returns when it is moved past it.</summary>
|
||||
Task WaitUntilAsync(DateTimeOffset dueUtc, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The real clock of the machine.</summary>
|
||||
public sealed class SystemClock : IClock
|
||||
{
|
||||
public static SystemClock Instance { get; } = new();
|
||||
|
||||
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
|
||||
|
||||
public async Task WaitUntilAsync(DateTimeOffset dueUtc, CancellationToken cancellationToken)
|
||||
{
|
||||
// Wake at least once a minute: after a sleep of the computer the remaining time is recomputed (trap 21).
|
||||
while (true)
|
||||
{
|
||||
var remaining = dueUtc - UtcNow;
|
||||
if (remaining <= TimeSpan.Zero)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(remaining < TimeSpan.FromMinutes(1) ? remaining : TimeSpan.FromMinutes(1), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A clock that moves only when told to: tests and the frozen demo clock (SPEC 13.1).</summary>
|
||||
public sealed class ManualClock(DateTimeOffset start) : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<(DateTimeOffset Due, TaskCompletionSource Done)> _waiters = [];
|
||||
private DateTimeOffset _now = start.ToUniversalTime();
|
||||
|
||||
public DateTimeOffset UtcNow
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Set(DateTimeOffset value)
|
||||
{
|
||||
List<TaskCompletionSource> ready;
|
||||
lock (_gate)
|
||||
{
|
||||
_now = value.ToUniversalTime();
|
||||
ready = _waiters.Where(w => w.Due <= _now).Select(w => w.Done).ToList();
|
||||
_waiters.RemoveAll(w => w.Due <= _now);
|
||||
}
|
||||
|
||||
foreach (var done in ready)
|
||||
{
|
||||
done.TrySetResult();
|
||||
}
|
||||
}
|
||||
|
||||
public void Advance(TimeSpan by) => Set(UtcNow + by);
|
||||
|
||||
/// <summary>Number of callers waiting for a future moment; lets tests know a loop has gone to sleep.</summary>
|
||||
public int Waiting
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _waiters.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task WaitUntilAsync(DateTimeOffset dueUtc, CancellationToken cancellationToken)
|
||||
{
|
||||
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
lock (_gate)
|
||||
{
|
||||
if (dueUtc <= _now)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
_waiters.Add((dueUtc, done));
|
||||
}
|
||||
|
||||
cancellationToken.Register(() =>
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_waiters.RemoveAll(w => w.Done == done);
|
||||
}
|
||||
|
||||
done.TrySetCanceled(cancellationToken);
|
||||
});
|
||||
return done.Task;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System.Threading.Channels;
|
||||
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>
|
||||
/// In-process event bus (ADR 0003) on <see cref="System.Threading.Channels"/>. Every subscriber gets its own
|
||||
/// bounded queue: a slow reader loses its oldest events instead of blocking the publisher (prices and orders
|
||||
/// must never wait for the interface).
|
||||
/// </summary>
|
||||
public sealed class EventBus
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<Subscription> _subscriptions = [];
|
||||
|
||||
/// <summary>Delivers <paramref name="message"/> to every current subscriber of <typeparamref name="T"/> (or a base type).</summary>
|
||||
public void Publish<T>(T message)
|
||||
where T : notnull
|
||||
{
|
||||
Subscription[] targets;
|
||||
lock (_gate)
|
||||
{
|
||||
targets = [.. _subscriptions];
|
||||
}
|
||||
|
||||
foreach (var subscription in targets)
|
||||
{
|
||||
if (subscription.Type.IsInstanceOfType(message))
|
||||
{
|
||||
subscription.Writer.TryWrite(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Starts receiving messages of type <typeparamref name="T"/>. Dispose the result to stop.</summary>
|
||||
public EventSubscription<T> Subscribe<T>(int capacity = 256)
|
||||
{
|
||||
var channel = Channel.CreateBounded<object>(new BoundedChannelOptions(capacity)
|
||||
{
|
||||
FullMode = BoundedChannelFullMode.DropOldest,
|
||||
SingleReader = true,
|
||||
});
|
||||
var subscription = new Subscription(typeof(T), channel.Writer);
|
||||
lock (_gate)
|
||||
{
|
||||
_subscriptions.Add(subscription);
|
||||
}
|
||||
|
||||
return new EventSubscription<T>(channel.Reader, () =>
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_subscriptions.Remove(subscription);
|
||||
}
|
||||
|
||||
channel.Writer.TryComplete();
|
||||
});
|
||||
}
|
||||
|
||||
public int SubscriberCount
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _subscriptions.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record Subscription(Type Type, ChannelWriter<object> Writer);
|
||||
}
|
||||
|
||||
/// <summary>A live subscription to the <see cref="EventBus"/>.</summary>
|
||||
public sealed class EventSubscription<T>(ChannelReader<object> reader, Action unsubscribe) : IDisposable
|
||||
{
|
||||
public async IAsyncEnumerable<T> ReadAllAsync([System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
await foreach (var item in reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
yield return (T)item;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryRead(out T? message)
|
||||
{
|
||||
if (reader.TryRead(out var item))
|
||||
{
|
||||
message = (T)item;
|
||||
return true;
|
||||
}
|
||||
|
||||
message = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Dispose() => unsubscribe();
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Every number and date the user reads, written the Italian way (SPEC 13.3): decimal comma, dot for
|
||||
/// thousands, currency symbol after a non-breaking space, typographic minus, plus sign on results.
|
||||
/// The rest of the code never formats user-facing numbers by itself.
|
||||
/// </summary>
|
||||
public static class Format
|
||||
{
|
||||
/// <summary>U+2212, the typographic minus.</summary>
|
||||
public const char Minus = '−';
|
||||
|
||||
/// <summary>U+00A0, the space between a number and its currency symbol.</summary>
|
||||
public const char NonBreakingSpace = ' ';
|
||||
|
||||
private static readonly NumberFormatInfo _italian = new()
|
||||
{
|
||||
NumberDecimalSeparator = ",",
|
||||
NumberGroupSeparator = ".",
|
||||
NumberGroupSizes = [3],
|
||||
NegativeSign = Minus.ToString(),
|
||||
PositiveSign = "+",
|
||||
};
|
||||
|
||||
private static readonly string[] _days = ["dom", "lun", "mar", "mer", "gio", "ven", "sab"];
|
||||
private static readonly string[] _daysLong = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
|
||||
private static readonly string[] _months = ["gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic"];
|
||||
private static readonly string[] _monthsLong =
|
||||
["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
|
||||
|
||||
/// <summary>A number with Italian separators, rounded half away from zero: <c>10.412</c>, <c>−2,57</c>.</summary>
|
||||
public static string Number(decimal value, int decimals = 0, bool withSign = false)
|
||||
{
|
||||
var rounded = Math.Round(value, decimals, MidpointRounding.AwayFromZero);
|
||||
var text = Math.Abs(rounded).ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), _italian);
|
||||
if (rounded < 0)
|
||||
{
|
||||
return Minus + text;
|
||||
}
|
||||
|
||||
return withSign && rounded > 0 ? "+" + text : text;
|
||||
}
|
||||
|
||||
/// <summary>An amount with its currency after a non-breaking space: <c>1.299,84 €</c>, <c>+18,40 €</c>, <c>−26,00 €</c>.</summary>
|
||||
public static string Money(decimal value, string currency = "EUR", bool withSign = false, int decimals = 2) =>
|
||||
Number(value, decimals, withSign) + NonBreakingSpace + CurrencySymbol(currency);
|
||||
|
||||
public static string CurrencySymbol(string currency) => currency.ToUpperInvariant() switch
|
||||
{
|
||||
"EUR" => "€",
|
||||
"USD" => "$",
|
||||
_ => currency.ToUpperInvariant(),
|
||||
};
|
||||
|
||||
/// <summary>A percentage given in percent units: <c>Percent(4.12m, 2, true)</c> is <c>+4,12%</c>.</summary>
|
||||
public static string Percent(decimal percent, int decimals = 1, bool withSign = false) =>
|
||||
Number(percent, decimals, withSign) + "%";
|
||||
|
||||
/// <summary>
|
||||
/// Shares of a whole in percent that always add up to exactly 100 (largest remainder method, SPEC 13.3).
|
||||
/// Negative or zero weights get 0; with no positive weight every share is 0.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<decimal> Shares(IReadOnlyList<decimal> weights, int decimals = 1)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(weights);
|
||||
var positive = weights.Select(w => w > 0 ? w : 0m).ToArray();
|
||||
var total = positive.Sum();
|
||||
var result = new decimal[positive.Length];
|
||||
if (total == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var unit = 1m;
|
||||
for (var i = 0; i < decimals; i++)
|
||||
{
|
||||
unit /= 10m;
|
||||
}
|
||||
|
||||
var units = (long)Math.Round(100m / unit);
|
||||
var exact = positive.Select(w => w / total * units).ToArray();
|
||||
var floors = exact.Select(Math.Floor).ToArray();
|
||||
var missing = units - (long)floors.Sum();
|
||||
var order = Enumerable.Range(0, exact.Length)
|
||||
.OrderByDescending(i => exact[i] - floors[i])
|
||||
.ThenByDescending(i => positive[i])
|
||||
.ThenBy(i => i)
|
||||
.ToList();
|
||||
for (var k = 0; k < missing; k++)
|
||||
{
|
||||
floors[order[k % order.Count]] += 1;
|
||||
}
|
||||
|
||||
for (var i = 0; i < floors.Length; i++)
|
||||
{
|
||||
result[i] = floors[i] * unit;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Short spoken date in the user's time zone: <c>Oggi 06:10</c>, <c>Ieri 21:58</c>, <c>mar 6 ott</c>.</summary>
|
||||
public static string ShortDate(DateTimeOffset moment, DateTimeOffset now, TimeZoneInfo zone, bool withTime = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var local = TimeZoneInfo.ConvertTime(moment, zone);
|
||||
var today = TimeZoneInfo.ConvertTime(now, zone).Date;
|
||||
var time = local.ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||
if (local.Date == today)
|
||||
{
|
||||
return withTime ? "Oggi " + time : "Oggi";
|
||||
}
|
||||
|
||||
if (local.Date == today.AddDays(-1))
|
||||
{
|
||||
return withTime ? "Ieri " + time : "Ieri";
|
||||
}
|
||||
|
||||
if (local.Date == today.AddDays(1))
|
||||
{
|
||||
return withTime ? "Domani " + time : "Domani";
|
||||
}
|
||||
|
||||
var text = $"{_days[(int)local.DayOfWeek]} {local.Day.ToString(CultureInfo.InvariantCulture)} {_months[local.Month - 1]}";
|
||||
if (local.Year != today.Year)
|
||||
{
|
||||
text += " " + local.Year.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>Full date for the top bar: <c>Venerdì 9 ottobre 2026, ore 08:21</c>.</summary>
|
||||
public static string LongDateTime(DateTimeOffset moment, TimeZoneInfo zone)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var local = TimeZoneInfo.ConvertTime(moment, zone);
|
||||
var day = _daysLong[(int)local.DayOfWeek];
|
||||
return string.Create(CultureInfo.InvariantCulture,
|
||||
$"{char.ToUpperInvariant(day[0])}{day[1..]} {local.Day} {_monthsLong[local.Month - 1]} {local.Year}, ore {local:HH:mm}");
|
||||
}
|
||||
|
||||
/// <summary>A date without time: <c>12 agosto 2026</c>.</summary>
|
||||
public static string LongDate(DateOnly date) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{date.Day} {_monthsLong[date.Month - 1]} {date.Year}");
|
||||
|
||||
/// <summary>How long ago, in words: <c>4 secondi fa</c>, <c>3 minuti fa</c>.</summary>
|
||||
public static string Ago(TimeSpan elapsed)
|
||||
{
|
||||
if (elapsed < TimeSpan.Zero)
|
||||
{
|
||||
elapsed = TimeSpan.Zero;
|
||||
}
|
||||
|
||||
static string Unit(long n, string one, string many) =>
|
||||
n.ToString(CultureInfo.InvariantCulture) + " " + (n == 1 ? one : many) + " fa";
|
||||
|
||||
return elapsed.TotalSeconds < 60 ? Unit((long)elapsed.TotalSeconds, "secondo", "secondi")
|
||||
: elapsed.TotalMinutes < 60 ? Unit((long)elapsed.TotalMinutes, "minuto", "minuti")
|
||||
: elapsed.TotalHours < 24 ? Unit((long)elapsed.TotalHours, "ora", "ore")
|
||||
: Unit((long)elapsed.TotalDays, "giorno", "giorni");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CSV export (SPEC 13.3): semicolon separator, decimal comma, UTF-8 with BOM, Italian headers.
|
||||
/// Decimals are written without thousands separators so spreadsheets read them as numbers.
|
||||
/// </summary>
|
||||
public static byte[] Csv(IReadOnlyList<string> headers, IEnumerable<IReadOnlyList<object?>> rows)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(headers);
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var text = new StringBuilder();
|
||||
text.AppendJoin(';', headers.Select(CsvField)).Append("\r\n");
|
||||
foreach (var row in rows)
|
||||
{
|
||||
text.AppendJoin(';', row.Select(cell => CsvField(CsvValue(cell)))).Append("\r\n");
|
||||
}
|
||||
|
||||
var preamble = Encoding.UTF8.GetPreamble();
|
||||
var body = Encoding.UTF8.GetBytes(text.ToString());
|
||||
return [.. preamble, .. body];
|
||||
}
|
||||
|
||||
private static string CsvValue(object? cell) => cell switch
|
||||
{
|
||||
null => "",
|
||||
decimal d => d.ToString(CultureInfo.InvariantCulture).Replace('.', ','),
|
||||
double f => f.ToString("R", CultureInfo.InvariantCulture).Replace('.', ','),
|
||||
int or long => Convert.ToString(cell, CultureInfo.InvariantCulture)!,
|
||||
DateOnly date => date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
|
||||
DateTimeOffset moment => moment.ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture),
|
||||
_ => Convert.ToString(cell, CultureInfo.InvariantCulture) ?? "",
|
||||
};
|
||||
|
||||
private static string CsvField(string value) =>
|
||||
value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>Surrogate keys (SPEC 5.4): UUID version 7, ordered by creation time.</summary>
|
||||
public static class Ids
|
||||
{
|
||||
/// <summary>A new UUIDv7 whose time part comes from the injected clock, so ids follow simulated time too.</summary>
|
||||
public static Guid NewId(IClock clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
return Guid.CreateVersion7(clock.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>A random token for sessions and fingerprints, URL-safe base64 of 32 bytes.</summary>
|
||||
public static string NewToken(int bytes = 32)
|
||||
{
|
||||
var buffer = RandomNumberGenerator.GetBytes(bytes);
|
||||
return Convert.ToBase64String(buffer).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Removes keys, signatures, passwords and authentication headers from text before it is written to a log
|
||||
/// (trap 17, SPEC 15.4). Two layers: known secret values registered at runtime, and patterns for the
|
||||
/// shapes secrets take in headers, URLs and key=value pairs.
|
||||
/// </summary>
|
||||
public static partial class Redactor
|
||||
{
|
||||
public const string Mask = "***";
|
||||
|
||||
private static readonly Lock _gate = new();
|
||||
private static string[] _known = [];
|
||||
|
||||
/// <summary>Registers a secret value (a key read from the environment, a password) so it is masked wherever it appears.</summary>
|
||||
public static void Register(string? secret)
|
||||
{
|
||||
// Very short values would mask ordinary words; secrets that short are rejected elsewhere anyway.
|
||||
if (string.IsNullOrEmpty(secret) || secret.Length < 6)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_known.Contains(secret, StringComparer.Ordinal))
|
||||
{
|
||||
_known = [.. _known.Append(secret).OrderByDescending(s => s.Length)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static string Redact(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return text ?? "";
|
||||
}
|
||||
|
||||
foreach (var secret in _known)
|
||||
{
|
||||
text = text.Replace(secret, Mask, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
text = SensitiveHeader().Replace(text, m => m.Groups["name"].Value + m.Groups["sep"].Value + Mask);
|
||||
text = Bearer().Replace(text, m => m.Groups["scheme"].Value + " " + Mask);
|
||||
text = SensitivePair().Replace(text, m => m.Groups["name"].Value + m.Groups["sep"].Value + Mask);
|
||||
text = UrlCredentials().Replace(text, m => m.Groups["scheme"].Value + Mask + "@");
|
||||
text = TelegramToken().Replace(text, Mask);
|
||||
return text;
|
||||
}
|
||||
|
||||
// Broker authentication headers (Alpaca, OKX) and the standard ones.
|
||||
[GeneratedRegex(@"(?<name>\b(?:APCA-API-KEY-ID|APCA-API-SECRET-KEY|OK-ACCESS-KEY|OK-ACCESS-SIGN|OK-ACCESS-PASSPHRASE|Authorization|Proxy-Authorization|Cookie|Set-Cookie|X-Api-Key)\b)(?<sep>\s*[:=]\s*)[^\r\n]+", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex SensitiveHeader();
|
||||
|
||||
[GeneratedRegex(@"(?<scheme>\b(?:Bearer|Basic|token))\s+[A-Za-z0-9\-._~+/]{8,}=*", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex Bearer();
|
||||
|
||||
// key=value, "key": "value", key: value for names that carry secrets.
|
||||
[GeneratedRegex(@"(?<name>[""']?[A-Za-z0-9_\-]*(?:password|passwd|secret|token|api[_-]?key|apikey|passphrase|signature|sign|private[_-]?key)[""']?)(?<sep>\s*[:=]\s*[""']?)[^\s""'&,;}]+", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex SensitivePair();
|
||||
|
||||
// Credentials inside connection URLs: postgres://user:password@host.
|
||||
[GeneratedRegex(@"(?<scheme>\b[a-z][a-z0-9+.\-]*://)[^\s/@:]+:[^\s/@]+@", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex UrlCredentials();
|
||||
|
||||
[GeneratedRegex(@"\d{8,10}:[A-Za-z0-9_\-]{35}\b")]
|
||||
private static partial Regex TelegramToken();
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>A trading session as the broker's calendar gives it (SPEC 5.5): early closes included.</summary>
|
||||
public sealed record MarketSession(DateOnly Date, DateTimeOffset OpenUtc, DateTimeOffset CloseUtc);
|
||||
|
||||
/// <summary>
|
||||
/// Market calendar. Market times are never derived from Italian time: US and European daylight saving
|
||||
/// change in different weeks (trap 2). The real calendar comes from the broker in phase 2.
|
||||
/// </summary>
|
||||
public interface IMarketCalendar
|
||||
{
|
||||
/// <summary>The session of the exchange's local <paramref name="day"/>, or null when the market is closed.</summary>
|
||||
MarketSession? SessionOn(DateOnly day);
|
||||
}
|
||||
|
||||
public enum MarketAnchor
|
||||
{
|
||||
Open,
|
||||
Close,
|
||||
}
|
||||
|
||||
/// <summary>When a job runs. <see cref="NextAfter"/> is pure: it depends only on its argument.</summary>
|
||||
public abstract record Schedule
|
||||
{
|
||||
/// <summary>The first run strictly after <paramref name="afterUtc"/>, or null if there is none in sight.</summary>
|
||||
public abstract DateTimeOffset? NextAfter(DateTimeOffset afterUtc);
|
||||
|
||||
/// <summary>Every day at a wall-clock time in a time zone, e.g. 03:30 Europe/Rome or 00:05 UTC.</summary>
|
||||
public static Schedule Daily(TimeOnly time, TimeZoneInfo zone) => new DailySchedule(time, zone);
|
||||
|
||||
/// <summary>At fixed intervals from midnight UTC, e.g. every 5 minutes.</summary>
|
||||
public static Schedule Every(TimeSpan interval) => new IntervalSchedule(interval);
|
||||
|
||||
/// <summary>Relative to the open or close of each trading session, e.g. 5 minutes after the open.</summary>
|
||||
public static Schedule Market(MarketAnchor anchor, TimeSpan offset, IMarketCalendar calendar) =>
|
||||
new MarketSchedule(anchor, offset, calendar);
|
||||
}
|
||||
|
||||
internal sealed record DailySchedule(TimeOnly Time, TimeZoneInfo Zone) : Schedule
|
||||
{
|
||||
public override DateTimeOffset? NextAfter(DateTimeOffset afterUtc)
|
||||
{
|
||||
var startDay = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(afterUtc, Zone).DateTime).AddDays(-1);
|
||||
for (var day = startDay; day <= startDay.AddDays(3); day = day.AddDays(1))
|
||||
{
|
||||
var candidate = ToUtc(day.ToDateTime(Time));
|
||||
if (candidate > afterUtc)
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// A time skipped by daylight saving moves forward by the gap; a repeated one takes its first occurrence.
|
||||
private DateTimeOffset ToUtc(DateTime local)
|
||||
{
|
||||
local = DateTime.SpecifyKind(local, DateTimeKind.Unspecified);
|
||||
while (Zone.IsInvalidTime(local))
|
||||
{
|
||||
local = local.AddMinutes(1);
|
||||
}
|
||||
|
||||
var offset = Zone.IsAmbiguousTime(local) ? Zone.GetAmbiguousTimeOffsets(local).Max() : Zone.GetUtcOffset(local);
|
||||
return new DateTimeOffset(local, offset).ToUniversalTime();
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record IntervalSchedule(TimeSpan Interval) : Schedule
|
||||
{
|
||||
public override DateTimeOffset? NextAfter(DateTimeOffset afterUtc)
|
||||
{
|
||||
if (Interval <= TimeSpan.Zero)
|
||||
{
|
||||
throw new InvalidOperationException("The interval must be positive.");
|
||||
}
|
||||
|
||||
var ticks = afterUtc.UtcTicks;
|
||||
var next = (ticks / Interval.Ticks + 1) * Interval.Ticks;
|
||||
return new DateTimeOffset(next, TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record MarketSchedule(MarketAnchor Anchor, TimeSpan Offset, IMarketCalendar Calendar) : Schedule
|
||||
{
|
||||
public override DateTimeOffset? NextAfter(DateTimeOffset afterUtc)
|
||||
{
|
||||
// Sessions are looked up by exchange date; two days of margin cover any offset and time zone.
|
||||
var first = DateOnly.FromDateTime(afterUtc.UtcDateTime).AddDays(-2);
|
||||
for (var day = first; day <= first.AddDays(16); day = day.AddDays(1))
|
||||
{
|
||||
var session = Calendar.SessionOn(day);
|
||||
if (session is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var at = (Anchor == MarketAnchor.Open ? session.OpenUtc : session.CloseUtc) + Offset;
|
||||
if (at > afterUtc)
|
||||
{
|
||||
return at;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A job registered with the <see cref="Scheduler"/>.</summary>
|
||||
public sealed record ScheduledJob(string Name, string Description, Schedule Schedule, Func<CancellationToken, Task> Run)
|
||||
{
|
||||
/// <summary>
|
||||
/// How late a run may start. After a sleep of the computer or a long pause, a run later than this is
|
||||
/// skipped and reported instead of executed blindly (trap 21, SPEC 5.6).
|
||||
/// </summary>
|
||||
public TimeSpan MaxLateness { get; init; } = TimeSpan.FromMinutes(15);
|
||||
}
|
||||
|
||||
public enum JobOutcome
|
||||
{
|
||||
Completed,
|
||||
Failed,
|
||||
Skipped,
|
||||
}
|
||||
|
||||
/// <summary>Published on the bus after every run, skip or failure.</summary>
|
||||
public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset StartedUtc, DateTimeOffset FinishedUtc, JobOutcome Outcome, string? Error);
|
||||
|
||||
/// <summary>A run coming up, for "Prossime mosse" and the jobs list.</summary>
|
||||
public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc);
|
||||
|
||||
/// <summary>
|
||||
/// Runs jobs at fixed times, at intervals, or relative to market open and close (SPEC 5.5).
|
||||
/// All waiting goes through <see cref="IClock"/>, so tests drive it with a manual clock.
|
||||
/// </summary>
|
||||
public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Scheduler>? logger = null)
|
||||
{
|
||||
private readonly ILogger _logger = logger ?? NullLogger<Scheduler>.Instance;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<string, (ScheduledJob Job, DateTimeOffset? Due)> _jobs = new(StringComparer.Ordinal);
|
||||
private TaskCompletionSource _changed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
/// <summary>Moment of the last loop iteration; the health check uses it to see the loop is alive.</summary>
|
||||
public DateTimeOffset? LastBeatUtc { get; private set; }
|
||||
|
||||
public void Add(ScheduledJob job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
lock (_gate)
|
||||
{
|
||||
_jobs[job.Name] = (job, job.Schedule.NextAfter(clock.UtcNow));
|
||||
_changed.TrySetResult();
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<UpcomingRun> Upcoming(int count = 10)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _jobs.Values.Where(j => j.Due is not null)
|
||||
.OrderBy(j => j.Due)
|
||||
.Take(count)
|
||||
.Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
LastBeatUtc = clock.UtcNow;
|
||||
DateTimeOffset? next;
|
||||
Task changed;
|
||||
lock (_gate)
|
||||
{
|
||||
next = _jobs.Values.Where(j => j.Due is not null).Select(j => j.Due).Min();
|
||||
changed = _changed.Task;
|
||||
}
|
||||
|
||||
// Wake at the next due time, when a job is added, or at least every minute for the heartbeat.
|
||||
var wakeAt = next is { } due && due < clock.UtcNow.AddMinutes(1) ? due : clock.UtcNow.AddMinutes(1);
|
||||
using (var wakeCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
|
||||
{
|
||||
var waiting = clock.WaitUntilAsync(wakeAt, wakeCancel.Token);
|
||||
await Task.WhenAny(waiting, changed).ConfigureAwait(false);
|
||||
await wakeCancel.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await waiting.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// A new job arrived: recompute.
|
||||
}
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_changed.Task.IsCompleted)
|
||||
{
|
||||
_changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
|
||||
await RunDueAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs every job whose time has come, once, and schedules its next run.</summary>
|
||||
public async Task RunDueAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
List<(ScheduledJob Job, DateTimeOffset Due)> due;
|
||||
lock (_gate)
|
||||
{
|
||||
due = _jobs.Values.Where(j => j.Due is { } d && d <= now).Select(j => (j.Job, j.Due!.Value)).OrderBy(j => j.Value).ToList();
|
||||
foreach (var (job, _) in due)
|
||||
{
|
||||
_jobs[job.Name] = (job, job.Schedule.NextAfter(now));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (job, dueAt) in due)
|
||||
{
|
||||
var started = clock.UtcNow;
|
||||
if (started - dueAt > job.MaxLateness)
|
||||
{
|
||||
LogSkipped(_logger, job.Name, dueAt);
|
||||
bus.Publish(new JobRun(job.Name, dueAt, started, started, JobOutcome.Skipped, "Orario superato di troppo: il lavoro non è stato eseguito."));
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await job.Run(cancellationToken).ConfigureAwait(false);
|
||||
bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Completed, null));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
LogFailed(_logger, ex, job.Name);
|
||||
bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Failed, ex.Message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Job {Job} skipped: it was due at {Due} and is too late to run")]
|
||||
private static partial void LogSkipped(ILogger logger, string job, DateTimeOffset due);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Job {Job} failed")]
|
||||
private static partial void LogFailed(ILogger logger, Exception exception, string job);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Anubis.Db;
|
||||
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>Whether a secret is set and where it comes from. Never the value (SPEC 13.5, 15.4).</summary>
|
||||
public sealed record SecretStatus(string Name, bool IsSet, bool FromEnvironment, DateTimeOffset? UpdatedAt);
|
||||
|
||||
/// <summary>
|
||||
/// Secrets encrypted in the database with AES-GCM under the installation's secret key (SPEC 15.4). The name is
|
||||
/// bound to the ciphertext as associated data, so a value cannot be moved under another name. Values never go
|
||||
/// to logs or API answers: the store registers them with the <see cref="Redactor"/> as soon as they are read.
|
||||
/// A key from the environment wins over the saved one (SPEC 15.1).
|
||||
/// </summary>
|
||||
public sealed class SecretStore(Database db, IClock clock, byte[] key, IReadOnlyDictionary<string, string>? environmentKeys = null)
|
||||
{
|
||||
private const int NonceSize = 12;
|
||||
private const int TagSize = 16;
|
||||
|
||||
private readonly IReadOnlyDictionary<string, string> _environment = environmentKeys ?? new Dictionary<string, string>();
|
||||
|
||||
public async Task SetAsync(string name, string value, string changedBy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(name);
|
||||
ArgumentException.ThrowIfNullOrEmpty(value);
|
||||
if (_environment.ContainsKey(name))
|
||||
{
|
||||
throw new ReadOnlySettingException("secret:" + name, "variabile d'ambiente " + name);
|
||||
}
|
||||
|
||||
Redactor.Register(value);
|
||||
var sealedValue = Seal(name, value);
|
||||
var now = clock.UtcNow;
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
var exists = await s.CountAsync("SELECT COUNT(*) FROM secrets WHERE name = @n", ("n", name)).ConfigureAwait(false) > 0;
|
||||
if (exists)
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE secrets SET ciphertext = @c, updated_at = @t WHERE name = @n", cancellationToken, ("n", name), ("c", sealedValue), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO secrets (id, name, ciphertext, created_at, updated_at) VALUES (@id, @n, @c, @t, @t)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("n", name), ("c", sealedValue), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Log(s, name, exists ? "impostato" : "non impostato", "impostato", changedBy, now, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveAsync(string name, string changedBy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
return await db.WriteAsync(async s =>
|
||||
{
|
||||
var removed = await s.ExecuteAsync("DELETE FROM secrets WHERE name = @n", cancellationToken, ("n", name)).ConfigureAwait(false) > 0;
|
||||
if (removed)
|
||||
{
|
||||
await Log(s, name, "impostato", "non impostato", changedBy, now, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The plain value, for the code that needs it (adapters). Never pass it to the interface.</summary>
|
||||
public async Task<string?> RevealAsync(string name, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_environment.TryGetValue(name, out var fromEnvironment))
|
||||
{
|
||||
return fromEnvironment;
|
||||
}
|
||||
|
||||
var stored = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT ciphertext FROM secrets WHERE name = @n", r => r.Bytes("ciphertext"), ("n", name)), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (stored is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var value = Open(name, stored);
|
||||
Redactor.Register(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
public async Task<SecretStatus> StatusAsync(string name, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_environment.ContainsKey(name))
|
||||
{
|
||||
return new SecretStatus(name, true, true, null);
|
||||
}
|
||||
|
||||
var updated = await db.ReadAsync(s => s.QueryAsync("SELECT updated_at FROM secrets WHERE name = @n", r => r.Moment("updated_at"), ("n", name)), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return new SecretStatus(name, updated.Count > 0, false, updated.Count > 0 ? updated[0] : null);
|
||||
}
|
||||
|
||||
internal byte[] Seal(string name, string value)
|
||||
{
|
||||
var nonce = RandomNumberGenerator.GetBytes(NonceSize);
|
||||
var plain = Encoding.UTF8.GetBytes(value);
|
||||
var cipher = new byte[plain.Length];
|
||||
var tag = new byte[TagSize];
|
||||
using var aes = new AesGcm(key, TagSize);
|
||||
aes.Encrypt(nonce, plain, cipher, tag, Encoding.UTF8.GetBytes(name));
|
||||
return [.. nonce, .. tag, .. cipher];
|
||||
}
|
||||
|
||||
internal string Open(string name, byte[] stored)
|
||||
{
|
||||
if (stored.Length < NonceSize + TagSize)
|
||||
{
|
||||
throw new CryptographicException("Stored secret is too short.");
|
||||
}
|
||||
|
||||
var plain = new byte[stored.Length - NonceSize - TagSize];
|
||||
using var aes = new AesGcm(key, TagSize);
|
||||
try
|
||||
{
|
||||
aes.Decrypt(stored.AsSpan(0, NonceSize), stored.AsSpan(NonceSize + TagSize), stored.AsSpan(NonceSize, TagSize), plain, Encoding.UTF8.GetBytes(name));
|
||||
}
|
||||
catch (AuthenticationTagMismatchException ex)
|
||||
{
|
||||
throw new CryptographicException("Il segreto non si decifra: la chiave dei segreti è cambiata. Reinserisci il valore dalle Impostazioni.", ex);
|
||||
}
|
||||
|
||||
return Encoding.UTF8.GetString(plain);
|
||||
}
|
||||
|
||||
private Task<int> Log(DbSession s, string name, string old, string updated, string changedBy, DateTimeOffset now, CancellationToken cancellationToken) =>
|
||||
s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("k", "secret:" + name), ("o", new DbJson(JsonSerializer.Serialize(old))), ("n", new DbJson(JsonSerializer.Serialize(updated))),
|
||||
("by", changedBy), ("t", now));
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Text.Json;
|
||||
using Anubis.Db;
|
||||
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>A setting the interface may change: key, default and allowed values.</summary>
|
||||
public sealed record SettingDefinition(string Key, string Label, string Default, IReadOnlyList<string>? Allowed = null);
|
||||
|
||||
/// <summary>A value fixed by the startup configuration: it wins and is shown read-only with where to change it (SPEC 13.5).</summary>
|
||||
public sealed record StartupOverride(string Value, string Source);
|
||||
|
||||
public sealed record SettingValue(string Key, string Value, bool ReadOnly, string? Source);
|
||||
|
||||
public sealed record SettingChange(string Key, string? OldValue, string? NewValue, string ChangedBy, DateTimeOffset At);
|
||||
|
||||
/// <summary>Published on the bus after a change, so open pages update.</summary>
|
||||
public sealed record SettingChanged(string Key, string Value);
|
||||
|
||||
public sealed class ReadOnlySettingException(string key, string source)
|
||||
: InvalidOperationException($"Questa impostazione arriva dalla configurazione d'avvio e si cambia lì: {source}.")
|
||||
{
|
||||
public string Key { get; } = key;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings saved in the database with their change log (SPEC 13.5, 15.4): every change records when, the old
|
||||
/// and the new value, and who. Values of the startup configuration are read-only here.
|
||||
/// </summary>
|
||||
public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IReadOnlyDictionary<string, StartupOverride>? overrides = null)
|
||||
{
|
||||
public static readonly SettingDefinition Theme = new("appearance.theme", "Tema", "auto", ["auto", "light", "dark"]);
|
||||
public static readonly SettingDefinition Currency = new("appearance.currency", "Valuta", "EUR", ["EUR", "USD"]);
|
||||
|
||||
/// <summary>Bot state behind the top bar buttons: active, paused (no new entries) or stopped (kill switch, SPEC 9.3).</summary>
|
||||
public static readonly SettingDefinition BotState = new("bot.state", "Stato del bot", "active", ["active", "paused", "stopped"]);
|
||||
|
||||
public static readonly IReadOnlyList<SettingDefinition> All = [Theme, Currency, BotState];
|
||||
|
||||
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
|
||||
|
||||
public static SettingDefinition Definition(string key) =>
|
||||
All.FirstOrDefault(d => d.Key == key) ?? throw new ArgumentException("Impostazione sconosciuta: " + key, nameof(key));
|
||||
|
||||
public async Task<SettingValue> GetAsync(string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var definition = Definition(key);
|
||||
if (_overrides.TryGetValue(key, out var fixedValue))
|
||||
{
|
||||
return new SettingValue(key, fixedValue.Value, true, fixedValue.Source);
|
||||
}
|
||||
|
||||
var saved = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return new SettingValue(key, saved is null ? definition.Default : JsonSerializer.Deserialize<string>(saved)!, false, null);
|
||||
}
|
||||
|
||||
public async Task SetAsync(string key, string value, string changedBy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
var definition = Definition(key);
|
||||
if (_overrides.TryGetValue(key, out var fixedValue))
|
||||
{
|
||||
throw new ReadOnlySettingException(key, fixedValue.Source);
|
||||
}
|
||||
|
||||
if (definition.Allowed is { } allowed && !allowed.Contains(value, StringComparer.Ordinal))
|
||||
{
|
||||
throw new ArgumentException($"Valore non ammesso per {definition.Label}: {value}.", nameof(value));
|
||||
}
|
||||
|
||||
var now = clock.UtcNow;
|
||||
var json = new DbJson(JsonSerializer.Serialize(value));
|
||||
var changed = await db.WriteAsync(async s =>
|
||||
{
|
||||
var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false);
|
||||
if (old == json.Text)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (old is null)
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("k", key), ("v", json), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE config SET value = @v, updated_at = @t WHERE key = @k", cancellationToken,
|
||||
("k", key), ("v", json), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var previous = old is null ? new DbJson(JsonSerializer.Serialize(definition.Default)) : new DbJson(old);
|
||||
await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("k", key), ("o", previous), ("n", json), ("by", changedBy), ("t", now)).ConfigureAwait(false);
|
||||
return true;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (changed)
|
||||
{
|
||||
bus.Publish(new SettingChanged(key, value));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The change log, newest first. Secret values never appear: their entries say only "impostato" or "tolto".</summary>
|
||||
public Task<List<SettingChange>> HistoryAsync(string? key = null, int limit = 100, CancellationToken cancellationToken = default) =>
|
||||
db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT key, old_value, new_value, changed_by, created_at FROM config_history" + (key is null ? "" : " WHERE key = @k") + " ORDER BY created_at DESC, id DESC LIMIT @n",
|
||||
r => new SettingChange(r.Text("key"), Decode(r.TextOrNull("old_value")), Decode(r.TextOrNull("new_value")), r.Text("changed_by"), r.Moment("created_at")),
|
||||
key is null ? [("n", limit)] : [("k", key), ("n", limit)]), cancellationToken);
|
||||
|
||||
private static string? Decode(string? json) => json is null ? null : JsonSerializer.Deserialize<string>(json);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
using System.Data.Common;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Anubis.Core;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Db;
|
||||
|
||||
/// <summary>What an archive contains: written as index.json next to one JSONL file per table.</summary>
|
||||
public sealed record ArchiveIndex(
|
||||
string Format,
|
||||
int FormatVersion,
|
||||
int SchemaVersion,
|
||||
DateTimeOffset CreatedAt,
|
||||
string SourceEngine,
|
||||
IReadOnlyList<ArchiveTable> Tables,
|
||||
IReadOnlyDictionary<string, string> AccountingTotals);
|
||||
|
||||
public sealed record ArchiveTable(string Name, string File, long Count);
|
||||
|
||||
/// <summary>
|
||||
/// Engine-independent export and import (SPEC 5.4): <c>anubis db export</c> and <c>anubis db import</c>.
|
||||
/// Used by nightly backups, restores and moves between PostgreSQL and SQLite.
|
||||
/// </summary>
|
||||
public static class Archive
|
||||
{
|
||||
public const string FormatName = "anubis-archive";
|
||||
public const string IndexFile = "index.json";
|
||||
|
||||
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web) { WriteIndented = true };
|
||||
|
||||
/// <summary>
|
||||
/// Writes every table in a single read-only transaction, so the archive is a picture of one instant.
|
||||
/// Money is written as exact decimal text, moments as UTC ISO text, identifiers as text.
|
||||
/// </summary>
|
||||
public static async Task<ArchiveIndex> ExportAsync(Database db, string folder, IClock clock, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
Directory.CreateDirectory(folder);
|
||||
if (Directory.EnumerateFileSystemEntries(folder).Any())
|
||||
{
|
||||
throw new IOException($"La cartella {folder} non è vuota: un archivio va scritto in una cartella nuova.");
|
||||
}
|
||||
|
||||
var index = await db.ReadAsync(async s =>
|
||||
{
|
||||
var version = await CurrentVersionAsync(s).ConfigureAwait(false);
|
||||
var tables = new List<ArchiveTable>();
|
||||
var totals = new Totals();
|
||||
|
||||
// The tables of the database's own version: a backup before a migration reads the old schema.
|
||||
foreach (var table in Schema.Parse(Migrations.All.Take(version)))
|
||||
{
|
||||
var file = table.Name + ".jsonl";
|
||||
long count = 0;
|
||||
await using var stream = new FileStream(Path.Combine(folder, file), FileMode.CreateNew, FileAccess.Write);
|
||||
await using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\n" };
|
||||
var columns = string.Join(", ", table.Columns.Select(c => c.Name));
|
||||
await s.ForEachAsync($"SELECT {columns} FROM {table.Name} ORDER BY id", async reader =>
|
||||
{
|
||||
var row = ReadRow(reader, table, s.Engine);
|
||||
totals.Add(table, row);
|
||||
await writer.WriteLineAsync(row.ToJsonString()).ConfigureAwait(false);
|
||||
count++;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
tables.Add(new ArchiveTable(table.Name, file, count));
|
||||
}
|
||||
|
||||
return new ArchiveIndex(FormatName, 1, version, clock.UtcNow, s.Engine.ToString().ToLowerInvariant(), tables, totals.ToDictionary());
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await File.WriteAllTextAsync(Path.Combine(folder, IndexFile), JsonSerializer.Serialize(index, _json), cancellationToken).ConfigureAwait(false);
|
||||
return index;
|
||||
}
|
||||
|
||||
public static async Task<ArchiveIndex> ReadIndexAsync(string folder, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var path = Path.Combine(folder, IndexFile);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
throw new FileNotFoundException("Questa cartella non contiene un archivio di Anubis (manca index.json).", path);
|
||||
}
|
||||
|
||||
var index = JsonSerializer.Deserialize<ArchiveIndex>(await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false), _json)
|
||||
?? throw new InvalidDataException("index.json vuoto.");
|
||||
if (index.Format != FormatName || index.FormatVersion != 1)
|
||||
{
|
||||
throw new InvalidDataException("Formato d'archivio sconosciuto.");
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads an archive into an empty database: creates the schema of the archive's version, inserts every row,
|
||||
/// checks counts and accounting totals against the index, then brings the schema to the latest version.
|
||||
/// Anything that does not match aborts the import and leaves nothing behind.
|
||||
/// </summary>
|
||||
public static async Task<ArchiveIndex> ImportAsync(Database db, string folder, IClock clock, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var index = await ReadIndexAsync(folder, cancellationToken).ConfigureAwait(false);
|
||||
if (index.SchemaVersion > Migrations.Latest)
|
||||
{
|
||||
throw new SchemaException($"L'archivio è alla versione {index.SchemaVersion} dello schema, più recente di questa versione di Anubis.");
|
||||
}
|
||||
|
||||
var status = await Migrations.StatusAsync(db, cancellationToken).ConfigureAwait(false);
|
||||
if (!status.IsEmpty && !await IsEmptyAsync(db, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
throw new InvalidOperationException("Il database di arrivo non è vuoto: l'importazione si fa solo in un database vuoto.");
|
||||
}
|
||||
|
||||
if (status.Current > index.SchemaVersion)
|
||||
{
|
||||
throw new InvalidOperationException("Il database di arrivo ha già uno schema più recente dell'archivio: usa un database vuoto.");
|
||||
}
|
||||
|
||||
await Migrations.MigrateAsync(db, clock, null, cancellationToken, upTo: index.SchemaVersion).ConfigureAwait(false);
|
||||
var tables = Schema.Parse(Migrations.All.Take(index.SchemaVersion));
|
||||
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
foreach (var entry in index.Tables)
|
||||
{
|
||||
var table = tables.FirstOrDefault(t => t.Name == entry.Name)
|
||||
?? throw new InvalidDataException($"L'archivio contiene la tabella sconosciuta {entry.Name}.");
|
||||
var sql = $"INSERT INTO {table.Name} ({string.Join(", ", table.Columns.Select(c => c.Name))}) VALUES ({string.Join(", ", table.Columns.Select(c => "@" + c.Name))})";
|
||||
long count = 0;
|
||||
using var reader = new StreamReader(Path.Combine(folder, entry.File), Encoding.UTF8);
|
||||
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
|
||||
{
|
||||
if (line.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var row = JsonNode.Parse(line)!.AsObject();
|
||||
var args = table.Columns.Select(c => (c.Name, FromJson(row[c.Name], c))).ToArray();
|
||||
await s.ExecuteAsync(sql, cancellationToken, args).ConfigureAwait(false);
|
||||
count++;
|
||||
}
|
||||
|
||||
if (count != entry.Count)
|
||||
{
|
||||
throw new InvalidDataException($"La tabella {entry.Name} ha {count} righe nel file e {entry.Count} nell'indice: archivio incompleto.");
|
||||
}
|
||||
}
|
||||
|
||||
// Re-read what was written, in the same transaction, and compare with the index.
|
||||
var totals = new Totals();
|
||||
foreach (var table in tables)
|
||||
{
|
||||
var columns = string.Join(", ", table.Columns.Select(c => c.Name));
|
||||
long count = 0;
|
||||
await s.ForEachAsync($"SELECT {columns} FROM {table.Name}", reader =>
|
||||
{
|
||||
totals.Add(table, ReadRow(reader, table, s.Engine));
|
||||
count++;
|
||||
return Task.CompletedTask;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
var expected = index.Tables.FirstOrDefault(t => t.Name == table.Name)?.Count ?? 0;
|
||||
if (count != expected)
|
||||
{
|
||||
throw new InvalidDataException($"Dopo l'importazione {table.Name} ha {count} righe invece di {expected}.");
|
||||
}
|
||||
}
|
||||
|
||||
var written = totals.ToDictionary();
|
||||
foreach (var (key, value) in index.AccountingTotals)
|
||||
{
|
||||
if (!written.TryGetValue(key, out var actual) || actual != value)
|
||||
{
|
||||
throw new InvalidDataException($"Il totale {key} non coincide: {value} nell'archivio, {actual ?? "nessuno"} nel database.");
|
||||
}
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await Migrations.MigrateAsync(db, clock, null, cancellationToken).ConfigureAwait(false);
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>Row counts of every table, for comparisons in tests and on the System page.</summary>
|
||||
public static async Task<Dictionary<string, long>> CountsAsync(Database db, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
return await db.ReadAsync(async s =>
|
||||
{
|
||||
var counts = new Dictionary<string, long>(StringComparer.Ordinal);
|
||||
foreach (var table in Schema.Tables)
|
||||
{
|
||||
counts[table.Name] = await s.CountAsync($"SELECT COUNT(*) FROM {table.Name}").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return counts;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Accounting totals computed in C#, never in SQL, so both engines give the same result (SPEC 5.4).</summary>
|
||||
public static async Task<IReadOnlyDictionary<string, string>> AccountingTotalsAsync(Database db, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
return await db.ReadAsync(async s =>
|
||||
{
|
||||
var totals = new Totals();
|
||||
foreach (var table in Schema.Tables.Where(t => Schema.AccountingTables.Contains(t.Name)))
|
||||
{
|
||||
await s.ForEachAsync($"SELECT {string.Join(", ", table.Columns.Select(c => c.Name))} FROM {table.Name}", reader =>
|
||||
{
|
||||
totals.Add(table, ReadRow(reader, table, s.Engine));
|
||||
return Task.CompletedTask;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (IReadOnlyDictionary<string, string>)totals.ToDictionary();
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task<bool> IsEmptyAsync(Database db, CancellationToken cancellationToken)
|
||||
{
|
||||
var counts = await CountsAsync(db, cancellationToken).ConfigureAwait(false);
|
||||
return counts.Values.All(c => c == 0);
|
||||
}
|
||||
|
||||
private static async Task<int> CurrentVersionAsync(DbSession s) =>
|
||||
await Migrations.TableExistsAsync(s, Migrations.VersionTable).ConfigureAwait(false)
|
||||
? (int)await s.CountAsync($"SELECT COALESCE(MAX(version), 0) FROM {Migrations.VersionTable}").ConfigureAwait(false)
|
||||
: 0;
|
||||
|
||||
private static JsonObject ReadRow(DbDataReader reader, Table table, DbEngine engine)
|
||||
{
|
||||
var row = new DbRow(reader, engine);
|
||||
var json = new JsonObject();
|
||||
foreach (var column in table.Columns)
|
||||
{
|
||||
json[column.Name] = row.IsNull(column.Name) ? null : column.Kind switch
|
||||
{
|
||||
ColumnKind.Money => JsonValue.Create(DbValues.MoneyText(row.Money(column.Name))),
|
||||
ColumnKind.Uuid => JsonValue.Create(row.Id(column.Name).ToString("D")),
|
||||
ColumnKind.Moment => JsonValue.Create(DbValues.MomentText(row.Moment(column.Name))),
|
||||
ColumnKind.Json => JsonValue.Create(row.Json(column.Name).Text),
|
||||
ColumnKind.Bool => JsonValue.Create(row.Bool(column.Name)),
|
||||
ColumnKind.Bytes => JsonValue.Create(Convert.ToBase64String(row.Bytes(column.Name))),
|
||||
ColumnKind.Measure => JsonValue.Create(row.Measure(column.Name)),
|
||||
ColumnKind.Number => JsonValue.Create(row.Number(column.Name)),
|
||||
_ => JsonValue.Create(row.Text(column.Name)),
|
||||
};
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
private static object? FromJson(JsonNode? node, Column column)
|
||||
{
|
||||
if (node is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return column.Kind switch
|
||||
{
|
||||
ColumnKind.Money => DbValues.ParseMoney(node.GetValue<string>()),
|
||||
ColumnKind.Uuid => Guid.Parse(node.GetValue<string>()),
|
||||
ColumnKind.Moment => DbValues.ParseMoment(node.GetValue<string>()),
|
||||
ColumnKind.Json => new DbJson(node.GetValue<string>()),
|
||||
ColumnKind.Bool => node.GetValue<bool>(),
|
||||
ColumnKind.Bytes => Convert.FromBase64String(node.GetValue<string>()),
|
||||
ColumnKind.Measure => node.GetValue<double>(),
|
||||
ColumnKind.Number => node.GetValue<long>(),
|
||||
_ => node.GetValue<string>(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Sum of every money column of the accounting tables, as exact decimal text keyed "table.column".</summary>
|
||||
private sealed class Totals
|
||||
{
|
||||
private readonly SortedDictionary<string, decimal> _sums = new(StringComparer.Ordinal);
|
||||
|
||||
public void Add(Table table, JsonObject row)
|
||||
{
|
||||
if (!Schema.AccountingTables.Contains(table.Name))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var column in table.Columns.Where(c => c.Kind == ColumnKind.Money))
|
||||
{
|
||||
var key = table.Name + "." + column.Name;
|
||||
var value = row[column.Name] is { } node ? decimal.Parse(node.GetValue<string>(), NumberStyles.Number, CultureInfo.InvariantCulture) : 0m;
|
||||
_sums[key] = (_sums.TryGetValue(key, out var sum) ? sum : 0m) + value;
|
||||
}
|
||||
}
|
||||
|
||||
public Dictionary<string, string> ToDictionary() =>
|
||||
_sums.ToDictionary(kv => kv.Key, kv => DbValues.Normalize(kv.Value).ToString(CultureInfo.InvariantCulture), StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Core;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Db;
|
||||
|
||||
/// <summary>A backup folder in /data/backups.</summary>
|
||||
public sealed record BackupInfo(string Folder, string Name, DateTimeOffset TakenAt, string Reason, bool HasSqliteCopy);
|
||||
|
||||
/// <summary>
|
||||
/// Backups (SPEC 5.4): the engine-independent archive, plus a consistent copy of the SQLite file made with the
|
||||
/// backup API. Nightly at 03:30 Italian time, before every migration, and on request. The last 14 are kept.
|
||||
/// </summary>
|
||||
public sealed class Backups(DataDirectory data, IClock clock)
|
||||
{
|
||||
public const int Keep = 14;
|
||||
public const string ArchiveFolder = "archivio";
|
||||
public const string SqliteCopy = "anubis.sqlite3";
|
||||
|
||||
public async Task<BackupInfo> TakeAsync(Database db, string reason, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
Directory.CreateDirectory(data.Backups);
|
||||
var now = clock.UtcNow;
|
||||
var name = now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + "-" + reason;
|
||||
var folder = Path.Combine(data.Backups, name);
|
||||
for (var n = 2; Directory.Exists(folder); n++)
|
||||
{
|
||||
folder = Path.Combine(data.Backups, name + "-" + n.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
// Written under a temporary name and renamed at the end: a half-written backup never looks complete.
|
||||
var temp = folder + ".partial";
|
||||
try
|
||||
{
|
||||
await Archive.ExportAsync(db, Path.Combine(temp, ArchiveFolder), clock, cancellationToken).ConfigureAwait(false);
|
||||
if (db.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
await db.BackupSqliteFileAsync(Path.Combine(temp, SqliteCopy), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Directory.Move(temp, folder);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (Directory.Exists(temp))
|
||||
{
|
||||
Directory.Delete(temp, recursive: true);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
Prune();
|
||||
return Describe(folder)!;
|
||||
}
|
||||
|
||||
/// <summary>Backups from the newest, only complete ones.</summary>
|
||||
public IReadOnlyList<BackupInfo> List() =>
|
||||
!Directory.Exists(data.Backups)
|
||||
? []
|
||||
: Directory.EnumerateDirectories(data.Backups)
|
||||
.Where(d => !d.EndsWith(".partial", StringComparison.Ordinal))
|
||||
.Select(Describe)
|
||||
.OfType<BackupInfo>()
|
||||
.OrderByDescending(b => b.TakenAt)
|
||||
.ThenByDescending(b => b.Name, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
|
||||
private void Prune()
|
||||
{
|
||||
foreach (var old in List().Skip(Keep))
|
||||
{
|
||||
Directory.Delete(old.Folder, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static BackupInfo? Describe(string folder)
|
||||
{
|
||||
var name = Path.GetFileName(folder);
|
||||
if (name.Length < 16 || !File.Exists(Path.Combine(folder, ArchiveFolder, Archive.IndexFile))
|
||||
|| !DateTime.TryParseExact(name[..15], "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var taken))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var reason = name.Length > 16 ? name[16..] : "";
|
||||
return new BackupInfo(folder, name, new DateTimeOffset(taken, TimeSpan.Zero), reason, File.Exists(Path.Combine(folder, SqliteCopy)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Globalization;
|
||||
using Anubis.Platform;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Npgsql;
|
||||
|
||||
namespace Anubis.Db;
|
||||
|
||||
/// <summary>
|
||||
/// Access to the configured database with plain ADO.NET (ADR 0003). The same SQL runs on PostgreSQL and
|
||||
/// SQLite; values pass through <see cref="DbValues"/>. On SQLite all writes go through one writer at a time
|
||||
/// (SPEC 5.4) while reads run in parallel thanks to WAL.
|
||||
/// </summary>
|
||||
public sealed class Database : IAsyncDisposable
|
||||
{
|
||||
private readonly SemaphoreSlim _writer = new(1, 1);
|
||||
private readonly string _connectionString;
|
||||
|
||||
// SQLite once the file has been seen: the same place, but never created again.
|
||||
private readonly string? _existingConnectionString;
|
||||
private readonly NpgsqlDataSource? _postgres;
|
||||
private volatile bool _sqliteSeen;
|
||||
|
||||
private Database(DbEngine engine, string connectionString, NpgsqlDataSource? postgres, string description, string? sqlitePath = null)
|
||||
{
|
||||
Engine = engine;
|
||||
SqlitePath = sqlitePath is null ? null : Path.GetFullPath(sqlitePath);
|
||||
_connectionString = connectionString;
|
||||
if (engine == DbEngine.Sqlite)
|
||||
{
|
||||
_existingConnectionString = new SqliteConnectionStringBuilder(connectionString) { Mode = SqliteOpenMode.ReadWrite }.ToString();
|
||||
}
|
||||
|
||||
_postgres = postgres;
|
||||
Description = description;
|
||||
}
|
||||
|
||||
public DbEngine Engine { get; }
|
||||
|
||||
/// <summary>Full path of the SQLite file; null on PostgreSQL.</summary>
|
||||
public string? SqlitePath { get; }
|
||||
|
||||
/// <summary>Engine and place, without the password.</summary>
|
||||
public string Description { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Opens the configured database. With SQLite, <paramref name="allowCreate"/> false refuses to create a missing
|
||||
/// file: a data folder that already belongs to an installation never gets a new empty database by itself (trap 20).
|
||||
/// PostgreSQL databases are never created by Anubis (SPEC 15.1).
|
||||
/// </summary>
|
||||
public static Database Open(DbSettings settings, bool allowCreate = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
if (settings.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
var path = settings.SqlitePath ?? throw new InvalidOperationException("SQLite path missing.");
|
||||
var builder = new SqliteConnectionStringBuilder
|
||||
{
|
||||
DataSource = path,
|
||||
Mode = allowCreate ? SqliteOpenMode.ReadWriteCreate : SqliteOpenMode.ReadWrite,
|
||||
Pooling = true,
|
||||
ForeignKeys = true,
|
||||
DefaultTimeout = 5,
|
||||
};
|
||||
if (allowCreate)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
||||
}
|
||||
|
||||
return new Database(DbEngine.Sqlite, builder.ToString(), null, settings.Describe(), path);
|
||||
}
|
||||
|
||||
var pg = settings.Url is { } url ? new NpgsqlConnectionStringBuilder(ToKeyValue(url)) : new NpgsqlConnectionStringBuilder
|
||||
{
|
||||
Host = settings.Host,
|
||||
Port = settings.Port,
|
||||
Database = settings.Database,
|
||||
Username = settings.User,
|
||||
Password = settings.Password,
|
||||
};
|
||||
pg.Timeout = 5;
|
||||
pg.CommandTimeout = 60;
|
||||
pg.ApplicationName = "anubis";
|
||||
var dataSource = new NpgsqlDataSourceBuilder(pg.ToString()).Build();
|
||||
return new Database(DbEngine.Postgres, pg.ToString(), dataSource, settings.Describe());
|
||||
}
|
||||
|
||||
// ANUBIS_DB_URL may be a postgres:// URL or already a key=value connection string.
|
||||
private static string ToKeyValue(string url)
|
||||
{
|
||||
if (!url.StartsWith("postgres://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("postgresql://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return url;
|
||||
}
|
||||
|
||||
var uri = new Uri(url);
|
||||
var builder = new NpgsqlConnectionStringBuilder
|
||||
{
|
||||
Host = uri.Host,
|
||||
Port = uri.Port > 0 ? uri.Port : 5432,
|
||||
Database = Uri.UnescapeDataString(uri.AbsolutePath.TrimStart('/')),
|
||||
};
|
||||
var userInfo = uri.UserInfo.Split(':', 2);
|
||||
builder.Username = Uri.UnescapeDataString(userInfo[0]);
|
||||
if (userInfo.Length > 1)
|
||||
{
|
||||
builder.Password = Uri.UnescapeDataString(userInfo[1]);
|
||||
}
|
||||
|
||||
foreach (var pair in uri.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var kv = pair.Split('=', 2);
|
||||
builder[Uri.UnescapeDataString(kv[0])] = kv.Length > 1 ? Uri.UnescapeDataString(kv[1]) : "";
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
public async Task<DbConnection> OpenConnectionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_postgres is not null)
|
||||
{
|
||||
return await _postgres.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Once the file existed it must stay where the configuration says: a pooled connection would keep answering
|
||||
// from a deleted file (on Linux the inode lives on) and a new one would create an empty database (trap 20).
|
||||
if (_sqliteSeen && !File.Exists(SqlitePath))
|
||||
{
|
||||
throw new FileNotFoundException("Il file del database SQLite non c'è più: " + SqlitePath);
|
||||
}
|
||||
|
||||
// Checking first is not enough: the file can go between the check and the open, and an open allowed to create
|
||||
// would put an empty database in its place. Once seen, the open itself refuses a missing file.
|
||||
var connection = new SqliteConnection(_sqliteSeen ? _existingConnectionString : _connectionString);
|
||||
try
|
||||
{
|
||||
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
_sqliteSeen = true;
|
||||
await using var pragma = connection.CreateCommand();
|
||||
pragma.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;";
|
||||
await pragma.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
|
||||
return connection;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Checks the database answers. Throws when it does not.</summary>
|
||||
public async Task PingAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT 1";
|
||||
await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> in a read-only transaction that sees a single instant of the database.</summary>
|
||||
public async Task<T> ReadAsync<T>(Func<DbSession, Task<T>> work, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(work);
|
||||
await using var connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var transaction = Engine == DbEngine.Postgres
|
||||
? await connection.BeginTransactionAsync(IsolationLevel.RepeatableRead, cancellationToken).ConfigureAwait(false)
|
||||
: ((SqliteConnection)connection).BeginTransaction(deferred: true);
|
||||
var session = new DbSession(Engine, connection, transaction);
|
||||
if (Engine == DbEngine.Postgres)
|
||||
{
|
||||
await session.ExecuteAsync("SET TRANSACTION READ ONLY", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var result = await work(session).ConfigureAwait(false);
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> in a write transaction, committed only if it completes.</summary>
|
||||
public async Task<T> WriteAsync<T>(Func<DbSession, Task<T>> work, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(work);
|
||||
await _writer.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var transaction = Engine == DbEngine.Postgres
|
||||
? await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken).ConfigureAwait(false)
|
||||
: ((SqliteConnection)connection).BeginTransaction(deferred: false);
|
||||
var result = await work(new DbSession(Engine, connection, transaction)).ConfigureAwait(false);
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_writer.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public Task WriteAsync(Func<DbSession, Task> work, CancellationToken cancellationToken = default) =>
|
||||
WriteAsync(async s =>
|
||||
{
|
||||
await work(s).ConfigureAwait(false);
|
||||
return true;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>A consistent copy of the SQLite file through the online backup API (SPEC 5.4). Not available on PostgreSQL.</summary>
|
||||
public async Task BackupSqliteFileAsync(string destination, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Engine != DbEngine.Sqlite)
|
||||
{
|
||||
throw new InvalidOperationException("File copies exist only for SQLite.");
|
||||
}
|
||||
|
||||
await using var source = (SqliteConnection)await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var target = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = destination, Pooling = false }.ToString());
|
||||
await target.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
source.BackupDatabase(target);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_postgres is not null)
|
||||
{
|
||||
await _postgres.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
SqliteConnection.ClearPool(new SqliteConnection(_connectionString));
|
||||
SqliteConnection.ClearPool(new SqliteConnection(_existingConnectionString));
|
||||
}
|
||||
|
||||
_writer.Dispose();
|
||||
}
|
||||
|
||||
public override string ToString() => Description + " (" + Engine.ToString().ToLower(CultureInfo.InvariantCulture) + ")";
|
||||
}
|
||||
|
||||
/// <summary>One open transaction. Parameters are named <c>@name</c> on both engines.</summary>
|
||||
public sealed class DbSession(DbEngine engine, DbConnection connection, DbTransaction transaction)
|
||||
{
|
||||
public DbEngine Engine => engine;
|
||||
|
||||
public DbConnection Connection => connection;
|
||||
|
||||
public async Task<int> ExecuteAsync(string sql, CancellationToken cancellationToken = default, params (string Name, object? Value)[] args)
|
||||
{
|
||||
await using var command = Command(sql, args);
|
||||
return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public Task<int> ExecuteAsync(string sql, params (string Name, object? Value)[] args) => ExecuteAsync(sql, CancellationToken.None, args);
|
||||
|
||||
public async Task<List<T>> QueryAsync<T>(string sql, Func<DbRow, T> map, params (string Name, object? Value)[] args)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
await using var command = Command(sql, args);
|
||||
await using var reader = await command.ExecuteReaderAsync().ConfigureAwait(false);
|
||||
var result = new List<T>();
|
||||
var row = new DbRow(reader, engine);
|
||||
while (await reader.ReadAsync().ConfigureAwait(false))
|
||||
{
|
||||
result.Add(map(row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<T?> FirstOrDefaultAsync<T>(string sql, Func<DbRow, T> map, params (string Name, object? Value)[] args) =>
|
||||
(await QueryAsync(sql, map, args).ConfigureAwait(false)).FirstOrDefault();
|
||||
|
||||
public async Task<long> CountAsync(string sql, params (string Name, object? Value)[] args)
|
||||
{
|
||||
await using var command = Command(sql, args);
|
||||
var value = await command.ExecuteScalarAsync().ConfigureAwait(false);
|
||||
return Convert.ToInt64(value, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>Streams rows without loading them all, for exports.</summary>
|
||||
public async Task ForEachAsync(string sql, Func<DbDataReader, Task> onRow, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(onRow);
|
||||
await using var command = Command(sql, []);
|
||||
await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
|
||||
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await onRow(reader).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private DbCommand Command(string sql, (string Name, object? Value)[] args)
|
||||
{
|
||||
var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = sql;
|
||||
foreach (var (name, value) in args)
|
||||
{
|
||||
var parameter = command.CreateParameter();
|
||||
parameter.ParameterName = name.StartsWith('@') ? name : "@" + name;
|
||||
parameter.Value = DbValues.ToProvider(value, engine);
|
||||
if (engine == DbEngine.Postgres && value is DbJson)
|
||||
{
|
||||
((NpgsqlParameter)parameter).NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Json;
|
||||
}
|
||||
|
||||
command.Parameters.Add(parameter);
|
||||
}
|
||||
|
||||
return command;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Typed reading of the current row, the mirror of <see cref="DbValues.ToProvider"/>.</summary>
|
||||
public readonly struct DbRow(DbDataReader reader, DbEngine engine)
|
||||
{
|
||||
private int Ordinal(string column) => reader.GetOrdinal(column);
|
||||
|
||||
public bool IsNull(string column) => reader.IsDBNull(Ordinal(column));
|
||||
|
||||
public string Text(string column) => reader.GetString(Ordinal(column));
|
||||
|
||||
public string? TextOrNull(string column) => IsNull(column) ? null : Text(column);
|
||||
|
||||
public long Number(string column) => Convert.ToInt64(reader.GetValue(Ordinal(column)), CultureInfo.InvariantCulture);
|
||||
|
||||
public bool Bool(string column) => engine == DbEngine.Sqlite ? Number(column) != 0 : reader.GetBoolean(Ordinal(column));
|
||||
|
||||
public decimal Money(string column) => engine == DbEngine.Sqlite
|
||||
? DbValues.ParseMoney(reader.GetString(Ordinal(column)))
|
||||
: DbValues.Normalize(reader.GetDecimal(Ordinal(column)));
|
||||
|
||||
public decimal? MoneyOrNull(string column) => IsNull(column) ? null : Money(column);
|
||||
|
||||
public Guid Id(string column) => engine == DbEngine.Sqlite ? Guid.Parse(reader.GetString(Ordinal(column))) : reader.GetGuid(Ordinal(column));
|
||||
|
||||
public Guid? IdOrNull(string column) => IsNull(column) ? null : Id(column);
|
||||
|
||||
public DateTimeOffset Moment(string column) => engine == DbEngine.Sqlite
|
||||
? DbValues.ParseMoment(reader.GetString(Ordinal(column)))
|
||||
: new DateTimeOffset(DateTime.SpecifyKind(reader.GetDateTime(Ordinal(column)), DateTimeKind.Utc));
|
||||
|
||||
public DateTimeOffset? MomentOrNull(string column) => IsNull(column) ? null : Moment(column);
|
||||
|
||||
public DbJson Json(string column) => new(reader.GetString(Ordinal(column)));
|
||||
|
||||
public byte[] Bytes(string column) => (byte[])reader.GetValue(Ordinal(column));
|
||||
|
||||
public byte[]? BytesOrNull(string column) => IsNull(column) ? null : Bytes(column);
|
||||
|
||||
public double Measure(string column) => Convert.ToDouble(reader.GetValue(Ordinal(column)), CultureInfo.InvariantCulture);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Db;
|
||||
|
||||
/// <summary>A JSON document column (SPEC 5.4: generic JSON, no engine-specific operators). Stored as written.</summary>
|
||||
public readonly record struct DbJson(string Text);
|
||||
|
||||
/// <summary>
|
||||
/// The in-house column types of SPEC 5.4, the same on both engines (ADR 0007):
|
||||
/// <list type="bullet">
|
||||
/// <item>money, quantities and prices: <see cref="decimal"/>, <c>NUMERIC(38,18)</c> on PostgreSQL and canonical text on SQLite, rounded to 18 decimals before writing (trap 19);</item>
|
||||
/// <item>moments: <see cref="DateTimeOffset"/> in UTC, microsecond precision, ISO text on SQLite; a <see cref="DateTime"/> without time zone is refused;</item>
|
||||
/// <item>identifiers: <see cref="Guid"/> (UUIDv7), <c>UUID</c> on PostgreSQL and lowercase text on SQLite.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public static class DbValues
|
||||
{
|
||||
/// <summary>NUMERIC(38,18) keeps 20 digits before the decimal point.</summary>
|
||||
public static readonly decimal MaxMagnitude = 99_999_999_999_999_999_999m;
|
||||
|
||||
public const int Scale = 18;
|
||||
|
||||
private const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'";
|
||||
|
||||
/// <summary>Rounds to 18 decimals (half away from zero, as PostgreSQL does) and refuses values the column cannot hold.</summary>
|
||||
public static decimal Money(decimal value)
|
||||
{
|
||||
if (Math.Abs(value) > MaxMagnitude)
|
||||
{
|
||||
throw new OverflowException($"Value {value.ToString(CultureInfo.InvariantCulture)} exceeds NUMERIC(38,18).");
|
||||
}
|
||||
|
||||
return Normalize(Math.Round(value, Scale, MidpointRounding.AwayFromZero));
|
||||
}
|
||||
|
||||
/// <summary>Removes trailing zeros so the same number always has the same text: 1.500 becomes 1.5.</summary>
|
||||
public static decimal Normalize(decimal value) => value / 1.000000000000000000000000000000000m;
|
||||
|
||||
public static string MoneyText(decimal value) => Money(value).ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
public static decimal ParseMoney(string text) => Normalize(decimal.Parse(text, NumberStyles.Number, CultureInfo.InvariantCulture));
|
||||
|
||||
/// <summary>UTC, truncated to microseconds (the precision of PostgreSQL TIMESTAMPTZ).</summary>
|
||||
public static DateTimeOffset Moment(DateTimeOffset value)
|
||||
{
|
||||
var utc = value.ToUniversalTime();
|
||||
return new DateTimeOffset(utc.UtcTicks - (utc.UtcTicks % 10), TimeSpan.Zero);
|
||||
}
|
||||
|
||||
public static string MomentText(DateTimeOffset value) => Moment(value).ToString(TimestampFormat, CultureInfo.InvariantCulture);
|
||||
|
||||
public static DateTimeOffset ParseMoment(string text)
|
||||
{
|
||||
if (!text.EndsWith('Z'))
|
||||
{
|
||||
throw new FormatException("A stored moment has no time zone: " + text);
|
||||
}
|
||||
|
||||
return DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
}
|
||||
|
||||
/// <summary>Converts a .NET value to what the engine's driver should receive.</summary>
|
||||
public static object ToProvider(object? value, DbEngine engine) => value switch
|
||||
{
|
||||
null => DBNull.Value,
|
||||
decimal d => engine == DbEngine.Sqlite ? MoneyText(d) : Money(d),
|
||||
DateTimeOffset t => engine == DbEngine.Sqlite ? MomentText(t) : Moment(t),
|
||||
DateTime dt => dt.Kind == DateTimeKind.Utc
|
||||
? ToProvider(new DateTimeOffset(dt), engine)
|
||||
: throw new ArgumentException("Moments must carry a time zone: use DateTimeOffset or a UTC DateTime."),
|
||||
Guid g => engine == DbEngine.Sqlite ? g.ToString("D") : g,
|
||||
bool b => engine == DbEngine.Sqlite ? (b ? 1L : 0L) : b,
|
||||
DbJson j => j.Text,
|
||||
int i => (long)i,
|
||||
_ => value,
|
||||
};
|
||||
|
||||
/// <summary>The column type behind each token of the migration files.</summary>
|
||||
public static string ColumnType(string token, DbEngine engine) => (token, engine) switch
|
||||
{
|
||||
("money", DbEngine.Postgres) => "NUMERIC(38,18)",
|
||||
("money", DbEngine.Sqlite) => "TEXT",
|
||||
("uuid", DbEngine.Postgres) => "UUID",
|
||||
("uuid", DbEngine.Sqlite) => "TEXT",
|
||||
("timestamp", DbEngine.Postgres) => "TIMESTAMPTZ",
|
||||
("timestamp", DbEngine.Sqlite) => "TEXT",
|
||||
("json", DbEngine.Postgres) => "JSON",
|
||||
("json", DbEngine.Sqlite) => "TEXT",
|
||||
("bool", DbEngine.Postgres) => "BOOLEAN",
|
||||
("bool", DbEngine.Sqlite) => "INTEGER",
|
||||
("bytes", DbEngine.Postgres) => "BYTEA",
|
||||
("bytes", DbEngine.Sqlite) => "BLOB",
|
||||
("float", DbEngine.Postgres) => "DOUBLE PRECISION",
|
||||
("float", DbEngine.Sqlite) => "REAL",
|
||||
("strict", DbEngine.Postgres) => "",
|
||||
("strict", DbEngine.Sqlite) => " STRICT",
|
||||
_ => throw new InvalidOperationException($"Unknown column type token '{token}'."),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
-- Phase 1 schema (SPEC 5.4, ADR 0007). The same text runs on PostgreSQL and SQLite: the tokens in braces
|
||||
-- become the engine's column types (DbValues.ColumnType). Every table has a UUIDv7 key and created_at in UTC.
|
||||
-- Tables of later phases (bars, news, models, backtests, signals, decisions) arrive with their own migration.
|
||||
|
||||
-- Identity of the installation and fingerprint of the live database (SPEC 15.1). Exactly one row.
|
||||
CREATE TABLE installation (
|
||||
id {uuid} PRIMARY KEY,
|
||||
fingerprint TEXT NOT NULL,
|
||||
engine TEXT NOT NULL,
|
||||
protected_restart {bool} NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
renewed_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE users (
|
||||
id {uuid} PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
must_change_password {bool} NOT NULL,
|
||||
totp_secret {bytes},
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE sessions (
|
||||
id {uuid} PRIMARY KEY,
|
||||
user_id {uuid} NOT NULL REFERENCES users (id),
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
user_agent TEXT,
|
||||
address TEXT,
|
||||
created_at {timestamp} NOT NULL,
|
||||
last_seen_at {timestamp} NOT NULL,
|
||||
expires_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX sessions_user ON sessions (user_id);
|
||||
|
||||
-- Settings saved from the interface; startup configuration values win over them and are never stored here.
|
||||
CREATE TABLE config (
|
||||
id {uuid} PRIMARY KEY,
|
||||
key TEXT NOT NULL UNIQUE,
|
||||
value {json} NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
-- Change log of settings, activations and the kill switch (SPEC 13.5, 15.4). Append-only.
|
||||
CREATE TABLE config_history (
|
||||
id {uuid} PRIMARY KEY,
|
||||
key TEXT NOT NULL,
|
||||
old_value {json},
|
||||
new_value {json},
|
||||
changed_by TEXT NOT NULL,
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX config_history_key ON config_history (key, created_at);
|
||||
|
||||
-- Encrypted secrets (AES-GCM with the installation's secret key). Never returned by the API.
|
||||
CREATE TABLE secrets (
|
||||
id {uuid} PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
ciphertext {bytes} NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE jobs (
|
||||
id {uuid} PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
description TEXT NOT NULL,
|
||||
last_due_at {timestamp},
|
||||
last_started_at {timestamp},
|
||||
last_finished_at {timestamp},
|
||||
last_outcome TEXT,
|
||||
last_error TEXT,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE notifications (
|
||||
id {uuid} PRIMARY KEY,
|
||||
channel TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
sent_at {timestamp},
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
-- The bot's diary (SPEC 13.6): short sentences in Italian with a kind and a reason code.
|
||||
CREATE TABLE journal (
|
||||
id {uuid} PRIMARY KEY,
|
||||
occurred_at {timestamp} NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
code TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
data {json},
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX journal_time ON journal (occurred_at);
|
||||
|
||||
CREATE TABLE instruments (
|
||||
id {uuid} PRIMARY KEY,
|
||||
venue TEXT NOT NULL,
|
||||
symbol TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
asset_class TEXT NOT NULL,
|
||||
quote_currency TEXT NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
UNIQUE (venue, symbol)
|
||||
){strict};
|
||||
|
||||
CREATE TABLE accounts (
|
||||
id {uuid} PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
broker TEXT NOT NULL,
|
||||
environment TEXT NOT NULL,
|
||||
base_currency TEXT NOT NULL,
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE strategy_state (
|
||||
id {uuid} PRIMARY KEY,
|
||||
strategy TEXT NOT NULL UNIQUE,
|
||||
account_id {uuid} REFERENCES accounts (id),
|
||||
stage TEXT NOT NULL,
|
||||
capital {money} NOT NULL,
|
||||
state {json} NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE strategy_stage_history (
|
||||
id {uuid} PRIMARY KEY,
|
||||
strategy TEXT NOT NULL,
|
||||
from_stage TEXT,
|
||||
to_stage TEXT NOT NULL,
|
||||
reason TEXT NOT NULL,
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE orders (
|
||||
id {uuid} PRIMARY KEY,
|
||||
account_id {uuid} NOT NULL REFERENCES accounts (id),
|
||||
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
|
||||
strategy TEXT NOT NULL,
|
||||
client_order_id TEXT NOT NULL UNIQUE,
|
||||
broker_order_id TEXT,
|
||||
side TEXT NOT NULL,
|
||||
order_type TEXT NOT NULL,
|
||||
quantity {money} NOT NULL,
|
||||
limit_price {money},
|
||||
stop_price {money},
|
||||
status TEXT NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
-- Accounting tables (fills, lots, cash_ledger) are append-only: errors are fixed with reversal rows, never UPDATE.
|
||||
-- The same execution, from the stream and from the fallback query, is recorded once (account + execution id).
|
||||
CREATE TABLE fills (
|
||||
id {uuid} PRIMARY KEY,
|
||||
account_id {uuid} NOT NULL REFERENCES accounts (id),
|
||||
order_id {uuid} REFERENCES orders (id),
|
||||
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
|
||||
execution_id TEXT NOT NULL,
|
||||
side TEXT NOT NULL,
|
||||
quantity {money} NOT NULL,
|
||||
price {money} NOT NULL,
|
||||
fee {money} NOT NULL,
|
||||
fee_currency TEXT NOT NULL,
|
||||
reverses_id {uuid} REFERENCES fills (id),
|
||||
executed_at {timestamp} NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
UNIQUE (account_id, execution_id)
|
||||
){strict};
|
||||
|
||||
CREATE TABLE lots (
|
||||
id {uuid} PRIMARY KEY,
|
||||
account_id {uuid} NOT NULL REFERENCES accounts (id),
|
||||
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
|
||||
fill_id {uuid} NOT NULL REFERENCES fills (id),
|
||||
strategy TEXT NOT NULL,
|
||||
quantity {money} NOT NULL,
|
||||
price {money} NOT NULL,
|
||||
reverses_id {uuid} REFERENCES lots (id),
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE cash_ledger (
|
||||
id {uuid} PRIMARY KEY,
|
||||
account_id {uuid} NOT NULL REFERENCES accounts (id),
|
||||
currency TEXT NOT NULL,
|
||||
amount {money} NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
fill_id {uuid} REFERENCES fills (id),
|
||||
reverses_id {uuid} REFERENCES cash_ledger (id),
|
||||
note TEXT,
|
||||
occurred_at {timestamp} NOT NULL,
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE TABLE positions (
|
||||
id {uuid} PRIMARY KEY,
|
||||
account_id {uuid} NOT NULL REFERENCES accounts (id),
|
||||
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
|
||||
strategy TEXT NOT NULL,
|
||||
quantity {money} NOT NULL,
|
||||
average_price {money} NOT NULL,
|
||||
last_price {money},
|
||||
stop_price {money},
|
||||
opened_at {timestamp} NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL,
|
||||
UNIQUE (account_id, instrument_id, strategy)
|
||||
){strict};
|
||||
|
||||
-- Equity over time: account_id and strategy both empty for the total, one of them set for its own series.
|
||||
CREATE TABLE equity_snapshots (
|
||||
id {uuid} PRIMARY KEY,
|
||||
taken_at {timestamp} NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
account_id {uuid} REFERENCES accounts (id),
|
||||
strategy TEXT,
|
||||
equity {money} NOT NULL,
|
||||
cash {money},
|
||||
invested {money},
|
||||
benchmark {money},
|
||||
drawdown_pct {money},
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
CREATE INDEX equity_snapshots_scope ON equity_snapshots (scope, taken_at);
|
||||
|
||||
CREATE TABLE risk_events (
|
||||
id {uuid} PRIMARY KEY,
|
||||
occurred_at {timestamp} NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
severity TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
data {json},
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
@@ -0,0 +1,158 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Anubis.Core;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Db;
|
||||
|
||||
/// <summary>A numbered SQL migration embedded in the library (Db/Migrations/NNNN_name.sql).</summary>
|
||||
public sealed record Migration(int Version, string Name, string Sql)
|
||||
{
|
||||
/// <summary>Hash of the file as written, so an applied migration changed afterwards is detected.</summary>
|
||||
public string Checksum { get; } = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(Sql.ReplaceLineEndings("\n"))));
|
||||
|
||||
/// <summary>The SQL with the type tokens replaced for <paramref name="engine"/>.</summary>
|
||||
public string SqlFor(DbEngine engine) => Migrations.Tokens().Replace(Sql, m => DbValues.ColumnType(m.Groups[1].Value, engine));
|
||||
}
|
||||
|
||||
/// <summary>Where the database stands compared to the migrations this version knows.</summary>
|
||||
public sealed record SchemaStatus(int Current, int Latest, IReadOnlyList<Migration> Pending)
|
||||
{
|
||||
public bool IsEmpty => Current == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The in-house migration runner (ADR 0003): numbered SQL files, a version table, each migration in its own
|
||||
/// transaction. A backup runs before migrating a database that already has data (SPEC 5.4, 15.6).
|
||||
/// </summary>
|
||||
public static partial class Migrations
|
||||
{
|
||||
public const string VersionTable = "schema_versions";
|
||||
|
||||
[GeneratedRegex(@"\{(money|uuid|timestamp|json|bool|bytes|float|strict)\}")]
|
||||
internal static partial Regex Tokens();
|
||||
|
||||
[GeneratedRegex(@"^(\d{4})_([a-z0-9_]+)\.sql$")]
|
||||
private static partial Regex FileName();
|
||||
|
||||
private static readonly Lazy<IReadOnlyList<Migration>> _all = new(Load);
|
||||
|
||||
public static IReadOnlyList<Migration> All => _all.Value;
|
||||
|
||||
public static int Latest => All[^1].Version;
|
||||
|
||||
private static List<Migration> Load()
|
||||
{
|
||||
var assembly = typeof(Migrations).Assembly;
|
||||
const string prefix = "Anubis.Db.Migrations.";
|
||||
var list = new List<Migration>();
|
||||
foreach (var resource in assembly.GetManifestResourceNames().Where(n => n.StartsWith(prefix, StringComparison.Ordinal)))
|
||||
{
|
||||
var match = FileName().Match(resource[prefix.Length..]);
|
||||
if (!match.Success)
|
||||
{
|
||||
throw new InvalidOperationException("Badly named migration: " + resource);
|
||||
}
|
||||
|
||||
using var stream = assembly.GetManifestResourceStream(resource)!;
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
list.Add(new Migration(int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), match.Groups[2].Value, reader.ReadToEnd()));
|
||||
}
|
||||
|
||||
list.Sort((a, b) => a.Version.CompareTo(b.Version));
|
||||
for (var i = 0; i < list.Count; i++)
|
||||
{
|
||||
if (list[i].Version != i + 1)
|
||||
{
|
||||
throw new InvalidOperationException("Migration numbers must be consecutive from 0001.");
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static async Task<SchemaStatus> StatusAsync(Database db, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
return await db.ReadAsync(async s =>
|
||||
{
|
||||
if (!await TableExistsAsync(s, VersionTable).ConfigureAwait(false))
|
||||
{
|
||||
return new SchemaStatus(0, Latest, All);
|
||||
}
|
||||
|
||||
var applied = await s.QueryAsync($"SELECT version, checksum FROM {VersionTable} ORDER BY version",
|
||||
r => (Version: (int)r.Number("version"), Checksum: r.Text("checksum"))).ConfigureAwait(false);
|
||||
foreach (var (version, checksum) in applied)
|
||||
{
|
||||
if (version > Latest)
|
||||
{
|
||||
throw new SchemaException($"Il database è alla versione {version}, più recente di questa versione di Anubis (che arriva alla {Latest}). Aggiorna Anubis prima di usarlo.");
|
||||
}
|
||||
|
||||
if (All[version - 1].Checksum != checksum)
|
||||
{
|
||||
throw new SchemaException($"La migrazione {version:D4} applicata al database è diversa da quella di questa versione di Anubis.");
|
||||
}
|
||||
}
|
||||
|
||||
var current = applied.Count == 0 ? 0 : applied[^1].Version;
|
||||
return new SchemaStatus(current, Latest, All.Skip(current).ToList());
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings the database to the latest version. <paramref name="backupBeforeMigrating"/> runs first when the database
|
||||
/// already has a schema and something is pending; if it fails, nothing is migrated.
|
||||
/// </summary>
|
||||
public static async Task<int> MigrateAsync(Database db, IClock clock, Func<CancellationToken, Task>? backupBeforeMigrating, CancellationToken cancellationToken, int? upTo = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var status = await StatusAsync(db, cancellationToken).ConfigureAwait(false);
|
||||
var pending = status.Pending.Where(m => upTo is null || m.Version <= upTo).ToList();
|
||||
if (pending.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!status.IsEmpty && backupBeforeMigrating is not null)
|
||||
{
|
||||
await backupBeforeMigrating(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var migration in pending)
|
||||
{
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
if (migration.Version == 1)
|
||||
{
|
||||
await s.ExecuteAsync(
|
||||
$"CREATE TABLE {VersionTable} (version INTEGER PRIMARY KEY, name TEXT NOT NULL, checksum TEXT NOT NULL, applied_at {DbValues.ColumnType("timestamp", db.Engine)} NOT NULL){DbValues.ColumnType("strict", db.Engine)}",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await s.ExecuteAsync(migration.SqlFor(db.Engine), cancellationToken).ConfigureAwait(false);
|
||||
await s.ExecuteAsync($"INSERT INTO {VersionTable} (version, name, checksum, applied_at) VALUES (@v, @n, @c, @t)", cancellationToken,
|
||||
("v", migration.Version), ("n", migration.Name), ("c", migration.Checksum), ("t", clock.UtcNow)).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return pending.Count;
|
||||
}
|
||||
|
||||
public static async Task<bool> TableExistsAsync(DbSession session, string table)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
var sql = session.Engine == DbEngine.Sqlite
|
||||
? "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = @t"
|
||||
: "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = @t";
|
||||
return await session.CountAsync(sql, ("t", table)).ConfigureAwait(false) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The database schema cannot be used by this version: shown on the error page.</summary>
|
||||
public sealed class SchemaException(string message) : Exception(message);
|
||||
@@ -0,0 +1,120 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Anubis.Db;
|
||||
|
||||
public enum ColumnKind
|
||||
{
|
||||
Text,
|
||||
Number,
|
||||
Money,
|
||||
Uuid,
|
||||
Moment,
|
||||
Json,
|
||||
Bool,
|
||||
Bytes,
|
||||
Measure,
|
||||
}
|
||||
|
||||
public sealed record Column(string Name, ColumnKind Kind, bool Nullable);
|
||||
|
||||
public sealed record Table(string Name, IReadOnlyList<Column> Columns);
|
||||
|
||||
/// <summary>
|
||||
/// The tables and typed columns, read from the migration files themselves: the SQL stays the only source of
|
||||
/// truth and export, import and checks know each column's kind on both engines. Tables are listed in creation
|
||||
/// order, which respects foreign keys.
|
||||
/// </summary>
|
||||
public static partial class Schema
|
||||
{
|
||||
/// <summary>Accounting tables: append-only, their money columns are the totals checked after an import (SPEC 5.4).</summary>
|
||||
public static readonly string[] AccountingTables = ["fills", "lots", "cash_ledger"];
|
||||
|
||||
private static readonly Lazy<IReadOnlyList<Table>> _tables = new(() => Parse(Migrations.All));
|
||||
|
||||
public static IReadOnlyList<Table> Tables => _tables.Value;
|
||||
|
||||
public static Table Get(string name) => Tables.First(t => t.Name == name);
|
||||
|
||||
[GeneratedRegex(@"CREATE\s+TABLE\s+(\w+)\s*\((.*?)\)\s*\{strict\}\s*;", RegexOptions.Singleline | RegexOptions.IgnoreCase)]
|
||||
private static partial Regex CreateTable();
|
||||
|
||||
[GeneratedRegex(@"ALTER\s+TABLE\s+(\w+)\s+ADD\s+COLUMN\s+(.+?);", RegexOptions.Singleline | RegexOptions.IgnoreCase)]
|
||||
private static partial Regex AddColumn();
|
||||
|
||||
[GeneratedRegex(@"--[^\n]*")]
|
||||
private static partial Regex Comment();
|
||||
|
||||
internal static IReadOnlyList<Table> Parse(IEnumerable<Migration> migrations)
|
||||
{
|
||||
var tables = new List<(string Name, List<Column> Columns)>();
|
||||
foreach (var migration in migrations)
|
||||
{
|
||||
var sql = Comment().Replace(migration.Sql, "");
|
||||
foreach (Match match in CreateTable().Matches(sql))
|
||||
{
|
||||
var columns = SplitTopLevel(match.Groups[2].Value).Select(ParseColumn).OfType<Column>().ToList();
|
||||
tables.Add((match.Groups[1].Value, columns));
|
||||
}
|
||||
|
||||
foreach (Match match in AddColumn().Matches(sql))
|
||||
{
|
||||
var column = ParseColumn(match.Groups[2].Value) ?? throw new InvalidOperationException("Unreadable column in " + migration.Name);
|
||||
tables.First(t => t.Name == match.Groups[1].Value).Columns.Add(column);
|
||||
}
|
||||
}
|
||||
|
||||
return tables.Select(t => new Table(t.Name, t.Columns)).ToList();
|
||||
}
|
||||
|
||||
private static Column? ParseColumn(string definition)
|
||||
{
|
||||
var parts = definition.Trim().Split((char[])[' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2 || parts[0].ToUpperInvariant() is "UNIQUE" or "PRIMARY" or "FOREIGN" or "CHECK" or "CONSTRAINT")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var kind = parts[1].ToUpperInvariant() switch
|
||||
{
|
||||
"{MONEY}" => ColumnKind.Money,
|
||||
"{UUID}" => ColumnKind.Uuid,
|
||||
"{TIMESTAMP}" => ColumnKind.Moment,
|
||||
"{JSON}" => ColumnKind.Json,
|
||||
"{BOOL}" => ColumnKind.Bool,
|
||||
"{BYTES}" => ColumnKind.Bytes,
|
||||
"{FLOAT}" => ColumnKind.Measure,
|
||||
"TEXT" => ColumnKind.Text,
|
||||
"INTEGER" or "BIGINT" => ColumnKind.Number,
|
||||
var other => throw new InvalidOperationException($"Column type {other} is not portable: use TEXT, INTEGER, BIGINT or a token."),
|
||||
};
|
||||
var upper = definition.ToUpperInvariant();
|
||||
var nullable = !upper.Contains("NOT NULL", StringComparison.Ordinal) && !upper.Contains("PRIMARY KEY", StringComparison.Ordinal);
|
||||
return new Column(parts[0], kind, nullable);
|
||||
}
|
||||
|
||||
private static List<string> SplitTopLevel(string body)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
var depth = 0;
|
||||
var start = 0;
|
||||
for (var i = 0; i < body.Length; i++)
|
||||
{
|
||||
switch (body[i])
|
||||
{
|
||||
case '(':
|
||||
depth++;
|
||||
break;
|
||||
case ')':
|
||||
depth--;
|
||||
break;
|
||||
case ',' when depth == 0:
|
||||
parts.Add(body[start..i]);
|
||||
start = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
parts.Add(body[start..]);
|
||||
return parts.Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"_nota": "Valori dell'appendice F di docs/SPEC.md che hanno solo un totale o una statistica. Letti solo dalla modalità dimostrativa (SPEC 13.1).",
|
||||
"adesso": "2026-10-09T08:21:00+02:00",
|
||||
"avvio": "2026-08-12",
|
||||
"capitale_iniziale": "10000.00",
|
||||
"giorno": 58,
|
||||
"dati_aggiornati_secondi": 4,
|
||||
"piattaforma": "Docker",
|
||||
"database": "PostgreSQL",
|
||||
"versione": "0.9.2",
|
||||
"bot": "active",
|
||||
"soldi_veri": false,
|
||||
"cambio_eur_usd": "1.1601",
|
||||
"totali": {
|
||||
"patrimonio": "10412.46",
|
||||
"risultato": "412.46",
|
||||
"risultato_pct": "4.12",
|
||||
"oggi": "18.40",
|
||||
"oggi_pct": "0.18",
|
||||
"sette_giorni": "96.10",
|
||||
"sette_giorni_pct": "0.93",
|
||||
"trenta_giorni": "251.70",
|
||||
"trenta_giorni_pct": "2.48",
|
||||
"senza_bot": "9974.00",
|
||||
"senza_bot_risultato": "-26.00",
|
||||
"senza_bot_pct": "-0.26",
|
||||
"investito": "6671.13",
|
||||
"investito_pct": "64.1",
|
||||
"liquidita": "3741.33",
|
||||
"liquidita_pct": "35.9",
|
||||
"risultato_aperto": "173.18",
|
||||
"calo_peggiore_pct": "-2.82",
|
||||
"calo_peggiore_data": "2026-09-05"
|
||||
},
|
||||
"conti": [
|
||||
{
|
||||
"nome": "OKX Europe", "tipo": "Crypto", "ambiente": "simulatore interno", "capitale": "4000.00", "patrimonio": "4231.60",
|
||||
"risultato": "231.60", "risultato_pct": "5.79", "liquidita": "1905.10", "investito": "2326.50", "incassati": "163.45",
|
||||
"aperti": "68.15", "commissioni": "14.49", "trenta_giorni": "158.20", "risposta_ms": 84
|
||||
},
|
||||
{
|
||||
"nome": "Alpaca", "tipo": "Azioni USA", "ambiente": "conto di prova", "capitale": "6000.00", "patrimonio": "6180.86", "patrimonio_usd": "7170.41",
|
||||
"risultato": "180.86", "risultato_pct": "3.01", "liquidita": "1836.23", "investito": "4344.63", "incassati": "75.83",
|
||||
"aperti": "105.03", "commissioni": "0.33", "trenta_giorni": "93.50", "risposta_ms": 61
|
||||
}
|
||||
],
|
||||
"strategie": [
|
||||
{ "nome": "crypto_trend", "etichetta": "Trend crypto", "conto": "OKX Europe", "giorno": 58, "di": 60, "quota_pct": 40, "capitale": "4000", "risultato": "231.60", "risultato_pct": "5.79", "calo_peggiore_pct": "-4.1", "chiuse": 9, "in_guadagno": 5 },
|
||||
{ "nome": "equity_momentum", "etichetta": "Momentum azioni USA", "conto": "Alpaca", "giorno": 58, "di": 60, "quota_pct": 45, "capitale": "4500", "risultato": "169.50", "risultato_pct": "3.77", "calo_peggiore_pct": "-3.2", "chiuse": 11, "in_guadagno": 7 },
|
||||
{ "nome": "equity_meanrev", "etichetta": "Mean reversion azioni USA", "conto": "Alpaca", "giorno": 58, "di": 60, "quota_pct": 15, "capitale": "1500", "risultato": "11.36", "risultato_pct": "0.76", "calo_peggiore_pct": "-1.1", "chiuse": 21, "in_guadagno": 10 }
|
||||
],
|
||||
"operazioni": { "chiuse": 41, "in_guadagno": 22, "guadagno_medio": "28.42", "perdita_media": "-20.31", "rapporto": "1.62", "incassati": "239.28", "commissioni": "14.82" },
|
||||
"notizie": { "lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50" },
|
||||
"apprendimento": { "stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56 },
|
||||
"sistema": {
|
||||
"controllo_secondi": 5, "notizie_fonti": 16, "database_gb": "1.8", "ultimo_salvataggio": "03:30", "telegram_ultimo": "08:00",
|
||||
"cpu_pct": 6, "memoria_gb": "1.1", "memoria_totale_gb": 4, "disco_gb": "2.3", "disco_totale_gb": 50
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
data;patrimonio_eur;senza_bot_eur;calo_pct
|
||||
2026-08-12;10000,00;10000,00;0,00
|
||||
2026-08-13;10049,17;9898,01;0,00
|
||||
2026-08-14;10087,89;9998,64;0,00
|
||||
2026-08-15;10085,38;10046,35;-0,02
|
||||
2026-08-16;10098,31;10048,96;0,00
|
||||
2026-08-17;10143,92;10093,14;0,00
|
||||
2026-08-18;10091,56;9979,39;-0,52
|
||||
2026-08-19;10154,99;9904,91;0,00
|
||||
2026-08-20;10186,43;9974,91;0,00
|
||||
2026-08-21;10250,57;9947,97;0,00
|
||||
2026-08-22;10257,92;9891,37;0,00
|
||||
2026-08-23;10254,68;9903,32;-0,03
|
||||
2026-08-24;10231,51;9844,47;-0,26
|
||||
2026-08-25;10189,02;9746,55;-0,67
|
||||
2026-08-26;10276,77;9716,33;0,00
|
||||
2026-08-27;10269,26;9686,41;-0,07
|
||||
2026-08-28;10220,22;9756,88;-0,55
|
||||
2026-08-29;10162,96;9777,91;-1,11
|
||||
2026-08-30;10154,80;9741,13;-1,19
|
||||
2026-08-31;10102,80;9615,19;-1,69
|
||||
2026-09-01;10077,13;9763,93;-1,94
|
||||
2026-09-02;9992,93;9729,55;-2,76
|
||||
2026-09-03;10006,93;9629,62;-2,63
|
||||
2026-09-04;10045,33;9591,40;-2,25
|
||||
2026-09-05;9987,08;9639,42;-2,82
|
||||
2026-09-06;10047,74;9651,06;-2,23
|
||||
2026-09-07;10095,79;9693,95;-1,76
|
||||
2026-09-08;10132,43;9673,13;-1,40
|
||||
2026-09-09;10160,76;9662,70;-1,13
|
||||
2026-09-10;10167,99;9647,61;-1,06
|
||||
2026-09-11;10142,45;9603,46;-1,31
|
||||
2026-09-12;10129,43;9480,28;-1,43
|
||||
2026-09-13;10149,62;9447,18;-1,24
|
||||
2026-09-14;10146,01;9506,25;-1,27
|
||||
2026-09-15;10121,86;9561,70;-1,51
|
||||
2026-09-16;10142,77;9722,09;-1,30
|
||||
2026-09-17;10208,79;9791,60;-0,66
|
||||
2026-09-18;10205,70;9825,49;-0,69
|
||||
2026-09-19;10174,28;9872,38;-1,00
|
||||
2026-09-20;10203,45;9838,07;-0,71
|
||||
2026-09-21;10206,21;9829,79;-0,69
|
||||
2026-09-22;10255,00;9861,96;-0,21
|
||||
2026-09-23;10282,67;10008,21;0,00
|
||||
2026-09-24;10269,16;10083,10;-0,13
|
||||
2026-09-25;10331,03;10100,31;0,00
|
||||
2026-09-26;10322,66;10019,39;-0,08
|
||||
2026-09-27;10314,46;10100,35;-0,16
|
||||
2026-09-28;10388,02;10005,58;0,00
|
||||
2026-09-29;10340,65;9980,52;-0,46
|
||||
2026-09-30;10302,26;9985,59;-0,83
|
||||
2026-10-01;10320,81;10002,01;-0,65
|
||||
2026-10-02;10316,36;9943,23;-0,69
|
||||
2026-10-03;10285,25;9937,24;-0,99
|
||||
2026-10-04;10315,99;9896,36;-0,69
|
||||
2026-10-05;10331,17;9982,05;-0,55
|
||||
2026-10-06;10340,15;9998,34;-0,46
|
||||
2026-10-07;10365,81;10012,27;-0,21
|
||||
2026-10-08;10394,06;9941,64;0,00
|
||||
2026-10-09;10412,46;9974,00;0,00
|
||||
|
@@ -0,0 +1,16 @@
|
||||
Giorno;Ora;Voce;Tipo
|
||||
Oggi;08:20;Controllo periodico: registri in ordine, conto Alpaca allineato.;Sistema
|
||||
Oggi;08:00;Inviato il riepilogo del mattino su Telegram.;Sistema
|
||||
Oggi;07:52;Notizia sui verbali della banca centrale USA: nessun effetto.;Notizie
|
||||
Oggi;06:10;Ho cambiato una regola per 24 ore: non aumento la posizione su SOL. Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana.;Notizie
|
||||
Oggi;03:00;Controllo del modello: nessuna anomalia.;Apprendimento
|
||||
Oggi;02:06;Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.;Ordini
|
||||
Oggi;02:05;Chiusura giornaliera crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.;Decisioni
|
||||
Ieri;22:41;Ho messo una restrizione fino a martedì: niente mean reversion su JPM. Motivo: JPMorgan pubblica i conti martedì prima dell'apertura.;Notizie
|
||||
Ieri;22:21;Azioni: nessun nuovo acquisto. AAPL resta aperta: non è ancora tornata sopra la media a 5 giorni.;Decisioni
|
||||
Ieri;21:58;Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni. (con il collegamento "Perché l'ho comprata e venduta");Ordini
|
||||
Ieri;18:20;Ricontrollata la voce sui prelievi rallentati di un exchange: rientrata.;Notizie
|
||||
Ieri;16:20;Voce non confermata su un exchange. Nessuna azione: ricontrollo tra 2 ore.;Notizie
|
||||
Ieri;15:36;Comprate 2 AAPL a 259,80 $. Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.;Ordini
|
||||
Ieri;15:35;Rimessi 6 stop giornalieri sulle frazioni di azione.;Ordini
|
||||
Ieri;14:31;Richieste di sussidi USA sotto le attese: impatto medio, nessun blocco.;Notizie
|
||||
|
Can't render this file because it contains an unexpected character in line 11 and column 81.
|
@@ -0,0 +1,11 @@
|
||||
Strumento;Nome;Conto;Strategia;Quantità;Prezzo medio;Prezzo ora;Valore €;Risultato €;Risultato %;Stop;Aperta da (giorni);Rischio all'ingresso %
|
||||
BTC/EUR;Bitcoin;OKX Europe;Trend crypto;0,0182;68.950,00 €;71.420,00 €;1.299,84;+44,95;+3,58;66.180 €;23;0,95
|
||||
ETH/EUR;Ether;OKX Europe;Trend crypto;0,262;2.488,00 €;2.611,00 €;684,08;+32,23;+4,94;2.395 €;19;0,62
|
||||
AVGO;Broadcom;Alpaca;Momentum;2,1;352,10 $;367,90 $;665,97;+28,60;+4,49;338,50 $;18;0,48
|
||||
NVDA;Nvidia;Alpaca;Momentum;4,2;171,30 $;182,45 $;660,54;+40,37;+6,51;166,00 $;25;0,52
|
||||
LLY;Eli Lilly;Alpaca;Momentum;0,9;812,00 $;846,30 $;656,56;+26,61;+4,22;795,00 $;11;0,41
|
||||
JPM;JPMorgan Chase;Alpaca;Momentum;2,6;291,40 $;287,15 $;643,56;−9,53;−1,46;276,90 $;4;0,36
|
||||
XOM;Exxon Mobil;Alpaca;Momentum;6,1;118,90 $;121,35 $;638,08;+12,89;+2,06;115,20 $;11;0,33
|
||||
COST;Costco;Alpaca;Momentum;0,75;968,20 $;981,60 $;634,60;+8,66;+1,38;941,00 $;4;0,30
|
||||
AAPL;Apple;Alpaca;Mean reversion;2;259,80 $;258,31 $;445,32;−2,57;−0,57;249,40 $;1;0,17
|
||||
SOL/EUR;Solana;OKX Europe;Trend crypto;2,68;131,20 €;127,83 €;342,58;−9,03;−2,57;118,40 €;6;0,38
|
||||
|
@@ -0,0 +1,42 @@
|
||||
n;strategia;risultato_eur;simbolo
|
||||
1;crypto_trend;27,32;
|
||||
2;equity_momentum;16,21;
|
||||
3;equity_meanrev;-12,85;
|
||||
4;equity_momentum;33,93;
|
||||
5;equity_meanrev;7,61;
|
||||
6;equity_momentum;-67,16;TSLA
|
||||
7;equity_momentum;27,43;
|
||||
8;equity_meanrev;-8,53;
|
||||
9;equity_momentum;-51,17;
|
||||
10;equity_meanrev;-11,58;
|
||||
11;equity_meanrev;-7,31;
|
||||
12;equity_momentum;40,39;
|
||||
13;equity_meanrev;13,54;
|
||||
14;equity_meanrev;-5,28;
|
||||
15;equity_meanrev;15,14;
|
||||
16;equity_momentum;44,26;
|
||||
17;equity_meanrev;-12,63;
|
||||
18;equity_meanrev;5,38;
|
||||
19;crypto_trend;42,50;
|
||||
20;equity_meanrev;8,74;
|
||||
21;equity_meanrev;16,58;
|
||||
22;equity_meanrev;5,28;
|
||||
23;crypto_trend;-29,31;
|
||||
24;crypto_trend;50,05;
|
||||
25;equity_momentum;40,74;
|
||||
26;equity_meanrev;-4,99;
|
||||
27;crypto_trend;52,70;
|
||||
28;equity_meanrev;-8,11;
|
||||
29;crypto_trend;-29,03;
|
||||
30;crypto_trend;-18,18;
|
||||
31;equity_momentum;-54,77;
|
||||
32;equity_meanrev;-4,90;
|
||||
33;equity_meanrev;12,10;
|
||||
34;equity_meanrev;-3,75;PG
|
||||
35;crypto_trend;89,54;LINK/EUR
|
||||
36;equity_meanrev;7,95;V
|
||||
37;crypto_trend;-22,14;ADA/EUR
|
||||
38;equity_momentum;59,35;AMD
|
||||
39;equity_momentum;-27,31;UNH
|
||||
40;equity_meanrev;-6,94;KO
|
||||
41;equity_meanrev;8,48;MSFT
|
||||
|
@@ -0,0 +1,224 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Demo;
|
||||
|
||||
/// <summary>
|
||||
/// Demo mode (SPEC 13.1, appendix F): a separate SQLite database in a new temporary folder, never the configured
|
||||
/// one (trap 27), filled with the rows of appendix F; the clock frozen at Friday 9 October 2026, 08:21 Italian
|
||||
/// time; no broker. Values that appendix F gives only as totals go to an aggregates file that only this mode reads.
|
||||
/// Rows of tables that later phases create (closed trades, news, models) are loaded by those phases.
|
||||
/// </summary>
|
||||
public static class DemoMode
|
||||
{
|
||||
public const string AggregatesFile = "demo-aggregates.json";
|
||||
|
||||
/// <summary>"Adesso" in the demo: Friday 9 October 2026, 08:21 in Rome.</summary>
|
||||
public static readonly DateTimeOffset Now = new(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2));
|
||||
|
||||
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
|
||||
|
||||
/// <summary>Demo folders older than this are removed when a new demo starts.</summary>
|
||||
public static readonly TimeSpan KeepFolders = TimeSpan.FromDays(7);
|
||||
|
||||
/// <summary>
|
||||
/// A brand-new folder under the system temporary directory; it never reuses another folder. <paramref name="wallClock"/>
|
||||
/// is the real clock (the demo's own clock stands still): it names the folder and clears demos older than a week.
|
||||
/// </summary>
|
||||
public static DataDirectory CreateFolder(IClock wallClock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(wallClock);
|
||||
var now = wallClock.UtcNow;
|
||||
var parent = Path.Combine(Path.GetTempPath(), "anubis-demo");
|
||||
RemoveOldFolders(parent, now);
|
||||
var root = Path.Combine(parent, now.ToString("yyyyMMdd-HHmmss", _it) + "-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
if (Directory.Exists(root))
|
||||
{
|
||||
throw new IOException("Demo folder already exists: " + root);
|
||||
}
|
||||
|
||||
var data = new DataDirectory(root);
|
||||
data.Ensure();
|
||||
return data;
|
||||
}
|
||||
|
||||
// Only folders named the way CreateFolder names them, and only by the date in the name: nothing else is touched.
|
||||
private static void RemoveOldFolders(string parent, DateTimeOffset now)
|
||||
{
|
||||
if (!Directory.Exists(parent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var folder in Directory.EnumerateDirectories(parent))
|
||||
{
|
||||
var name = Path.GetFileName(folder);
|
||||
if (name.Length != 24 || name[15] != '-' ||
|
||||
!DateTimeOffset.TryParseExact(name[..15], "yyyyMMdd-HHmmss", _it, DateTimeStyles.AssumeUniversal, out var created) ||
|
||||
now - created < KeepFolders)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Still in use by another demo, or protected: left for next time.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static StartupConfig Config(DataDirectory data) => new()
|
||||
{
|
||||
Platform = PlatformKind.Desktop,
|
||||
Data = data,
|
||||
Db = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile },
|
||||
TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"),
|
||||
SecretKey = new ProtectedSecretKey(new RestrictedFileStore(Path.Combine(data.Root, "keys"))),
|
||||
AllowLive = false,
|
||||
};
|
||||
|
||||
/// <summary>Loads appendix F into an empty, migrated database and writes the aggregates file next to it.</summary>
|
||||
public static async Task SeedAsync(Database db, DataDirectory data, IClock clock, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
if (db.SqlitePath is null || !db.SqlitePath.StartsWith(Path.GetFullPath(data.Root), StringComparison.Ordinal))
|
||||
{
|
||||
throw new InvalidOperationException("Demo data go only into the demo's own SQLite database.");
|
||||
}
|
||||
|
||||
File.WriteAllText(Path.Combine(data.Root, AggregatesFile), Resource("aggregates.json"));
|
||||
var rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
|
||||
var now = clock.UtcNow;
|
||||
var ids = new IdSource(now);
|
||||
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
var okx = ids.Next();
|
||||
var alpaca = ids.Next();
|
||||
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t), (@id2, 'Alpaca', 'alpaca', 'demo', 'USD', @t)",
|
||||
cancellationToken, ("id", okx), ("id2", alpaca), ("t", now)).ConfigureAwait(false);
|
||||
|
||||
var strategies = new Dictionary<string, (string Name, Guid Account, decimal Capital)>
|
||||
{
|
||||
["Trend crypto"] = ("crypto_trend", okx, 4000m),
|
||||
["Momentum"] = ("equity_momentum", alpaca, 4500m),
|
||||
["Mean reversion"] = ("equity_meanrev", alpaca, 1500m),
|
||||
};
|
||||
foreach (var (name, account, capital) in strategies.Values)
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @st, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// F.4: the ten open positions.
|
||||
foreach (var row in Csv("positions.csv").Skip(1))
|
||||
{
|
||||
var symbol = row[0];
|
||||
var crypto = symbol.Contains('/', StringComparison.Ordinal);
|
||||
var instrument = ids.Next();
|
||||
var (strategy, account, _) = strategies[row[3]];
|
||||
await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)",
|
||||
cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", row[1]), ("c", crypto ? "crypto" : "equity"),
|
||||
("q", crypto ? "EUR" : "USD"), ("t", now)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @q, @p, @l, @st, @o, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("q", Number(row[4])), ("p", Number(row[5])), ("l", Number(row[6])),
|
||||
("st", Number(row[10])), ("o", now.AddDays(-int.Parse(row[11], _it))), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// F.6: the daily series of the total; accounts and strategies are generated to end on their F.2 and F.3 results.
|
||||
var daily = Csv("daily.csv").Skip(1).Select(r => (Day: DateOnly.ParseExact(r[0], "yyyy-MM-dd", _it), Equity: Number(r[1]), Benchmark: Number(r[2]), Drawdown: Number(r[3]))).ToList();
|
||||
var total = daily[^1].Equity - 10000m;
|
||||
(string Scope, Guid? Account, string? Strategy, decimal Start, decimal Result)[] series =
|
||||
[
|
||||
("account", okx, null, 4000m, 231.60m),
|
||||
("account", alpaca, null, 6000m, 180.86m),
|
||||
("strategy", null, "crypto_trend", 4000m, 231.60m),
|
||||
("strategy", null, "equity_momentum", 4500m, 169.50m),
|
||||
("strategy", null, "equity_meanrev", 1500m, 11.36m),
|
||||
];
|
||||
foreach (var (day, equity, benchmark, drawdown) in daily)
|
||||
{
|
||||
var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0))));
|
||||
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', @e, @b, @d, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("t", now)).ConfigureAwait(false);
|
||||
foreach (var (scope, account, strategy, start, result) in series)
|
||||
{
|
||||
var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero);
|
||||
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, @a, @st, @e, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// F.10: the diary, newest first in the appendix.
|
||||
var today = DateOnly.FromDateTime(Now.DateTime);
|
||||
foreach (var row in Csv("journal.csv").Skip(1))
|
||||
{
|
||||
var day = row[0] == "Oggi" ? today : today.AddDays(-1);
|
||||
var local = day.ToDateTime(TimeOnly.ParseExact(row[1], "HH:mm", _it));
|
||||
await s.ExecuteAsync("INSERT INTO journal (id, occurred_at, kind, code, message, created_at) VALUES (@id, @at, @k, 'demo', @m, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("at", new DateTimeOffset(local, rome.GetUtcOffset(local))), ("k", row[3]), ("m", row[2]), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, 'bot.state', @v, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("v", new DbJson(JsonSerializer.Serialize("active"))), ("t", now)).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Reads the aggregates file of a demo folder.</summary>
|
||||
public static JsonDocument? ReadAggregates(DataDirectory data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var path = Path.Combine(data.Root, AggregatesFile);
|
||||
return File.Exists(path) ? JsonDocument.Parse(File.ReadAllText(path)) : null;
|
||||
}
|
||||
|
||||
// "68.950,00 €", "+3,58", "66.180 €", "0,0182" → decimal.
|
||||
private static decimal Number(string text)
|
||||
{
|
||||
var clean = new StringBuilder();
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (char.IsAsciiDigit(c) || c == ',')
|
||||
{
|
||||
clean.Append(c == ',' ? '.' : c);
|
||||
}
|
||||
else if (c is '-' or '−')
|
||||
{
|
||||
clean.Append('-');
|
||||
}
|
||||
}
|
||||
|
||||
return decimal.Parse(clean.ToString(), NumberStyles.Number, _it);
|
||||
}
|
||||
|
||||
private static IEnumerable<string[]> Csv(string name) =>
|
||||
Resource(name).Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(l => l.TrimEnd('\r').Split(';'));
|
||||
|
||||
private static string Resource(string name)
|
||||
{
|
||||
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Anubis.Demo.Data." + name)
|
||||
?? throw new InvalidOperationException("Missing demo resource " + name);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
/// <summary>UUIDv7 in insertion order, all at the demo's frozen time.</summary>
|
||||
private sealed class IdSource(DateTimeOffset at)
|
||||
{
|
||||
private int _n;
|
||||
|
||||
public Guid Next() => Guid.CreateVersion7(at.AddMilliseconds(_n++));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// The data folder (SPEC 15.2, 15.6): <c>/data</c> in Docker, the user's application folder on desktop.
|
||||
/// Same layout on both: db/, models/, research/, import/, backups/, logs/, installation.json.
|
||||
/// </summary>
|
||||
public sealed record DataDirectory(string Root)
|
||||
{
|
||||
public static readonly string[] Folders = ["db", "models", "research", "import", "backups", "logs"];
|
||||
|
||||
public string Db => Path.Combine(Root, "db");
|
||||
|
||||
public string Models => Path.Combine(Root, "models");
|
||||
|
||||
public string Research => Path.Combine(Root, "research");
|
||||
|
||||
public string Import => Path.Combine(Root, "import");
|
||||
|
||||
public string Backups => Path.Combine(Root, "backups");
|
||||
|
||||
public string Logs => Path.Combine(Root, "logs");
|
||||
|
||||
public string InstallationFile => Path.Combine(Root, "installation.json");
|
||||
|
||||
public string ConfigFile => Path.Combine(Root, "config.toml");
|
||||
|
||||
public string SqliteFile => Path.Combine(Db, "anubis.sqlite3");
|
||||
|
||||
/// <summary>Creates the folder and its sub-folders when missing. Never deletes anything.</summary>
|
||||
public void Ensure()
|
||||
{
|
||||
Directory.CreateDirectory(Root);
|
||||
foreach (var folder in Folders)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(Root, folder));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The standard per-user folder (SPEC 15.6): %APPDATA%\Anubis, ~/Library/Application Support/Anubis, ~/.local/share/anubis.</summary>
|
||||
public static DataDirectory ForCurrentUser()
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Anubis"));
|
||||
}
|
||||
|
||||
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
return new(Path.Combine(home, "Library", "Application Support", "Anubis"));
|
||||
}
|
||||
|
||||
var xdg = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
|
||||
return new(Path.Combine(string.IsNullOrEmpty(xdg) ? Path.Combine(home, ".local", "share") : xdg, "anubis"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>Content of <c>installation.json</c> in the data folder (SPEC 15.1).</summary>
|
||||
public sealed record InstallationFile(Guid InstallationId, string Fingerprint, string Engine, DateTimeOffset CreatedAt, DateTimeOffset RenewedAt);
|
||||
|
||||
/// <summary>The installation row in the database.</summary>
|
||||
public sealed record InstallationRow(Guid Id, string Fingerprint, string Engine, bool ProtectedRestart, DateTimeOffset CreatedAt, DateTimeOffset RenewedAt);
|
||||
|
||||
public enum IdentityVerdict
|
||||
{
|
||||
/// <summary>Same installation and same fingerprint: the engine may start.</summary>
|
||||
Match,
|
||||
|
||||
/// <summary>Empty database and a data folder that belongs to nobody: a new installation was created.</summary>
|
||||
Created,
|
||||
|
||||
/// <summary>The database knows the installation but the data folder lost its file: it was rewritten from the database.</summary>
|
||||
FileRestored,
|
||||
|
||||
/// <summary>The database is empty while the data folder belongs to an existing installation.</summary>
|
||||
EmptyDatabase,
|
||||
|
||||
/// <summary>Database and data folder belong to two different installations.</summary>
|
||||
DifferentInstallation,
|
||||
|
||||
/// <summary>Same installation, older fingerprint: a stale copy of the database (trap 26).</summary>
|
||||
StaleDatabase,
|
||||
}
|
||||
|
||||
public sealed record IdentityCheck(IdentityVerdict Verdict, InstallationFile? File, InstallationRow? Row)
|
||||
{
|
||||
public bool CanStart => Verdict is IdentityVerdict.Match or IdentityVerdict.Created or IdentityVerdict.FileRestored;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Identity of the installation and fingerprint of the database (SPEC 15.1): one live database per
|
||||
/// installation. Every import, restore or move gets a new fingerprint, written to the target database and to
|
||||
/// installation.json; a database left with an older fingerprint stops at the error page.
|
||||
/// </summary>
|
||||
public static class Installation
|
||||
{
|
||||
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web) { WriteIndented = true };
|
||||
|
||||
public static InstallationFile? ReadFile(DataDirectory data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
return File.Exists(data.InstallationFile)
|
||||
? JsonSerializer.Deserialize<InstallationFile>(File.ReadAllText(data.InstallationFile), _json)
|
||||
: null;
|
||||
}
|
||||
|
||||
public static void WriteFile(DataDirectory data, InstallationFile file)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
Directory.CreateDirectory(data.Root);
|
||||
var temp = data.InstallationFile + ".tmp";
|
||||
File.WriteAllText(temp, JsonSerializer.Serialize(file, _json));
|
||||
File.Move(temp, data.InstallationFile, overwrite: true);
|
||||
}
|
||||
|
||||
public static async Task<InstallationRow?> ReadRowAsync(Database db, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
return await db.ReadAsync(s => s.FirstOrDefaultAsync(
|
||||
"SELECT id, fingerprint, engine, protected_restart, created_at, renewed_at FROM installation",
|
||||
r => new InstallationRow(r.Id("id"), r.Text("fingerprint"), r.Text("engine"), r.Bool("protected_restart"), r.Moment("created_at"), r.Moment("renewed_at"))),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compares database and data folder at start. Creates the installation only when both are new; never
|
||||
/// touches a database that belongs elsewhere.
|
||||
/// </summary>
|
||||
public static async Task<IdentityCheck> CheckAsync(Database db, DataDirectory data, IClock clock, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var file = ReadFile(data);
|
||||
var row = await ReadRowAsync(db, cancellationToken).ConfigureAwait(false);
|
||||
switch (row, file)
|
||||
{
|
||||
case (null, null):
|
||||
var created = await CreateAsync(db, data, clock, cancellationToken).ConfigureAwait(false);
|
||||
return new IdentityCheck(IdentityVerdict.Created, created.File, created.Row);
|
||||
case (null, not null):
|
||||
return new IdentityCheck(IdentityVerdict.EmptyDatabase, file, null);
|
||||
case (not null, null):
|
||||
var restored = new InstallationFile(row.Id, row.Fingerprint, row.Engine, row.CreatedAt, row.RenewedAt);
|
||||
WriteFile(data, restored);
|
||||
return new IdentityCheck(IdentityVerdict.FileRestored, restored, row);
|
||||
default:
|
||||
if (row.Id != file.InstallationId)
|
||||
{
|
||||
return new IdentityCheck(IdentityVerdict.DifferentInstallation, file, row);
|
||||
}
|
||||
|
||||
return row.Fingerprint == file.Fingerprint
|
||||
? new IdentityCheck(IdentityVerdict.Match, file, row)
|
||||
: new IdentityCheck(IdentityVerdict.StaleDatabase, file, row);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<(InstallationFile File, InstallationRow Row)> CreateAsync(Database db, DataDirectory data, IClock clock, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var row = new InstallationRow(Ids.NewId(clock), Ids.NewToken(), db.Engine.ToString().ToLowerInvariant(), false, now, now);
|
||||
await db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO installation (id, fingerprint, engine, protected_restart, created_at, renewed_at) VALUES (@id, @f, @e, @p, @c, @r)",
|
||||
cancellationToken, ("id", row.Id), ("f", row.Fingerprint), ("e", row.Engine), ("p", false), ("c", now), ("r", now)), cancellationToken).ConfigureAwait(false);
|
||||
var file = new InstallationFile(row.Id, row.Fingerprint, row.Engine, now, now);
|
||||
WriteFile(data, file);
|
||||
return (file, row);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After an import, a restore, a move, or when the user adopts this database: a new fingerprint in the database
|
||||
/// and in installation.json, the installation id of the data folder kept (or taken from the database when
|
||||
/// <paramref name="adoptDatabaseIdentity"/>), and the protected restart switched on (SPEC 15.1).
|
||||
/// </summary>
|
||||
public static async Task<InstallationFile> RenewAsync(Database db, DataDirectory data, IClock clock, bool adoptDatabaseIdentity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var now = clock.UtcNow;
|
||||
var fingerprint = Ids.NewToken();
|
||||
var file = ReadFile(data);
|
||||
var row = await ReadRowAsync(db, cancellationToken).ConfigureAwait(false);
|
||||
var id = adoptDatabaseIdentity || file is null ? row?.Id ?? Ids.NewId(clock) : file.InstallationId;
|
||||
var createdAt = row?.CreatedAt ?? file?.CreatedAt ?? now;
|
||||
var engine = db.Engine.ToString().ToLowerInvariant();
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("DELETE FROM installation", cancellationToken).ConfigureAwait(false);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO installation (id, fingerprint, engine, protected_restart, created_at, renewed_at) VALUES (@id, @f, @e, @p, @c, @r)",
|
||||
cancellationToken, ("id", id), ("f", fingerprint), ("e", engine), ("p", true), ("c", createdAt), ("r", now)).ConfigureAwait(false);
|
||||
|
||||
// Sessions of the old database do not survive: everyone signs in again.
|
||||
await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// SPEC 15.1: after an import, a restore or a move the bot restarts with "Ferma tutto" on, whatever the archive said.
|
||||
var key = Core.SettingsStore.BotState.Key;
|
||||
var stopped = new DbJson(JsonSerializer.Serialize("stopped"));
|
||||
var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false);
|
||||
if (old != stopped.Text)
|
||||
{
|
||||
await s.ExecuteAsync(old is null
|
||||
? "INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)"
|
||||
: "UPDATE config SET value = @v, updated_at = @t WHERE key = @k",
|
||||
cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", stopped), ("t", now)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("k", key), ("o", new DbJson(old ?? JsonSerializer.Serialize(Core.SettingsStore.BotState.Default))), ("n", stopped),
|
||||
("by", "ripartenza protetta"), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
var renewed = new InstallationFile(id, fingerprint, engine, createdAt, now);
|
||||
WriteFile(data, renewed);
|
||||
return renewed;
|
||||
}
|
||||
|
||||
/// <summary>"Comincia da capo": the data folder forgets its installation so an empty database can start a new one.</summary>
|
||||
public static void StartOver(DataDirectory data, IClock clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
if (File.Exists(data.InstallationFile))
|
||||
{
|
||||
var stamp = clock.UtcNow.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture);
|
||||
File.Move(data.InstallationFile, data.InstallationFile + ".precedente-" + stamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The user confirmed the protected restart (phase 9 adds the full procedure of SPEC 15.1).</summary>
|
||||
public static Task ClearProtectedRestartAsync(Database db, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
return db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @p", cancellationToken, ("p", false)), cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Anubis.Core;
|
||||
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Docker (SPEC 15.1): everything from environment variables. Missing or wrong values become
|
||||
/// <see cref="ConfigProblem"/>s for the error page; nothing falls back to another database (trap 20).
|
||||
/// </summary>
|
||||
public static class DockerPlatform
|
||||
{
|
||||
public const string DefaultTimeZone = "Europe/Rome";
|
||||
|
||||
/// <summary>Optional keys accepted from the environment (SPEC 15.1), each also with the _DEMO suffix.</summary>
|
||||
public static readonly string[] OptionalKeys =
|
||||
[
|
||||
"ALPACA_API_KEY", "ALPACA_API_SECRET", "OKX_API_KEY", "OKX_API_SECRET", "OKX_API_PASSPHRASE",
|
||||
"TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "LLM_API_KEY", "FINNHUB_API_KEY", "FRED_API_KEY",
|
||||
];
|
||||
|
||||
public static StartupConfig Load(IReadOnlyDictionary<string, string?> env, string dataRoot = "/data")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(env);
|
||||
string? Get(string name) => env.TryGetValue(name, out var v) && !string.IsNullOrWhiteSpace(v) ? v.Trim() : null;
|
||||
|
||||
var problems = new List<ConfigProblem>();
|
||||
var data = new DataDirectory(dataRoot);
|
||||
|
||||
var zone = ResolveTimeZone(Get("TZ") ?? DefaultTimeZone, problems, "TZ");
|
||||
var db = LoadDb(Get, data, problems);
|
||||
|
||||
var secret = Get("ANUBIS_SECRET_KEY");
|
||||
if (secret is null)
|
||||
{
|
||||
problems.Add(new("ANUBIS_SECRET_KEY", "Manca la chiave che cifra i segreti nel database.",
|
||||
"Imposta ANUBIS_SECRET_KEY con almeno 32 caratteri casuali e riavvia il container. Conservala: se cambia, le chiavi dei conti vanno reinserite."));
|
||||
}
|
||||
else if (secret.Length < EnvironmentSecretKey.MinimumLength)
|
||||
{
|
||||
problems.Add(new("ANUBIS_SECRET_KEY", "La chiave che cifra i segreti è troppo corta.",
|
||||
"Usa almeno 32 caratteri casuali in ANUBIS_SECRET_KEY e riavvia il container."));
|
||||
}
|
||||
|
||||
var admin = Get("ANUBIS_ADMIN_PASSWORD");
|
||||
if (admin is null)
|
||||
{
|
||||
problems.Add(new("ANUBIS_ADMIN_PASSWORD", "Manca la password iniziale.",
|
||||
"Imposta ANUBIS_ADMIN_PASSWORD e riavvia il container. Al primo accesso ne sceglierai una nuova; questa resta la chiave delle scelte di questa pagina."));
|
||||
}
|
||||
|
||||
Redactor.Register(secret);
|
||||
Redactor.Register(admin);
|
||||
Redactor.Register(db?.Password);
|
||||
|
||||
var allowLive = ParseAllowLive(Get("ANUBIS_ALLOW_LIVE"), problems);
|
||||
var port = ParsePort(Get("PORT"), 8787, "PORT", problems);
|
||||
var puid = ParseInt(Get("PUID"), 99, "PUID", problems);
|
||||
var pgid = ParseInt(Get("PGID"), 100, "PGID", problems);
|
||||
|
||||
var keys = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var name in OptionalKeys.SelectMany(k => new[] { k, k + "_DEMO" }))
|
||||
{
|
||||
if (Get(name) is { } value)
|
||||
{
|
||||
keys[name] = value;
|
||||
Redactor.Register(value);
|
||||
}
|
||||
}
|
||||
|
||||
return new StartupConfig
|
||||
{
|
||||
Platform = PlatformKind.Docker,
|
||||
Data = data,
|
||||
Db = db,
|
||||
TimeZone = zone,
|
||||
Port = port,
|
||||
AllowNetwork = true,
|
||||
AllowLive = allowLive,
|
||||
AdminPassword = admin,
|
||||
SecretKey = new EnvironmentSecretKey(secret),
|
||||
Puid = puid,
|
||||
Pgid = pgid,
|
||||
HeartbeatUrl = Get("ANUBIS_HEARTBEAT_URL"),
|
||||
EnvironmentKeys = keys,
|
||||
Problems = problems,
|
||||
};
|
||||
}
|
||||
|
||||
private static DbSettings? LoadDb(Func<string, string?> get, DataDirectory data, List<ConfigProblem> problems)
|
||||
{
|
||||
var engine = get("ANUBIS_DB_ENGINE");
|
||||
if (engine is null)
|
||||
{
|
||||
problems.Add(new("ANUBIS_DB_ENGINE", "Non è indicato quale database usare.",
|
||||
"Imposta ANUBIS_DB_ENGINE a postgres oppure a sqlite e riavvia il container."));
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (engine.ToLowerInvariant())
|
||||
{
|
||||
case "sqlite":
|
||||
return new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile };
|
||||
case "postgres":
|
||||
break;
|
||||
default:
|
||||
problems.Add(new("ANUBIS_DB_ENGINE", $"Il valore '{engine}' non è un database conosciuto.",
|
||||
"Usa postgres oppure sqlite e riavvia il container."));
|
||||
return null;
|
||||
}
|
||||
|
||||
var url = get("ANUBIS_DB_URL");
|
||||
if (url is not null)
|
||||
{
|
||||
return new DbSettings { Engine = DbEngine.Postgres, Url = url };
|
||||
}
|
||||
|
||||
var host = get("ANUBIS_DB_HOST");
|
||||
var password = get("ANUBIS_DB_PASSWORD");
|
||||
if (host is null)
|
||||
{
|
||||
problems.Add(new("ANUBIS_DB_HOST", "Manca l'indirizzo del server PostgreSQL.",
|
||||
"Imposta ANUBIS_DB_HOST (per esempio l'indirizzo IP del server o il nome del container) e riavvia."));
|
||||
}
|
||||
|
||||
if (password is null)
|
||||
{
|
||||
problems.Add(new("ANUBIS_DB_PASSWORD", "Manca la password dell'utente di PostgreSQL.",
|
||||
"Imposta ANUBIS_DB_PASSWORD con la password dell'utente dedicato ad Anubis e riavvia."));
|
||||
}
|
||||
|
||||
var port = ParsePort(get("ANUBIS_DB_PORT"), 5432, "ANUBIS_DB_PORT", problems);
|
||||
return host is null || password is null
|
||||
? null
|
||||
: new DbSettings
|
||||
{
|
||||
Engine = DbEngine.Postgres,
|
||||
Host = host,
|
||||
Port = port,
|
||||
Database = get("ANUBIS_DB_NAME") ?? "anubis",
|
||||
User = get("ANUBIS_DB_USER") ?? "anubis",
|
||||
Password = password,
|
||||
};
|
||||
}
|
||||
|
||||
internal static TimeZoneInfo ResolveTimeZone(string id, List<ConfigProblem> problems, string setting)
|
||||
{
|
||||
try
|
||||
{
|
||||
return TimeZoneInfo.FindSystemTimeZoneById(id);
|
||||
}
|
||||
catch (Exception ex) when (ex is TimeZoneNotFoundException or InvalidTimeZoneException)
|
||||
{
|
||||
problems.Add(new(setting, $"Il fuso orario '{id}' non esiste.", "Usa un nome come Europe/Rome e riavvia."));
|
||||
return TimeZoneInfo.Utc;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ParseAllowLive(string? value, List<ConfigProblem> problems)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case null or "0":
|
||||
return false;
|
||||
case "1":
|
||||
return true;
|
||||
default:
|
||||
problems.Add(new("ANUBIS_ALLOW_LIVE", $"Il valore '{value}' non è ammesso.", "Usa 0 (predefinito) oppure 1 e riavvia."));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int ParseInt(string? value, int fallback, string setting, List<ConfigProblem> problems)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
|
||||
if (int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var parsed))
|
||||
{
|
||||
return parsed;
|
||||
}
|
||||
|
||||
problems.Add(new(setting, $"Il valore '{value}' non è un numero intero.", $"Correggi {setting} e riavvia."));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
internal static int ParsePort(string? value, int fallback, string setting, List<ConfigProblem> problems)
|
||||
{
|
||||
var port = ParseInt(value, fallback, setting, problems);
|
||||
if (port is < 1 or > 65535)
|
||||
{
|
||||
problems.Add(new(setting, $"La porta {port.ToString(CultureInfo.InvariantCulture)} non è valida.", "Usa un numero tra 1 e 65535."));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Desktop (SPEC 15.6): <c>config.toml</c> in the user's data folder, written by the first-run wizard.
|
||||
/// The secret key and the PostgreSQL password never go in the file: they live in the <see cref="IProtectedStore"/>.
|
||||
/// </summary>
|
||||
public static class DesktopPlatform
|
||||
{
|
||||
public const string DbPasswordName = "db-password";
|
||||
|
||||
public static StartupConfig Load(DataDirectory data, IProtectedStore store)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
var problems = new List<ConfigProblem>();
|
||||
var secretKey = new ProtectedSecretKey(store);
|
||||
if (!File.Exists(data.ConfigFile))
|
||||
{
|
||||
return new StartupConfig
|
||||
{
|
||||
Platform = PlatformKind.Desktop,
|
||||
Data = data,
|
||||
TimeZone = TimeZoneInfo.Local,
|
||||
SecretKey = secretKey,
|
||||
NeedsFirstRun = true,
|
||||
};
|
||||
}
|
||||
|
||||
IReadOnlyDictionary<string, object> toml;
|
||||
try
|
||||
{
|
||||
toml = Toml.Parse(File.ReadAllText(data.ConfigFile));
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
problems.Add(new("config.toml", "Il file di configurazione non si legge: " + ex.Message,
|
||||
$"Correggi il file {data.ConfigFile} oppure rinominalo per ripetere la procedura di primo avvio."));
|
||||
return new StartupConfig { Platform = PlatformKind.Desktop, Data = data, TimeZone = TimeZoneInfo.Local, SecretKey = secretKey, Problems = problems };
|
||||
}
|
||||
|
||||
string? Text(string key) => toml.TryGetValue(key, out var v) ? v as string ?? Fail<string>(key, "testo tra virgolette") : null;
|
||||
long? Integer(string key) => toml.TryGetValue(key, out var v) ? v is long n ? n : Fail<long?>(key, "un numero intero") : null;
|
||||
bool? Flag(string key) => toml.TryGetValue(key, out var v) ? v is bool b ? b : Fail<bool?>(key, "true o false") : null;
|
||||
T? Fail<T>(string key, string expected)
|
||||
{
|
||||
problems.Add(new("config.toml", $"La voce '{key}' deve essere {expected}.", $"Correggi {data.ConfigFile} e riavvia."));
|
||||
return default;
|
||||
}
|
||||
|
||||
var zone = Text("timezone") is { } tz ? DockerPlatform.ResolveTimeZone(tz, problems, "config.toml: timezone") : TimeZoneInfo.Local;
|
||||
DbSettings? db = null;
|
||||
switch (Text("database.engine"))
|
||||
{
|
||||
case "sqlite":
|
||||
db = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile };
|
||||
break;
|
||||
case "postgres":
|
||||
var password = store.Read(DbPasswordName) is { } bytes ? Encoding.UTF8.GetString(bytes) : null;
|
||||
Redactor.Register(password);
|
||||
if (Text("database.host") is not { } host)
|
||||
{
|
||||
problems.Add(new("config.toml", "Manca l'indirizzo del server PostgreSQL (database.host).", $"Correggi {data.ConfigFile} e riavvia."));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (password is null)
|
||||
{
|
||||
problems.Add(new("Password del database", "La password di PostgreSQL non è nel portachiavi.",
|
||||
"Ripeti la procedura di primo avvio rinominando config.toml, oppure torna a SQLite."));
|
||||
}
|
||||
|
||||
db = new DbSettings
|
||||
{
|
||||
Engine = DbEngine.Postgres,
|
||||
Host = host,
|
||||
Port = (int)(Integer("database.port") ?? 5432),
|
||||
Database = Text("database.name") ?? "anubis",
|
||||
User = Text("database.user") ?? "anubis",
|
||||
Password = password,
|
||||
};
|
||||
}
|
||||
|
||||
break;
|
||||
case null:
|
||||
problems.Add(new("config.toml", "Non è indicato quale database usare (database.engine).", $"Scrivi engine = \"sqlite\" oppure \"postgres\" nella sezione [database] di {data.ConfigFile}."));
|
||||
break;
|
||||
case var other:
|
||||
problems.Add(new("config.toml", $"Il database '{other}' non è conosciuto.", "Usa \"sqlite\" oppure \"postgres\"."));
|
||||
break;
|
||||
}
|
||||
|
||||
var port = Integer("port") ?? 8787;
|
||||
if (port is < 1 or > 65535)
|
||||
{
|
||||
problems.Add(new("config.toml", "La porta non è valida.", "Usa un numero tra 1 e 65535."));
|
||||
port = 8787;
|
||||
}
|
||||
|
||||
return new StartupConfig
|
||||
{
|
||||
Platform = PlatformKind.Desktop,
|
||||
Data = data,
|
||||
Db = db,
|
||||
TimeZone = zone,
|
||||
Port = (int)port,
|
||||
AllowNetwork = Flag("allow_network") ?? false,
|
||||
AllowLive = Flag("allow_live") ?? false,
|
||||
SecretKey = secretKey,
|
||||
Problems = problems,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes config.toml at the end of the first-run wizard. <c>allow_live</c> is born false and only a hand edit
|
||||
/// turns it on (SPEC 15.6). The PostgreSQL password goes to the protected store, never into the file.
|
||||
/// </summary>
|
||||
public static void WriteConfig(DataDirectory data, IProtectedStore store, DbSettings db, int port = 8787, bool allowNetwork = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
var text = new StringBuilder();
|
||||
text.AppendLine("# Anubis: configurazione d'avvio (SPEC 15.6). Scritta dalla procedura di primo avvio.");
|
||||
text.AppendLine("# La chiave dei segreti e la password del database non stanno qui: sono nel portachiavi.");
|
||||
text.AppendLine();
|
||||
text.AppendLine("# Soldi veri: false. Si cambia solo a mano, mai dall'interfaccia.");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"allow_live = false");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"port = {port}");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"allow_network = {(allowNetwork ? "true" : "false")}");
|
||||
text.AppendLine();
|
||||
text.AppendLine("[database]");
|
||||
if (db.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
text.AppendLine("engine = \"sqlite\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
text.AppendLine("engine = \"postgres\"");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"host = {Toml.Quote(db.Host ?? "")}");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"port = {db.Port}");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"name = {Toml.Quote(db.Database)}");
|
||||
text.AppendLine(CultureInfo.InvariantCulture, $"user = {Toml.Quote(db.User)}");
|
||||
store.Write(DbPasswordName, Encoding.UTF8.GetBytes(db.Password ?? ""));
|
||||
}
|
||||
|
||||
data.Ensure();
|
||||
var temp = data.ConfigFile + ".tmp";
|
||||
File.WriteAllText(temp, text.ToString().ReplaceLineEndings("\n"));
|
||||
File.Move(temp, data.ConfigFile, overwrite: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Custody of the key that encrypts the secrets in the database (SPEC 15.4, 15.6). The interface says
|
||||
/// where the key lives, so Settings can declare it.
|
||||
/// </summary>
|
||||
public interface ISecretKeyStore
|
||||
{
|
||||
/// <summary>Where the key lives, in plain Italian, for Settings → Sistema.</summary>
|
||||
string Description { get; }
|
||||
|
||||
/// <summary>True when the key exists (or, in Docker, the variable is set).</summary>
|
||||
bool HasKey { get; }
|
||||
|
||||
/// <summary>The 32-byte key. Desktop stores create it on first use.</summary>
|
||||
byte[] GetOrCreateKey();
|
||||
}
|
||||
|
||||
/// <summary>Docker: the key derives from <c>ANUBIS_SECRET_KEY</c> (at least 32 characters, SPEC 15.1).</summary>
|
||||
public sealed class EnvironmentSecretKey(string? value) : ISecretKeyStore
|
||||
{
|
||||
public const int MinimumLength = 32;
|
||||
|
||||
public string Description => "Variabile d'ambiente ANUBIS_SECRET_KEY del container";
|
||||
|
||||
public bool HasKey => value is { Length: >= MinimumLength };
|
||||
|
||||
public byte[] GetOrCreateKey()
|
||||
{
|
||||
if (!HasKey)
|
||||
{
|
||||
throw new InvalidOperationException("ANUBIS_SECRET_KEY is missing or shorter than 32 characters.");
|
||||
}
|
||||
|
||||
return HKDF.DeriveKey(HashAlgorithmName.SHA256, Encoding.UTF8.GetBytes(value!), 32, salt: [], info: "anubis-secrets-v1"u8.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Small values kept outside config.toml: the desktop secret key and the PostgreSQL password (SPEC 15.6).</summary>
|
||||
public interface IProtectedStore
|
||||
{
|
||||
string Description { get; }
|
||||
|
||||
byte[]? Read(string name);
|
||||
|
||||
void Write(string name, byte[] value);
|
||||
}
|
||||
|
||||
/// <summary>Windows: files in the data folder encrypted with DPAPI for the current user (ADR 0003 in place of keyring).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public sealed class DpapiStore(string folder) : IProtectedStore
|
||||
{
|
||||
private static readonly byte[] _entropy = "Anubis protected store v1"u8.ToArray();
|
||||
|
||||
public string Description => "Protetta da Windows per il tuo utente (DPAPI), nella cartella dei dati";
|
||||
|
||||
public byte[]? Read(string name)
|
||||
{
|
||||
var path = PathOf(name);
|
||||
return File.Exists(path) ? ProtectedData.Unprotect(File.ReadAllBytes(path), _entropy, DataProtectionScope.CurrentUser) : null;
|
||||
}
|
||||
|
||||
public void Write(string name, byte[] value)
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
File.WriteAllBytes(PathOf(name), ProtectedData.Protect(value, _entropy, DataProtectionScope.CurrentUser));
|
||||
}
|
||||
|
||||
private string PathOf(string name) => Path.Combine(folder, name + ".dpapi");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where no system keychain exists (Linux without a session, macOS for now, the tests): a file readable
|
||||
/// only by its owner. The interface declares it (SPEC 15.6).
|
||||
/// </summary>
|
||||
public sealed class RestrictedFileStore(string folder) : IProtectedStore
|
||||
{
|
||||
public string Description => "File con permessi ristretti nella cartella dei dati (nessun portachiavi disponibile)";
|
||||
|
||||
public byte[]? Read(string name)
|
||||
{
|
||||
var path = PathOf(name);
|
||||
return File.Exists(path) ? Convert.FromBase64String(File.ReadAllText(path).Trim()) : null;
|
||||
}
|
||||
|
||||
public void Write(string name, byte[] value)
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
var path = PathOf(name);
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
File.WriteAllText(path, Convert.ToBase64String(value));
|
||||
return;
|
||||
}
|
||||
|
||||
// Create with 0600 from the start, so the value is never readable by others even for an instant.
|
||||
using var stream = new FileStream(path, new FileStreamOptions
|
||||
{
|
||||
Mode = FileMode.Create,
|
||||
Access = FileAccess.Write,
|
||||
UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite,
|
||||
});
|
||||
stream.Write(Encoding.ASCII.GetBytes(Convert.ToBase64String(value)));
|
||||
}
|
||||
|
||||
private string PathOf(string name) => Path.Combine(folder, name + ".key");
|
||||
}
|
||||
|
||||
/// <summary>Desktop: a random 32-byte key born on first start and kept in an <see cref="IProtectedStore"/>.</summary>
|
||||
public sealed class ProtectedSecretKey(IProtectedStore store) : ISecretKeyStore
|
||||
{
|
||||
private const string Name = "secret-key";
|
||||
|
||||
public string Description => store.Description;
|
||||
|
||||
public bool HasKey => store.Read(Name) is { Length: 32 };
|
||||
|
||||
public byte[] GetOrCreateKey()
|
||||
{
|
||||
if (store.Read(Name) is { Length: 32 } existing)
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
|
||||
var key = RandomNumberGenerator.GetBytes(32);
|
||||
store.Write(Name, key);
|
||||
return key;
|
||||
}
|
||||
|
||||
/// <summary>The store for this machine: DPAPI on Windows, a restricted file elsewhere.</summary>
|
||||
public static IProtectedStore DefaultStore(DataDirectory data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var folder = Path.Combine(data.Root, "keys");
|
||||
return OperatingSystem.IsWindows() ? new DpapiStore(folder) : new RestrictedFileStore(folder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
namespace Anubis.Platform;
|
||||
|
||||
public enum PlatformKind
|
||||
{
|
||||
Docker,
|
||||
Desktop,
|
||||
}
|
||||
|
||||
public enum DbEngine
|
||||
{
|
||||
Sqlite,
|
||||
Postgres,
|
||||
}
|
||||
|
||||
/// <summary>How to reach the database. The password never appears in <see cref="ToString"/>.</summary>
|
||||
public sealed record DbSettings
|
||||
{
|
||||
public required DbEngine Engine { get; init; }
|
||||
|
||||
/// <summary>SQLite file path; null for PostgreSQL.</summary>
|
||||
public string? SqlitePath { get; init; }
|
||||
|
||||
public string? Host { get; init; }
|
||||
|
||||
public int Port { get; init; } = 5432;
|
||||
|
||||
public string Database { get; init; } = "anubis";
|
||||
|
||||
public string User { get; init; } = "anubis";
|
||||
|
||||
public string? Password { get; init; }
|
||||
|
||||
/// <summary>A full PostgreSQL address (<c>ANUBIS_DB_URL</c>) that replaces the five fields.</summary>
|
||||
public string? Url { get; init; }
|
||||
|
||||
/// <summary>What the interface shows: engine and place, never the password.</summary>
|
||||
public string Describe() => Engine switch
|
||||
{
|
||||
DbEngine.Sqlite => "SQLite, " + SqlitePath,
|
||||
_ when Url is not null => "PostgreSQL, indirizzo completo da ANUBIS_DB_URL",
|
||||
_ => $"PostgreSQL, {Host}:{Port}/{Database} come {User}",
|
||||
};
|
||||
|
||||
public override string ToString() => Describe();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The startup configuration (SPEC 15.1, 15.6): everything needed before the database is reachable.
|
||||
/// It comes from environment variables in Docker and from <c>config.toml</c> on desktop. Values here win
|
||||
/// over the ones saved from the interface, which shows them read-only.
|
||||
/// </summary>
|
||||
public sealed record StartupConfig
|
||||
{
|
||||
public required PlatformKind Platform { get; init; }
|
||||
|
||||
public required DataDirectory Data { get; init; }
|
||||
|
||||
/// <summary>Null when the configuration does not say which database to use (the error page explains what is missing).</summary>
|
||||
public DbSettings? Db { get; init; }
|
||||
|
||||
public required TimeZoneInfo TimeZone { get; init; }
|
||||
|
||||
public int Port { get; init; } = 8787;
|
||||
|
||||
/// <summary>Desktop: listen on the home network too (SPEC 15.6). Docker always listens on every interface of the container.</summary>
|
||||
public bool AllowNetwork { get; init; }
|
||||
|
||||
/// <summary><c>ANUBIS_ALLOW_LIVE=1</c> or <c>allow_live = true</c>: only then adapters accept a real account (SPEC 2.2).</summary>
|
||||
public bool AllowLive { get; init; }
|
||||
|
||||
/// <summary>Docker: the initial password (<c>ANUBIS_ADMIN_PASSWORD</c>), also the key of the error page choices.</summary>
|
||||
public string? AdminPassword { get; init; }
|
||||
|
||||
public required ISecretKeyStore SecretKey { get; init; }
|
||||
|
||||
public int Puid { get; init; } = 99;
|
||||
|
||||
public int Pgid { get; init; } = 100;
|
||||
|
||||
public string? HeartbeatUrl { get; init; }
|
||||
|
||||
/// <summary>Optional broker and service keys from the environment (SPEC 15.1), by variable name.</summary>
|
||||
public IReadOnlyDictionary<string, string> EnvironmentKeys { get; init; } = new Dictionary<string, string>();
|
||||
|
||||
/// <summary>Problems that stop the start: the error page lists them with what to do.</summary>
|
||||
public IReadOnlyList<ConfigProblem> Problems { get; init; } = [];
|
||||
|
||||
/// <summary>Desktop only: <c>config.toml</c> does not exist yet, the first-run wizard writes it.</summary>
|
||||
public bool NeedsFirstRun { get; init; }
|
||||
|
||||
public bool IsComplete => Problems.Count == 0 && Db is not null && !NeedsFirstRun;
|
||||
}
|
||||
|
||||
/// <summary>Something missing or wrong in the startup configuration, said in plain Italian with the remedy.</summary>
|
||||
public sealed record ConfigProblem(string Setting, string What, string Remedy);
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Anubis.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// The subset of TOML that <c>config.toml</c> needs (ADR 0003, no external parser): comments, tables
|
||||
/// <c>[name]</c>, and <c>key = value</c> with basic strings, integers and booleans. Anything else is an error
|
||||
/// with its line number, so a hand edit gone wrong shows on the error page instead of being guessed.
|
||||
/// </summary>
|
||||
public static class Toml
|
||||
{
|
||||
/// <summary>Parses into "table.key" → value (string, long or bool). Keys outside a table have no prefix.</summary>
|
||||
public static IReadOnlyDictionary<string, object> Parse(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var result = new Dictionary<string, object>(StringComparer.Ordinal);
|
||||
var table = "";
|
||||
var lineNumber = 0;
|
||||
foreach (var rawLine in text.Split('\n'))
|
||||
{
|
||||
lineNumber++;
|
||||
var line = StripComment(rawLine).Trim();
|
||||
if (line.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.StartsWith('['))
|
||||
{
|
||||
if (!line.EndsWith(']') || line.StartsWith("[[", StringComparison.Ordinal))
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: intestazione di sezione non valida.");
|
||||
}
|
||||
|
||||
table = line[1..^1].Trim();
|
||||
if (!IsBareKey(table))
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: nome di sezione non valido.");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var equals = line.IndexOf('=', StringComparison.Ordinal);
|
||||
if (equals <= 0)
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: manca il segno '='.");
|
||||
}
|
||||
|
||||
var key = line[..equals].Trim();
|
||||
if (!IsBareKey(key))
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: nome non valido '{key}'.");
|
||||
}
|
||||
|
||||
var fullKey = table.Length == 0 ? key : table + "." + key;
|
||||
if (!result.TryAdd(fullKey, ParseValue(line[(equals + 1)..].Trim(), lineNumber)))
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: '{fullKey}' compare due volte.");
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static object ParseValue(string value, int lineNumber)
|
||||
{
|
||||
if (value.StartsWith('"'))
|
||||
{
|
||||
return ParseString(value, lineNumber);
|
||||
}
|
||||
|
||||
if (value is "true")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value is "false")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (long.TryParse(value.Replace("_", "", StringComparison.Ordinal), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var number))
|
||||
{
|
||||
return number;
|
||||
}
|
||||
|
||||
throw new FormatException($"Riga {lineNumber}: valore non riconosciuto. Usa testo tra virgolette, un numero intero, true o false.");
|
||||
}
|
||||
|
||||
private static string ParseString(string value, int lineNumber)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
for (var i = 1; i < value.Length; i++)
|
||||
{
|
||||
var c = value[i];
|
||||
if (c == '"')
|
||||
{
|
||||
if (i != value.Length - 1)
|
||||
{
|
||||
throw new FormatException($"Riga {lineNumber}: testo dopo la chiusura delle virgolette.");
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
if (c == '\\')
|
||||
{
|
||||
if (++i >= value.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
text.Append(value[i] switch
|
||||
{
|
||||
'"' => '"',
|
||||
'\\' => '\\',
|
||||
'n' => '\n',
|
||||
't' => '\t',
|
||||
'r' => '\r',
|
||||
_ => throw new FormatException($"Riga {lineNumber}: sequenza '\\{value[i]}' non ammessa."),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
text.Append(c);
|
||||
}
|
||||
|
||||
throw new FormatException($"Riga {lineNumber}: virgolette non chiuse.");
|
||||
}
|
||||
|
||||
// A '#' starts a comment unless it is inside a string.
|
||||
private static string StripComment(string line)
|
||||
{
|
||||
var inString = false;
|
||||
for (var i = 0; i < line.Length; i++)
|
||||
{
|
||||
if (line[i] == '\\' && inString)
|
||||
{
|
||||
i++;
|
||||
}
|
||||
else if (line[i] == '"')
|
||||
{
|
||||
inString = !inString;
|
||||
}
|
||||
else if (line[i] == '#' && !inString)
|
||||
{
|
||||
return line[..i];
|
||||
}
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
private static bool IsBareKey(string key) =>
|
||||
key.Length > 0 && key.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-');
|
||||
|
||||
public static string Quote(string value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
return "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal)
|
||||
.Replace("\n", "\\n", StringComparison.Ordinal).Replace("\r", "\\r", StringComparison.Ordinal).Replace("\t", "\\t", StringComparison.Ordinal) + "\"";
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,8 @@ Le cartelle nascono con il primo codice che le riempie:
|
||||
|---|---|---|---|
|
||||
| `Core/` | `Anubis.Core` | orologio, bus degli eventi, pianificatore, impostazioni, segreti, registri, identificativi, guardia, formati | 1 |
|
||||
| `Platform/` | `Anubis.Platform` | configurazione d'avvio Docker e desktop, cartella dei dati, custodia dei segreti | 1 |
|
||||
| `Db/` | `Anubis.Db` | accesso ADO.NET, repository, migrazioni SQL | 1 |
|
||||
| `Db/` | `Anubis.Db` | accesso ADO.NET, tipi portabili, migrazioni SQL, esportazione e importazione, salvataggi | 1 |
|
||||
| `Access/` | `Anubis.Access` | password, secondo fattore, sessioni, limite ai tentativi | 1 |
|
||||
| `Brokers/` | `Anubis.Brokers` | interfaccia, Alpaca, OKX, simulatore, batteria di conformità | 2–3 |
|
||||
| `Data/` | `Anubis.Data` | strumenti, barre, raccolta, qualità, importatori, cambi, calendari | 2 |
|
||||
| `News/` | `Anubis.News` | fonti, pipeline, classificatore, analista, impatto | 7 |
|
||||
|
||||
@@ -1,6 +1,81 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {}
|
||||
"net10.0": {
|
||||
"Microsoft.Data.Sqlite": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Data.Sqlite.Core": "10.0.14",
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.3, )",
|
||||
"resolved": "10.0.3",
|
||||
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.0",
|
||||
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.bundle_e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
|
||||
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
|
||||
}
|
||||
},
|
||||
"SQLitePCLRaw.core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
|
||||
},
|
||||
"SQLitePCLRaw.lib.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
|
||||
},
|
||||
"SQLitePCLRaw.provider.e_sqlite3": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.1.13",
|
||||
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.13"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>Export, import and backups (issue #9, SPEC 5.4).</summary>
|
||||
[TestClass]
|
||||
public sealed class ArchiveTests
|
||||
{
|
||||
private static readonly ManualClock _clock = new(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
|
||||
|
||||
/// <summary>Fills a database with rows of every column kind, including accounting rows and a reversal.</summary>
|
||||
internal static async Task SeedAsync(Database db)
|
||||
{
|
||||
var (account, instrument) = await DatabaseTests.SeedAccountAsync(db).ConfigureAwait(false);
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
var fill = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(1));
|
||||
var reversal = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(2));
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO fills (id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at) VALUES (@id, @a, @i, 'EX-1', 'buy', @q, @p, @f, 'EUR', @t, @t)",
|
||||
("id", fill), ("a", account), ("i", instrument), ("q", 0.0182m), ("p", 68950m), ("f", 1.254890000000000001m), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO fills (id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, reverses_id, executed_at, created_at) VALUES (@id, @a, @i, 'EX-1-R', 'buy', @q, @p, @f, 'EUR', @r, @t, @t)",
|
||||
("id", reversal), ("a", account), ("i", instrument), ("q", -0.0182m), ("p", 68950m), ("f", -1.254890000000000001m), ("r", fill), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
||||
for (var i = 0; i < 25; i++)
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, currency, amount, kind, note, occurred_at, created_at) VALUES (@id, @a, 'EUR', @v, 'deposit', @n, @t, @t)",
|
||||
("id", Guid.CreateVersion7(_clock.UtcNow.AddSeconds(10 + i))), ("a", account), ("v", 100.01m * i - 333.333333333333333333m), ("n", i % 3 == 0 ? null : "nota \"" + i + "\" ;\n"),
|
||||
("t", _clock.UtcNow.AddDays(-i))).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await s.ExecuteAsync("INSERT INTO journal (id, occurred_at, kind, code, message, data, created_at) VALUES (@id, @t, 'Ordini', 'stop_raised', @m, @d, @t)",
|
||||
("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow), ("m", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €."), ("d", new DbJson("{\"from\": \"65400\", \"to\": \"66180\"}"))).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, 'admin', 'h', @m, @s, @t, @t)",
|
||||
("id", Guid.CreateVersion7(_clock.UtcNow)), ("m", true), ("s", new byte[] { 0, 1, 2, 255 }), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ExportThenImportOnTheSameEngineKeepsEverything()
|
||||
{
|
||||
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await RoundTripAsync(source, target).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ExportFromOneEngineImportsIntoTheOtherWithSameCountsAndTotals()
|
||||
{
|
||||
if (!await TestDb.PostgresAvailableAsync().ConfigureAwait(false))
|
||||
{
|
||||
Assert.Inconclusive("PostgreSQL per i test non raggiungibile: la prova tra motori gira in CI e con `tasks ci`.");
|
||||
}
|
||||
|
||||
foreach (var (from, to) in new[] { (DbEngine.Sqlite, DbEngine.Postgres), (DbEngine.Postgres, DbEngine.Sqlite) })
|
||||
{
|
||||
await using var source = await TestDb.CreateAsync(from).ConfigureAwait(false);
|
||||
await Migrations.MigrateAsync(source.Db, _clock, null, CancellationToken.None).ConfigureAwait(false);
|
||||
await using var target = await TestDb.CreateAsync(to).ConfigureAwait(false);
|
||||
await RoundTripAsync(source, target).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task RoundTripAsync(TestDb source, TestDb target)
|
||||
{
|
||||
await SeedAsync(source.Db).ConfigureAwait(false);
|
||||
var folder = TempFolder.Create("archive");
|
||||
try
|
||||
{
|
||||
var index = await Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
||||
Assert.AreEqual(Migrations.Latest, index.SchemaVersion);
|
||||
Assert.AreEqual(2L, index.Tables.Single(t => t.Name == "fills").Count);
|
||||
Assert.AreEqual("0", index.AccountingTotals["fills.quantity"], "il fill e il suo storno si annullano");
|
||||
|
||||
await Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
||||
|
||||
CollectionAssert.AreEquivalent(
|
||||
(await Archive.CountsAsync(source.Db).ConfigureAwait(false)).ToList(),
|
||||
(await Archive.CountsAsync(target.Db).ConfigureAwait(false)).ToList(), $"{source.Db.Engine} → {target.Db.Engine}");
|
||||
CollectionAssert.AreEquivalent(
|
||||
(await Archive.AccountingTotalsAsync(source.Db).ConfigureAwait(false)).ToList(),
|
||||
(await Archive.AccountingTotalsAsync(target.Db).ConfigureAwait(false)).ToList());
|
||||
|
||||
// A second export of the target is identical row by row.
|
||||
await Archive.ExportAsync(target.Db, Path.Combine(folder, "b"), _clock).ConfigureAwait(false);
|
||||
foreach (var table in Schema.Tables)
|
||||
{
|
||||
CollectionAssert.AreEqual(
|
||||
File.ReadAllLines(Path.Combine(folder, "a", table.Name + ".jsonl")),
|
||||
File.ReadAllLines(Path.Combine(folder, "b", table.Name + ".jsonl")), table.Name);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ImportRefusesANonEmptyDatabaseAndATamperedArchive()
|
||||
{
|
||||
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
await SeedAsync(source.Db).ConfigureAwait(false);
|
||||
var folder = TempFolder.Create("archive-bad");
|
||||
try
|
||||
{
|
||||
await Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => Archive.ImportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
|
||||
|
||||
var cash = Path.Combine(folder, "a", "cash_ledger.jsonl");
|
||||
var lines = File.ReadAllLines(cash);
|
||||
File.WriteAllLines(cash, lines.Skip(1));
|
||||
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await Assert.ThrowsAsync<InvalidDataException>(() => Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
|
||||
Assert.AreEqual(0L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["accounts"], "un'importazione fallita non lascia righe");
|
||||
|
||||
await Assert.ThrowsAsync<IOException>(() => Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task BackupsKeepTheLastFourteenAndCopyTheSqliteFile()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
await SeedAsync(test.Db).ConfigureAwait(false);
|
||||
var folder = TempFolder.Create("backups");
|
||||
try
|
||||
{
|
||||
var clock = new ManualClock(_clock.UtcNow);
|
||||
var backups = new Backups(new DataDirectory(folder), clock);
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
await backups.TakeAsync(test.Db, i == 0 ? "prima-della-migrazione" : "notturno").ConfigureAwait(false);
|
||||
clock.Advance(TimeSpan.FromDays(1));
|
||||
}
|
||||
|
||||
var list = backups.List();
|
||||
Assert.HasCount(Backups.Keep, list);
|
||||
Assert.AreEqual(clock.UtcNow.AddDays(-1).Date, list[0].TakenAt.UtcDateTime.Date, "la più recente è la prima");
|
||||
Assert.AreEqual(test.Db.Engine == DbEngine.Sqlite, list[0].HasSqliteCopy);
|
||||
Assert.IsFalse(Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories).Any(d => d.EndsWith(".partial", StringComparison.Ordinal)));
|
||||
|
||||
if (test.Db.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
// The copy made with the backup API opens and has the same rows.
|
||||
await using var copy = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(list[0].Folder, Backups.SqliteCopy) }, allowCreate: false);
|
||||
CollectionAssert.AreEquivalent((await Archive.CountsAsync(test.Db).ConfigureAwait(false)).ToList(), (await Archive.CountsAsync(copy).ConfigureAwait(false)).ToList());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task MigratingADatabaseWithDataTakesABackupFirst()
|
||||
{
|
||||
await using var test = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
var calls = 0;
|
||||
await Migrations.MigrateAsync(test.Db, _clock, _ =>
|
||||
{
|
||||
calls++;
|
||||
return Task.CompletedTask;
|
||||
}, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual(0, calls, "un database vuoto non ha nulla da salvare");
|
||||
|
||||
// A failing backup stops the migration (simulated on an older schema by removing the version row).
|
||||
await test.Db.WriteAsync(s => s.ExecuteAsync($"DELETE FROM {Migrations.VersionTable} WHERE version = @v", ("v", Migrations.Latest))).ConfigureAwait(false);
|
||||
if (Migrations.Latest > 1)
|
||||
{
|
||||
await Assert.ThrowsAsync<IOException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// SPEC 13.4: the seven text colours reach 4.5:1 on the page and on the panels, the control border 3:1 on the panels,
|
||||
/// in both themes; and the style uses no colour outside appendix C.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[TestCategory(Category.Unit)]
|
||||
public sealed partial class ContrastTests
|
||||
{
|
||||
private static readonly string[] _texts = ["--text", "--text-2", "--text-3", "--link", "--gain", "--loss", "--attention"];
|
||||
|
||||
private static string Css() => File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis.Server", "Assets", "app.css"));
|
||||
|
||||
private static Dictionary<string, string> Block(string css, string selector)
|
||||
{
|
||||
var start = css.IndexOf(selector + " {", StringComparison.Ordinal);
|
||||
Assert.IsGreaterThanOrEqualTo(0, start, "Missing block " + selector);
|
||||
var end = css.IndexOf('}', start);
|
||||
return Token().Matches(css[start..end]).ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value.ToLowerInvariant(), StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> Themes() => [[":root"], [":root[data-theme=\"dark\"]"], [":root:not([data-theme=\"light\"])"]];
|
||||
|
||||
[TestMethod]
|
||||
[DynamicData(nameof(Themes))]
|
||||
public void TextAndControlsAreReadable(string selector)
|
||||
{
|
||||
var tokens = Block(Css(), selector);
|
||||
foreach (var text in _texts)
|
||||
{
|
||||
foreach (var background in new[] { "--page", "--surface" })
|
||||
{
|
||||
var ratio = Ratio(tokens[text], tokens[background]);
|
||||
Assert.IsGreaterThanOrEqualTo(4.5, ratio, $"{selector} {text} on {background}: {ratio:0.00}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsGreaterThanOrEqualTo(3.0, Ratio(tokens["--control"], tokens["--surface"]), selector + " control border");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DarkThemeIsTheSameForTheSystemAndTheSetting()
|
||||
{
|
||||
var css = Css();
|
||||
CollectionAssert.AreEquivalent(Block(css, ":root[data-theme=\"dark\"]").ToList(), Block(css, ":root:not([data-theme=\"light\"])").ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyColoursOfAppendixC()
|
||||
{
|
||||
var spec = File.ReadAllText(Path.Combine(Repo.Root.FullName, "docs", "SPEC.md"));
|
||||
var appendix = spec[spec.IndexOf("## Appendice C", StringComparison.Ordinal)..spec.IndexOf("## Appendice D", StringComparison.Ordinal)];
|
||||
var allowed = Hex().Matches(appendix).Select(m => m.Value.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
var used = Hex().Matches(Css()).Select(m => m.Value.ToLowerInvariant()).Distinct().ToList();
|
||||
Assert.IsNotEmpty(used);
|
||||
foreach (var colour in used)
|
||||
{
|
||||
Assert.Contains(colour, allowed, colour + " is not in appendix C");
|
||||
}
|
||||
}
|
||||
|
||||
private static double Ratio(string a, string b)
|
||||
{
|
||||
var (la, lb) = (Luminance(a), Luminance(b));
|
||||
return (Math.Max(la, lb) + 0.05) / (Math.Min(la, lb) + 0.05);
|
||||
}
|
||||
|
||||
private static double Luminance(string hex)
|
||||
{
|
||||
double Channel(int i)
|
||||
{
|
||||
var c = int.Parse(hex.AsSpan(1 + (2 * i), 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) / 255.0;
|
||||
return c <= 0.03928 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
return (0.2126 * Channel(0)) + (0.7152 * Channel(1)) + (0.0722 * Channel(2));
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"(--[a-z0-9-]+):\s*(#[0-9a-fA-F]{6})")]
|
||||
private static partial Regex Token();
|
||||
|
||||
[GeneratedRegex(@"#[0-9a-fA-F]{6}(?![0-9a-fA-F])")]
|
||||
private static partial Regex Hex();
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
using Anubis.Core;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
[TestClass]
|
||||
public sealed class CoreTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void IdsAreVersion7AndFollowTheInjectedClock()
|
||||
{
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
|
||||
var first = Ids.NewId(clock);
|
||||
clock.Advance(TimeSpan.FromMilliseconds(5));
|
||||
var second = Ids.NewId(clock);
|
||||
Assert.AreEqual(7, first.Version);
|
||||
Assert.IsLessThan(0, string.CompareOrdinal(first.ToString(), second.ToString()), "gli identificativi seguono il tempo");
|
||||
Assert.AreNotEqual(Ids.NewToken(), Ids.NewToken());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task ManualClockReleasesWaitersOnlyWhenMoved()
|
||||
{
|
||||
var clock = new ManualClock(DateTimeOffset.UnixEpoch);
|
||||
var waiting = clock.WaitUntilAsync(DateTimeOffset.UnixEpoch.AddMinutes(5), CancellationToken.None);
|
||||
clock.Advance(TimeSpan.FromMinutes(4));
|
||||
Assert.IsFalse(waiting.IsCompleted);
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await waiting.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task BusDeliversToEachSubscriberAndDropsOldestWhenFull()
|
||||
{
|
||||
var bus = new EventBus();
|
||||
using var all = bus.Subscribe<object>();
|
||||
using var small = bus.Subscribe<string>(capacity: 2);
|
||||
bus.Publish("a");
|
||||
bus.Publish("b");
|
||||
bus.Publish("c");
|
||||
bus.Publish(42);
|
||||
|
||||
var received = new List<string>();
|
||||
while (small.TryRead(out var message))
|
||||
{
|
||||
received.Add(message!);
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "b", "c" }, received, "un lettore lento perde i più vecchi, non blocca chi pubblica");
|
||||
var count = 0;
|
||||
while (all.TryRead(out _))
|
||||
{
|
||||
count++;
|
||||
}
|
||||
|
||||
Assert.AreEqual(4, count);
|
||||
all.Dispose();
|
||||
Assert.AreEqual(1, bus.SubscriberCount);
|
||||
await Task.CompletedTask.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void RedactorRemovesKeysSignaturesAndHeaders()
|
||||
{
|
||||
Redactor.Register("registered-secret-value-123");
|
||||
var samples = new Dictionary<string, string>
|
||||
{
|
||||
["OK-ACCESS-SIGN: " + "abc123signature=="] = "abc123signature",
|
||||
["APCA-API-SECRET-KEY: " + "Sk1234567890abcdef"] = "Sk1234567890abcdef",
|
||||
["Authorization: Bearer " + "eyJhbGciOiJIUzI1NiJ9.payload"] = "eyJhbGciOiJIUzI1NiJ9",
|
||||
["{\"api_key\": \"" + "AK12345678\"}"] = "AK12345678",
|
||||
["password=" + "hunter2hunter2&x=1"] = "hunter2hunter2",
|
||||
["postgres://anubis:" + "S3cretPw@db:5432/anubis"] = "S3cretPw",
|
||||
["bot" + "123456789:" + "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq"] = "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq",
|
||||
["value registered-secret-value-123 in text"] = "registered-secret-value-123",
|
||||
};
|
||||
foreach (var (input, secret) in samples)
|
||||
{
|
||||
var output = Redactor.Redact(input);
|
||||
Assert.IsFalse(output.Contains(secret, StringComparison.Ordinal), $"Segreto rimasto in: {output}");
|
||||
Assert.Contains(Redactor.Mask, output);
|
||||
}
|
||||
|
||||
Assert.AreEqual("Ordine eseguito: 2 AAPL a 259,80 $", Redactor.Redact("Ordine eseguito: 2 AAPL a 259,80 $"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The scheduler with a fake calendar (issue #10): fixed times, intervals, open and close, sleeps.</summary>
|
||||
[TestClass]
|
||||
public sealed class SchedulerTests
|
||||
{
|
||||
private static readonly TimeZoneInfo _rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
|
||||
private static readonly TimeZoneInfo _newYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
|
||||
|
||||
/// <summary>New York, 09:30–16:00 on weekdays, 13:00 close on the day after Thanksgiving 2026, closed on 3 July.</summary>
|
||||
private sealed class FakeCalendar : IMarketCalendar
|
||||
{
|
||||
public MarketSession? SessionOn(DateOnly day)
|
||||
{
|
||||
if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday || day == new DateOnly(2026, 7, 3))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var close = day == new DateOnly(2026, 11, 27) ? new TimeOnly(13, 0) : new TimeOnly(16, 0);
|
||||
return new MarketSession(day, At(day, new TimeOnly(9, 30)), At(day, close));
|
||||
}
|
||||
|
||||
private static DateTimeOffset At(DateOnly day, TimeOnly time)
|
||||
{
|
||||
var local = day.ToDateTime(time);
|
||||
return new DateTimeOffset(local, _newYork.GetUtcOffset(local)).ToUniversalTime();
|
||||
}
|
||||
}
|
||||
|
||||
private static DateTimeOffset Rome(int y, int mo, int d, int h, int mi)
|
||||
{
|
||||
var local = new DateTime(y, mo, d, h, mi, 0);
|
||||
return new DateTimeOffset(local, _rome.GetUtcOffset(local));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void MarketTimesFollowTheExchangeNotItalianTime()
|
||||
{
|
||||
var calendar = new FakeCalendar();
|
||||
var afterOpen = Schedule.Market(MarketAnchor.Open, TimeSpan.FromMinutes(5), calendar);
|
||||
|
||||
// Normal week: 09:35 in New York is 15:35 in Rome.
|
||||
Assert.AreEqual(Rome(2026, 10, 9, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 8, 21)));
|
||||
|
||||
// 16 March 2026: the USA already moved to summer time, Europe not yet: 09:35 NY is 14:35 in Rome.
|
||||
Assert.AreEqual(Rome(2026, 3, 16, 14, 35), afterOpen.NextAfter(Rome(2026, 3, 16, 8, 0)));
|
||||
|
||||
// Friday after the open: the next run is Monday.
|
||||
Assert.AreEqual(Rome(2026, 10, 12, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 16, 0)));
|
||||
|
||||
// Holiday skipped (Friday 3 July): Monday 6 July.
|
||||
Assert.AreEqual(Rome(2026, 7, 6, 15, 35), afterOpen.NextAfter(Rome(2026, 7, 2, 16, 0)));
|
||||
|
||||
// Early close: 5 minutes before a 13:00 close is 12:55 in New York, 18:55 in Rome.
|
||||
var beforeClose = Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(-5), calendar);
|
||||
Assert.AreEqual(Rome(2026, 11, 27, 18, 55), beforeClose.NextAfter(Rome(2026, 11, 27, 9, 0)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void DailyAndIntervalSchedules()
|
||||
{
|
||||
var backup = Schedule.Daily(new TimeOnly(3, 30), _rome);
|
||||
Assert.AreEqual(Rome(2026, 10, 10, 3, 30), backup.NextAfter(Rome(2026, 10, 9, 8, 21)));
|
||||
|
||||
// The night summer time ends (25 October 2026) 03:30 exists once, in winter time.
|
||||
Assert.AreEqual(Rome(2026, 10, 25, 3, 30), backup.NextAfter(Rome(2026, 10, 24, 12, 0)));
|
||||
|
||||
// 02:30 does not exist on 29 March 2026 in Rome: it moves to 03:00.
|
||||
var skipped = Schedule.Daily(new TimeOnly(2, 30), _rome);
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 3, 29, 1, 0, 0, TimeSpan.Zero), skipped.NextAfter(Rome(2026, 3, 28, 12, 0)));
|
||||
|
||||
var crypto = Schedule.Daily(new TimeOnly(0, 5), TimeZoneInfo.Utc);
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 0, 5, 0, TimeSpan.Zero), crypto.NextAfter(Rome(2026, 10, 9, 8, 21)));
|
||||
|
||||
var every5 = Schedule.Every(TimeSpan.FromMinutes(5));
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero)));
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 30, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task RunsDueJobsOnceAndSkipsRunsMissedDuringASleep()
|
||||
{
|
||||
var clock = new ManualClock(Rome(2026, 10, 9, 8, 21));
|
||||
var bus = new EventBus();
|
||||
using var runs = bus.Subscribe<JobRun>();
|
||||
var scheduler = new Scheduler(clock, bus);
|
||||
var count = 0;
|
||||
scheduler.Add(new ScheduledJob("backup", "Salvataggio", Schedule.Daily(new TimeOnly(3, 30), _rome), _ =>
|
||||
{
|
||||
count++;
|
||||
return Task.CompletedTask;
|
||||
}));
|
||||
scheduler.Add(new ScheduledJob("broken", "Rotto", Schedule.Daily(new TimeOnly(3, 30), _rome), _ => throw new InvalidOperationException("guasto")));
|
||||
|
||||
Assert.HasCount(2, scheduler.Upcoming());
|
||||
|
||||
clock.Set(Rome(2026, 10, 10, 3, 30));
|
||||
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual(1, count);
|
||||
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual(1, count, "un lavoro già eseguito non riparte");
|
||||
|
||||
// The computer slept two days: the 03:30 run is found late by hours and is skipped, not run blindly.
|
||||
clock.Set(Rome(2026, 10, 11, 9, 0));
|
||||
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual(1, count);
|
||||
|
||||
var outcomes = new List<JobRun>();
|
||||
while (runs.TryRead(out var run))
|
||||
{
|
||||
outcomes.Add(run!);
|
||||
}
|
||||
|
||||
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Completed));
|
||||
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Skipped));
|
||||
Assert.IsTrue(outcomes.Any(r => r.Name == "broken" && r.Outcome == JobOutcome.Failed && r.Error == "guasto"));
|
||||
Assert.AreEqual(Rome(2026, 10, 12, 3, 30), scheduler.Upcoming().Single(u => u.Name == "backup").DueUtc);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task LoopWaitsOnTheInjectedClock()
|
||||
{
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
|
||||
var scheduler = new Scheduler(clock, new EventBus());
|
||||
var ran = new TaskCompletionSource();
|
||||
scheduler.Add(new ScheduledJob("tick", "Prova", Schedule.Every(TimeSpan.FromMinutes(5)), _ =>
|
||||
{
|
||||
ran.TrySetResult();
|
||||
return Task.CompletedTask;
|
||||
}));
|
||||
using var cts = new CancellationTokenSource();
|
||||
var loop = scheduler.RunAsync(cts.Token);
|
||||
await WaitUntil(() => clock.Waiting > 0).ConfigureAwait(false);
|
||||
Assert.IsFalse(ran.Task.IsCompleted, "nessun lavoro prima dell'orario");
|
||||
|
||||
clock.Set(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero));
|
||||
await ran.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
|
||||
Assert.IsNotNull(scheduler.LastBeatUtc);
|
||||
|
||||
await cts.CancelAsync().ConfigureAwait(false);
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => loop).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task WaitUntil(Func<bool> condition)
|
||||
{
|
||||
for (var i = 0; i < 500 && !condition(); i++)
|
||||
{
|
||||
await Task.Delay(10).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Assert.IsTrue(condition(), "condizione non raggiunta in tempo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The portable database (issue #8): every test runs on the engine of this run (ANUBIS_TEST_DB), so the same
|
||||
/// battery passes on SQLite and on PostgreSQL.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class DatabaseTests
|
||||
{
|
||||
private static readonly ManualClock _clock = new(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
|
||||
|
||||
internal static async Task<TestDb> MigratedAsync()
|
||||
{
|
||||
var test = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None).ConfigureAwait(false);
|
||||
return test;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task MigrationsCreateTheSchemaAndRunOnce()
|
||||
{
|
||||
await using var test = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
Assert.IsTrue((await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false)).IsEmpty);
|
||||
Assert.AreEqual(Migrations.Latest, await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None).ConfigureAwait(false));
|
||||
Assert.AreEqual(0, await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None).ConfigureAwait(false));
|
||||
var status = await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual(Migrations.Latest, status.Current);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ColumnsInTheDatabaseMatchTheSchemaReadFromMigrations()
|
||||
{
|
||||
await using var test = await MigratedAsync().ConfigureAwait(false);
|
||||
foreach (var table in Schema.Tables)
|
||||
{
|
||||
var actual = await test.Db.ReadAsync(s => s.QueryAsync(
|
||||
s.Engine == DbEngine.Sqlite
|
||||
? $"SELECT name, type, \"notnull\" AS required FROM pragma_table_info('{table.Name}')"
|
||||
: $"SELECT column_name AS name, data_type AS type, CASE WHEN is_nullable = 'NO' THEN 1 ELSE 0 END AS required FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = '{table.Name}'",
|
||||
r => (Name: r.Text("name"), Type: r.Text("type").ToUpperInvariant(), Required: r.Number("required") != 0))).ConfigureAwait(false);
|
||||
CollectionAssert.AreEquivalent(table.Columns.Select(c => c.Name).ToList(), actual.Select(a => a.Name).ToList(), table.Name);
|
||||
foreach (var column in table.Columns)
|
||||
{
|
||||
var found = actual.Single(a => a.Name == column.Name);
|
||||
if (column.Kind == ColumnKind.Money)
|
||||
{
|
||||
Assert.IsTrue(found.Type is "TEXT" or "NUMERIC", $"{table.Name}.{column.Name} è {found.Type}: il denaro non è mai in virgola mobile");
|
||||
}
|
||||
|
||||
if (!column.Nullable)
|
||||
{
|
||||
Assert.IsTrue(found.Required || column.Name == "id", $"{table.Name}.{column.Name} dovrebbe essere obbligatoria");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task DecimalsDatesAndIdsRoundTripExactly()
|
||||
{
|
||||
await using var test = await MigratedAsync().ConfigureAwait(false);
|
||||
await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'Prova', 'paper', 'simulation', 'EUR', @t)",
|
||||
("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow))).ConfigureAwait(false);
|
||||
var account = await test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM accounts", r => r.Id("id"))).ConfigureAwait(false);
|
||||
|
||||
decimal[] values =
|
||||
[
|
||||
0m, 1m, -1m, 0.000000000000000001m, -0.000000000000000001m, 1299.84m, 0.1m + 0.2m,
|
||||
99_999_999_999_999_999_999m, -99_999_999_999_999_999_999m, 1234567890.123456789012345678m,
|
||||
12345678901.12345678901234567m, 7.000000000000000000m, 79228162514.264337593543950335m,
|
||||
];
|
||||
var moments = new[]
|
||||
{
|
||||
new DateTimeOffset(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2)),
|
||||
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero),
|
||||
new DateTimeOffset(2099, 12, 31, 23, 59, 59, TimeSpan.Zero).AddTicks(1234567),
|
||||
};
|
||||
|
||||
var rows = new List<(Guid Id, decimal Value, DateTimeOffset At)>();
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
{
|
||||
rows.Add((Guid.CreateVersion7(_clock.UtcNow.AddMilliseconds(i)), values[i], moments[i % moments.Length]));
|
||||
}
|
||||
|
||||
await test.Db.WriteAsync(async s =>
|
||||
{
|
||||
foreach (var (id, value, at) in rows)
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, currency, amount, kind, occurred_at, created_at) VALUES (@id, @a, 'EUR', @v, 'test', @at, @t)",
|
||||
("id", id), ("a", account), ("v", value), ("at", at), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
||||
}
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
var read = await test.Db.ReadAsync(s => s.QueryAsync("SELECT id, amount, occurred_at FROM cash_ledger ORDER BY id",
|
||||
r => (Id: r.Id("id"), Value: r.Money("amount"), At: r.Moment("occurred_at")))).ConfigureAwait(false);
|
||||
Assert.HasCount(rows.Count, read);
|
||||
for (var i = 0; i < rows.Count; i++)
|
||||
{
|
||||
Assert.AreEqual(rows[i].Id, read[i].Id);
|
||||
Assert.AreEqual(DbValues.Money(rows[i].Value), read[i].Value, $"valore {rows[i].Value}");
|
||||
Assert.AreEqual(DbValues.Moment(rows[i].At), read[i].At);
|
||||
Assert.AreEqual(TimeSpan.Zero, read[i].At.Offset, "si rilegge sempre in UTC");
|
||||
}
|
||||
|
||||
// More than 18 decimals: rounded half away from zero, the same on both engines.
|
||||
Assert.AreEqual(0.000000000000000002m, DbValues.Money(0.0000000000000000015m));
|
||||
Assert.AreEqual(1.123456789012345679m, DbValues.Money(1.1234567890123456789m));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ValuesOutsideNumeric38And18AndMomentsWithoutZoneAreRefused()
|
||||
{
|
||||
Assert.Throws<OverflowException>(() => DbValues.Money(100_000_000_000_000_000_000m));
|
||||
Assert.Throws<OverflowException>(() => DbValues.Money(decimal.MaxValue));
|
||||
Assert.Throws<ArgumentException>(() => DbValues.ToProvider(new DateTime(2026, 10, 9), DbEngine.Sqlite));
|
||||
Assert.Throws<FormatException>(() => DbValues.ParseMoment("2026-10-09T08:21:00"));
|
||||
Assert.AreEqual("1.5", DbValues.MoneyText(1.500m));
|
||||
Assert.AreEqual("0", DbValues.MoneyText(0.000m));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void MoneyRoundTripsForAnyValue() =>
|
||||
Property.ForAll(g => g.Decimal(-1_000_000m, 1_000_000m, 12), value =>
|
||||
{
|
||||
var text = DbValues.MoneyText(value);
|
||||
Assert.AreEqual(DbValues.Money(value), DbValues.ParseMoney(text));
|
||||
});
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task SameExecutionIsRecordedOnce()
|
||||
{
|
||||
await using var test = await MigratedAsync().ConfigureAwait(false);
|
||||
var (account, instrument) = await SeedAccountAsync(test.Db).ConfigureAwait(false);
|
||||
async Task InsertFill() => await test.Db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO fills (id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at) VALUES (@id, @a, @i, 'EX-1', 'buy', 1, 100, 0, 'EUR', @t, @t)",
|
||||
("id", Guid.NewGuid()), ("a", account), ("i", instrument), ("t", _clock.UtcNow))).ConfigureAwait(false);
|
||||
await InsertFill().ConfigureAwait(false);
|
||||
await Assert.ThrowsAsync<System.Data.Common.DbException>(InsertFill).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task FailedWritesLeaveNothingBehind()
|
||||
{
|
||||
await using var test = await MigratedAsync().ConfigureAwait(false);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => test.Db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'X', 'paper', 'simulation', 'EUR', @t)",
|
||||
("id", Guid.NewGuid()), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
||||
throw new InvalidOperationException("stop");
|
||||
})).ConfigureAwait(false);
|
||||
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM accounts")).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task SqliteUsesWalFullSyncAndForeignKeys()
|
||||
{
|
||||
if (TestDatabase.Engine != "sqlite")
|
||||
{
|
||||
Assert.Inconclusive("Solo su SQLite.");
|
||||
}
|
||||
|
||||
await using var test = await MigratedAsync().ConfigureAwait(false);
|
||||
var pragmas = await test.Db.ReadAsync(async s => (
|
||||
Journal: await s.FirstOrDefaultAsync("PRAGMA journal_mode", r => r.Text("journal_mode")).ConfigureAwait(false),
|
||||
Sync: await s.CountAsync("PRAGMA synchronous").ConfigureAwait(false),
|
||||
Keys: await s.CountAsync("PRAGMA foreign_keys").ConfigureAwait(false),
|
||||
Busy: await s.CountAsync("PRAGMA busy_timeout").ConfigureAwait(false))).ConfigureAwait(false);
|
||||
Assert.AreEqual("wal", pragmas.Journal);
|
||||
Assert.AreEqual(2L, pragmas.Sync, "synchronous=FULL");
|
||||
Assert.AreEqual(1L, pragmas.Keys);
|
||||
Assert.AreEqual(5000L, pragmas.Busy);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void SqliteDoesNotCreateAMissingFileWhenAskedNotTo()
|
||||
{
|
||||
var folder = TempFolder.Create("nocreate");
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(folder, "db", "anubis.sqlite3");
|
||||
var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = path }, allowCreate: false);
|
||||
Assert.ThrowsAsync<Microsoft.Data.Sqlite.SqliteException>(() => db.PingAsync(CancellationToken.None)).GetAwaiter().GetResult();
|
||||
Assert.IsFalse(File.Exists(path));
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void MigrationsUseOnlyPortableSql()
|
||||
{
|
||||
string[] forbidden = ["SERIAL", "AUTOINCREMENT", "JSONB", "MATERIALIZED", "PARTITION", "LISTEN", "NOTIFY", "REAL", "FLOAT", "DOUBLE", "pg_advisory", "RETURNING"];
|
||||
foreach (var migration in Migrations.All)
|
||||
{
|
||||
var sql = System.Text.RegularExpressions.Regex.Replace(migration.Sql, @"--[^\n]*|\{[a-z]+\}", "");
|
||||
foreach (var word in forbidden)
|
||||
{
|
||||
Assert.IsFalse(System.Text.RegularExpressions.Regex.IsMatch(sql, $@"\b{word}\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
|
||||
$"{migration.Version:D4}: '{word}' non è portabile");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsTrue(Schema.Tables.All(t => t.Columns.Any(c => c.Name == "id" && c.Kind == ColumnKind.Uuid)), "ogni tabella ha una chiave UUID");
|
||||
Assert.IsTrue(Schema.Tables.All(t => t.Columns.Any(c => c.Name == "created_at" && c.Kind == ColumnKind.Moment)), "ogni tabella ha created_at");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AccountingTablesAreNeverUpdatedOrDeletedInCode()
|
||||
{
|
||||
var pattern = new System.Text.RegularExpressions.Regex(@"\b(UPDATE\s+(fills|lots|cash_ledger)\b|DELETE\s+FROM\s+(fills|lots|cash_ledger)\b)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
var offenders = Repo.Files()
|
||||
.Where(f => f.Extension is ".cs" or ".sql" && Repo.Relative(f).StartsWith("src/", StringComparison.Ordinal))
|
||||
.Where(f => pattern.IsMatch(File.ReadAllText(f.FullName)))
|
||||
.Select(Repo.Relative)
|
||||
.ToList();
|
||||
Assert.IsEmpty(offenders, "Le tabelle contabili si correggono con righe di storno: " + string.Join(", ", offenders));
|
||||
}
|
||||
|
||||
internal static async Task<(Guid Account, Guid Instrument)> SeedAccountAsync(Database db)
|
||||
{
|
||||
var account = Guid.CreateVersion7(_clock.UtcNow);
|
||||
var instrument = Guid.CreateVersion7(_clock.UtcNow.AddMilliseconds(1));
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t)",
|
||||
("id", account), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, 'okx', 'BTC/EUR', 'Bitcoin', 'crypto', 'EUR', @t)",
|
||||
("id", instrument), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
return (account, instrument);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user