Compare commits

...
4 Commits
Author SHA1 Message Date
Alby96 6eef15c487 Merge M1 · Strato dati (#116)
Wiki / Publish the wiki (push) Successful in 6s
Release / Image and release (push) Successful in 2m16s
CI / PostgreSQL 16 integration (push) Successful in 1m10s
CI / Build and test (SQLite) (push) Successful in 47s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 4s
CI / PostgreSQL 17 integration (push) Successful in 1m7s
2026-11-11 13:18:03 +01:00
Alby96andClaude Opus 5.5 738c43ba0a feat: data layer with SQLite and PostgreSQL providers, migrations and encrypted company registry (M1)
CI / Build and test (SQLite) (pull_request) Successful in 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 3s
CI / Docker image (pull_request) Successful in 51s
Every later milestone stores its data through this layer, so it has to behave the same on both engines and be safe
by construction:

- Khaemhat.Data: explicit entity maps, typed queries over a safe expression subset, SqlFragment where every
  interpolated value becomes a parameter, unit of work with transactions, repositories with audit columns and
  optimistic concurrency on row_version, retries on transient errors.
- SQLite provider (STRICT tables, WAL, exact decimals as integers scaled by 10^6, Unicode case-insensitive LIKE,
  serialised writes) and PostgreSQL 16+ provider (numeric(19,6), timestamptz, jsonb, advisory locks, database
  creation and server info). Databases are configured from postgres:// and sqlite:// URLs whose password never
  appears in messages.
- C# migrations with system and company catalogues, schema_version with checksums, one transaction per migration
  under a lock, refusal of unknown applied versions; first system tables sys_companies and sys_settings.
- CompanyRegistry stores each company's database URL encrypted with the instance key (AES-256-GCM, HKDF-derived key,
  purpose as associated data), so a copied row cannot be read for another company.
- tools/Khaemhat.DataModelTool, scripts/gen-datamodel.sh and scripts/new-migration.sh: the current schema section of
  docs/DATA-MODEL.md is generated from the migrations and a test fails when it is stale.
- C# 14 binds array.Contains to MemoryExtensions over spans; the query translator unwraps the span conversion.
- Tests run every data scenario on SQLite and PostgreSQL (PostgreSQL in CI); ADR 0018 records where the contracts
  differ from SPEC 5.1. Docs, wiki, changelog and status updated.

Closes #7, #8, #9, #10, #11, #12, #13, #14

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:11:34 +01:00
Alby96 28e7a6e18a Merge M0 · Bootstrap (#115)
Wiki / Publish the wiki (push) Successful in 13s
Release / Image and release (push) Successful in 2m18s
CI / PostgreSQL 16 integration (push) Successful in 1m21s
CI / Build and test (SQLite) (push) Successful in 38s
CI / Docker image (push) Skipped
CI / YAML check (push) Successful in 19s
CI / PostgreSQL 17 integration (push) Successful in 1m28s
Closes #1, #2, #3, #4, #5, #114
2026-11-11 11:57:24 +01:00
Alby96andClaude Opus 5.5 12277733f5 feat: bootstrap solution, Docker image and Gitea pipelines (M0)
CI / Build and test (SQLite) (pull_request) Successful in 43s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 15s
CI / Docker image (pull_request) Successful in 59s
Start development with the skeleton every later milestone builds on, so
that code, image and release path exist and are verified from day one.

- Khaemhat.sln with the ten projects of SPEC section 3 and six MSTest
  projects; shared build rules with warnings as errors, analyzers and
  Central Package Management restricted to the allowlist.
- Architecture tests and scripts/check-packages.sh fail on any project
  reference or package that SPEC does not allow.
- Khaemhat.Web serves an Italian "under construction" page with the
  official icons and version, plus /health/live, /health/ready and
  /health (ADR 0012); honours KHAEMHAT_URLS and KHAEMHAT_LOG_LEVEL.
- docker/Dockerfile (non-root app user aligned to PUID/PGID by the
  entrypoint, pg_dump 17, healthcheck, OCI and Unraid labels) and
  compose files for PostgreSQL and a standalone SQLite demo.
- Gitea Actions: ci.yml (build, tests, image smoke test, PostgreSQL
  16/17 on tags, YAML check), release.yml (image and release from a
  vX.Y.Z tag, skipping versions already published) and wiki.yml.
- Development scripts, VS Code launch/tasks for debugging, and ADR
  0012-0017 deciding the M0 open points of docs/STATUS.md.

Closes #1, #2, #3, #4, #5, #114

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:53:39 +01:00
192 changed files with 11647 additions and 108 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Build context for docker/Dockerfile: sources and build files only.
**/bin/
**/obj/
.git/
.gitea/
.vs/
.vscode/
.idea/
.claude/
.data/
out/
docs/
deploy/
*.md
!README.md
**/*.user
**/.env
+81
View File
@@ -0,0 +1,81 @@
# Khaemhat code style (SPEC §1.11, §19). Build enforces analyzers and code style (EnforceCodeStyleInBuild).
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
[*.{csproj,props,targets,xml,json,yml,yaml,razor.css,css,js,html,svg}]
indent_size = 2
[*.razor]
indent_size = 4
[*.md]
trim_trailing_whitespace = false
[*.sh]
end_of_line = lf
[*.cs]
# Namespaces and usings
csharp_style_namespace_declarations = file_scoped:warning
dotnet_sort_system_directives_first = true
csharp_using_directive_placement = outside_namespace:warning
# var and expression style
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:suggestion
csharp_prefer_braces = when_multiline:suggestion
dotnet_style_qualification_for_field = false:warning
dotnet_style_qualification_for_property = false:warning
dotnet_style_qualification_for_method = false:warning
dotnet_style_predefined_type_for_locals_parameters_members = true:warning
dotnet_style_readonly_field = true:warning
csharp_style_prefer_primary_constructors = true:suggestion
# Naming: private fields _camelCase, constants PascalCase
dotnet_naming_rule.private_fields.symbols = private_fields
dotnet_naming_rule.private_fields.style = underscore_camel
dotnet_naming_rule.private_fields.severity = warning
dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
dotnet_naming_style.underscore_camel.required_prefix = _
dotnet_naming_style.underscore_camel.capitalization = camel_case
dotnet_naming_rule.constants.symbols = constants
dotnet_naming_rule.constants.style = pascal
dotnet_naming_rule.constants.severity = warning
dotnet_naming_symbols.constants.applicable_kinds = field
dotnet_naming_symbols.constants.required_modifiers = const
dotnet_naming_style.pascal.capitalization = pascal_case
# Analyzer adjustments (each with its reason)
# CA1515 (make types internal): Khaemhat is an application, but its libraries are consumed across projects.
dotnet_diagnostic.CA1515.severity = none
# CA1848/CA1873 (LoggerMessage delegates): adopted where logging is hot (Infrastructure/Logging, M2), not everywhere.
dotnet_diagnostic.CA1848.severity = suggestion
dotnet_diagnostic.CA1873.severity = suggestion
# CA2007 (ConfigureAwait): ASP.NET Core has no synchronization context.
dotnet_diagnostic.CA2007.severity = none
# IDE0005 (unnecessary using) needs GenerateDocumentationFile, which is on: keep it as an error-free warning.
dotnet_diagnostic.IDE0005.severity = warning
[tests/**.cs]
# CA1707 (underscores in names): test names read as Method_Condition_Result.
dotnet_diagnostic.CA1707.severity = none
# CA1861/CA1847/CA1862: tests pass literal arrays and write the string predicates the query translator must handle.
dotnet_diagnostic.CA1861.severity = none
dotnet_diagnostic.CA1847.severity = none
dotnet_diagnostic.CA1862.severity = none
# MSTEST0037 and friends stay at their defaults.
# Migration classes are named after their version, M<yyyymmdd>_<nnn>_<Name> (SPEC 5.3).
[**/Migrations/*.cs]
dotnet_diagnostic.CA1707.severity = none
+22
View File
@@ -0,0 +1,22 @@
# Parses each YAML file given on the command line and fails on the first syntax error (Gitea rejects a workflow that
# does not parse, Docker Compose a compose file). Workflows must also declare "on" and "jobs".
require "yaml"
failed = false
ARGV.each do |path|
begin
document = YAML.safe_load(File.read(path), aliases: true)
if path.include?(".gitea/workflows/")
# YAML 1.1 reads the bare key "on" as true.
missing = []
missing << "on" unless document.key?("on") || document.key?(true)
missing << "jobs" unless document.key?("jobs")
raise "missing #{missing.join(', ')}" unless missing.empty?
end
puts "ok #{path}"
rescue StandardError => e
failed = true
puts "ERROR #{path}: #{e.message}"
end
end
exit(failed ? 1 : 0)
+180
View File
@@ -0,0 +1,180 @@
name: CI
# Gitea Actions (ADR 0009). The runner is act_runner in Docker mode on the server that also runs Gitea: one job at a
# time, so the triggers are frugal. The .NET jobs use the SDK image and check out with git (the image has no Node.js
# for JavaScript actions); nothing is cached or uploaded. Builds use BUILD_CPUS cores so the host keeps room for Gitea.
on:
pull_request:
branches: [main]
push:
branches: [main]
tags: ["v*"]
paths-ignore: ["docs/**", "*.md", "assets/**", "deploy/**"]
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
DOTNET_NOLOGO: "1"
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1"
BUILD_CPUS: "4"
KHAEMHAT_LICENSE_MODE: test
jobs:
build:
name: Build and test (SQLite)
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/dotnet/sdk:10.0
timeout-minutes: 30
defaults:
run:
shell: bash
steps:
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
git checkout -q FETCH_HEAD
git log -1 --format='%h %s'
- name: Package allowlist
run: bash scripts/check-packages.sh
- name: Build (warnings are errors)
run: dotnet build Khaemhat.sln -c Release -warnaserror -m:"$BUILD_CPUS"
- name: Test
run: dotnet test Khaemhat.sln -c Release --no-build
# PostgreSQL integration (SPEC §20): only on release tags and manual runs, against the two supported servers.
postgres:
name: PostgreSQL ${{ matrix.pg }} integration
needs: build
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
strategy:
fail-fast: false
matrix:
pg: ["16", "17"]
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/dotnet/sdk:10.0
timeout-minutes: 30
services:
postgres:
image: postgres:${{ matrix.pg }}
env:
POSTGRES_USER: khaemhat
POSTGRES_PASSWORD: khaemhat-ci
POSTGRES_DB: khaemhat_test
defaults:
run:
shell: bash
env:
KHAEMHAT_TEST_PG: postgres://khaemhat:khaemhat-ci@postgres:5432/khaemhat_test
steps:
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
git checkout -q FETCH_HEAD
- name: Test · Data (PostgreSQL)
run: dotnet test tests/Khaemhat.Data.Tests -c Release -m:"$BUILD_CPUS"
# The image builds and answers /health/live (issue #2). The runner's own image has the docker CLI and talks to the
# host's daemon; the job joins a network of its own to reach the container. Everything is labelled with the job
# container's id: a cancelled job skips its clean-up, so the next one removes what a vanished job left on the host.
# Release tags skip it: release.yml builds and tests the same image.
docker:
name: Docker image
needs: build
if: "!startsWith(github.ref, 'refs/tags/')"
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Remove what cancelled jobs left
run: |
echo "NAME=khaemhat-ci-$(hostname)" >> "$GITHUB_ENV"
for c in $(docker ps -aq --filter label=khaemhat-ci.job); do
job="$(docker inspect -f '{{index .Config.Labels "khaemhat-ci.job"}}' "$c")"
docker inspect "$job" > /dev/null 2>&1 || docker rm -f -v "$c"
done
for n in $(docker network ls -q --filter label=khaemhat-ci.job); do
job="$(docker network inspect -f '{{index .Labels "khaemhat-ci.job"}}' "$n")"
docker inspect "$job" > /dev/null 2>&1 || docker network rm "$n"
done
for i in $(docker image ls -q --filter label=khaemhat-ci.job | sort -u); do
job="$(docker image inspect -f '{{index .Config.Labels "khaemhat-ci.job"}}' "$i")"
docker inspect "$job" > /dev/null 2>&1 || docker image rm -f "$i"
done
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
git checkout -q FETCH_HEAD
- name: Build image
run: |
docker build -f docker/Dockerfile --build-arg VERSION=0.0.0-ci --build-arg GIT_SHA="$(git rev-parse --short HEAD)" \
--label khaemhat-ci.job="$(hostname)" -t "$NAME:image" .
- name: Smoke test (/health/live, non-root user, PUID/PGID)
run: |
docker network create --label khaemhat-ci.job="$(hostname)" "$NAME"
docker network connect "$NAME" "$(hostname)"
docker run -d --name "$NAME-app" --network "$NAME" --label khaemhat-ci.job="$(hostname)" \
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test -e PUID=99 -e PGID=100 "$NAME:image"
for i in $(seq 1 30); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/live"; then echo; break; fi
sleep 2
done
curl -fsS --max-time 5 "http://$NAME-app:8080/health"
echo
curl -fsS --max-time 5 "http://$NAME-app:8080/" | grep -q "in costruzione"
test "$(docker exec "$NAME-app" sh -c 'stat -c %u:%g /proc/1')" = "99:100"
test "$(docker exec "$NAME-app" stat -c %u:%g /data)" = "99:100"
docker exec "$NAME-app" pg_dump --version
- name: Container logs and clean-up
if: always()
run: |
docker logs "$NAME-app" || true
docker rm -f -v "$NAME-app" || true
docker network disconnect "$NAME" "$(hostname)" || true
docker network rm "$NAME" || true
docker image rm "$NAME:image" || true
# Gitea fails a workflow that does not parse. The Ruby image has no git: the sources come as an archive.
yaml:
name: YAML check
runs-on: ubuntu-latest
container:
image: ruby:3.3-alpine
timeout-minutes: 10
steps:
- name: Workflows and compose files
env:
TOKEN: ${{ github.token }}
run: |
wget -q --header "Authorization: token $TOKEN" -O /tmp/sources.tar.gz \
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/archive/${{ github.sha }}.tar.gz"
mkdir -p /tmp/sources && tar -xzf /tmp/sources.tar.gz -C /tmp/sources
cd /tmp/sources/*/
ruby .gitea/scripts/check-yaml.rb .gitea/workflows/*.yml deploy/*.yml
+184
View File
@@ -0,0 +1,184 @@
name: Release
# A tag vX.Y.Z[-pre] publishes the image gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z (ADR 0009, 0010, 0015) and a
# Gitea release whose notes are the CHANGELOG.md section of that version (no binaries). When the version is already
# in the registry (published by scripts/publish-image.sh) the build is skipped and only the release is created.
# The runner's own image has the docker CLI and builds with the host's daemon.
on:
push:
tags: ["v*"]
workflow_dispatch:
inputs:
tag:
description: "Tag esistente da (ri)pubblicare, es. v0.0.1"
required: true
arm64:
description: "Anche linux/arm64 (richiede QEMU e buildx sull'host)"
type: boolean
default: false
permissions:
contents: write
packages: write
env:
TAG: ${{ github.event.inputs.tag || github.ref_name }}
# Where people and programs reach Gitea (the runner itself uses github.server_url). Variable PUBLIC_URL overrides it.
PUBLIC_URL: ${{ vars.PUBLIC_URL || 'https://gitea.encke-hake.ts.net' }}
jobs:
release:
name: Image and release
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- name: Remove what cancelled jobs left
run: |
echo "NAME=khaemhat-rel-$(hostname)" >> "$GITHUB_ENV"
for c in $(docker ps -aq --filter label=khaemhat-ci.job); do
job="$(docker inspect -f '{{index .Config.Labels "khaemhat-ci.job"}}' "$c")"
docker inspect "$job" > /dev/null 2>&1 || docker rm -f -v "$c"
done
for n in $(docker network ls -q --filter label=khaemhat-ci.job); do
job="$(docker network inspect -f '{{index .Labels "khaemhat-ci.job"}}' "$n")"
docker inspect "$job" > /dev/null 2>&1 || docker network rm "$n"
done
- name: Version
run: |
case "$TAG" in
v[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "::error title=Tag::$TAG is not vX.Y.Z[-pre]"; exit 1 ;;
esac
version="${TAG#v}"
prerelease=false
case "$version" in *-*) prerelease=true ;; esac
major_minor="${version%%-*}"
major_minor="${major_minor%.*}"
owner="$(printf '%s' "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')"
registry="${{ vars.REGISTRY }}"
registry="${registry:-$(printf '%s' "$PUBLIC_URL" | sed -E 's#^[a-z]+://##; s#/.*$##')}"
{
echo "VERSION=$version"
echo "PRERELEASE=$prerelease"
echo "MAJOR_MINOR=$major_minor"
echo "REGISTRY_HOST=$registry"
echo "IMAGE=$registry/$owner/khaemhat"
} >> "$GITHUB_ENV"
echo "Tag $TAG -> image $registry/$owner/khaemhat:$version (prerelease: $prerelease)"
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "refs/tags/$TAG:refs/tags/$TAG"
git checkout -q "refs/tags/$TAG"
echo "GIT_SHA=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
- name: Sign in to the registry
env:
USER: ${{ vars.REGISTRY_USER || github.actor }}
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
if [ -z "$TOKEN" ] || ! printf '%s' "$TOKEN" | docker login "$REGISTRY_HOST" -u "$USER" --password-stdin; then
echo "::error title=Registry::Sign-in to $REGISTRY_HOST refused. The organisation secret REGISTRY_TOKEN must be an access token with package read and write."
exit 1
fi
status="$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: token $TOKEN" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/container/khaemhat/$VERSION")"
if [ "$status" = "200" ]; then
echo "Version $VERSION is already in the registry: build and push skipped (ADR 0015)."
echo "PUBLISHED=true" >> "$GITHUB_ENV"
else
echo "PUBLISHED=false" >> "$GITHUB_ENV"
fi
- name: Build image
if: env.PUBLISHED != 'true'
run: |
icon="$PUBLIC_URL/${{ github.repository }}/raw/branch/main/assets/icon-256.png"
if [ -f "assets/icon-v$MAJOR_MINOR-256.png" ]; then
icon="$PUBLIC_URL/${{ github.repository }}/raw/branch/main/assets/icon-v$MAJOR_MINOR-256.png"
fi
echo "ICON_URL=$icon" >> "$GITHUB_ENV"
docker build -f docker/Dockerfile \
--build-arg VERSION="$VERSION" \
--build-arg GIT_SHA="$GIT_SHA" \
--build-arg CREATED="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--build-arg SOURCE_URL="$PUBLIC_URL/${{ github.repository }}" \
--build-arg ICON_URL="$icon" \
--label khaemhat-ci.job="$(hostname)" \
-t "$IMAGE:$VERSION" .
- name: Smoke test (/health/live)
if: env.PUBLISHED != 'true'
run: |
docker network create --label khaemhat-ci.job="$(hostname)" "$NAME"
docker network connect "$NAME" "$(hostname)"
docker run -d --name "$NAME-app" --network "$NAME" --label khaemhat-ci.job="$(hostname)" \
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test "$IMAGE:$VERSION"
for i in $(seq 1 30); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/live"; then echo; break; fi
sleep 2
done
report="$(curl -fsS --max-time 5 "http://$NAME-app:8080/health")"
echo "$report"
echo "$report" | grep -q "\"version\":\"$VERSION\""
- name: Push
if: env.PUBLISHED != 'true'
run: |
docker push "$IMAGE:$VERSION"
if [ "$PRERELEASE" != "true" ]; then
docker tag "$IMAGE:$VERSION" "$IMAGE:latest"
docker push "$IMAGE:latest"
fi
echo "Image: $IMAGE:$VERSION$([ "$PRERELEASE" != "true" ] && echo " and :latest")"
- name: Multi-architecture push (arm64)
if: env.PUBLISHED != 'true' && github.event.inputs.arm64 == 'true'
run: |
docker buildx build --platform linux/amd64,linux/arm64 -f docker/Dockerfile \
--build-arg VERSION="$VERSION" --build-arg GIT_SHA="$GIT_SHA" \
--build-arg SOURCE_URL="$PUBLIC_URL/${{ github.repository }}" --build-arg ICON_URL="$ICON_URL" \
-t "$IMAGE:$VERSION" --push .
# Notes: the "## [X.Y.Z]" section of CHANGELOG.md. The release is created or, when it exists, left as it is.
- name: Gitea release
env:
TOKEN: ${{ github.token }}
run: |
api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}"
if curl -fs -o /dev/null -H "Authorization: token $TOKEN" "$api/releases/tags/$TAG"; then
echo "Release $TAG already exists."
exit 0
fi
awk -v v="$VERSION" '
index($0, "## [" v "]") == 1 { on = 1; next }
on && /^## \[/ { exit }
on { print }
' CHANGELOG.md > "$RUNNER_TEMP/notes.md"
if [ ! -s "$RUNNER_TEMP/notes.md" ]; then
echo "::warning title=Changelog::No section [$VERSION] in CHANGELOG.md"
echo "Vedi CHANGELOG.md." > "$RUNNER_TEMP/notes.md"
fi
printf '\nImmagine: `%s:%s`\n' "$IMAGE" "$VERSION" >> "$RUNNER_TEMP/notes.md"
body="$(awk 'BEGIN { ORS = "\\n" } { gsub(/\r/, ""); gsub(/\\/, "\\\\"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); print }' "$RUNNER_TEMP/notes.md")"
printf '{"tag_name":"%s","name":"Khaemhat %s","body":"%s","draft":false,"prerelease":%s}' \
"$TAG" "$VERSION" "$body" "$PRERELEASE" > "$RUNNER_TEMP/release.json"
curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
--data-binary "@$RUNNER_TEMP/release.json" "$api/releases" > /dev/null
echo "Release $TAG created."
- name: Clean up
if: always()
run: |
docker logs "$NAME-app" 2> /dev/null || true
docker rm -f -v "$NAME-app" 2> /dev/null || true
docker network disconnect "$NAME" "$(hostname)" 2> /dev/null || true
docker network rm "$NAME" 2> /dev/null || true
docker image rm "$IMAGE:$VERSION" "$IMAGE:latest" 2> /dev/null || true
docker logout "$REGISTRY_HOST" || true
+38
View File
@@ -0,0 +1,38 @@
name: Wiki
# docs/wiki/ is the source of the Gitea wiki (ADR 0009): every push to main that touches it publishes it with
# scripts/publish-wiki.sh, which makes Khaemhat.wiki.git an exact copy. The secret WIKI_TOKEN (an access token with
# repository write) overrides the workflow's own token if that one cannot push to the wiki.
on:
push:
branches: [main]
paths: ["docs/wiki/**"]
workflow_dispatch:
concurrency:
group: wiki
cancel-in-progress: false
jobs:
publish:
name: Publish the wiki
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
env:
TOKEN: ${{ github.token }}
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
git -c http.extraheader="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" fetch -q --depth=1 origin "${{ github.sha }}"
git checkout -q FETCH_HEAD
- name: Publish docs/wiki
env:
GITEA_TOKEN: ${{ secrets.WIKI_TOKEN || github.token }}
WIKI_REMOTE: ${{ github.server_url }}/${{ github.repository }}.wiki.git
GIT_AUTHOR_NAME: Khaemhat CI
GIT_AUTHOR_EMAIL: ci@khaemhat.invalid
run: bash scripts/publish-wiki.sh
+10
View File
@@ -414,3 +414,13 @@ FodyWeavers.xsd
# Built Visual Studio Code Extensions
*.vsix
# Khaemhat
# Real deploy settings and secrets never go to the repository (deploy/.env.example is the template).
.env
deploy/.env
# Local development data (scripts/run-dev.sh) and test output.
.data/
out/
# License signing keys (tools/Khaemhat.LicenseTool): the private key never enters the repository (ADR 0008).
*.khkey
+8
View File
@@ -0,0 +1,8 @@
{
"recommendations": [
"ms-dotnettools.csdevkit",
"ms-dotnettools.csharp",
"editorconfig.editorconfig",
"ms-azuretools.vscode-docker"
]
}
+70
View File
@@ -0,0 +1,70 @@
{
// Debug di Khaemhat da Visual Studio Code (estensione C# / C# Dev Kit, vedi extensions.json).
// Le variabili sono quelle di scripts/run-dev.sh: SQLite in .data/dev, licenze di test, solo per sviluppo.
"version": "0.2.0",
"configurations": [
{
"name": "Khaemhat (web, SQLite)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/src/Khaemhat.Web/bin/Debug/net10.0/Khaemhat.Web.dll",
"args": ["--urls", "http://localhost:5080"],
"cwd": "${workspaceFolder}/src/Khaemhat.Web",
"stopAtEntry": false,
"console": "internalConsole",
"serverReadyAction": {
"action": "openExternally",
"pattern": "Now listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"KHAEMHAT_DATA_DIR": "${workspaceFolder}/.data/dev",
"KHAEMHAT_SYSTEM_DB": "sqlite:///${workspaceFolder}/.data/dev/system.db",
"KHAEMHAT_SECRET_KEY": "a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=",
"KHAEMHAT_SUPERUSER": "root",
"KHAEMHAT_SUPERUSER_PASSWORD": "Khaemhat-dev-1",
"KHAEMHAT_COMPANY_CODE": "DEMO",
"KHAEMHAT_COMPANY_NAME": "Khaemhat Demo S.r.l.",
"KHAEMHAT_LICENSE_MODE": "test",
"KHAEMHAT_SEED_DEMO": "true",
"KHAEMHAT_LOG_LEVEL": "Debug"
}
},
{
"name": "Khaemhat (web, PostgreSQL)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/src/Khaemhat.Web/bin/Debug/net10.0/Khaemhat.Web.dll",
"args": ["--urls", "http://localhost:5080"],
"cwd": "${workspaceFolder}/src/Khaemhat.Web",
"console": "internalConsole",
"serverReadyAction": {
"action": "openExternally",
"pattern": "Now listening on:\\s+(https?://\\S+)"
},
// Server locale, ad esempio: docker run -d --name khaemhat-pg -p 5432:5432 -e POSTGRES_USER=khaemhat
// -e POSTGRES_PASSWORD=khaemhat-dev -e POSTGRES_DB=khaemhat_system postgres:17
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"KHAEMHAT_DATA_DIR": "${workspaceFolder}/.data/dev-pg",
"KHAEMHAT_SYSTEM_DB": "postgres://khaemhat:khaemhat-dev@localhost:5432/khaemhat_system",
"KHAEMHAT_DB_SERVER": "postgres://khaemhat:khaemhat-dev@localhost:5432/",
"KHAEMHAT_SECRET_KEY": "a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=",
"KHAEMHAT_SUPERUSER": "root",
"KHAEMHAT_SUPERUSER_PASSWORD": "Khaemhat-dev-1",
"KHAEMHAT_COMPANY_CODE": "DEMO",
"KHAEMHAT_COMPANY_NAME": "Khaemhat Demo S.r.l.",
"KHAEMHAT_LICENSE_MODE": "test",
"KHAEMHAT_SEED_DEMO": "true",
"KHAEMHAT_LOG_LEVEL": "Debug"
}
},
{
"name": "Collega a un processo",
"type": "coreclr",
"request": "attach"
}
]
}
+51
View File
@@ -0,0 +1,51 @@
{
// Attività di Visual Studio Code: Terminale > Esegui attività. "build" è quella usata dal debug (launch.json).
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "process",
"command": "dotnet",
"args": ["build", "${workspaceFolder}/Khaemhat.sln", "-c", "Debug", "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary"],
"group": { "kind": "build", "isDefault": true },
"problemMatcher": "$msCompile"
},
{
"label": "test",
"type": "process",
"command": "dotnet",
"args": ["test", "${workspaceFolder}/Khaemhat.sln", "-c", "Debug", "/property:GenerateFullPaths=true"],
"options": { "env": { "KHAEMHAT_LICENSE_MODE": "test" } },
"group": { "kind": "test", "isDefault": true },
"problemMatcher": "$msCompile"
},
{
"label": "watch (web)",
"type": "process",
"command": "dotnet",
"args": ["watch", "run", "--project", "${workspaceFolder}/src/Khaemhat.Web", "--", "--urls", "http://localhost:5080"],
"options": {
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"KHAEMHAT_DATA_DIR": "${workspaceFolder}/.data/dev",
"KHAEMHAT_SYSTEM_DB": "sqlite:///${workspaceFolder}/.data/dev/system.db",
"KHAEMHAT_LICENSE_MODE": "test"
}
},
"isBackground": true,
"problemMatcher": "$msCompile"
},
{
"label": "check-packages",
"type": "shell",
"command": "bash scripts/check-packages.sh",
"problemMatcher": []
},
{
"label": "docker build",
"type": "shell",
"command": "docker build -f docker/Dockerfile -t khaemhat:dev .",
"problemMatcher": []
}
]
}
+57
View File
@@ -7,6 +7,63 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
## [Unreleased]
## [0.1.0] - 2026-11-11
M1 — Strato dati. Nessuna funzione visibile nell'interfaccia: è il motore su cui si appoggiano tutte le milestone
successive.
### Added
- Micro-ORM interno in `Khaemhat.Data` (ADR 0004, ADR 0018): mappe esplicite `EntityMap<T>`, query tipizzate
`Query.For<T>().Where(...)` con un sottoinsieme sicuro di espressioni, `SqlFragment` con valori sempre
parametrizzati, `IUnitOfWork` con transazioni, `IRepository<T,TKey>` con colonne di audit e concorrenza
ottimistica su `row_version` (`ConcurrencyException`), tentativi automatici sugli errori transitori.
- Provider SQLite (tabelle `STRICT`, WAL, decimali esatti come interi scalati x10^6, LIKE senza distinzione di
maiuscole anche per le lettere accentate, scritture serializzate) e PostgreSQL 16+ (`numeric(19,6)`, `timestamptz`,
`jsonb`, `ILIKE`, lock di transazione, creazione ed eliminazione dei database aziendali, informazioni sul server).
- Configurazione dei database da URL `postgres://` e `sqlite://` (`DatabaseUrl`), con la password mai mostrata nei
messaggi.
- Migrazioni in C#: cataloghi di sistema e aziendale, `schema_version` con checksum in ogni database, una
migrazione per transazione sotto lock, rifiuto delle versioni sconosciute; prime tabelle di sistema
`sys_companies` e `sys_settings`.
- Registro delle aziende (`CompanyRegistry`) con la posizione del database cifrata e risoluzione
`DatabaseScope.System` / `DatabaseScope.Company(codice)` in `IUnitOfWorkFactory`.
- Cifratura dei segreti a riposo con AES-256-GCM e chiave derivata da `KHAEMHAT_SECRET_KEY` (`SecretProtector`,
formato `khs1`), con il mattone della rotazione delle chiavi.
- `scripts/new-migration.sh` e `scripts/gen-datamodel.sh` (con `tools/Khaemhat.DataModelTool`): la sezione
*Schema attuale* di `docs/DATA-MODEL.md` è generata dalle migrazioni e un test ne verifica l'aggiornamento.
- Test su SQLite e PostgreSQL (tipi, decimali, paginazione, upsert, LIKE, ordinamento temporale, CRUD, concorrenza,
transazioni, input ostile, migrazioni, registro, cifratura) e misure di riferimento delle prestazioni.
## [0.0.1] - 2026-11-11
Prima versione: M0 — Bootstrap. Nessuna funzione gestionale ancora; c'è lo scheletro su cui costruirle.
### Added
- Soluzione `Khaemhat.sln` con i progetti di SPEC §3 e i relativi progetti di test (MSTest); regole di build comuni,
warning come errori, analyzer, `.editorconfig`, Central Package Management con l'allowlist dei pacchetti.
- Test architetturali: riferimenti fra progetti ammessi da SPEC §3 e pacchetti ammessi da SPEC §1.2;
`scripts/check-packages.sh` fa lo stesso controllo prima di ogni build.
- Pagina "in costruzione" in italiano con marca, icone e versione; pagine di errore e 404.
- Endpoint di salute `/health/live`, `/health/ready` e `/health` con stato e versione (ADR 0012).
- Variabili `KHAEMHAT_URLS` e `KHAEMHAT_LOG_LEVEL`; log JSON su stdout fuori dallo sviluppo.
- Immagine Docker `gitea.encke-hake.ts.net/balbosoft/khaemhat`: multi-stage, utente non root con `PUID`/`PGID`
(ADR 0013), `pg_dump` 17, `HEALTHCHECK`, etichette OCI e Unraid, `restore-system.sh` incluso (ADR 0017).
- `deploy/docker-compose.yml` (PostgreSQL 17, Redis facoltativo) e `deploy/docker-compose.sqlite.yml` (demo);
versione dell'immagine scelta con `KHAEMHAT_VERSION`.
- Gitea Actions: `ci.yml` (build, test, immagine con smoke test, PostgreSQL 16/17 sui tag, controllo YAML),
`release.yml` (immagine e release dal tag, ADR 0015), `wiki.yml` (pubblicazione della wiki).
- Script `build.sh`, `test.sh`, `run-dev.sh`, `publish-image.sh`, `publish-wiki.sh` e stub delle milestone successive.
- Configurazioni di Visual Studio Code per debug, attività ed estensioni consigliate (`.vscode/`).
- ADR 0012-0017 sui punti aperti di M0 (salute, utente, varianti `_FILE`, tag e pubblicazione, icona versionata,
script di ripristino).
### Changed
- I file di `deploy/` puntano alla versione `0.0.1` e all'icona non versionata fino alla 1.0 (ADR 0016).
## Preparazione - 2026-11-10
Documentazione e pianificazione, nessun codice e nessun tag.
### Added
- Specifica di progetto in `docs/SPEC.md` ed emendamenti in `CLAUDE.md` (Gitea al posto di GitHub, solo Docker).
- ADR 0001-0011 sulle decisioni di base.
+38
View File
@@ -0,0 +1,38 @@
<Project>
<!-- Shared build rules for every project (SPEC §1.1, §1.11, §2 Versioning; ADR 0001). -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisLevel>latest</AnalysisLevel>
<AnalysisMode>Recommended</AnalysisMode>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Deterministic>true</Deterministic>
<InvariantGlobalization>false</InvariantGlobalization>
<SatelliteResourceLanguages>it;en</SatelliteResourceLanguages>
<NeutralLanguage>it-IT</NeutralLanguage>
<Company>BalboSoft</Company>
<Product>Khaemhat</Product>
<Copyright>BalboSoft</Copyright>
<RepositoryUrl>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat</RepositoryUrl>
<!--
Version: SemVer from the git tag (vX.Y.Z). Release builds pass it explicitly
(/p:Version=X.Y.Z /p:SourceRevisionId=<sha>, see docker/Dockerfile and scripts/build.sh);
a plain local build asks git through the KhaemhatGitVersion target below.
-->
<Version Condition="'$(Version)' == ''">0.0.0-dev</Version>
<IncludeSourceRevisionInInformationalVersion>true</IncludeSourceRevisionInInformationalVersion>
</PropertyGroup>
<PropertyGroup Condition="$(MSBuildProjectName.EndsWith('.Tests'))">
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<!-- Test methods are public by MSTest convention; XML docs are not required on them (the file stays on for IDE0005). -->
<NoWarn>$(NoWarn);CS1591</NoWarn>
</PropertyGroup>
</Project>
+22
View File
@@ -0,0 +1,22 @@
<Project>
<!--
Local builds without an explicit version read it from git: the nearest tag vX.Y.Z (as X.Y.Z) and the short
commit. Release builds pass /p:Version, and the Docker build context has no .git, so they skip this target.
-->
<Target Name="KhaemhatGitVersion" BeforeTargets="GetAssemblyVersion;GenerateAssemblyInfo"
Condition="'$(Version)' == '0.0.0-dev' And Exists('$(MSBuildThisFileDirectory).git')">
<Exec Command="git describe --tags --match v[0-9]* --abbrev=0" ConsoleToMSBuild="true" IgnoreExitCode="true"
StandardOutputImportance="low" StandardErrorImportance="low" WorkingDirectory="$(MSBuildThisFileDirectory)">
<Output TaskParameter="ConsoleOutput" PropertyName="_KhGitTag" />
<Output TaskParameter="ExitCode" PropertyName="_KhGitTagExit" />
</Exec>
<Exec Command="git rev-parse --short HEAD" ConsoleToMSBuild="true" IgnoreExitCode="true"
StandardOutputImportance="low" StandardErrorImportance="low" WorkingDirectory="$(MSBuildThisFileDirectory)">
<Output TaskParameter="ConsoleOutput" PropertyName="_KhGitSha" />
</Exec>
<PropertyGroup>
<Version Condition="'$(_KhGitTagExit)' == '0' And '$(_KhGitTag)' != ''">$(_KhGitTag.TrimStart('v'))-dev</Version>
<SourceRevisionId Condition="'$(SourceRevisionId)' == ''">$(_KhGitSha)</SourceRevisionId>
</PropertyGroup>
</Target>
</Project>
+19
View File
@@ -0,0 +1,19 @@
<Project>
<!--
Central Package Management: the ONLY packages Khaemhat may use (SPEC §1.2, ADR 0002).
Anything else is written in the repository. scripts/check-packages.sh and the architecture tests
fail the build if a PackageReference outside this list appears, or a test package lands outside tests/.
-->
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
</PropertyGroup>
<ItemGroup Label="Database providers (runtime)">
<PackageVersion Include="Npgsql" Version="10.0.3" />
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.15" />
</ItemGroup>
<ItemGroup Label="Tests only (never in the image)">
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.1" />
<PackageVersion Include="MSTest" Version="4.5.2" />
</ItemGroup>
</Project>
+283
View File
@@ -0,0 +1,283 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Application", "src\Khaemhat.Application\Khaemhat.Application.csproj", "{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Core", "src\Khaemhat.Core\Khaemhat.Core.csproj", "{B212CA0C-F7FF-4223-8FC5-961116D937B8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Data", "src\Khaemhat.Data\Khaemhat.Data.csproj", "{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Infrastructure", "src\Khaemhat.Infrastructure\Khaemhat.Infrastructure.csproj", "{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Fiscal.Abstractions", "src\Khaemhat.Fiscal.Abstractions\Khaemhat.Fiscal.Abstractions.csproj", "{F0A94F81-8CAB-4803-A209-C7E350160726}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Data.PostgreSql", "src\Khaemhat.Data.PostgreSql\Khaemhat.Data.PostgreSql.csproj", "{37AAC975-29AB-4649-A961-4115005042F1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Data.Sqlite", "src\Khaemhat.Data.Sqlite\Khaemhat.Data.Sqlite.csproj", "{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Fiscal.Italy", "src\Khaemhat.Fiscal.Italy\Khaemhat.Fiscal.Italy.csproj", "{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Web", "src\Khaemhat.Web\Khaemhat.Web.csproj", "{64DD5604-A3E4-45C0-9588-A1E38363C0C9}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Application.Tests", "tests\Khaemhat.Application.Tests\Khaemhat.Application.Tests.csproj", "{8BE00CC7-FE33-412E-8CE5-86425869D301}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Core.Tests", "tests\Khaemhat.Core.Tests\Khaemhat.Core.Tests.csproj", "{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Data.Tests", "tests\Khaemhat.Data.Tests\Khaemhat.Data.Tests.csproj", "{AD3903F9-037E-48AE-B555-84345C4895E0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Fiscal.Italy.Tests", "tests\Khaemhat.Fiscal.Italy.Tests\Khaemhat.Fiscal.Italy.Tests.csproj", "{ECD0F91C-C8D7-4686-9609-56F2A93F4113}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Infrastructure.Tests", "tests\Khaemhat.Infrastructure.Tests\Khaemhat.Infrastructure.Tests.csproj", "{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.Web.Tests", "tests\Khaemhat.Web.Tests\Khaemhat.Web.Tests.csproj", "{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E-EAC7-C090-1BA3-A61EC2A24D84}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.LicenseTool", "tools\Khaemhat.LicenseTool\Khaemhat.LicenseTool.csproj", "{4317FFD0-9473-43FD-8543-F80EF9BA812A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.DataModelTool", "tools\Khaemhat.DataModelTool\Khaemhat.DataModelTool.csproj", "{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|x64.ActiveCfg = Debug|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|x64.Build.0 = Debug|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|x86.ActiveCfg = Debug|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Debug|x86.Build.0 = Debug|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|Any CPU.Build.0 = Release|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|x64.ActiveCfg = Release|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|x64.Build.0 = Release|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|x86.ActiveCfg = Release|Any CPU
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5}.Release|x86.Build.0 = Release|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|x64.ActiveCfg = Debug|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|x64.Build.0 = Debug|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|x86.ActiveCfg = Debug|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Debug|x86.Build.0 = Debug|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|Any CPU.Build.0 = Release|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|x64.ActiveCfg = Release|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|x64.Build.0 = Release|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|x86.ActiveCfg = Release|Any CPU
{B212CA0C-F7FF-4223-8FC5-961116D937B8}.Release|x86.Build.0 = Release|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|x64.ActiveCfg = Debug|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|x64.Build.0 = Debug|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|x86.ActiveCfg = Debug|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Debug|x86.Build.0 = Debug|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|Any CPU.Build.0 = Release|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|x64.ActiveCfg = Release|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|x64.Build.0 = Release|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|x86.ActiveCfg = Release|Any CPU
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F}.Release|x86.Build.0 = Release|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|x64.ActiveCfg = Debug|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|x64.Build.0 = Debug|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|x86.ActiveCfg = Debug|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Debug|x86.Build.0 = Debug|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|Any CPU.Build.0 = Release|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|x64.ActiveCfg = Release|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|x64.Build.0 = Release|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|x86.ActiveCfg = Release|Any CPU
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C}.Release|x86.Build.0 = Release|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|x64.ActiveCfg = Debug|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|x64.Build.0 = Debug|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|x86.ActiveCfg = Debug|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Debug|x86.Build.0 = Debug|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|Any CPU.Build.0 = Release|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|x64.ActiveCfg = Release|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|x64.Build.0 = Release|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|x86.ActiveCfg = Release|Any CPU
{F0A94F81-8CAB-4803-A209-C7E350160726}.Release|x86.Build.0 = Release|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|x64.ActiveCfg = Debug|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|x64.Build.0 = Debug|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|x86.ActiveCfg = Debug|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Debug|x86.Build.0 = Debug|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Release|Any CPU.Build.0 = Release|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Release|x64.ActiveCfg = Release|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Release|x64.Build.0 = Release|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Release|x86.ActiveCfg = Release|Any CPU
{37AAC975-29AB-4649-A961-4115005042F1}.Release|x86.Build.0 = Release|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|x64.ActiveCfg = Debug|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|x64.Build.0 = Debug|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|x86.ActiveCfg = Debug|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Debug|x86.Build.0 = Debug|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|Any CPU.Build.0 = Release|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|x64.ActiveCfg = Release|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|x64.Build.0 = Release|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|x86.ActiveCfg = Release|Any CPU
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F}.Release|x86.Build.0 = Release|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|x64.ActiveCfg = Debug|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|x64.Build.0 = Debug|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|x86.ActiveCfg = Debug|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Debug|x86.Build.0 = Debug|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|Any CPU.Build.0 = Release|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|x64.ActiveCfg = Release|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|x64.Build.0 = Release|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|x86.ActiveCfg = Release|Any CPU
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302}.Release|x86.Build.0 = Release|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|x64.ActiveCfg = Debug|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|x64.Build.0 = Debug|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|x86.ActiveCfg = Debug|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Debug|x86.Build.0 = Debug|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|Any CPU.Build.0 = Release|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|x64.ActiveCfg = Release|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|x64.Build.0 = Release|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|x86.ActiveCfg = Release|Any CPU
{64DD5604-A3E4-45C0-9588-A1E38363C0C9}.Release|x86.Build.0 = Release|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|x64.ActiveCfg = Debug|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|x64.Build.0 = Debug|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|x86.ActiveCfg = Debug|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Debug|x86.Build.0 = Debug|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|Any CPU.Build.0 = Release|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|x64.ActiveCfg = Release|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|x64.Build.0 = Release|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|x86.ActiveCfg = Release|Any CPU
{8BE00CC7-FE33-412E-8CE5-86425869D301}.Release|x86.Build.0 = Release|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|x64.ActiveCfg = Debug|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|x64.Build.0 = Debug|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|x86.ActiveCfg = Debug|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Debug|x86.Build.0 = Debug|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|Any CPU.Build.0 = Release|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|x64.ActiveCfg = Release|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|x64.Build.0 = Release|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|x86.ActiveCfg = Release|Any CPU
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D}.Release|x86.Build.0 = Release|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|x64.ActiveCfg = Debug|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|x64.Build.0 = Debug|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|x86.ActiveCfg = Debug|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Debug|x86.Build.0 = Debug|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|Any CPU.Build.0 = Release|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|x64.ActiveCfg = Release|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|x64.Build.0 = Release|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|x86.ActiveCfg = Release|Any CPU
{AD3903F9-037E-48AE-B555-84345C4895E0}.Release|x86.Build.0 = Release|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|x64.ActiveCfg = Debug|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|x64.Build.0 = Debug|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|x86.ActiveCfg = Debug|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Debug|x86.Build.0 = Debug|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|Any CPU.Build.0 = Release|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|x64.ActiveCfg = Release|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|x64.Build.0 = Release|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|x86.ActiveCfg = Release|Any CPU
{ECD0F91C-C8D7-4686-9609-56F2A93F4113}.Release|x86.Build.0 = Release|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|x64.ActiveCfg = Debug|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|x64.Build.0 = Debug|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|x86.ActiveCfg = Debug|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Debug|x86.Build.0 = Debug|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|Any CPU.Build.0 = Release|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|x64.ActiveCfg = Release|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|x64.Build.0 = Release|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|x86.ActiveCfg = Release|Any CPU
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699}.Release|x86.Build.0 = Release|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|x64.ActiveCfg = Debug|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|x64.Build.0 = Debug|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|x86.ActiveCfg = Debug|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Debug|x86.Build.0 = Debug|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|Any CPU.Build.0 = Release|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|x64.ActiveCfg = Release|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|x64.Build.0 = Release|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|x86.ActiveCfg = Release|Any CPU
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A}.Release|x86.Build.0 = Release|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|x64.ActiveCfg = Debug|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|x64.Build.0 = Debug|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|x86.ActiveCfg = Debug|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Debug|x86.Build.0 = Debug|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|Any CPU.Build.0 = Release|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|x64.ActiveCfg = Release|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|x64.Build.0 = Release|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|x86.ActiveCfg = Release|Any CPU
{4317FFD0-9473-43FD-8543-F80EF9BA812A}.Release|x86.Build.0 = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|x64.ActiveCfg = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|x64.Build.0 = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|x86.ActiveCfg = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Debug|x86.Build.0 = Debug|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|Any CPU.Build.0 = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x64.ActiveCfg = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x64.Build.0 = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x86.ActiveCfg = Release|Any CPU
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{6A70BA3E-47A7-40EC-AF2A-FB6FA9BFD6C5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{B212CA0C-F7FF-4223-8FC5-961116D937B8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{6A4CD6EB-E529-4A76-B028-CFF8F5D59E2F} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{4E7F3565-DD8A-4B25-BB27-7090F1144F4C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{F0A94F81-8CAB-4803-A209-C7E350160726} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{37AAC975-29AB-4649-A961-4115005042F1} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{EF1EDA79-1E49-41CB-AF44-1C1ACC94611F} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{0CAFB3CA-3C92-4816-A63A-4670D7AD2302} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{64DD5604-A3E4-45C0-9588-A1E38363C0C9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{8BE00CC7-FE33-412E-8CE5-86425869D301} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{F6C68A01-8C27-47D5-8C45-E2D00D9BC32D} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{AD3903F9-037E-48AE-B555-84345C4895E0} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{ECD0F91C-C8D7-4686-9609-56F2A93F4113} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{C5C8124F-3B12-43A9-BD0F-5AA5F7261699} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{4317FFD0-9473-43FD-8543-F80EF9BA812A} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
EndGlobalSection
EndGlobal
+19 -2
View File
@@ -8,7 +8,8 @@
Blazor Server, PostgreSQL (o SQLite per demo e test) e **nessuna libreria esterna**. Si installa **solo con Docker**:
l'unico artefatto distribuito è l'immagine nel registro pacchetti di Gitea.
> **Stato:** progettazione completata, sviluppo non ancora avviato. Vedi [`docs/STATUS.md`](docs/STATUS.md) e la
> **Stato:** sviluppo avviato. M0 (struttura, immagine Docker, CI) consegna la versione 0.0.1 con una pagina
> "in costruzione"; le funzioni arrivano milestone dopo milestone. Vedi [`docs/STATUS.md`](docs/STATUS.md) e la
> [Roadmap](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Roadmap).
Il nome viene da Khaemhat (Mahu), scriba reale e sovrintendente al doppio granaio dell'Alto e del Basso Egitto sotto
@@ -25,18 +26,34 @@ Amenhotep III: un contabile e un magazziniere dell'antichità. Vedi
- Più aziende sulla stessa istanza (un database di sistema + un database per azienda), moduli attivabili con
licenza, temi chiaro/scuro, dashboard a widget.
## Installazione (dalla prima versione rilasciata)
## Installazione
```bash
docker pull gitea.encke-hake.ts.net/balbosoft/khaemhat:<versione>
```
- Qualunque host Docker: [`deploy/docker-compose.yml`](deploy/docker-compose.yml) (con PostgreSQL) e
[`deploy/.env.example`](deploy/.env.example); per una prova veloce
[`deploy/docker-compose.sqlite.yml`](deploy/docker-compose.sqlite.yml).
- Unraid: template [`deploy/unraid/khaemhat.xml`](deploy/unraid/khaemhat.xml) o
[`deploy/docker-compose.unraid.yml`](deploy/docker-compose.unraid.yml) con [`deploy/.env.example`](deploy/.env.example).
- Guide: [Installazione Unraid](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Unraid) ·
[Installazione Docker](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Installazione-Docker) ·
[Primi passi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Primi-passi).
## Sviluppo
Serve l'SDK .NET 10 (`global.json`); Docker solo per costruire e provare l'immagine.
```bash
scripts/build.sh # allowlist dei pacchetti + build con warning come errori
scripts/test.sh # tutti i test (PostgreSQL con KHAEMHAT_TEST_PG, Redis con KHAEMHAT_TEST_REDIS)
scripts/run-dev.sh # avvio locale su http://localhost:5080 con SQLite in .data/dev
docker build -f docker/Dockerfile -t khaemhat:dev .
```
Processo, rami e Definition of Done in [`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md).
## Documentazione
| Cosa | Dove |
+5 -1
View File
@@ -1,4 +1,6 @@
# Copia in .env accanto a docker-compose.unraid.yml (mai committare .env)
# Copia in .env accanto al file compose (docker-compose.yml o docker-compose.unraid.yml); mai committare .env.
# Versione dell'immagine: sempre esplicita, mai latest in produzione (ADR 0015).
KHAEMHAT_VERSION=0.0.1
POSTGRES_PASSWORD=cambiami-subito
KHAEMHAT_SECRET_KEY= # openssl rand -base64 48
KHAEMHAT_SUPERUSER=root
@@ -11,3 +13,5 @@ KHAEMHAT_LICENSE_MODE=production
KHAEMHAT_SEED_DEMO=false
# KHAEMHAT_REDIS=redis://:cambiami@khaemhat-redis:6379/0
# REDIS_PASSWORD=cambiami
# PUID=99 # utente e gruppo proprietari di /data (ADR 0013); predefiniti 1654 = utente app dell'immagine
# PGID=100
+29
View File
@@ -0,0 +1,29 @@
# Demo autonoma: un solo container, database SQLite nel volume /data, dati di esempio al primo avvio.
# Solo per prove: per lavorare con più utenti serve PostgreSQL (docker-compose.yml).
# docker compose -f docker-compose.sqlite.yml up
services:
khaemhat:
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
ports:
- "${KHAEMHAT_PORT:-8080}:8080"
environment:
KHAEMHAT_SYSTEM_DB: sqlite:///data/system.db
KHAEMHAT_SECRET_KEY: ${KHAEMHAT_SECRET_KEY:-}
KHAEMHAT_SUPERUSER: root
KHAEMHAT_SUPERUSER_PASSWORD: ${KHAEMHAT_SUPERUSER_PASSWORD:-}
KHAEMHAT_COMPANY_CODE: DEMO
KHAEMHAT_COMPANY_NAME: Khaemhat Demo S.r.l.
KHAEMHAT_SEED_DEMO: "true"
KHAEMHAT_LICENSE_MODE: test
TZ: ${TZ:-Europe/Rome}
volumes:
- khaemhat-demo:/data
healthcheck:
test: ["CMD", "curl", "-fs", "http://localhost:8080/health/live"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
volumes:
khaemhat-demo:
+2 -2
View File
@@ -3,7 +3,7 @@
# Le etichette net.unraid.docker.* mostrano icona e link WebUI nella pagina Docker di Unraid.
services:
khaemhat:
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:1.0.0
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
container_name: khaemhat
restart: unless-stopped
depends_on:
@@ -32,7 +32,7 @@ services:
labels:
net.unraid.docker.managed: composeman
net.unraid.docker.webui: "http://[IP]:[PORT:8080]/"
net.unraid.docker.icon: "https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-256.png"
net.unraid.docker.icon: "https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-256.png"
healthcheck:
test: ["CMD", "curl", "-fs", "http://localhost:8080/health/live"]
interval: 30s
+65
View File
@@ -0,0 +1,65 @@
# Khaemhat con PostgreSQL su qualunque host Docker (installazione consigliata, wiki Installazione-Docker).
# Copia accanto a questo file .env.example come .env e compila i valori. Usa sempre una versione esplicita.
# docker compose up -d applicazione + PostgreSQL
# docker compose --profile redis up -d anche Redis (poi imposta KHAEMHAT_REDIS nel .env)
services:
khaemhat:
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
restart: unless-stopped
depends_on:
khaemhat-db:
condition: service_healthy
ports:
- "${KHAEMHAT_PORT:-8080}:8080"
environment:
KHAEMHAT_SYSTEM_DB: postgres://khaemhat:${POSTGRES_PASSWORD:?imposta POSTGRES_PASSWORD nel .env}@khaemhat-db:5432/khaemhat_system
KHAEMHAT_DB_SERVER: postgres://khaemhat:${POSTGRES_PASSWORD}@khaemhat-db:5432/
KHAEMHAT_SECRET_KEY: ${KHAEMHAT_SECRET_KEY:-}
KHAEMHAT_SUPERUSER: ${KHAEMHAT_SUPERUSER:-root}
KHAEMHAT_SUPERUSER_PASSWORD: ${KHAEMHAT_SUPERUSER_PASSWORD:-}
KHAEMHAT_SUPERUSER_EMAIL: ${KHAEMHAT_SUPERUSER_EMAIL:-}
KHAEMHAT_COMPANY_CODE: ${KHAEMHAT_COMPANY_CODE:-DEMO}
KHAEMHAT_COMPANY_NAME: ${KHAEMHAT_COMPANY_NAME:-La mia azienda S.r.l.}
KHAEMHAT_PUBLIC_URL: ${KHAEMHAT_PUBLIC_URL:-http://localhost:8080}
KHAEMHAT_REDIS: ${KHAEMHAT_REDIS:-}
KHAEMHAT_LICENSE_MODE: ${KHAEMHAT_LICENSE_MODE:-production}
KHAEMHAT_LICENSE: ${KHAEMHAT_LICENSE:-}
KHAEMHAT_SEED_DEMO: ${KHAEMHAT_SEED_DEMO:-false}
KHAEMHAT_LOG_LEVEL: ${KHAEMHAT_LOG_LEVEL:-Information}
TZ: ${TZ:-Europe/Rome}
PUID: ${PUID:-1654}
PGID: ${PGID:-1654}
volumes:
- khaemhat-data:/data
healthcheck:
test: ["CMD", "curl", "-fs", "http://localhost:8080/health/live"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
khaemhat-db:
image: postgres:17
restart: unless-stopped
environment:
POSTGRES_DB: khaemhat_system
POSTGRES_USER: khaemhat
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
TZ: ${TZ:-Europe/Rome}
volumes:
- khaemhat-pg:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U khaemhat -d khaemhat_system"]
interval: 10s
timeout: 5s
retries: 10
khaemhat-redis:
image: redis:7
restart: unless-stopped
profiles: ["redis"]
command: ["redis-server", "--requirepass", "${REDIS_PASSWORD:-cambiami}", "--save", "", "--appendonly", "no"]
volumes:
khaemhat-data:
khaemhat-pg:
+3 -3
View File
@@ -1,10 +1,10 @@
<?xml version="1.0"?>
<!-- Template Unraid (formato Community Applications) per Khaemhat.
Importalo da Docker › Add Container › Template. Immagine dal registro pacchetti di Gitea (ADR 0009).
Importalo da Docker → Add Container → Template. Immagine dal registro pacchetti di Gitea (ADR 0009).
Icona e template sono serviti come file raw dal repository pubblico BalboSoft/Khaemhat. -->
<Container version="2">
<Name>khaemhat</Name>
<Repository>gitea.encke-hake.ts.net/balbosoft/khaemhat:1.0.0</Repository>
<Repository>gitea.encke-hake.ts.net/balbosoft/khaemhat:0.0.1</Repository>
<Registry>https://gitea.encke-hake.ts.net/BalboSoft/-/packages/container/khaemhat</Registry>
<Network>khaemhat-net</Network>
<Privileged>false</Privileged>
@@ -14,7 +14,7 @@
<Category>Productivity: Tools:</Category>
<WebUI>http://[IP]:[PORT:8080]/</WebUI>
<TemplateURL>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/deploy/unraid/khaemhat.xml</TemplateURL>
<Icon>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-256.png</Icon>
<Icon>https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-256.png</Icon>
<ExtraParams>--health-cmd="curl -fs http://localhost:8080/health/live || exit 1" --health-interval=30s --health-timeout=5s --health-retries=3</ExtraParams>
<Requires>Un database PostgreSQL 16 o 17 raggiungibile (consigliato il template ufficiale postgres sulla rete khaemhat-net) e un ruolo con permesso CREATEDB.</Requires>
<Config Name="Porta web" Target="8080" Default="8080" Mode="tcp" Description="Interfaccia web (dietro reverse proxy TLS)" Type="Port" Display="always" Required="true" Mask="false">8080</Config>
+90
View File
@@ -0,0 +1,90 @@
# syntax=docker/dockerfile:1
# Khaemhat image (SPEC §16.1, ADR 0009, 0010, 0013, 0015, 0016, 0017). Build from the repository root:
# docker build -f docker/Dockerfile --build-arg VERSION=0.0.1 --build-arg GIT_SHA=$(git rev-parse --short HEAD) .
ARG DOTNET_VERSION=10.0
# ---------------------------------------------------------------------------------------------------------------------
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build
ARG VERSION=0.0.0-dev
ARG GIT_SHA=unknown
ARG RUN_TESTS=false
ENV DOTNET_NOLOGO=1 DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
WORKDIR /src
# Restore first, from the build files only, so the layer is reused while no project or package changes.
COPY global.json Directory.Build.props Directory.Build.targets Directory.Packages.props .editorconfig ./
COPY src/Khaemhat.Core/Khaemhat.Core.csproj src/Khaemhat.Core/
COPY src/Khaemhat.Fiscal.Abstractions/Khaemhat.Fiscal.Abstractions.csproj src/Khaemhat.Fiscal.Abstractions/
COPY src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj src/Khaemhat.Fiscal.Italy/
COPY src/Khaemhat.Data/Khaemhat.Data.csproj src/Khaemhat.Data/
COPY src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj src/Khaemhat.Data.Sqlite/
COPY src/Khaemhat.Data.PostgreSql/Khaemhat.Data.PostgreSql.csproj src/Khaemhat.Data.PostgreSql/
COPY src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj src/Khaemhat.Infrastructure/
COPY src/Khaemhat.Application/Khaemhat.Application.csproj src/Khaemhat.Application/
COPY src/Khaemhat.Web/Khaemhat.Web.csproj src/Khaemhat.Web/
RUN dotnet restore src/Khaemhat.Web/Khaemhat.Web.csproj
COPY . .
RUN bash scripts/check-packages.sh
RUN if [ "$RUN_TESTS" = "true" ]; then \
dotnet test Khaemhat.sln -c Release /p:Version="$VERSION" /p:SourceRevisionId="$GIT_SHA"; \
fi
RUN dotnet publish src/Khaemhat.Web/Khaemhat.Web.csproj -c Release -o /app --no-restore \
/p:Version="$VERSION" /p:SourceRevisionId="$GIT_SHA" /p:UseAppHost=false
# ---------------------------------------------------------------------------------------------------------------------
FROM mcr.microsoft.com/dotnet/aspnet:${DOTNET_VERSION} AS runtime
ARG VERSION=0.0.0-dev
ARG GIT_SHA=unknown
ARG CREATED=unknown
ARG SOURCE_URL=https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat
ARG ICON_URL=https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-256.png
# OS tools allowed by SPEC §1.2 (not application components): pg_dump/pg_restore 17 from the PGDG repository (a
# client >= the server: works with PostgreSQL 16 and 17), curl for the health check, tzdata for TZ.
RUN set -eux; \
apt-get update; \
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates curl tzdata; \
. /etc/os-release; \
install -d /usr/share/postgresql-common/pgdg; \
curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc https://www.postgresql.org/media/keys/ACCC4CF8.asc; \
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${VERSION_CODENAME}-pgdg main" \
> /etc/apt/sources.list.d/pgdg.list; \
apt-get update; \
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends postgresql-client-17; \
rm -rf /var/lib/apt/lists/*; \
pg_dump --version
ENV ASPNETCORE_ENVIRONMENT=Production \
ASPNETCORE_HTTP_PORTS=8080 \
KHAEMHAT_DATA_DIR=/data \
DOTNET_NOLOGO=1 \
TZ=Europe/Rome
WORKDIR /app
COPY --from=build /app ./
COPY docker/entrypoint.sh /app/entrypoint.sh
COPY scripts/restore-system.sh /app/scripts/restore-system.sh
RUN chmod 0755 /app/entrypoint.sh /app/scripts/restore-system.sh \
&& install -d -o app -g app -m 0750 /data
LABEL org.opencontainers.image.title="Khaemhat" \
org.opencontainers.image.description="Gestionale ERP e CRM per PMI italiane" \
org.opencontainers.image.vendor="BalboSoft" \
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.revision="${GIT_SHA}" \
org.opencontainers.image.created="${CREATED}" \
org.opencontainers.image.source="${SOURCE_URL}" \
org.opencontainers.image.url="${SOURCE_URL}" \
org.opencontainers.image.documentation="${SOURCE_URL}/wiki" \
net.unraid.docker.icon="${ICON_URL}" \
net.unraid.docker.webui="http://[IP]:[PORT:8080]/"
VOLUME /data
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD curl -fs http://localhost:8080/health/live || exit 1
# Starts as root only to align the app user with PUID/PGID; the .NET process runs as "app" (ADR 0013).
ENTRYPOINT ["/app/entrypoint.sh"]
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
# Container entrypoint (docs/DEPLOY.md §2.4, ADR 0013, ADR 0014). It only prepares the user, waits for the system
# database and starts the app: migrations and bootstrap live in the .NET code.
set -euo pipefail
APP_DLL=/app/Khaemhat.Web.dll
DATA_DIR="${KHAEMHAT_DATA_DIR:-/data}"
DB_WAIT_SECONDS=120
log() { printf '%s khaemhat-entrypoint: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >&2; }
fail() { log "ERRORE: $*"; exit 1; }
# The system database URL, from KHAEMHAT_SYSTEM_DB or KHAEMHAT_SYSTEM_DB_FILE (ADR 0014). Only host and port are used.
system_db() {
if [[ -n "${KHAEMHAT_SYSTEM_DB:-}" && -n "${KHAEMHAT_SYSTEM_DB_FILE:-}" ]]; then
fail "KHAEMHAT_SYSTEM_DB e KHAEMHAT_SYSTEM_DB_FILE sono entrambe impostate: usane una sola."
fi
if [[ -n "${KHAEMHAT_SYSTEM_DB_FILE:-}" ]]; then
[[ -r "$KHAEMHAT_SYSTEM_DB_FILE" ]] || fail "KHAEMHAT_SYSTEM_DB_FILE: file non leggibile ($KHAEMHAT_SYSTEM_DB_FILE)."
head -n 1 "$KHAEMHAT_SYSTEM_DB_FILE" | tr -d '\r\n'
else
printf '%s' "${KHAEMHAT_SYSTEM_DB:-}"
fi
}
# Waits until the PostgreSQL server of the system database accepts connections. SQLite needs no wait.
wait_for_database() {
local url host port rest deadline
url="$(system_db)"
case "$url" in
postgres://* | postgresql://*) ;;
*) return 0 ;;
esac
rest="${url#*://}" # user:pwd@host:port/db?x
rest="${rest##*@}" # host:port/db?x
rest="${rest%%/*}" # host:port
rest="${rest%%\?*}"
host="${rest%%:*}"
port=5432
[[ "$rest" == *:* ]] && port="${rest##*:}"
[[ -n "$host" ]] || fail "KHAEMHAT_SYSTEM_DB: host mancante."
deadline=$((SECONDS + DB_WAIT_SECONDS))
until pg_isready -q -h "$host" -p "$port" -t 3; do
if (( SECONDS >= deadline )); then
fail "il database di sistema su $host:$port non risponde dopo ${DB_WAIT_SECONDS}s."
fi
log "attendo il database di sistema su $host:$port..."
sleep 2
done
log "database di sistema raggiungibile su $host:$port."
}
# Aligns the "app" user with PUID/PGID and gives it /data (ADR 0013). Only when started as root.
prepare_user() {
local puid="${PUID:-$(id -u app)}" pgid="${PGID:-$(id -g app)}"
[[ "$puid" =~ ^[0-9]+$ && "$pgid" =~ ^[0-9]+$ ]] || fail "PUID e PGID devono essere numeri (PUID=$puid, PGID=$pgid)."
(( puid != 0 && pgid != 0 )) || fail "PUID e PGID non possono essere 0: l'applicazione non gira come root."
if [[ "$(id -g app)" != "$pgid" ]]; then
groupmod -o -g "$pgid" app
fi
if [[ "$(id -u app)" != "$puid" ]]; then
usermod -o -u "$puid" app
fi
mkdir -p "$DATA_DIR"
if [[ "$(stat -c '%u:%g' "$DATA_DIR")" != "$puid:$pgid" ]]; then
log "assegno $DATA_DIR a $puid:$pgid..."
chown -R "$puid:$pgid" "$DATA_DIR"
fi
}
wait_for_database
if [[ "$(id -u)" == "0" ]]; then
prepare_user
log "avvio Khaemhat come utente app ($(id -u app):$(id -g app))."
exec setpriv --reuid=app --regid=app --init-groups -- dotnet "$APP_DLL" "$@"
fi
log "avvio Khaemhat come utente $(id -u):$(id -g)."
exec dotnet "$APP_DLL" "$@"
+14
View File
@@ -0,0 +1,14 @@
-- Optional init script for the official postgres image (mount it in /docker-entrypoint-initdb.d/): it runs once,
-- when the data directory is empty. Khaemhat creates every table itself (migrations in .NET, one database per
-- company), so this only sets defaults for the application role.
--
-- The role must be able to create databases (CREATEDB): the POSTGRES_USER of the official image is a superuser and
-- already can; for an existing server see docs/DEPLOY.md.
DO $$
BEGIN
-- Timestamps are stored as timestamptz and handled in UTC by the application.
EXECUTE format('ALTER ROLE %I SET timezone TO %L', current_user, 'UTC');
EXECUTE format('ALTER ROLE %I SET client_encoding TO %L', current_user, 'UTF8');
END
$$;
+15 -10
View File
@@ -1,6 +1,6 @@
# Architettura di Khaemhat
> Stato: bozza · Revisione 2026-11-10 · Fonte: SPEC §1, §2, §3, §4, §5, §7, §9, §13, §15, §19, §21; ADR 0009-0011
> Stato: bozza · Revisione 2026-11-11 · Fonte: SPEC §1, §2, §3, §4, §5, §7, §9, §13, §15, §19, §21; ADR 0009-0018
Questo documento descrive l'architettura **prevista** del gestionale: livelli, progetti, regole di dipendenza,
composizione dei moduli, gestione multi-database, ciclo di una richiesta e servizi trasversali. Il codice non esiste
@@ -74,6 +74,7 @@ client degli aggiornamenti è `GiteaPackagesClient`.
| `Khaemhat.Application` | casi d'uso, moduli (`IModule`), motore documenti e contabile, seeding, report | M2 → M12 |
| `Khaemhat.Web` | host ASP.NET Core 10, Blazor Interactive Server, Minimal API, MCP, autenticazione | M0 → M13 |
| `tools/Khaemhat.LicenseTool` | CLI per chiavi ed emissione licenze (chiave privata mai nel repository; non distribuito) | M2 |
| `tools/Khaemhat.DataModelTool` | rigenera la sezione generata di `docs/DATA-MODEL.md` dalle migrazioni (non distribuito, ADR 0018) | M1 |
| `tests/*` | `Core`, `Data`, `Infrastructure`, `Fiscal.Italy`, `Application`, `Web` (MSTest) | ogni milestone |
## 3. Regole di dipendenza
@@ -171,11 +172,11 @@ tabelle è in [DATA-MODEL.md](DATA-MODEL.md).
| Tipo | Progetto | Responsabilità |
|---|---|---|
| `IDbProvider` | Data | motore (`DbEngine`), dialetto, `SchemaBuilder`, creazione connessioni, `EnsureDatabaseExistsAsync`, `DropDatabaseAsync`, `GetServerInfoAsync` |
| `ISqlDialect` | Data | quoting, parametri, paginazione, `InsertReturningId`, `Upsert`, `CaseInsensitiveLike`, `AdvisoryLock`, conversioni `ColumnType` |
| `IDbProvider` | Data | motore (`DbEngine`), dialetto, generatore DDL (`Ddl`), connection string da `DatabaseUrl`, creazione connessioni, `EnsureDatabaseExistsAsync`, `DatabaseExistsAsync`, `DropDatabaseAsync`, `GetServerInfoAsync`, `IsTransient`, `EnterWriteScopeAsync` (ADR 0018) |
| `ISqlDialect` | Data | quoting, parametri, paginazione, `InsertReturningId`, `Upsert`, `CaseInsensitiveLike` e `AdvisoryLock` come `SqlFragment`, conversioni `ColumnType` |
| `IUnitOfWorkFactory` | Data | `CreateAsync(DatabaseScope scope)` dove lo scope è `System` oppure `Company(code)` |
| `IUnitOfWork` / `IRepository<T,TKey>` | Data | transazione, repository tipizzati, `ExecuteAsync`/`QueryAsync`/`StreamAsync` su `SqlFragment` |
| `ICompanyRegistry` (`CompanyRegistry`) | Data | risolve `companyCode → (IDbProvider, connection string decifrata)` leggendo `sys_companies` |
| `ICompanyRegistry` (`CompanyRegistry`) | Data | registra le aziende e risolve `companyCode → DatabaseTarget` (provider + connection string) decifrando l'URL salvato in `sys_companies` |
| `ICompanyContext` | Core (interfaccia), Web (`CompanyContextAccessor`) | azienda corrente: **per circuito Blazor** e **per richiesta API** (header `X-Company`) |
| `SecretProtector` | Infrastructure | AES-256-GCM con chiave derivata da `KHAEMHAT_SECRET_KEY` per connection string e credenziali |
@@ -391,8 +392,12 @@ Khaemhat/
Differenze rispetto a SPEC §4: `.gitea/workflows/` al posto di `.github/workflows/`; registro pacchetti Gitea al
posto di GHCR; nessun repository `khaemhat-assets` (icona servita come file raw del repository pubblico);
`docs/SPEC.md` contiene la specifica e `CLAUDE.md` è breve (ADR 0011); `docs/mockups/thumbs/` aggiunta;
`scripts/restore-system.sh` è citato in SPEC §13 e qui riportato nell'albero. Nessun installer né binario
distribuito (ADR 0010).
`scripts/restore-system.sh` è citato in SPEC §13 e qui riportato nell'albero; è copiato nell'immagine in
`/app/scripts/` (ADR 0017). Nessun installer né binario distribuito (ADR 0010). In più `.vscode/` (debug e attività
di Visual Studio Code) e `.gitea/scripts/check-yaml.rb` (controllo YAML della CI).
Le regole di dipendenza della §3 e l'allowlist dei pacchetti sono verificate da test: `Khaemhat.Core.Tests`,
cartella `Architecture/`, legge i file di progetto e fallisce su ogni riferimento non ammesso.
## 10. Classi principali per progetto
@@ -436,11 +441,11 @@ stando fuori dal pacchetto fiscale: è la collocazione indicata da SPEC §21.
| Area | Classi |
|---|---|
| Contratti | `IDbProvider`, `ISqlDialect`, `ISchemaBuilder`, `IUnitOfWork`, `IUnitOfWorkFactory`, `IRepository<,>`, `Repository<,>` |
| Registro database | `ICompanyRegistry`, `CompanyRegistry`, `DatabaseScope` |
| Contratti | `IDbProvider`, `ISqlDialect`, `ISchemaBuilder`, `IUnitOfWork`, `IUnitOfWorkFactory`, `IRepository<,>`, `Repository<,>`, `DatabaseUrl`, `DatabaseTarget`, `DbProviderCatalog` |
| Registro database | `ICompanyRegistry`, `CompanyRegistry`, `IDatabaseLocator`, `DatabaseLocator`, `DatabaseScope`, `CompanyCodes` |
| Mappe e query | `EntityMap<T>`, `ColumnMap`, `ColumnType`, `MapRegistry`, `QueryBuilder<T>`, `Query<T>`, `PagedResult<T>`, `SqlFragment`, `ExpressionTranslator` |
| Esecuzione | `DbExecutor`, `ReaderMapper<T>`, `CommandCache`, `TransientRetryPolicy` |
| Migrazioni | `IMigration`, `MigrationAttribute`, `MigrationRunner`, `MigrationCatalog` (System/Company), `SchemaVersionStore`, `TableDefinition`, `ColumnDefinition`, `IndexDefinition`, `ForeignKeyDefinition`, `DdlGenerator` |
| Esecuzione | `UnitOfWork`, `UnitOfWorkFactory`, `DataAccessContext` (orologio, utente, tentativi), `DbExecutor`, `ReaderMapper`, `CommandCache`, `TransientRetryPolicy` |
| Migrazioni | `IMigration`, `MigrationAttribute`, `MigrationRunner`, `MigrationReport`, `MigrationCatalog` (`ForSystem`/`ForCompany`), `SchemaVersionStore`, `SchemaModel`, `DataModelDocument`, `TableDefinition`, `ColumnDefinition`, `IndexDefinition`, `ForeignKeyDefinition`, `DdlGenerator` |
| SQLite | `SqliteProvider`, `SqliteDialect`, `SqliteSchemaBuilder`, `SqliteWriteLock`, `SqliteDecimalConverter` |
| PostgreSQL | `PostgresProvider`, `PostgresDialect`, `PostgresSchemaBuilder`, `PostgresDatabaseCreator`, `PostgresAdvisoryLocks`, `PostgresPartitioning`, `PostgresServerInfo` |
+132 -21
View File
@@ -1,12 +1,13 @@
# Modello dati
> Stato: bozza · Revisione 2026-11-10 · Fonte: SPEC §5, §7, §8, §9, §11, §12, §13, §14, §21
> Stato: in corso · Revisione 2026-11-11 (M1) · Fonte: SPEC §5, §7, §8, §9, §11, §12, §13, §14, §21
> **Versione pianificata.** A partire dalla milestone 1 questo file sarà **generato** da `scripts/gen-datamodel.sh`
> leggendo le mappe `XxxMap : EntityMap<Xxx>` e le migrazioni: non andrà più modificato a mano. Finché il codice non
> esiste, questa è la versione pianificata ricavata dalla specifica: nomi e colonne sono indicativi e verranno
> confermati (o corretti) dalla prima generazione. I nomi di tabella contrassegnati con **†** non compaiono
> letteralmente in SPEC: sono derivati dal nome dell'entità di SPEC §21 secondo la convenzione snake_case plurale.
> **Due parti.** La sezione [8. Schema attuale](#8-schema-attuale-generato) è **generata** da
> `scripts/gen-datamodel.sh` leggendo le migrazioni: non si modifica a mano e un test fallisce se non è aggiornata.
> Le sezioni 3-4 sono la **pianificazione** ricavata dalla specifica: nomi e colonne sono indicativi e vengono
> confermati (o corretti) dalla migrazione che crea ciascuna tabella, milestone dopo milestone. I nomi di tabella
> contrassegnati con **†** non compaiono letteralmente in SPEC: sono derivati dal nome dell'entità di SPEC §21
> secondo la convenzione snake_case plurale.
Documenti collegati: [ARCHITECTURE.md](ARCHITECTURE.md) · [MODULES.md](MODULES.md) · [API.md](API.md).
@@ -31,24 +32,29 @@ Documenti collegati: [ARCHITECTURE.md](ARCHITECTURE.md) · [MODULES.md](MODULES.
| `ColumnType` | PostgreSQL | SQLite | Note |
|---|---|---|---|
| `String(n)` | `varchar(n)` | `TEXT` | lunghezza verificata dall'applicazione su SQLite |
| `String(n)` | `varchar(n)` | `TEXT` + `CHECK (length(col) <= n)` | la lunghezza è imposta dal database su entrambi i motori |
| `Text` | `text` | `TEXT` | |
| `Int32` | `int` | `INTEGER` | |
| `Int32` | `integer` | `INTEGER` | |
| `Int64` | `bigint` | `INTEGER` | chiavi primarie ed esterne |
| `Decimal(19,6)` | `numeric(19,6)` | `INTEGER` scalato x10⁶ | vedi §1.3 |
| `Bool` | `boolean` | `INTEGER` 0/1 | |
| `Bool` | `boolean` | `INTEGER` + `CHECK (col IN (0, 1))` | |
| `Date` | `date` | `TEXT` `yyyy-MM-dd` | `DateOnly` in C# |
| `DateTimeUtc` | `timestamptz` | `TEXT` ISO 8601 UTC | `DateTime` UTC; conversione a `Europe/Rome` solo in presentazione |
| `DateTimeUtc` | `timestamptz` | `TEXT` `yyyy-MM-ddTHH:mm:ss.ffffffZ` | `DateTime` UTC al microsecondo su entrambi i motori; conversione a `Europe/Rome` solo in presentazione |
| `Guid` | `uuid` | `TEXT` | |
| `Bytes` | `bytea` | `BLOB` | |
| `Json` | `jsonb` | `TEXT` | diff di audit, payload dei canali, dati di log |
Le tabelle SQLite sono `STRICT`: un valore del tipo sbagliato è rifiutato invece di essere convertito. Le enumerazioni
sono memorizzate **per nome** (`String(40)`), così un riordino dei valori in C# non altera i dati.
### 1.3 Decimali scalati su SQLite
SQLite non ha un tipo decimale esatto: i valori `Decimal(19,6)` sono memorizzati come **interi moltiplicati per
10⁶** (`SqliteDecimalConverter`). Conseguenze per chi scrive query:
- `ISqlDialect.ToDbValue` / `FromDbValue` convertono in scrittura e in lettura; i parametri passano già scalati;
- l'arrotondamento al sesto decimale è *half away from zero* (`1,2345675` diventa `1,234568`), come `numeric(19,6)`
su PostgreSQL; un valore oltre l'intervallo solleva `OverflowException` invece di essere troncato;
- le **somme in SQL** (`SUM`, `GROUP BY`) operano sugli interi scalati e vengono **riscalate in lettura**: niente
aritmetica in virgola mobile;
- prodotti e divisioni fra due colonne decimali non vanno fatti in SQL su SQLite (il fattore di scala si
@@ -59,8 +65,14 @@ SQLite non ha un tipo decimale esatto: i valori `Decimal(19,6)` sono memorizzati
- Ogni entità ha una mappa `XxxMap : EntityMap<Xxx>` (tabella, colonne, chiave, indici, FK, conversioni); nessuna
riflessione a runtime oltre la costruzione iniziale (`MapRegistry`).
- `QueryBuilder<T>`: uguaglianza, confronto, `Contains`/`StartsWith`, `In`, `And`/`Or`/`Not`, `IsNull`; il resto come
`SqlFragment` parametrizzato. Mai concatenare input utente in SQL.
- `Query.For<T>().Where(x => ...)`: uguaglianza, confronto, `== null`, `Contains`/`StartsWith`/`EndsWith` (LIKE
senza distinzione di maiuscole e accenti compresi, con `%` e `_` dell'utente protetti), `lista.Contains(x.Col)`
(`IN`), `&&`/`||`/`!`, `string.IsNullOrEmpty`; il resto come `SqlFragment` parametrizzato. Un'espressione fuori da
questo insieme solleva `NotSupportedException`, non viene valutata in memoria. Mai concatenare input utente in SQL:
in `SqlFragment.Of($"... {valore}")` ogni valore interpolato diventa un parametro.
- `IRepository<T, TKey>` compila le colonne di audit, imposta `row_version = 1` all'inserimento e la incrementa a ogni
modifica; `IUnitOfWork.AcquireLockAsync(chiave)` prende un lock di transazione (`pg_advisory_xact_lock` o il lock di
scrittura di SQLite) per numeratori e chiusure.
- SQLite: `journal_mode=WAL; foreign_keys=ON; busy_timeout=5000`; scritture serializzate da `SqliteWriteLock`.
- PostgreSQL: pool separato per database (`MaxPoolSize` da impostazioni), `statement_timeout` per sessione,
`pg_advisory_xact_lock` per numeratori, chiusure e scheduler.
@@ -68,22 +80,24 @@ SQLite non ha un tipo decimale esatto: i valori `Decimal(19,6)` sono memorizzati
## 2. Migrazioni (SPEC §5.3)
```csharp
[Migration(20261013_001, "create_parties")]
public sealed class M20261013_001 : IMigration
[Migration(20261013_001, "create_parties")] // Target = MigrationTarget.Company se omesso
public sealed class M20261013_001_CreateParties : IMigration
{
public void Up(ISchemaBuilder sb) { /* tabelle, colonne, indici, FK in forma neutra */ }
public string? UpSql(ISqlDialect d) => null; // SQL specifico del dialetto, se serve
public void Up(ISchemaBuilder schema) { /* tabelle, colonne, indici, FK in forma neutra */ }
public string? UpSql(ISqlDialect dialect) => null; // SQL specifico del dialetto, se serve
}
```
| Regola | Dettaglio |
|---|---|
| Due cataloghi | `MigrationCatalog.System` (database di sistema) e `MigrationCatalog.Company` (ogni azienda) |
| Versioni | `schema_version(module, version, name, applied_at, checksum)` in **ogni** database |
| Esecuzione | `MigrationRunner` applica in transazione, è idempotente, registra l'esito nella sezione di log *Migrazioni* |
| Downgrade | non supportato: se trova versioni applicate non note rifiuta di partire |
| Due cataloghi | `MigrationCatalog.ForSystem()` (database di sistema) e `MigrationCatalog.ForCompany(assembly dei moduli)` |
| Versioni | `yyyymmdd_nnn` (11 cifre, data valida, `nnn` da 001), uniche per modulo; `schema_version(module, version, name, applied_at, checksum)` in **ogni** database, `checksum` = SHA-256 delle istruzioni generate |
| Esecuzione | `MigrationRunner` applica **una migrazione per transazione** sotto lock (più istanze che partono insieme non si pestano i piedi), è idempotente e restituisce un `MigrationReport`; la registrazione nella sezione di log *Migrazioni* arriva con il log (M2) |
| Checksum diverso | una migrazione già applicata e poi modificata produce un avviso, non un errore: le migrazioni applicate non si cambiano, se ne scrive una nuova |
| Downgrade | non supportato: se trova versioni applicate non note rifiuta di partire (`MigrationException`) |
| Avvio | il sistema è migrato all'avvio; le aziende all'avvio (impostazione) o dal pannello (SPEC §12.1) in modalità manutenzione |
| Nuova migrazione | `scripts/new-migration.sh` |
| Nuova migrazione | `scripts/new-migration.sh <system\|company> <nome_snake_case> [cartella] [modulo]` |
| Documentazione | `scripts/gen-datamodel.sh` rigenera la [sezione 8](#8-schema-attuale-generato); `--check` verifica soltanto |
| Test obbligatorio | tutte le migrazioni da zero su SQLite e PostgreSQL, `schema_version` coerente, riapplicazione senza effetti |
## 3. Database di sistema (`khaemhat_system`)
@@ -325,9 +339,106 @@ qualunque modifica ──► audit_log
- Obiettivi di prestazione di riferimento (SPEC §18): bilancio di verifica su 2 M righe < 10 s, pagina log con 1 M
righe < 1 s per filtro.
### 6.1 Misure di riferimento dello strato dati (M1)
`PerformanceBaselineTests` inserisce righe con tutti i tipi di colonna tramite `IRepository` in una sola transazione,
poi le legge tutte e legge una pagina filtrata con il conteggio totale. Con `KHAEMHAT_PERF=1` usa 100.000 righe,
altrimenti 2.000 (prova di fumo, sempre eseguita anche in CI).
```bash
KHAEMHAT_PERF=1 scripts/test.sh --filter TestCategory=Performance --logger "console;verbosity=detailed"
```
| Data | Motore | Macchina | Inserimenti | Lettura di tutte le righe | Pagina filtrata + conteggio |
|---|---|---|---|---|---|
| 2026-11-11 | SQLite (file in memoria) | Ryzen 5 2600X, Windows 11, .NET 10.0.403 | 100.000 in 5,6 s (circa 17.800/s) | 0,9 s | 17 ms |
Le misure servono a riconoscere un peggioramento, non come soglia: il test non fallisce sui tempi. Le misure su
PostgreSQL si aggiungono dal job `postgres` della CI alla chiusura della milestone.
## 7. Segreti nel database
Cifrati con AES-256-GCM e chiave derivata da `KHAEMHAT_SECRET_KEY` (`SecretProtector`): connection string delle
aziende (`sys_companies`), password SMTP/PEC/S3/WebDAV (`sys_settings`), token degli intermediari e credenziali dei
canali SDI (`sdi_channels`), credenziali dei canali e-commerce (`sales_channels`), segreti dei webhook. La rotazione
avviene con `KHAEMHAT_SECRET_KEY_NEW` (SPEC §12.9). Gli hash (password, chiavi API) non sono cifrati ma irreversibili.
## 8. Schema attuale (generato)
Questa sezione è scritta da `scripts/gen-datamodel.sh` a partire dalle migrazioni presenti nel codice; il test
`DataModelDocumentTests` fallisce se non è aggiornata. Comprende `schema_version`, presente in ogni database.
<!-- BEGIN GENERATED: scripts/gen-datamodel.sh, do not edit by hand -->
### Database di sistema
Migrazioni applicate in ordine:
- `core` 20261111001 `create_sys_companies` (M20261111_001_CreateSysCompanies)
- `core` 20261111002 `create_sys_settings` (M20261111_002_CreateSysSettings)
#### `schema_version`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `module` | String(50) | no | | chiave primaria |
| `version` | Int64 | no | | chiave primaria |
| `name` | String(200) | no | | |
| `applied_at` | DateTimeUtc | no | | |
| `checksum` | String(64) | no | | |
Chiave primaria: `module`, `version`.
#### `sys_companies`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(20) | no | | |
| `name` | String(200) | no | | |
| `engine` | String(20) | no | | |
| `connection_string` | Text | no | | |
| `status` | String(40) | no | `'Active'` | |
| `is_default` | Bool | no | `false` | |
| `notes` | Text | sì | | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_companies_code` su `code`
#### `sys_settings`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `key` | String(200) | no | | |
| `value` | Text | sì | | |
| `is_secret` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_sys_settings_key` su `key`
### Database aziendale
Nessuna migrazione: la tabella `schema_version` è l'unica presente.
#### `schema_version`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `module` | String(50) | no | | chiave primaria |
| `version` | Int64 | no | | chiave primaria |
| `name` | String(200) | no | | |
| `applied_at` | DateTimeUtc | no | | |
| `checksum` | String(64) | no | | |
Chiave primaria: `module`, `version`.
<!-- END GENERATED -->
+19 -17
View File
@@ -103,7 +103,8 @@ Note:
### 2.3 Utente e `PUID`/`PGID`
Le immagini `aspnet:10.0` includono già un utente non root `app`. SPEC chiede che i file in `/data` appartengano a
`PUID`/`PGID` (predefiniti 99/100 per Unraid). Due realizzazioni possibili, da fissare con un ADR in M0:
`PUID`/`PGID` (99/100 per Unraid). Le due realizzazioni valutate; **ADR 0013 sceglie la 1** (predefiniti `1654`,
l'utente `app` dell'immagine; la 2 resta possibile perché l'entrypoint salta la preparazione se non è root):
1. **avvio come root e cessione dei privilegi** in `entrypoint.sh`: allinea UID/GID di `app` a `PUID`/`PGID`,
esegue `chown` su `/data` solo se necessario e rilancia il processo come `app` con `setpriv` (util-linux, già
@@ -118,7 +119,8 @@ gira mai come root.
Sequenza (SPEC §4, §5.4):
1. legge le varianti `_FILE` delle variabili e le esporta (§5);
1. legge `KHAEMHAT_SYSTEM_DB` (o `KHAEMHAT_SYSTEM_DB_FILE`) solo per ricavarne host e porta: le varianti `_FILE` le
risolve l'applicazione, senza esportare segreti nell'ambiente (ADR 0014, §5);
2. se previsto, allinea utente e permessi (§2.3);
3. attende che `KHAEMHAT_SYSTEM_DB` sia raggiungibile (retry con backoff, timeout esplicito, messaggio chiaro);
4. avvia l'applicazione (`exec dotnet Khaemhat.Web.dll`), che in `StartupOrchestrator` valida le opzioni
@@ -128,7 +130,7 @@ Sequenza (SPEC §4, §5.4):
Le migrazioni restano nel codice .NET (`MigrationRunner`), non nello script shell: l'entrypoint fa solo attesa,
ambiente e `exec`. `docker/postgres/init.sql` è uno script di inizializzazione opzionale per il container PostgreSQL
(contenuto da definire in M0).
(montato in `/docker-entrypoint-initdb.d/`: imposta per il ruolo dell'applicazione fuso `UTC` e codifica `UTF8`).
## 3. File in `deploy/`
@@ -182,8 +184,8 @@ L'elenco completo e normativo delle variabili è SPEC §6 con le modifiche di E1
- `KHAEMHAT_SECRET_KEY` è obbligatoria (≥ 32 byte base64): cifra con AES-256-GCM i segreti in `sys_companies`,
`sys_settings` ecc. e i file di backup. Senza chiave l'app non parte.
- `KHAEMHAT_SUPERUSER*`, `KHAEMHAT_COMPANY_*` sono lette solo se le tabelle corrispondenti sono vuote.
- Varianti `_FILE` (Docker secrets): SPEC le prevede per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`. Proposta da
confermare in M2: supportarle per **tutte** le variabili sensibili (`KHAEMHAT_SECRET_KEY`,
- Varianti `_FILE` (Docker secrets): SPEC le prevede per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`. **Deciso con
ADR 0014**: sono supportate per **tutte** le variabili sensibili (`KHAEMHAT_SECRET_KEY`,
`KHAEMHAT_SECRET_KEY_NEW`, `KHAEMHAT_DB_SERVER`, `KHAEMHAT_REDIS`, `KHAEMHAT_LICENSE`, `KHAEMHAT_SMTP_PASSWORD`,
`KHAEMHAT_UPDATE_TOKEN`) con una sola regola in `EnvironmentConfigurationReader`: se esiste `X_FILE`, il valore è il
contenuto del file senza il fine riga finale; `X` e `X_FILE` insieme sono un errore di configurazione.
@@ -206,8 +208,8 @@ Regole (SPEC §16.6, E1):
`https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v<major.minor>-256.png`;
il file deve quindi essere **committato su `main` prima** del rilascio che lo referenzia;
- la conversione SVG → PNG richiede un rasterizzatore che l'applicazione non contiene (né deve contenere): si esegue
sulla macchina di sviluppo con uno strumento di sistema e il PNG si committa. La scelta dello strumento va
registrata in un ADR;
sulla macchina di sviluppo con uno strumento di sistema e il PNG si committa. Strumenti accettati:
`rsvg-convert`, `inkscape`, `magick` (ADR 0016);
- finché manca la variante della nuova versione si usa `icon-256.png` (non versionata).
## 7. Versioning
@@ -226,7 +228,7 @@ Regole (SPEC §16.6, E1):
|---|---|---|
| `GET /health/live` | liveness: il processo risponde. Usato da `HEALTHCHECK`, dal compose e da `<ExtraParams>` del template. Non deve dipendere dal database, altrimenti un DB lento fa riavviare il container | previsto da SPEC (§16.1, App. C) |
| `GET /health` | endpoint di base introdotto in M0 | previsto da SPEC (§20, M0) |
| readiness (proposta `GET /health/ready`) | database di sistema raggiungibile, migrazioni di sistema applicate, bootstrap concluso; `503` durante l'avvio | da definire con `HealthEndpoints` |
| readiness (proposta `GET /health/ready`) | database di sistema raggiungibile, migrazioni di sistema applicate, bootstrap concluso; `503` durante l'avvio | ADR 0012: in M0 sempre `200`, i controlli arrivano in M1-M2 |
| metriche (`MetricsEndpoint`) | formato e percorso | da definire |
Regole: risposte senza autenticazione e senza dati sensibili (niente versioni dei componenti, connection string o
@@ -278,9 +280,9 @@ Differenze rispetto all'Appendice D (ADR 0009): registro pacchetti di Gitea, var
`GITEA_TOKEN`, tag immagine senza `v`. La rigenerazione dell'icona sta in `scripts/build.sh` (§6).
**Tag git e doppio build.** Se lo script creasse e spingesse anche il tag `vX.Y.Z`, il push farebbe partire
`release.yml` e l'immagine verrebbe costruita due volte. Proposta: lo script **non** crea tag; il tag si crea alla
chiusura della milestone (E6). In alternativa `release.yml` controlla prima del build se la versione esiste già nel
registro (`GET /api/v1/packages/BalboSoft/container/khaemhat/<X.Y.Z>` → `200`) e in quel caso salta il push.
`release.yml` e l'immagine verrebbe costruita due volte. **Deciso con ADR 0015**: lo script **non** crea tag; il tag si crea alla
chiusura della milestone (E6). In più `release.yml` controlla prima del build se la versione esiste già nel
registro (`GET /api/v1/packages/BalboSoft/container/khaemhat/<X.Y.Z>` → `200`) e in quel caso salta build e push e crea solo la release.
## 10. Checklist di rilascio
@@ -307,7 +309,7 @@ registro (`GET /api/v1/packages/BalboSoft/container/khaemhat/<X.Y.Z>` → `200`)
- `MigrationRunner` rifiuta di partire se trova in `schema_version` versioni non note: il **downgrade non è
supportato**.
- Rollback: tag precedente; se la versione nuova ha applicato migrazioni, prima si ripristinano database di sistema
(`scripts/restore-system.sh`, istanza ferma) e aziende dai backup fatti prima dell'aggiornamento.
(`/app/scripts/restore-system.sh` nell'immagine, ADR 0017, istanza ferma) e aziende dai backup fatti prima dell'aggiornamento.
- Per questo ogni voce del changelog dichiara se contiene migrazioni.
Procedura per l'utente: wiki *Aggiornamento*.
@@ -346,11 +348,11 @@ documentazione utente chiede di conservare la vecchia chiave per tutta la retent
| Punto | Proposta | Quando |
|---|---|---|
| `PUID`/`PGID` con utente non root | avvio root + `setpriv` nell'entrypoint (§2.3) | ADR in M0 |
| Elenco delle variabili con `_FILE` | tutte le sensibili (§5) | M2 |
| Endpoint di readiness e metriche | `/health/ready`; metriche da definire (§8) | M0/M2 |
| Doppio build tag + script | lo script non crea tag (§9.2) | M0 |
| Rasterizzazione dell'icona versionata | strumento di sistema sulla macchina di sviluppo, PNG committato (§6) | M13 |
| `PUID`/`PGID` con utente non root | avvio root + `setpriv` nell'entrypoint (§2.3) | **deciso: ADR 0013** |
| Elenco delle variabili con `_FILE` | tutte le sensibili (§5) | **deciso: ADR 0014**; implementazione in M1-M2 |
| Endpoint di readiness e metriche | `/health/ready` (**ADR 0012**); metriche da definire (§8) | M2 |
| Doppio build tag + script | lo script non crea tag (§9.2) | **deciso: ADR 0015** |
| Rasterizzazione dell'icona versionata | strumento di sistema sulla macchina di sviluppo, PNG committato (§6) | **deciso: ADR 0016** |
| Backup cifrati dopo la rotazione della chiave | registro delle chiavi storiche o ri-cifratura (§13) | M12 |
| Connection string delle aziende e rotazione della password PostgreSQL | per le aziende create su `KHAEMHAT_DB_SERVER`, salvare un riferimento "credenziali del server" invece della stringa completa | M1/M2 |
| Decifratura dei backup fuori dall'applicazione | comando in `restore-system.sh` o sottocomando dedicato | M12 |
+70 -6
View File
@@ -1,10 +1,9 @@
# Processo di sviluppo
> Stato: bozza · Revisione 2026-11-10 · Fonte: SPEC §17-§20, §23, `CLAUDE.md`
> Stato: completo per M0 · Revisione 2026-11-11 · Fonte: SPEC §17-§20, §23, `CLAUDE.md`
Questo documento dice **come** si lavora su Khaemhat: unità di lavoro, rami, commit, verifica, chiusura delle
milestone. Le regole di prodotto stanno in [`SPEC.md`](SPEC.md) e negli emendamenti di [`CLAUDE.md`](../CLAUDE.md).
I comandi di build e test reali verranno completati in M0, quando esisterà il codice.
## 1. Prerequisiti
@@ -16,7 +15,53 @@ I comandi di build e test reali verranno completati in M0, quando esisterà il c
| PostgreSQL | 16 o 17 | facoltativo in locale: `KHAEMHAT_TEST_PG` attiva i test sul motore reale |
| Redis | 7 | facoltativo: `KHAEMHAT_TEST_REDIS` attiva i test del client RESP |
Se manca l'SDK 10 ci si ferma e lo si chiede al titolare (SPEC §23).
Se manca l'SDK 10 ci si ferma e lo si chiede al titolare (SPEC §23). Su Windows gli script si eseguono da Git Bash.
### 1.1 Comandi
| Comando | Cosa fa |
|---|---|
| `scripts/build.sh` | `check-packages.sh` + `dotnet build Khaemhat.sln -c Release -warnaserror` |
| `scripts/build.sh --icon [X.Y]` | anche l'icona versionata `assets/icon-vX.Y.svg` e, se c'è un rasterizzatore, i PNG (ADR 0016) |
| `scripts/test.sh [argomenti di dotnet test]` | allowlist + tutti i test; PostgreSQL con `KHAEMHAT_TEST_PG`, Redis con `KHAEMHAT_TEST_REDIS` |
| `scripts/run-dev.sh` | avvio locale su `http://localhost:5080`, SQLite in `.data/dev`, licenze di test |
| `scripts/check-packages.sh` | fallisce se un file MSBuild usa un pacchetto fuori allowlist o fuori dal suo progetto |
| `docker build -f docker/Dockerfile -t khaemhat:dev .` | immagine locale (`--build-arg RUN_TESTS=true` per eseguire i test nel build) |
| `docker compose -f deploy/docker-compose.sqlite.yml up` | demo autonoma (con `KHAEMHAT_VERSION` per scegliere l'immagine) |
| `scripts/publish-image.sh vX.Y.Z [--arm64]` | pubblicazione dalla macchina di sviluppo se il runner non c'è (ADR 0015) |
| `scripts/publish-wiki.sh` | pubblica `docs/wiki/` nel wiki Gitea senza passare dal runner |
| `scripts/new-migration.sh <system\|company> <nome_snake_case> [cartella] [modulo]` | crea `M<yyyymmdd>_<nnn>_<Nome>.cs` con il primo numero libero del giorno (SPEC §5.3) |
| `scripts/gen-datamodel.sh [--check]` | rigenera la sezione generata di `docs/DATA-MODEL.md` dalle migrazioni; `--check` verifica soltanto |
| `KHAEMHAT_PERF=1 scripts/test.sh --filter TestCategory=Performance` | misure di riferimento dello strato dati con 100.000 righe (`docs/DATA-MODEL.md` §6.1) |
Gli stub `seed.sh` (M4) e `restore-system.sh` (M12, incluso nell'immagine, ADR 0017) spiegano l'uso previsto ed
escono con errore finché la loro milestone non li completa.
#### Test sui due motori
I test dello strato dati girano con `[DataRow("Sqlite")]` e `[DataRow("PostgreSql")]`. SQLite usa un database in
memoria condiviso, sempre disponibile. PostgreSQL usa `KHAEMHAT_TEST_PG` (URL
`postgres://utente:password@host:5432/postgres` di un ruolo con `CREATEDB`): ogni test crea un database
`khaemhat_t_<casuale>` e lo elimina alla fine; senza la variabile i test PostgreSQL risultano *saltati*. In CI il
job `postgres` li esegue su PostgreSQL 16 e 17 sui tag e all'avvio manuale del workflow.
### 1.2 Visual Studio Code
La cartella `.vscode/` è nel repository:
- `launch.json`: **Khaemhat (web, SQLite)** compila (attività `build`) e avvia `Khaemhat.Web` in debug su
`http://localhost:5080` con le stesse variabili di `scripts/run-dev.sh` (SQLite in `.data/dev`, licenze di test,
log `Debug`) e apre il browser quando il server è pronto; **Khaemhat (web, PostgreSQL)** fa lo stesso contro un
PostgreSQL locale (comando per avviarlo nel commento); **Collega a un processo** si aggancia a un'istanza già avviata;
- `tasks.json`: `build` (predefinita, `Ctrl+Shift+B`), `test`, `watch (web)` con ricaricamento a caldo,
`check-packages`, `docker build`;
- `extensions.json`: C# Dev Kit, C#, EditorConfig, Docker.
Si apre la cartella del repository, si sceglie la configurazione nel pannello *Esegui e debug* e si preme `F5`. Le
chiavi e le password di `launch.json` valgono solo per lo sviluppo locale.
I test architetturali (`Khaemhat.Core.Tests/Architecture`) leggono i `.csproj`: un riferimento fra progetti non
previsto da SPEC §3 o un pacchetto fuori allowlist li fa fallire, oltre a far fallire `check-packages.sh`.
## 2. Ripresa di una sessione
@@ -108,9 +153,26 @@ La wiki si pubblica nel wiki Gitea da `wiki.yml` (push su `main` che tocca `docs
| `.gitea/workflows/release.yml` | tag `v*`; manuale | immagine, smoke test `/health/live`, push nel registro Gitea, release con note dal `CHANGELOG.md` |
| `.gitea/workflows/wiki.yml` | push su `main` che tocca `docs/wiki/**` | sincronizza il wiki Gitea |
Segreti e variabili: `REGISTRY_TOKEN` (segreto di organizzazione `BalboSoft`, permesso `write:package`, già presente);
il token automatico del job per checkout e wiki. Il runner è condiviso con altri progetti: niente matrici superflue,
`concurrency` con cancellazione dei job superati, `timeout-minutes` su ogni job.
`ci.yml` costruisce e prova anche l'immagine (job *Docker image*: `/health/live`, utente `PUID`/`PGID`, `pg_dump`)
su PR, push e avvio manuale; sui tag lo fa `release.yml`. Un controllo YAML (Ruby) valida workflow e compose.
| Nome | Tipo | Uso |
|---|---|---|
| `REGISTRY_TOKEN` | segreto di organizzazione (già presente) | login al registro e controllo delle versioni già pubblicate; permesso pacchetti lettura e scrittura |
| `REGISTRY_USER` | variabile (facoltativa) | utente del login al registro; predefinito: chi ha spinto il tag (`github.actor`), che deve essere il proprietario del token |
| `REGISTRY`, `PUBLIC_URL` | variabili (facoltative) | host del registro e indirizzo pubblico di Gitea; predefiniti `gitea.encke-hake.ts.net` |
| `WIKI_TOKEN` | segreto (facoltativo) | solo se il token automatico del job non può scrivere nel wiki |
| token automatico | del job | checkout, archivio per il controllo YAML, release Gitea, wiki |
Il runner (`act_runner` in modalità Docker, etichetta `ubuntu-latest`) deve vedere il daemon Docker dell'host: i job
senza `container:` usano la CLI `docker` dell'immagine del runner, come in Chronos. Il runner è condiviso con altri
progetti: niente matrici superflue (solo PostgreSQL 16/17 sui tag), `concurrency` con cancellazione dei job superati,
`timeout-minutes` su ogni job. Ciò che un job annullato lascia sull'host (container, reti, immagini con l'etichetta
`khaemhat-ci.job`) lo rimuove il job successivo.
**Rilascio** (ADR 0015): `CHANGELOG.md` con la sezione `## [X.Y.Z] - data`, commit su `main`, poi
`git tag -a vX.Y.Z -m "Khaemhat X.Y.Z" && git push origin vX.Y.Z`. Tag git `vX.Y.Z`, immagine `X.Y.Z` (più `latest`
se non è una pre-release). Se si è pubblicato con `publish-image.sh`, il push del tag crea solo la release.
## 10. Chiusura di una milestone
@@ -122,6 +184,8 @@ L'issue *Chiusura milestone* verifica la **Definition of Done** (SPEC §20):
- [ ] log per sezione dei nuovi moduli
- [ ] wiki delle funzioni consegnate *completa*; `docs/*.md` aggiornati; `CHANGELOG.md`
- [ ] `docs/STATUS.md` aggiornato con il punto di ripresa
- [ ] versione nei file di `deploy/` (`KHAEMHAT_VERSION` dei compose e di `.env.example`, `<Repository>` del template
Unraid); icona versionata con `scripts/build.sh --icon` se cambia `major.minor` dalla 1.0 in poi (ADR 0016)
- [ ] commit, tag `vX.Y.Z`, immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`, release Gitea
- [ ] l'immagine si costruisce in locale e la demo SQLite parte da zero
- [ ] le issue della milestone successiva passano in *Da fare*
+14 -5
View File
@@ -240,11 +240,17 @@ passaggio TOTP (prevenzione della session fixation).
- `SecretProtector` cifra con **AES-256-GCM** (`System.Security.Cryptography.AesGcm`) i segreti salvati: connection
string delle aziende (`sys_companies`), password SMTP/PEC/S3/WebDAV, token degli intermediari SDI, credenziali dei
canali e-commerce.
- La chiave AES è **derivata** da `KHAEMHAT_SECRET_KEY`. Proposta: HKDF-SHA256 (in-box, `HKDF`) con etichette di
contesto distinte per uso (`secrets`, `backup`, `totp`), così una chiave non viene riusata fra domini.
- Proposta di formato del testo cifrato: `v1` (versione/identificativo chiave) ‖ nonce 12 byte casuale ‖
ciphertext ‖ tag 16 byte, in base64. Il nonce non si riusa mai con la stessa chiave. Come dato associato (AAD)
usare tabella+colonna+id, così un segreto copiato in un'altra riga non si decifra.
- La chiave AES è **derivata** da `KHAEMHAT_SECRET_KEY` con HKDF-SHA256 (in-box, `HKDF`) ed etichetta di contesto
`khaemhat/secrets/aes-256-gcm/v1`; altri usi (backup, TOTP) avranno etichette proprie, così una chiave non viene
riusata fra domini. L'identificativo della chiave è una seconda derivazione HKDF di 4 byte (8 cifre esadecimali):
identifica la chiave senza rivelarla.
- **Formato del testo cifrato (M1):** `khs1.<id-chiave>.<base64url(nonce 12 byte | tag 16 byte | ciphertext)>`.
Il nonce è casuale e non si riusa mai con la stessa chiave. Il dato associato (AAD) è lo **scopo** del segreto
(per esempio `company:ACME:database` per la connessione di un'azienda): un valore copiato in un'altra riga o
usato per un altro scopo non si decifra. Un valore cifrato con un'altra chiave è rifiutato con un messaggio che
indica i due identificativi (`SecretProtectionException`), senza mai ripetere il segreto.
- Implementazione: `Khaemhat.Infrastructure.Security.SecretProtector` (con `SecretKey` e `SecretRotation`),
interfaccia `ISecretProtector` in `Khaemhat.Core`.
- La chiave e i segreti in chiaro **non vanno mai** in log, messaggi d'errore, diagnostica, risposte API o file su
disco (SPEC §1.5: nessun `appsettings.<Env>.json` con segreti, nessun file temporaneo).
- Le varianti `_FILE` delle variabili (Docker secrets) sono previste per `KHAEMHAT_SYSTEM_DB` e le credenziali del
@@ -258,6 +264,9 @@ passaggio TOTP (prevenzione della session fixation).
3. L'operatore sostituisce `KHAEMHAT_SECRET_KEY` con la nuova e rimuove `KHAEMHAT_SECRET_KEY_NEW`.
4. Evento in `sys_security_audit`.
In M1 esiste il mattone `SecretRotation` (`NeedsRotation` legge l'identificativo della chiave, `Rotate` decifra e
ri-cifra); la procedura che percorre tutte le colonne cifrate arriva in M12.
Da decidere con ADR: trattamento dei **backup già cifrati** con la vecchia chiave (ri-cifratura o conservazione
della vecchia chiave come chiave di sola decifratura identificata dalla versione nel formato).
+34 -16
View File
@@ -2,21 +2,33 @@
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
**Ultimo aggiornamento:** 2026-11-10
**Milestone corrente:** nessuna — documentazione e pianificazione completate, **sviluppo non ancora avviato**
**Prossimo passo:** attendere il via del titolare (emendamento E5 di `CLAUDE.md`), poi M0 — Bootstrap, partendo
dall'issue #1 *M0 · Soluzione, progetti e regole di build*
(colonna *Da fare* del progetto *Khaemhat 1.0 — Sviluppo*).
**Ultimo aggiornamento:** 2026-11-11
**Milestone corrente:** M1 — Strato dati (in chiusura sul ramo `feat/7-strato-dati`)
**Prossimo passo:** chiudere M1 (PR verso `main`, CI verde compreso il job `postgres` avviato a mano sul ramo, tag
`v0.1.0`, immagine e release; misure PostgreSQL in `docs/DATA-MODEL.md` §6.1), poi M2 — Sistema e sicurezza,
partendo dall'issue #15.
## Fatto
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
- ADR 0001-0011.
- ADR 0001-0018.
- Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice).
- Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid).
- Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`,
`MCP.md`, `DEPLOY.md`, `SECURITY.md`, `DEVELOPMENT.md`.
- Wiki completa in bozza in `docs/wiki/`, pubblicata nel wiki Gitea.
- **M0 (chiusa, `v0.0.1`):** soluzione `Khaemhat.sln` con i 10 progetti di SPEC §3 e 6 progetti di test; regole di build
(`Directory.Build.props/targets`, Central Package Management con l'allowlist, `.editorconfig`, warning come errori);
test architetturali delle dipendenze e dei pacchetti; `Khaemhat.Web` con pagina "in costruzione", icone,
`/health/live`, `/health/ready`, `/health` (ADR 0012); `docker/Dockerfile`, `entrypoint.sh` con `PUID`/`PGID`
(ADR 0013), `postgres/init.sql`; `deploy/docker-compose.yml` e `docker-compose.sqlite.yml`; Gitea Actions `ci.yml`,
`release.yml`, `wiki.yml` con controllo YAML; script di build, test, avvio, pubblicazione e stub; ADR 0012-0017.
- **M1 (in chiusura, `v0.1.0`):** micro-ORM in `Khaemhat.Data` (mappe, query tipizzate, `SqlFragment`, unit of work,
repository con audit e `row_version`), provider SQLite e PostgreSQL, `DatabaseUrl`, migrazioni con
`schema_version`, tabelle `sys_companies` e `sys_settings`, `CompanyRegistry` con URL cifrato, `SecretProtector`
(AES-256-GCM, formato `khs1`), `tools/Khaemhat.DataModelTool` e gli script `new-migration.sh` e
`gen-datamodel.sh`; ADR 0018. Test: 85 su SQLite verdi in locale, 21 su PostgreSQL eseguiti solo in CI (in locale
Docker non è disponibile).
- Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13)
e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36,
M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91,
@@ -24,11 +36,17 @@ dall'issue #1 *M0 · Soluzione, progetti e regole di build*
## Ambiente verificato
Da compilare all'inizio di M0: versioni di `dotnet`, `docker`, `git`; runner Gitea Actions disponibile.
Rilevato il 2026-11-11 sulla macchina di sviluppo (Windows 11, Git Bash per gli script):
| Strumento | Versione |
|---|---|
| .NET SDK | 10.0.403 (`global.json`: 10.0.100, `rollForward: latestFeature`) |
| Docker | 29.1.3 (Docker Desktop, daemon da avviare a mano) |
| Git | 2.54 |
| Runner Gitea Actions | `act_runner` in modalità Docker, etichetta `ubuntu-latest` (condiviso con Chronos) |
## In attesa del titolare
- Via allo sviluppo.
- PNG ad alta risoluzione delle 66 schermate disponibili solo come miniatura (issue #35, non bloccante).
- Scelta degli intermediari SDI e accreditamento SdICoop (issue #78, non bloccante).
- Prova del template su Unraid (issue #106).
@@ -43,15 +61,15 @@ Emersi durante la stesura della documentazione. Si decidono con un ADR quando si
### Installazione, aggiornamento, backup (dalla stesura di DEPLOY e wiki installazione)
1. `scripts/restore-system.sh` è l'unico modo di ripristinare il DB di sistema (§13), ma gli script non sono distribuiti (ADR 0010): oggi la wiki dice di scaricarlo dal repository. Valutare di includerlo nell'immagine (`/app/scripts/`).
1. `scripts/restore-system.sh` è l'unico modo di ripristinare il DB di sistema (§13), ma gli script non sono distribuiti (ADR 0010): oggi la wiki dice di scaricarlo dal repository. Valutare di includerlo nell'immagine (`/app/scripts/`). **Deciso in M0: ADR 0017.**
2. Backup cifrati con `KHAEMHAT_SECRET_KEY`: manca uno strumento di decifratura fuori dall'app e non è definito cosa succede ai backup vecchi dopo la rotazione della chiave (oggi: conservare la chiave vecchia per tutta la retention).
3. `PUID`/`PGID` e utente non root (§16.1): proposta di avviare come root e scendere di privilegi con `setpriv` nell'entrypoint; da decidere con ADR in M0.
4. Varianti `_FILE` definite solo per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`: proposta di estenderle a tutte le variabili sensibili (incluso `KHAEMHAT_SECRET_KEY`).
5. Salute: la specifica ha `/health/live` e `/health`; `/health/ready` e le metriche sono da definire.
6. Tag e doppia build: `publish-image.sh` (Appendice D) crea il tag git, ma con `release.yml` sui tag `v*` l'immagine verrebbe costruita due volte. Proposta: lo script non crea tag, oppure `release.yml` salta le versioni già nel registro.
7. Formato tag: tag git `vX.Y.Z`, tag immagine `X.Y.Z` (senza `v`).
8. Icona versionata: `build.sh` deve produrre PNG, serve un rasterizzatore; proposta: generarla sulla macchina di sviluppo e committarla prima del rilascio.
9. Rotazione della password PostgreSQL: le connection string delle aziende sono cifrate per intero in `sys_companies`; serve una procedura di aggiornamento.
3. `PUID`/`PGID` e utente non root (§16.1): proposta di avviare come root e scendere di privilegi con `setpriv` nell'entrypoint; da decidere con ADR in M0. **Deciso in M0: ADR 0013.**
4. Varianti `_FILE` definite solo per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`: proposta di estenderle a tutte le variabili sensibili (incluso `KHAEMHAT_SECRET_KEY`). **Deciso in M0: ADR 0014.**
5. Salute: la specifica ha `/health/live` e `/health`; `/health/ready` e le metriche sono da definire. **Deciso in M0: ADR 0012.**
6. Tag e doppia build: `publish-image.sh` (Appendice D) crea il tag git, ma con `release.yml` sui tag `v*` l'immagine verrebbe costruita due volte. Proposta: lo script non crea tag, oppure `release.yml` salta le versioni già nel registro. **Deciso in M0: ADR 0015.**
7. Formato tag: tag git `vX.Y.Z`, tag immagine `X.Y.Z` (senza `v`). **Deciso in M0: ADR 0015.**
8. Icona versionata: `build.sh` deve produrre PNG, serve un rasterizzatore; proposta: generarla sulla macchina di sviluppo e committarla prima del rilascio. **Deciso in M0: ADR 0016.**
9. Rotazione della password PostgreSQL: l'URL del database di ogni azienda è cifrato per intero in `sys_companies` (ADR 0018); serve una procedura di aggiornamento (M12).
10. Il mockup 085 mostra ancora `ghcr.io`: l'app mostrerà il registro Gitea (ADR 0009).
11. Non definiti: schermata di attivazione TOTP, nome dell'impostazione "migra aziende all'avvio", recupero password del super utente senza SMTP, chi modifica le impostazioni di backup cloud (scritto: super utente), flusso di ripristino da backup logico.
+32
View File
@@ -0,0 +1,32 @@
# ADR 0012 - Endpoint di salute
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §16.1, §20 (M0); chiude il punto aperto 5 di `docs/STATUS.md` (issue #114)
## Contesto
SPEC nomina `/health/live` (usato da `HEALTHCHECK`, dal compose e dal template Unraid) e un endpoint `/health` di
base in M0, ma non definisce la readiness né il contenuto delle risposte. Un controllo di liveness che dipende dal
database fa riavviare il container quando il database è solo lento.
## Decisione
| Endpoint | Risposta | Significato |
|---|---|---|
| `GET /health/live` | `200 text/plain "live"` | il processo risponde. Non tocca database, cache né file. È l'unico usato da `HEALTHCHECK` e dal compose |
| `GET /health/ready` | `200 "ready"` oppure `503 "starting"` | l'istanza può servire richieste: database di sistema raggiungibile, migrazioni di sistema applicate, bootstrap concluso. In M0 non ci sono dipendenze e risponde sempre `200`; i controlli si aggiungono in M1-M2 |
| `GET /health` | `200 application/json` `{status, live, ready, version, revision}` | riepilogo per l'amministratore e per la pagina *Stato sistema*; `status` è `ok` o `starting` |
Regole:
- risposte **senza autenticazione** e **senza dati sensibili**: niente versioni dei componenti, connection string,
nomi di aziende o percorsi. La versione del prodotto è pubblica (compare anche nella pagina di accesso);
- la modalità manutenzione di un'azienda non cambia la salute dell'istanza;
- le metriche (formato e percorso) si decidono in M2 con un ADR separato.
## Conseguenze
- `HealthEndpoints` in `Khaemhat.Web/Hosting` mappa i tre percorsi; i test web li chiamano su un host reale.
- In M1-M2 la readiness legge lo stato di `StartupOrchestrator`; un orchestratore esterno (Kubernetes o simili)
può usare `/health/ready` senza modifiche all'immagine.
@@ -0,0 +1,32 @@
# ADR 0013 - Utente non root con `PUID`/`PGID`
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §16.1, §16.4; chiude il punto aperto 3 di `docs/STATUS.md` (issue #114)
## Contesto
SPEC chiede un utente `app` non root e che i file in `/data` appartengano a `PUID`/`PGID` (99/100 su Unraid). Le
immagini `mcr.microsoft.com/dotnet/aspnet:10.0` hanno già un utente `app` (UID 1654). Le alternative erano: avviare
come root e cedere i privilegi nell'entrypoint, oppure avviare già come `app` e lasciare all'host la proprietà di
`/data` (rendendo inutili `PUID`/`PGID`).
## Decisione
- Il container **parte come root** solo per la preparazione; `docker/entrypoint.sh`:
1. legge `PUID`/`PGID` (predefiniti `1654`, l'utente `app` dell'immagine; i compose per Unraid passano `99`/`100`);
2. allinea UID e GID di `app` con `usermod`/`groupmod` se diversi;
3. crea `/data` se manca ed esegue `chown` **solo se** il proprietario della radice di `/data` non è già
`PUID:PGID` (niente `chown -R` a ogni avvio su volumi grandi);
4. avvia l'applicazione con `setpriv --reuid --regid --init-groups` (util-linux, già nell'immagine base): il
processo .NET **non gira mai come root**.
- Se il container è avviato già non root (`user:` nel compose, `--user`), l'entrypoint salta i passi 2-3 e avvia
direttamente l'applicazione: anche questa configurazione è supportata.
- `PUID=0` o `PGID=0` sono rifiutati con un messaggio esplicito.
## Conseguenze
- Funziona alla lettera con il template Unraid (variabili `PUID`/`PGID`) e con qualunque host Docker.
- Nessun pacchetto aggiuntivo (`setpriv`, `usermod`, `groupmod` sono nella base Debian dell'immagine).
- L'entrypoint è l'unico codice che gira come root; resta corto e senza logica applicativa (migrazioni e bootstrap
stanno nel codice .NET).
@@ -0,0 +1,28 @@
# ADR 0014 - Varianti `_FILE` delle variabili sensibili
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §6; chiude il punto aperto 4 di `docs/STATUS.md` (issue #114)
## Contesto
SPEC prevede la variante `_FILE` (Docker secrets) solo per `KHAEMHAT_SYSTEM_DB` e `KHAEMHAT_SUPERUSER_*`. Altre
variabili contengono segreti altrettanto delicati, a partire da `KHAEMHAT_SECRET_KEY`.
## Decisione
- Ammettono `_FILE` tutte le variabili sensibili: `KHAEMHAT_SYSTEM_DB`, `KHAEMHAT_DB_SERVER`,
`KHAEMHAT_SECRET_KEY`, `KHAEMHAT_SECRET_KEY_NEW`, `KHAEMHAT_SUPERUSER`, `KHAEMHAT_SUPERUSER_PASSWORD`,
`KHAEMHAT_SUPERUSER_EMAIL`, `KHAEMHAT_LICENSE`, `KHAEMHAT_REDIS`, `KHAEMHAT_SMTP_PASSWORD`,
`KHAEMHAT_UPDATE_TOKEN`.
- Una sola regola, in `EnvironmentConfigurationReader` (M1-M2): se esiste `X_FILE`, il valore di `X` è il contenuto
del file senza il fine riga finale; `X` e `X_FILE` impostati insieme sono un **errore di configurazione** che ferma
l'avvio con un messaggio esplicito; un file illeggibile è un errore.
- La risoluzione la fa **l'applicazione**, non l'entrypoint: i segreti non vengono esportati nell'ambiente dei
processi figli. L'entrypoint legge soltanto `KHAEMHAT_SYSTEM_DB` / `KHAEMHAT_SYSTEM_DB_FILE` per attendere il
database (ne usa host e porta, mai la password).
## Conseguenze
- La wiki *Installazione-Docker* e `docs/DEPLOY.md` elencano le variabili con `_FILE` secondo questo ADR.
- I test di `KhaemhatOptions` coprono: valore diretto, valore da file, entrambi (errore), file mancante (errore).
@@ -0,0 +1,29 @@
# ADR 0015 - Tag, versioni e pubblicazione dell'immagine
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §16.3, §16.5, Appendice D (con ADR 0009); chiude i punti aperti 6 e 7 di `docs/STATUS.md`
(issue #114)
## Contesto
Appendice D fa creare il tag git a `publish-image.sh`; con ADR 0009 `release.yml` parte sui tag `v*` e costruisce a
sua volta l'immagine: la stessa versione verrebbe costruita due volte. Il formato dei tag non era fissato.
## Decisione
- **Formato:** tag git `vX.Y.Z` (annotato, creato alla chiusura della milestone, E6); tag immagine `X.Y.Z` **senza
`v`**, più `latest` come comodità (mai in produzione). Versioni di prova: `vX.Y.Z-rc.N` → immagine `X.Y.Z-rc.N`,
senza `latest`.
- **Percorso normale:** push del tag → `release.yml` sul runner Gitea: build, smoke test di `/health/live`, push nel
registro pacchetti, release Gitea con le note dal `CHANGELOG.md`.
- **Percorso alternativo:** `scripts/publish-image.sh vX.Y.Z` costruisce e pubblica dalla macchina di sviluppo e
**non crea tag** git. Se in seguito si spinge il tag, `release.yml` vede che `X.Y.Z` è già nel registro
(`GET /api/v1/packages/<owner>/container/khaemhat/<X.Y.Z>` → `200`), salta build e push e crea solo la release.
- **Versione nel binario:** `/p:Version=X.Y.Z /p:SourceRevisionId=<sha>`; nelle build di sviluppo
`Directory.Build.targets` calcola `X.Y.Z-dev` dall'ultimo tag e lo SHA corrente.
## Conseguenze
- Ogni versione si costruisce una volta sola, qualunque sia il percorso.
- Il controllo aggiornamenti (§12.8, `GiteaPackagesClient`) confronta versioni SemVer senza `v`.
+28
View File
@@ -0,0 +1,28 @@
# ADR 0016 - Icona versionata generata sulla macchina di sviluppo
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §16.6 (con ADR 0009); chiude il punto aperto 8 di `docs/STATUS.md` (issue #114)
## Contesto
L'etichetta `net.unraid.docker.icon` e il template Unraid puntano a un PNG raggiungibile senza autenticazione (URL
raw del repository pubblico, ADR 0009). `scripts/build.sh` genera la variante SVG `icon-v<major.minor>.svg` con una
sostituzione di stringa, ma per il PNG serve un rasterizzatore, che l'applicazione non contiene né deve contenere
(SPEC §1.2).
## Decisione
- `scripts/build.sh --icon` genera `assets/icon-v<major.minor>.svg` dal modello `assets/icon-v1.0.svg` e, se sulla
macchina c'è un rasterizzatore, i PNG 128/256/512. Strumenti accettati, in ordine: `rsvg-convert` (librsvg),
`inkscape`, `magick` (ImageMagick). Senza nessuno dei tre lo script genera solo l'SVG e lo dice.
- I file generati si **committano su `main` prima** del tag che li usa.
- Al build dell'immagine (`release.yml`, `publish-image.sh`) l'URL dell'icona è
`.../raw/branch/main/assets/icon-v<major.minor>-256.png` se il file esiste nel repository, altrimenti
`.../assets/icon-256.png`. Le versioni `0.x` usano `icon-256.png`: la fascia "v 0.x" non serve prima della 1.0.
## Conseguenze
- Nessuna dipendenza nell'immagine né nella CI per la grafica.
- La checklist di chiusura milestone (`docs/DEVELOPMENT.md`) include la generazione dell'icona quando cambia
`major.minor`.
@@ -0,0 +1,25 @@
# ADR 0017 - `restore-system.sh` incluso nell'immagine
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §13, §16.1 (con ADR 0010); chiude il punto aperto 1 di `docs/STATUS.md` (issue #114)
## Contesto
Il database di sistema si ripristina solo da riga di comando, con l'istanza ferma (`scripts/restore-system.sh`,
SPEC §13). Con ADR 0010 l'unico artefatto distribuito è l'immagine: chi installa non ha il repository, e scaricare
uno script a parte al momento del bisogno è fragile (versione diversa da quella installata).
## Decisione
- L'immagine contiene `/app/scripts/restore-system.sh`, copiato dal repository alla stessa versione dell'app.
- Si usa con un container temporaneo sullo stesso volume e sulla stessa rete, con l'istanza ferma:
`docker compose run --rm --entrypoint /app/scripts/restore-system.sh khaemhat <file-di-backup>`.
- Lo script usa gli strumenti già presenti nell'immagine (`pg_restore` di `postgresql-client-17`, `curl`) e la
configurazione del container (`KHAEMHAT_SYSTEM_DB`, `KHAEMHAT_SECRET_KEY`). La logica completa arriva in M12; in
M0 è uno stub che spiega l'uso ed esce con errore.
## Conseguenze
- La wiki *Backup-e-ripristino* e *Aggiornamento* indicano il comando con `docker compose run`, non il download.
- Nessun altro script di sviluppo entra nell'immagine.
@@ -0,0 +1,44 @@
# ADR 0018 - Contratti dello strato dati: scostamenti da SPEC §5.1
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §5.1-§5.4, §3 (con ADR 0004); milestone M1, issue #7-#14
## Contesto
SPEC §5.1 elenca firme indicative di `IDbProvider`, `ISqlDialect`, `ICompanyRegistry` e del motore di migrazione.
Implementandole su due motori sono emersi punti in cui la firma letterale costringeva a soluzioni peggiori
(stringhe SQL da ricomporre, chiamate non annullabili, segreti in chiaro in memoria più del necessario). Questo ADR
fissa le firme effettive.
## Decisione
1. **`CancellationToken` ovunque.** Tutti i metodi asincroni di `IDbProvider`, `IUnitOfWork`, `IRepository<T,TKey>`,
`ICompanyRegistry` e `MigrationRunner` accettano un `CancellationToken` (default `default`).
2. **DDL fuori dal builder.** `IDbProvider` espone `DdlGenerator Ddl` invece di `ISchemaBuilder SchemaBuilder`:
le migrazioni scrivono su un `ISchemaBuilder` neutro che **registra** operazioni (`SchemaOperation`), e il
generatore del provider le traduce in istruzioni. Così la stessa registrazione serve per eseguire, calcolare il
checksum e generare `docs/DATA-MODEL.md`. Le classi dei provider mantengono i nomi di SPEC
(`SqliteSchemaBuilder`, `PostgresSchemaBuilder`) ma sono generatori DDL.
3. **Frammenti, non stringhe.** `ISqlDialect.CaseInsensitiveLike` e `AdvisoryLock` restituiscono `SqlFragment`
(testo + parametri), non `string`, perché il pattern e la chiave del lock sono valori e devono restare parametri.
4. **Membri aggiunti a `IDbProvider`:** `BuildConnectionString(DatabaseUrl)` (configurazione da URL `postgres://` o
`sqlite://`, mai stringhe ADO.NET nelle variabili), `DatabaseExistsAsync`, `IsTransient(Exception)` per i
tentativi automatici, `EnterWriteScopeAsync` (il `SqliteWriteLock` su SQLite, nulla su PostgreSQL).
5. **Registro aziende cifrato per intero.** `sys_companies.connection_string` contiene l'URL del database cifrato
con `SecretProtector` e scopo `company:<CODICE>:database`: una riga copiata su un'altra azienda non si decifra.
La rotazione della password PostgreSQL resta un punto aperto (`docs/STATUS.md`, punto 9).
6. **Esito delle migrazioni al chiamante.** `MigrationRunner.RunAsync` restituisce un `MigrationReport` (applicate con
durata, già presenti, avvisi); la scrittura nella sezione di log *Migrazioni* arriva con il log in M2. Ogni
migrazione gira in una propria transazione sotto lock, con un nuovo controllo di `schema_version` dopo il lock.
7. **Enumerazioni per nome.** Le proprietà enum sono salvate come testo (`String(40)`), non come intero.
8. **Strumento di sviluppo.** `tools/Khaemhat.DataModelTool` (dipende solo da `Khaemhat.Data`, non distribuito)
rigenera la sezione generata di `docs/DATA-MODEL.md`; la regola di dipendenza è nel test architetturale.
## Conseguenze
- Il codice sopra lo strato dati usa `DatabaseScope`, `IUnitOfWorkFactory` e `SqlFragment`; nessun riferimento a
Npgsql o Microsoft.Data.Sqlite fuori dai provider (verificato da un test).
- Chi scrive una migrazione usa `scripts/new-migration.sh` e poi `scripts/gen-datamodel.sh`; un test fallisce se il
documento non è aggiornato.
- Le firme di SPEC §5.1 restano il riferimento per i nomi; dove divergono vale questo ADR.
+1 -1
View File
@@ -109,7 +109,7 @@ che non conosce. Il rollback dipende quindi dalle migrazioni:
**Caso 2 — la nuova versione ha applicato migrazioni.**
1. Ferma l'applicazione: `docker compose stop khaemhat`.
2. Ripristina il **database di sistema** dal backup fatto prima dell'aggiornamento con `scripts/restore-system.sh`
2. Ripristina il **database di sistema** dal backup fatto prima dell'aggiornamento con `restore-system.sh` incluso nell'immagine
(vedi [Backup e ripristino](Backup-e-ripristino#ripristino-del-database-di-sistema)).
3. Ripristina i **database delle aziende** migrate, dagli stessi backup (con la procedura manuale `pg_restore`
descritta in [Backup e ripristino](Backup-e-ripristino#procedura-manuale-equivalente), perché l'applicazione è
+8 -5
View File
@@ -183,16 +183,19 @@ Khaemhat esegue un backup preventivo anche:
## Ripristino del database di sistema
Il database di sistema non si ripristina dall'interfaccia (l'interfaccia stessa dipende da lui). Si usa lo script
`scripts/restore-system.sh` del repository, **con l'istanza ferma**:
`restore-system.sh`, incluso nell'immagine in `/app/scripts/`, **con l'istanza ferma**:
1. Ferma l'applicazione: `docker compose stop khaemhat` (PostgreSQL resta acceso).
2. Esegui lo script indicando il file di backup del database di sistema. I parametri esatti sono documentati
nell'intestazione dello script, che sarà scritto nella milestone M12.
2. Esegui lo script in un container temporaneo, sullo stesso volume e sulla stessa rete, indicando il file di
backup del database di sistema:
```bash
docker compose run --rm --entrypoint /app/scripts/restore-system.sh khaemhat /data/backups/<file-di-backup>
```
Lo script completo arriva con la milestone M12; fino ad allora spiega l'uso ed esce senza fare nulla.
3. Riavvia: `docker compose start khaemhat`. All'avvio vengono applicate le eventuali migrazioni mancanti.
4. Accedi come super utente e controlla **Stato sistema** e l'elenco delle aziende.
Lo script è uno strumento del repository e non è incluso nell'immagine: scaricalo da
[`scripts/`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/scripts) sul server che esegue Docker.
Lo script ha sempre la stessa versione dell'applicazione installata, quindi non va scaricato a parte (ADR 0017).
## Procedura manuale equivalente
+4 -2
View File
@@ -1,6 +1,6 @@
# Changelog
> **Stato:** bozza · **Ultima revisione:** 2026-11-10
> **Stato:** completa per 0.1.0 · **Ultima revisione:** 2026-11-11
Le novità di ogni versione sono nel file
[`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository
@@ -11,7 +11,9 @@ Le novità di ogni versione sono nel file
| Versione | Data | Contenuto |
|---|---|---|
| *non rilasciata* | 2026-11-10 | Documentazione, specifica, mockup, wiki e pianificazione su Gitea. Nessun software ancora. |
| 0.1.0 | 2026-11-11 | M1 — Strato dati: accesso ai database SQLite e PostgreSQL, migrazioni dello schema, registro delle aziende, cifratura dei dati riservati. Nessuna funzione visibile nell'interfaccia. |
| 0.0.1 | 2026-11-11 | M0 — Bootstrap: struttura del codice, immagine Docker con pagina "in costruzione" ed endpoint di salute, compose, CI e rilascio su Gitea Actions. Nessuna funzione gestionale ancora. |
| *preparazione* | 2026-11-10 | Documentazione, specifica, mockup, wiki e pianificazione su Gitea. Nessun software. |
Ogni immagine Docker pubblicata ha lo stesso numero di versione del tag git (senza la `v` iniziale), ad esempio
`gitea.encke-hake.ts.net/balbosoft/khaemhat:0.1.0`. Prima di aggiornare leggi [Aggiornamento](Aggiornamento).
+1 -1
View File
@@ -1,6 +1,6 @@
# Khaemhat
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (sviluppo da avviare)
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** 0.0.1 (M0, pagina "in costruzione"; sviluppo in corso)
![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png)
+12 -8
View File
@@ -65,13 +65,14 @@ Regole pratiche:
### Il file compose
Il file definitivo è `deploy/docker-compose.yml` nel repository (sarà creato nella milestone M0). La struttura
prevista è questa: applicazione, `postgres:17` e `redis:7` attivabile con un profilo.
Il file è [`deploy/docker-compose.yml`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/deploy/docker-compose.yml)
nel repository: applicazione, `postgres:17` e `redis:7` attivabile con un profilo. La versione dell'immagine si
sceglie con `KHAEMHAT_VERSION` nel `.env`. In sintesi:
```yaml
services:
khaemhat:
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:1.0.0
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
restart: unless-stopped
depends_on:
khaemhat-db: { condition: service_healthy }
@@ -128,12 +129,12 @@ Note:
## Demo autonoma con SQLite
Per provare Khaemhat senza PostgreSQL esiste `deploy/docker-compose.sqlite.yml`: un solo container, database di
sistema e aziende come file SQLite nel volume `/data`, dati di esempio caricati al primo avvio. Struttura prevista:
sistema e aziende come file SQLite nel volume `/data`, dati di esempio caricati al primo avvio. In sintesi:
```yaml
services:
khaemhat:
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:1.0.0
image: gitea.encke-hake.ts.net/balbosoft/khaemhat:${KHAEMHAT_VERSION:-0.0.1}
ports: ["8080:8080"]
environment:
KHAEMHAT_SYSTEM_DB: sqlite:///data/system.db
@@ -189,7 +190,7 @@ obbligatoria, termina con un messaggio che indica quale.
| `KHAEMHAT_UPDATE_FEED` | no | `https://gitea.encke-hake.ts.net/api/v1/packages/BalboSoft?type=container&q=khaemhat` | API dei pacchetti Gitea per il controllo aggiornamenti |
| `KHAEMHAT_UPDATE_TOKEN` | no | token Gitea in sola lettura | solo se il pacchetto non è pubblico |
| `TZ` | no | `Europe/Rome` | fuso orario |
| `PUID` / `PGID` | no | `99` / `100` | utente e gruppo proprietari dei file in `/data` |
| `PUID` / `PGID` | no | `1654` / `1654` (Unraid: `99` / `100`) | utente e gruppo proprietari dei file in `/data`; l'applicazione non gira mai come root |
Le variabili del super utente e della prima azienda sono lette solo al primo avvio (quando le tabelle
corrispondenti sono vuote): cambiarle dopo non ha effetto. `KHAEMHAT_TEST_PG` e `KHAEMHAT_TEST_REDIS` servono solo
@@ -198,8 +199,11 @@ ai test automatici e non vanno impostate in un'installazione.
## Docker secrets
Per non scrivere le password in chiaro nel file compose, le variabili sensibili ammettono la variante `_FILE`: invece
del valore contengono il percorso di un file da cui leggerlo. La specifica la prevede per `KHAEMHAT_SYSTEM_DB` e per
le variabili `KHAEMHAT_SUPERUSER_*`; l'elenco completo delle variabili che la accettano sarà fissato in sviluppo.
del valore contengono il percorso di un file da cui leggerlo. La accettano tutte le variabili sensibili: `KHAEMHAT_SYSTEM_DB`,
`KHAEMHAT_DB_SERVER`, `KHAEMHAT_SECRET_KEY`, `KHAEMHAT_SECRET_KEY_NEW`, `KHAEMHAT_SUPERUSER`,
`KHAEMHAT_SUPERUSER_PASSWORD`, `KHAEMHAT_SUPERUSER_EMAIL`, `KHAEMHAT_LICENSE`, `KHAEMHAT_REDIS`,
`KHAEMHAT_SMTP_PASSWORD`, `KHAEMHAT_UPDATE_TOKEN`. Il valore è il contenuto del file senza il fine riga finale;
impostare insieme `X` e `X_FILE` è un errore che ferma l'avvio.
```yaml
services:
+10 -6
View File
@@ -1,12 +1,13 @@
# Modello dati
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M1 e seguenti)
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.1.0 (strato dati, M1); le tabelle funzionali arrivano con le milestone successive
> **Specifica:** SPEC §5, §11, §13, §14
Come Khaemhat organizza i dati, in sintesi. L'elenco completo di tabelle e colonne è in
[docs/DATA-MODEL.md](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/docs/DATA-MODEL.md): oggi è
la versione **pianificata**; dalla milestone M1 sarà generato automaticamente dal codice, quindi sempre allineato al
programma.
[docs/DATA-MODEL.md](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/docs/DATA-MODEL.md). La sua
sezione *Schema attuale* è **generata automaticamente** dalle migrazioni del programma, quindi è sempre allineata a
ciò che il programma crea davvero nei database; le altre sezioni descrivono le tabelle **pianificate**, che compaiono
nello schema attuale man mano che le milestone le realizzano.
## Due tipi di database
@@ -62,8 +63,11 @@ settimana).
Quando una nuova versione cambia la struttura dei dati, Khaemhat applica da solo le **migrazioni**: il database di
sistema all'avvio, le aziende all'avvio o dal pannello **Amministrazione → Istanza e database**, mettendo l'azienda in
manutenzione per il tempo necessario. Non è possibile tornare a una versione precedente dello schema: per questo prima
di ogni aggiornamento conviene un backup ([Aggiornamento](Aggiornamento), [Backup-e-ripristino](Backup-e-ripristino)).
manutenzione per il tempo necessario. Ogni migrazione è applicata
per intero o per niente, e più copie del programma avviate insieme non la applicano due volte. Non è possibile
tornare a una versione precedente dello schema: se il database contiene una migrazione che il programma non conosce
(per esempio dopo aver rimesso un'immagine più vecchia) Khaemhat si rifiuta di partire invece di rischiare i dati.
Per questo prima di ogni aggiornamento conviene un backup ([Aggiornamento](Aggiornamento), [Backup-e-ripristino](Backup-e-ripristino)).
## Pagine correlate
+2 -2
View File
@@ -30,8 +30,8 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
## Stato attuale
La documentazione e la pianificazione sono pronte (2026-11-10). Lo sviluppo parte dalla milestone M0 dopo il via
del titolare del progetto. Lo stato aggiornato è in
Sviluppo avviato il 2026-11-11. M0 consegna la versione 0.0.1 (struttura, immagine Docker, CI); poi si prosegue
milestone dopo milestone, a partire da M1 — Fondamenta dati. Lo stato aggiornato è in
[`docs/STATUS.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/docs/STATUS.md).
## Pagine correlate
+7
View File
@@ -0,0 +1,7 @@
{
"sdk": {
"version": "10.0.100",
"rollForward": "latestFeature",
"allowPrerelease": false
}
}
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
# Builds the solution with warnings as errors (SPEC §19).
# scripts/build.sh [-c Debug|Release] build
# scripts/build.sh --icon [X.Y] also generate the versioned icon (ADR 0016); X.Y from the last tag
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
configuration=Release
icon=""
while (( $# > 0 )); do
case "$1" in
-c | --configuration) configuration="${2:?manca la configurazione}"; shift 2 ;;
--icon)
if [[ "${2:-}" =~ ^[0-9]+\.[0-9]+$ ]]; then icon="$2"; shift 2; else icon="auto"; shift; fi ;;
-h | --help) sed -n '2,5p' "$0"; exit 0 ;;
*) echo "argomento sconosciuto: $1" >&2; exit 2 ;;
esac
done
# Generates assets/icon-v<X.Y>.svg from the template by string replacement, then the PNGs if a rasterizer exists.
generate_icon() {
local version="$1" svg png size tool=""
if [[ "$version" == "auto" ]]; then
version="$(git describe --tags --match 'v[0-9]*' --abbrev=0 2>/dev/null || true)"
[[ -n "$version" ]] || { echo "nessun tag vX.Y.Z: indica la versione, es. --icon 1.0" >&2; exit 2; }
version="${version#v}"
version="${version%.*}"
fi
svg="assets/icon-v${version}.svg"
if [[ "$version" != "1.0" ]]; then
sed "s/v 1\.0/v ${version}/" assets/icon-v1.0.svg > "$svg"
grep -q "v ${version}" "$svg" || { echo "il modello assets/icon-v1.0.svg non contiene il testo 'v 1.0'" >&2; exit 1; }
fi
echo "icona: $svg"
for candidate in rsvg-convert inkscape magick; do
if command -v "$candidate" > /dev/null 2>&1; then tool="$candidate"; break; fi
done
if [[ -z "$tool" ]]; then
echo "nessun rasterizzatore (rsvg-convert, inkscape, magick): genera i PNG su una macchina che ne ha uno (ADR 0016)." >&2
return 0
fi
for size in 128 256 512; do
png="assets/icon-v${version}-${size}.png"
case "$tool" in
rsvg-convert) rsvg-convert -w "$size" -h "$size" -o "$png" "$svg" ;;
inkscape) inkscape "$svg" --export-type=png --export-filename="$png" -w "$size" -h "$size" > /dev/null ;;
magick) magick -background none -density 384 "$svg" -resize "${size}x${size}" "$png" ;;
esac
echo "icona: $png ($tool)"
done
echo "Committa i file generati su main prima del tag che li usa (ADR 0016)."
}
bash scripts/check-packages.sh
dotnet build Khaemhat.sln -c "$configuration" -warnaserror
if [[ -n "$icon" ]]; then
generate_icon "$icon"
fi
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Package allowlist (SPEC §1.2, ADR 0002). Fails when an MSBuild file references a package that is not allowed, or an
# allowed package outside its project. The architecture tests check the same rules; this script runs before any build
# (Dockerfile, CI) so a forbidden package never gets restored.
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
# package -> where it may be referenced (a project file name, or "tests/" for any test project)
allowed_in() {
case "$1" in
Npgsql) echo "src/Khaemhat.Data.PostgreSql/Khaemhat.Data.PostgreSql.csproj" ;;
Microsoft.Data.Sqlite) echo "src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj" ;;
Microsoft.NET.Test.Sdk | MSTest) echo "tests/" ;;
*) echo "" ;;
esac
}
# Prints "<file> <package>" for each element of the given kind (PackageReference, PackageVersion).
references() {
local element="$1" file
while IFS= read -r file; do
file="${file#./}"
grep -oE "<${element}[[:space:]]+(Include|Update)=\"[^\"]+\"" "$file" \
| sed -E 's/.*="([^"]+)"/\1/' \
| while IFS= read -r package; do printf '%s %s\n' "$file" "$package"; done || true
done < <(find . \( -name bin -o -name obj -o -name .git -o -name .claude -o -name out \) -prune -o \
-type f \( -name '*.csproj' -o -name '*.props' -o -name '*.targets' \) -print | sort)
}
errors=0
checked=0
while read -r file package; do
checked=$((checked + 1))
where="$(allowed_in "$package")"
if [[ -z "$where" ]]; then
echo "ERRORE: $file: il pacchetto $package non è nell'allowlist (SPEC §1.2)." >&2
errors=$((errors + 1))
elif [[ "$where" == "tests/" && "$file" != tests/* ]]; then
echo "ERRORE: $file: $package è ammesso solo nei progetti di test." >&2
errors=$((errors + 1))
elif [[ "$where" != "tests/" && "$file" != "$where" ]]; then
echo "ERRORE: $file: $package è ammesso solo in $where." >&2
errors=$((errors + 1))
fi
done < <(references PackageReference)
while read -r file package; do
if [[ -z "$(allowed_in "$package")" ]]; then
echo "ERRORE: $file: versione centrale per $package, che non è nell'allowlist." >&2
errors=$((errors + 1))
fi
done < <(references PackageVersion)
if (( errors > 0 )); then
echo "check-packages: $errors violazioni." >&2
exit 1
fi
echo "check-packages: OK ($checked riferimenti a pacchetti, tutti ammessi)."
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Regenerates the generated section of docs/DATA-MODEL.md from the migrations (SPEC §18).
# scripts/gen-datamodel.sh rewrite the section
# scripts/gen-datamodel.sh --check only verify it is up to date (exit 1 if not)
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
dotnet run --project tools/Khaemhat.DataModelTool -c Release -- "$@" docs/DATA-MODEL.md
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# Creates a new numbered migration for the system or company schema (SPEC §5.3).
# scripts/new-migration.sh <system|company> <nome_snake_case> [cartella] [modulo]
# Example: scripts/new-migration.sh system create_sys_users
# The version is today's date plus the next free number of the day across the repository (yyyymmdd_nnn); the
# class is M<yyyymmdd>_<nnn>_<NomePascal> in the given folder (default: the system or company migrations folder).
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
usage() {
echo "Uso: scripts/new-migration.sh <system|company> <nome_snake_case> [cartella] [modulo]" >&2
exit 2
}
[ $# -ge 2 ] || usage
target="$1"
name="$2"
module="${4:-core}"
case "$target" in
system) dir="${3:-src/Khaemhat.Data/SystemDatabase/Migrations}"; attribute_target="MigrationTarget.System" ;;
company) dir="${3:-src/Khaemhat.Application/Migrations}"; attribute_target="MigrationTarget.Company" ;;
*) usage ;;
esac
if ! [[ "$name" =~ ^[a-z][a-z0-9_]{0,62}$ ]]; then
echo "Il nome deve essere snake_case (lettere minuscole, cifre, _): $name" >&2
exit 2
fi
if ! [[ "$module" =~ ^[a-z][a-z0-9_]{0,39}$ ]]; then
echo "Il modulo deve essere snake_case: $module" >&2
exit 2
fi
if [[ "$dir" != src/* ]]; then
echo "La cartella deve stare sotto src/: $dir" >&2
exit 2
fi
day="$(date +%Y%m%d)"
last="$(grep -rhoE "\[Migration\(${day}_[0-9]{3}" src --include='*.cs' 2>/dev/null | sed -E 's/.*_([0-9]{3})$/\1/' | sort -n | tail -1 || true)"
next=$(printf '%03d' $((10#${last:-0} + 1)))
pascal="$(echo "$name" | awk -F_ '{ for (i = 1; i <= NF; i++) printf "%s%s", toupper(substr($i, 1, 1)), substr($i, 2) }')"
class="M${day}_${next}_${pascal}"
namespace="$(echo "${dir#src/}" | tr '/' '.')"
file="$dir/$class.cs"
mkdir -p "$dir"
if [ -e "$file" ]; then
echo "Esiste già: $file" >&2
exit 1
fi
if [ "$attribute_target" = "MigrationTarget.Company" ]; then
target_argument=""
else
target_argument=", Target = $attribute_target"
fi
if [ "$module" = "core" ]; then
module_argument=""
else
module_argument=", Module = \"$module\""
fi
cat > "$file" <<CS
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace $namespace;
/// <summary>TODO: what this migration changes and why (SPEC section).</summary>
[Migration(${day}_${next}, "$name"$target_argument$module_argument)]
public sealed class $class : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
// schema.CreateTable("table_name", t => { t.Id(); t.AuditColumns(); });
}
}
CS
echo "Creata $file (versione ${day}_${next}, modulo $module)."
echo "Dopo averla scritta: aggiornare la mappa dell'entità, eseguire scripts/gen-datamodel.sh e i test."
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# Builds the image on this machine and pushes it to the Gitea package registry (ADR 0009, ADR 0015). The normal path
# is release.yml on a vX.Y.Z tag; use this when the runner is not available. It does NOT create git tags: pushing the
# tag later makes release.yml find the version in the registry and only create the release.
#
# scripts/publish-image.sh vX.Y.Z [--arm64] [--force]
#
# Environment: GITEA_TOKEN (required, scope write:package), GITEA_URL (https://gitea.encke-hake.ts.net),
# GITEA_OWNER (BalboSoft), GITEA_USER (login of the token owner; defaults to GITEA_OWNER).
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
tag="${1:-}"
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "uso: publish-image.sh vX.Y.Z [--arm64] [--force]" >&2; exit 2; }
shift
platforms="linux/amd64"
force=false
for arg in "$@"; do
case "$arg" in
--arm64) platforms="linux/amd64,linux/arm64" ;;
--force) force=true ;;
*) echo "argomento sconosciuto: $arg" >&2; exit 2 ;;
esac
done
gitea_url="${GITEA_URL:-https://gitea.encke-hake.ts.net}"
gitea_url="${gitea_url%/}"
registry="${gitea_url#https://}"
registry="${registry#http://}"
owner="${GITEA_OWNER:-BalboSoft}"
owner_lc="$(printf '%s' "$owner" | tr '[:upper:]' '[:lower:]')"
image="$registry/$owner_lc/khaemhat"
version="${tag#v}"
sha="$(git rev-parse --short HEAD)"
token="${GITEA_TOKEN:?imposta GITEA_TOKEN (permesso write:package)}"
if [[ -n "$(git status --porcelain)" ]]; then
echo "ATTENZIONE: ci sono modifiche non committate; l'immagine riporterà lo SHA $sha." >&2
fi
status="$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: token $token" \
"$gitea_url/api/v1/packages/$owner/container/khaemhat/$version")"
if [[ "$status" == "200" && "$force" != true ]]; then
echo "La versione $version è già nel registro: niente da fare (usa --force per sovrascriverla)." >&2
exit 1
fi
# Versioned icon for Unraid if committed, otherwise the plain one (ADR 0016).
major_minor="${version%%-*}"
major_minor="${major_minor%.*}"
icon_url="$gitea_url/$owner/Khaemhat/raw/branch/main/assets/icon-256.png"
if git cat-file -e "origin/main:assets/icon-v${major_minor}-256.png" 2>/dev/null; then
icon_url="$gitea_url/$owner/Khaemhat/raw/branch/main/assets/icon-v${major_minor}-256.png"
fi
tags=(-t "$image:$version")
[[ "$version" == *-* ]] || tags+=(-t "$image:latest")
printf '%s' "$token" | docker login "$registry" -u "${GITEA_USER:-$owner}" --password-stdin
docker buildx build --platform "$platforms" -f docker/Dockerfile \
--build-arg VERSION="$version" \
--build-arg GIT_SHA="$sha" \
--build-arg CREATED="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--build-arg SOURCE_URL="$gitea_url/$owner/Khaemhat" \
--build-arg ICON_URL="$icon_url" \
"${tags[@]}" --push .
echo "Pubblicata $image:$version ($platforms)."
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Publishes docs/wiki/ to the Gitea wiki (Khaemhat.wiki.git), the same job as .gitea/workflows/wiki.yml.
# The wiki becomes an exact copy of docs/wiki/: pages removed here are removed there.
#
# Environment: GITEA_URL (https://gitea.encke-hake.ts.net), GITEA_OWNER (BalboSoft); GITEA_TOKEN is optional (without
# it git uses the credentials already configured on this machine). WIKI_REMOTE overrides the whole URL.
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
gitea_url="${GITEA_URL:-https://gitea.encke-hake.ts.net}"
remote="${WIKI_REMOTE:-${gitea_url%/}/${GITEA_OWNER:-BalboSoft}/Khaemhat.wiki.git}"
sha="$(git rev-parse --short HEAD)"
auth=()
if [[ -n "${GITEA_TOKEN:-}" ]]; then
auth=(-c "http.extraheader=Authorization: basic $(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)")
fi
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
git "${auth[@]}" clone -q --depth 1 "$remote" "$work/wiki"
find "$work/wiki" -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} +
cp -R docs/wiki/. "$work/wiki/"
cd "$work/wiki"
git add -A
if git diff --cached --quiet; then
echo "Wiki già allineata a docs/wiki ($sha)."
exit 0
fi
git -c user.name="${GIT_AUTHOR_NAME:-Khaemhat wiki}" -c user.email="${GIT_AUTHOR_EMAIL:-wiki@khaemhat.invalid}" \
commit -q -m "docs(wiki): sync from $sha"
git "${auth[@]}" push -q origin HEAD
echo "Wiki pubblicata da docs/wiki ($sha): $(git diff --stat HEAD~1 | tail -n 1)"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Restores the system database from a backup with the instance stopped (SPEC §13, ADR 0017). Shipped in the image as /app/scripts/restore-system.sh.
# docker compose run --rm --entrypoint /app/scripts/restore-system.sh khaemhat <file-di-backup>
# Stub: completed in milestone M12 (SPEC §20). Until then it explains what it will do and exits with an error.
set -euo pipefail
echo "restore-system.sh: non ancora disponibile, arriva con la milestone M12." >&2
echo "Uso previsto: docker compose run --rm --entrypoint /app/scripts/restore-system.sh khaemhat <file-di-backup>" >&2
exit 1
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# Starts Khaemhat locally on http://localhost:5080 with SQLite in .data/dev (ignored by git).
# Any KHAEMHAT_* variable already set in the shell wins over the defaults below.
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
data_dir="$root/.data/dev"
mkdir -p "$data_dir"
export ASPNETCORE_ENVIRONMENT="${ASPNETCORE_ENVIRONMENT:-Development}"
export KHAEMHAT_DATA_DIR="${KHAEMHAT_DATA_DIR:-$data_dir}"
export KHAEMHAT_SYSTEM_DB="${KHAEMHAT_SYSTEM_DB:-sqlite://$data_dir/system.db}"
# Development-only key: never use it outside this script.
export KHAEMHAT_SECRET_KEY="${KHAEMHAT_SECRET_KEY:-a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=}"
export KHAEMHAT_SUPERUSER="${KHAEMHAT_SUPERUSER:-root}"
export KHAEMHAT_SUPERUSER_PASSWORD="${KHAEMHAT_SUPERUSER_PASSWORD:-Khaemhat-dev-1}"
export KHAEMHAT_COMPANY_CODE="${KHAEMHAT_COMPANY_CODE:-DEMO}"
export KHAEMHAT_COMPANY_NAME="${KHAEMHAT_COMPANY_NAME:-Khaemhat Demo S.r.l.}"
export KHAEMHAT_LICENSE_MODE="${KHAEMHAT_LICENSE_MODE:-test}"
export KHAEMHAT_SEED_DEMO="${KHAEMHAT_SEED_DEMO:-true}"
echo "Khaemhat in sviluppo: http://localhost:5080 (dati in $KHAEMHAT_DATA_DIR)"
exec dotnet run --project src/Khaemhat.Web -- --urls http://localhost:5080 "$@"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Loads base tables and demo data into a company database (SPEC §15).
# scripts/seed.sh --base | --demo [--scale N] [--company CODE]
# Stub: completed in milestone M4 (SPEC §20). Until then it explains what it will do and exits with an error.
set -euo pipefail
echo "seed.sh: non ancora disponibile, arriva con la milestone M4." >&2
echo "Uso previsto: scripts/seed.sh --base | --demo [--scale N] [--company CODE]" >&2
exit 1
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Runs every test (SPEC §20). SQLite always; PostgreSQL when KHAEMHAT_TEST_PG is set
# (e.g. postgres://khaemhat:secret@localhost:5432/postgres); Redis when KHAEMHAT_TEST_REDIS is set.
# Extra arguments go to "dotnet test", e.g. scripts/test.sh --filter FullyQualifiedName~Health
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"
export KHAEMHAT_LICENSE_MODE=test
echo "PostgreSQL: ${KHAEMHAT_TEST_PG:+attivo}${KHAEMHAT_TEST_PG:-non configurato (KHAEMHAT_TEST_PG), test saltati}"
echo "Redis: ${KHAEMHAT_TEST_REDIS:+attivo}${KHAEMHAT_TEST_REDIS:-non configurato (KHAEMHAT_TEST_REDIS), test saltati}"
bash scripts/check-packages.sh
dotnet test Khaemhat.sln -c Release "$@"
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>Khaemhat.Application</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
<ProjectReference Include="../Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj" />
<ProjectReference Include="../Khaemhat.Fiscal.Abstractions/Khaemhat.Fiscal.Abstractions.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,51 @@
namespace Khaemhat.Core.Common;
/// <summary>
/// Thrown when a row changed (or was deleted) after it was read: the update found no row with the expected
/// <c>row_version</c> (SPEC §5.2). The interface reloads and asks the user; the API answers <c>409</c>.
/// </summary>
public sealed class ConcurrencyException : Exception
{
/// <summary>Creates the exception for a row of <paramref name="table"/>.</summary>
/// <param name="table">The table name.</param>
/// <param name="key">The primary key of the row, as text.</param>
/// <param name="expectedVersion">The <c>row_version</c> the caller read.</param>
public ConcurrencyException(string table, string key, long expectedVersion)
: base($"The row {key} of {table} was changed or deleted by someone else (expected version {expectedVersion}).")
{
Table = table;
Key = key;
ExpectedVersion = expectedVersion;
}
/// <summary>Creates the exception with a message only.</summary>
/// <param name="message">The message.</param>
public ConcurrencyException(string message) : base(message)
{
Table = string.Empty;
Key = string.Empty;
}
/// <summary>Creates the exception with a message and an inner exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public ConcurrencyException(string message, Exception innerException) : base(message, innerException)
{
Table = string.Empty;
Key = string.Empty;
}
/// <summary>Creates the exception without details.</summary>
public ConcurrencyException() : this("The row was changed or deleted by someone else.")
{
}
/// <summary>The table of the row.</summary>
public string Table { get; }
/// <summary>The primary key of the row, as text.</summary>
public string Key { get; }
/// <summary>The <c>row_version</c> the caller read.</summary>
public long ExpectedVersion { get; }
}
@@ -0,0 +1,66 @@
using System.Globalization;
using System.Reflection;
namespace Khaemhat.Core.Common;
/// <summary>
/// The product version as shown to people (SPEC §16.5): the SemVer number, its <c>major.minor</c> short form for the
/// top bar and the versioned icon, and the source revision for the status bar and the system status page.
/// </summary>
/// <param name="Version">SemVer without build metadata, for example <c>1.2.3</c> or <c>0.1.0-dev</c>.</param>
/// <param name="Revision">Short source revision (git commit), or an empty string when unknown.</param>
public sealed record ProductVersion(string Version, string Revision)
{
/// <summary>The <c>major.minor</c> part of <see cref="Version"/>, for example <c>1.2</c>.</summary>
public string MajorMinor
{
get
{
var core = Version.Split('-', 2)[0];
var parts = core.Split('.');
return parts.Length >= 2 ? string.Create(CultureInfo.InvariantCulture, $"{parts[0]}.{parts[1]}") : core;
}
}
/// <summary>The full form, <c>version+revision</c> when the revision is known.</summary>
public string Full => Revision.Length == 0 ? Version : $"{Version}+{Revision}";
/// <inheritdoc />
public override string ToString() => Full;
/// <summary>
/// Parses an informational version such as <c>1.2.3+abc1234</c>. A long revision (a full commit hash) is
/// shortened to 7 characters.
/// </summary>
/// <param name="informationalVersion">The value of <see cref="AssemblyInformationalVersionAttribute"/>.</param>
public static ProductVersion Parse(string? informationalVersion)
{
if (string.IsNullOrWhiteSpace(informationalVersion))
{
return new ProductVersion("0.0.0-dev", string.Empty);
}
var plus = informationalVersion.IndexOf('+', StringComparison.Ordinal);
if (plus < 0)
{
return new ProductVersion(informationalVersion.Trim(), string.Empty);
}
var version = informationalVersion[..plus].Trim();
var revision = informationalVersion[(plus + 1)..].Trim();
if (revision.Length > 7)
{
revision = revision[..7];
}
return new ProductVersion(version, revision);
}
/// <summary>Reads the version of the given assembly (by default the entry assembly).</summary>
/// <param name="assembly">The assembly to read; <see langword="null"/> means the entry assembly.</param>
public static ProductVersion FromAssembly(Assembly? assembly = null)
{
var source = assembly ?? Assembly.GetEntryAssembly() ?? typeof(ProductVersion).Assembly;
return Parse(source.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion);
}
}
+27
View File
@@ -0,0 +1,27 @@
namespace Khaemhat.Core.Entities;
/// <summary>
/// Convenience base class for entities with an identity key and the audit columns. Entities may also implement
/// <see cref="IEntity{TKey}"/> and <see cref="IAuditable"/> directly.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
public abstract class Entity<TKey> : IEntity<TKey>, IAuditable
{
/// <inheritdoc />
public TKey Id { get; set; } = default!;
/// <inheritdoc />
public DateTime CreatedAt { get; set; }
/// <inheritdoc />
public string? CreatedBy { get; set; }
/// <inheritdoc />
public DateTime? UpdatedAt { get; set; }
/// <inheritdoc />
public string? UpdatedBy { get; set; }
/// <inheritdoc />
public long RowVersion { get; set; }
}
+27
View File
@@ -0,0 +1,27 @@
namespace Khaemhat.Core.Entities;
/// <summary>
/// An entity with the audit columns of SPEC §5.2 (<c>created_at</c>, <c>created_by</c>, <c>updated_at</c>,
/// <c>updated_by</c>) and the <c>row_version</c> used for optimistic concurrency. The data layer fills them; code above
/// it only reads them.
/// </summary>
public interface IAuditable
{
/// <summary>When the row was inserted, in UTC.</summary>
DateTime CreatedAt { get; set; }
/// <summary>Who inserted the row (user name, or a system actor such as <c>system</c>), when known.</summary>
string? CreatedBy { get; set; }
/// <summary>When the row was last updated, in UTC; <see langword="null"/> if it never was.</summary>
DateTime? UpdatedAt { get; set; }
/// <summary>Who last updated the row, when known.</summary>
string? UpdatedBy { get; set; }
/// <summary>
/// Incremented by every update. An update succeeds only if the stored value still equals this one; otherwise the
/// data layer throws <see cref="Common.ConcurrencyException"/>.
/// </summary>
long RowVersion { get; set; }
}
@@ -0,0 +1,8 @@
namespace Khaemhat.Core.Entities;
/// <summary>An entity whose rows can be created by the demo seeder and removed with it (SPEC §14, column <c>is_demo</c>).</summary>
public interface IDemoMarkable
{
/// <summary><see langword="true"/> for rows created by the demo data seeder.</summary>
bool IsDemo { get; set; }
}
+9
View File
@@ -0,0 +1,9 @@
namespace Khaemhat.Core.Entities;
/// <summary>An entity with an identity of type <typeparamref name="TKey"/>, stored in the <c>id</c> column (SPEC §5.2).</summary>
/// <typeparam name="TKey">The key type: <see cref="long"/> for identity keys, which is the default for every table.</typeparam>
public interface IEntity<TKey>
{
/// <summary>The primary key. For identity keys it is the default value until the row is inserted.</summary>
TKey Id { get; set; }
}
+31
View File
@@ -0,0 +1,31 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Instance;
/// <summary>
/// A company in the instance registry (<c>sys_companies</c>, SPEC §5.4): its code, name and the location of its own
/// database. The location is stored encrypted and is never shown or logged.
/// </summary>
public sealed class Company : Entity<long>
{
/// <summary>Company code: upper-case letters, digits and underscore, 1 to 20 characters (database <c>khaemhat_code</c>).</summary>
public string Code { get; set; } = string.Empty;
/// <summary>Company name (ragione sociale).</summary>
public string Name { get; set; } = string.Empty;
/// <summary>The database engine name: <c>Sqlite</c> or <c>PostgreSql</c>.</summary>
public string Engine { get; set; } = string.Empty;
/// <summary>The database URL, encrypted with the instance key.</summary>
public string ConnectionString { get; set; } = string.Empty;
/// <summary>The company state.</summary>
public CompanyStatus Status { get; set; }
/// <summary>Whether this is the company opened by default.</summary>
public bool IsDefault { get; set; }
/// <summary>Free notes for administrators.</summary>
public string? Notes { get; set; }
}
@@ -0,0 +1,17 @@
namespace Khaemhat.Core.Instance;
/// <summary>State of a company database in the registry (SPEC §5.4, §12.1).</summary>
public enum CompanyStatus
{
/// <summary>In use.</summary>
Active = 0,
/// <summary>Maintenance in progress (migration, restore): nobody but administrators can open it.</summary>
Maintenance = 1,
/// <summary>Readable only, for example an archive.</summary>
ReadOnly = 2,
/// <summary>Kept but not available.</summary>
Disabled = 3,
}
@@ -0,0 +1,16 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Instance;
/// <summary>An instance setting (<c>sys_settings</c>). Secret values are stored encrypted (<see cref="IsSecret"/>).</summary>
public sealed class SystemSetting : Entity<long>
{
/// <summary>The setting key, for example <c>smtp.host</c>.</summary>
public string Key { get; set; } = string.Empty;
/// <summary>The value; encrypted when <see cref="IsSecret"/> is set.</summary>
public string? Value { get; set; }
/// <summary>Whether <see cref="Value"/> is a secret encrypted with the instance key.</summary>
public bool IsSecret { get; set; }
}
+7
View File
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>Khaemhat.Core</RootNamespace>
</PropertyGroup>
</Project>
@@ -0,0 +1,22 @@
namespace Khaemhat.Core.Security;
/// <summary>
/// Encrypts secrets stored in the databases (company connection strings, SMTP/PEC/S3/WebDAV passwords, tokens) with
/// the instance key <c>KHAEMHAT_SECRET_KEY</c> (SPEC §5.4). The <c>purpose</c> binds a ciphertext to its use: a value
/// protected for one purpose cannot be read back for another.
/// </summary>
public interface ISecretProtector
{
/// <summary>Encrypts <paramref name="plaintext"/>; the result is printable text safe to store in a column.</summary>
/// <param name="plaintext">The secret.</param>
/// <param name="purpose">What the secret is for, for example <c>company:DEMO:database</c>.</param>
/// <returns>The protected value.</returns>
string Protect(string plaintext, string purpose);
/// <summary>Decrypts a value produced by <see cref="Protect"/> with the same key and purpose.</summary>
/// <param name="protectedValue">The protected value.</param>
/// <param name="purpose">The purpose given to <see cref="Protect"/>.</param>
/// <returns>The secret.</returns>
/// <exception cref="SecretProtectionException">The value was protected with another key or purpose, or is damaged.</exception>
string Unprotect(string protectedValue, string purpose);
}
@@ -0,0 +1,26 @@
namespace Khaemhat.Core.Security;
/// <summary>
/// A secret could not be decrypted: wrong instance key, wrong purpose or damaged value. The message never contains
/// the secret or the ciphertext.
/// </summary>
public sealed class SecretProtectionException : Exception
{
/// <summary>Creates the exception.</summary>
public SecretProtectionException() : base("The secret cannot be decrypted.")
{
}
/// <summary>Creates the exception with a message.</summary>
/// <param name="message">The message (never the secret).</param>
public SecretProtectionException(string message) : base(message)
{
}
/// <summary>Creates the exception with a message and a cause.</summary>
/// <param name="message">The message (never the secret).</param>
/// <param name="innerException">The cause.</param>
public SecretProtectionException(string message, Exception innerException) : base(message, innerException)
{
}
}
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>Khaemhat.Data.PostgreSql</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Npgsql" />
</ItemGroup>
</Project>
@@ -0,0 +1,26 @@
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// Application locks on PostgreSQL (SPEC §5.2) for numerators, closings and the scheduler. The text key is hashed to
/// 64 bits by the server (<c>hashtextextended</c>); transaction locks are released by commit or rollback.
/// </summary>
public static class PostgresAdvisoryLocks
{
/// <summary>Waits for the lock and holds it until the end of the transaction.</summary>
/// <param name="key">The lock key.</param>
/// <returns>The statement.</returns>
public static SqlFragment TransactionLock(string key)
{
ArgumentException.ThrowIfNullOrEmpty(key);
return SqlFragment.Of($"SELECT pg_advisory_xact_lock(hashtextextended({key}, 0))");
}
/// <summary>Takes the lock if free, without waiting; the statement returns a boolean.</summary>
/// <param name="key">The lock key.</param>
/// <returns>The statement.</returns>
public static SqlFragment TryTransactionLock(string key)
{
ArgumentException.ThrowIfNullOrEmpty(key);
return SqlFragment.Of($"SELECT pg_try_advisory_xact_lock(hashtextextended({key}, 0))");
}
}
@@ -0,0 +1,92 @@
using System.Diagnostics.CodeAnalysis;
using Npgsql;
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// Creates and drops company databases on the server of <c>KHAEMHAT_DB_SERVER</c> (SPEC §5.4). It connects to the
/// maintenance database <c>postgres</c> with the same credentials. Database names are validated identifiers: they
/// cannot be parameters in DDL, so nothing else may reach the statement.
/// </summary>
public static class PostgresDatabaseCreator
{
private const string MaintenanceDatabase = "postgres";
/// <summary>Creates the database of <paramref name="connectionString"/> if it does not exist (UTF-8, from <c>template0</c>).</summary>
/// <param name="connectionString">The connection string of the database to create.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task EnsureExistsAsync(string connectionString, CancellationToken cancellationToken = default)
{
var name = DatabaseName(connectionString);
if (await ExistsAsync(connectionString, cancellationToken).ConfigureAwait(false))
{
return;
}
try
{
await ExecuteOnMaintenanceAsync(
connectionString, $"CREATE DATABASE \"{name}\" TEMPLATE template0 ENCODING 'UTF8'", cancellationToken).ConfigureAwait(false);
}
catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.DuplicateDatabase)
{
// Created concurrently by another instance: the goal is reached.
}
}
/// <summary>Drops the database, closing its connections (<c>WITH (FORCE)</c>). Used only by the registry and restores.</summary>
/// <param name="connectionString">The connection string of the database to drop.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task DropAsync(string connectionString, CancellationToken cancellationToken = default)
{
var name = DatabaseName(connectionString);
if (name == MaintenanceDatabase)
{
throw new InvalidOperationException("The maintenance database cannot be dropped.");
}
using (var connection = new NpgsqlConnection(connectionString))
{
NpgsqlConnection.ClearPool(connection);
}
await ExecuteOnMaintenanceAsync(connectionString, $"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", cancellationToken).ConfigureAwait(false);
}
/// <summary>Whether the database exists.</summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> if it exists.</returns>
public static async Task<bool> ExistsAsync(string connectionString, CancellationToken cancellationToken = default)
{
var name = DatabaseName(connectionString);
await using var connection = new NpgsqlConnection(MaintenanceConnectionString(connectionString));
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
await using var command = new NpgsqlCommand("SELECT 1 FROM pg_database WHERE datname = @name", connection);
command.Parameters.AddWithValue("name", name);
return await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false) is not null;
}
private static string DatabaseName(string connectionString)
{
var name = new NpgsqlConnectionStringBuilder(connectionString).Database ?? string.Empty;
return SqlNames.IsValidIdentifier(name)
? name
: throw new ArgumentException("The database name must be lower-case letters, digits and underscore.", nameof(connectionString));
}
private static string MaintenanceConnectionString(string connectionString) =>
new NpgsqlConnectionStringBuilder(connectionString) { Database = MaintenanceDatabase, Pooling = false }.ToString();
[SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities",
Justification = "The only variable part is a database name validated as a snake_case identifier.")]
private static async Task ExecuteOnMaintenanceAsync(string connectionString, string sql, CancellationToken cancellationToken)
{
await using var connection = new NpgsqlConnection(MaintenanceConnectionString(connectionString));
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
await using var command = new NpgsqlCommand(sql, connection);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,126 @@
using System.Data.Common;
using System.Globalization;
using Khaemhat.Data.Schema;
using Npgsql;
using NpgsqlTypes;
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// The PostgreSQL dialect (SPEC §5.2): <c>varchar(n)/text/integer/bigint/numeric(19,6)/boolean/date/timestamptz/uuid/
/// bytea/jsonb</c>, <c>ILIKE</c> for case-insensitive search and <c>pg_advisory_xact_lock</c> for application locks.
/// Parameters get an explicit driver type, so <c>jsonb</c> and <c>timestamptz</c> columns accept them without casts.
/// </summary>
public sealed class PostgresDialect : SqlDialectBase
{
/// <summary>The shared instance.</summary>
public static PostgresDialect Instance { get; } = new();
/// <inheritdoc />
public override DbEngine Engine => DbEngine.PostgreSql;
/// <inheritdoc />
public override string CurrentTimestampUtc => "now()";
/// <inheritdoc />
public override SqlFragment CaseInsensitiveLike(SqlFragment column, SqlFragment pattern) =>
column + SqlFragment.Literal(" ILIKE ") + pattern + SqlFragment.Literal(" ESCAPE '\\'");
/// <inheritdoc />
public override SqlFragment AdvisoryLock(string key) => PostgresAdvisoryLocks.TransactionLock(key);
/// <inheritdoc />
public override object ToDbValue(object? value, ColumnType type)
{
if (value is null or DBNull)
{
return DBNull.Value;
}
return type switch
{
ColumnType.String or ColumnType.Text or ColumnType.Json => value as string ?? Convert.ToString(value, CultureInfo.InvariantCulture)!,
ColumnType.Int32 => value is Enum ? Convert.ToInt32(value, CultureInfo.InvariantCulture) : ConvertTo<int>(value),
ColumnType.Int64 => value is Enum ? Convert.ToInt64(value, CultureInfo.InvariantCulture) : ConvertTo<long>(value),
ColumnType.Decimal => ConvertTo<decimal>(value),
ColumnType.Bool => ConvertTo<bool>(value),
ColumnType.Date => ToDate(value),
ColumnType.DateTimeUtc => ToUtc(value),
ColumnType.Guid => value is Guid g ? g : Guid.Parse((string)value, CultureInfo.InvariantCulture),
ColumnType.Bytes => (byte[])value,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
/// <inheritdoc />
public override object? FromDbValue(object? value, ColumnType type)
{
if (value is null or DBNull)
{
return null;
}
return type switch
{
ColumnType.String or ColumnType.Text or ColumnType.Json => value as string ?? Convert.ToString(value, CultureInfo.InvariantCulture),
ColumnType.Int32 => ConvertTo<int>(value),
ColumnType.Int64 => ConvertTo<long>(value),
ColumnType.Decimal => ConvertTo<decimal>(value),
ColumnType.Bool => ConvertTo<bool>(value),
ColumnType.Date => ToDate(value),
ColumnType.DateTimeUtc => ToUtc(value),
ColumnType.Guid => value is Guid g ? g : Guid.Parse(Convert.ToString(value, CultureInfo.InvariantCulture)!, CultureInfo.InvariantCulture),
ColumnType.Bytes => (byte[])value,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
/// <inheritdoc />
public override string SqlType(ColumnType type, int? length, int? scale) => type switch
{
ColumnType.String => length is null ? "text" : string.Create(CultureInfo.InvariantCulture, $"varchar({length})"),
ColumnType.Text => "text",
ColumnType.Int32 => "integer",
ColumnType.Int64 => "bigint",
ColumnType.Decimal => string.Create(CultureInfo.InvariantCulture, $"numeric({ColumnTypes.DecimalPrecision},{scale ?? ColumnTypes.DecimalScale})"),
ColumnType.Bool => "boolean",
ColumnType.Date => "date",
ColumnType.DateTimeUtc => "timestamptz",
ColumnType.Guid => "uuid",
ColumnType.Bytes => "bytea",
ColumnType.Json => "jsonb",
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
/// <inheritdoc />
public override string Literal(object? value, ColumnType type) => value switch
{
bool b => b ? "TRUE" : "FALSE",
decimal d => d.ToString(CultureInfo.InvariantCulture),
_ => base.Literal(value, type),
};
/// <inheritdoc />
public override void ConfigureParameter(DbParameter parameter, object? value, ColumnType? type)
{
base.ConfigureParameter(parameter, value, type);
var logical = type ?? (value is null ? null : ColumnTypes.FromClrType(value.GetType()));
if (parameter is NpgsqlParameter npgsql && logical is not null)
{
npgsql.NpgsqlDbType = logical.Value switch
{
ColumnType.String or ColumnType.Text => NpgsqlDbType.Text,
ColumnType.Int32 => NpgsqlDbType.Integer,
ColumnType.Int64 => NpgsqlDbType.Bigint,
ColumnType.Decimal => NpgsqlDbType.Numeric,
ColumnType.Bool => NpgsqlDbType.Boolean,
ColumnType.Date => NpgsqlDbType.Date,
ColumnType.DateTimeUtc => NpgsqlDbType.TimestampTz,
ColumnType.Guid => NpgsqlDbType.Uuid,
ColumnType.Bytes => NpgsqlDbType.Bytea,
ColumnType.Json => NpgsqlDbType.Jsonb,
_ => npgsql.NpgsqlDbType,
};
}
}
}
@@ -0,0 +1,46 @@
using System.Globalization;
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// Yearly range partitioning for the large tables (SPEC §5.2: <c>gl_entry_lines</c>, <c>inventory_entry_lines</c>,
/// <c>audit_log</c>, <c>sys_log</c>). Prepared, not active: tables record their partition column with
/// <c>TableBuilder.PartitionByYear</c>; when one exceeds 50 million rows a migration (through
/// <c>ISchemaBuilder.Sql</c>) recreates it partitioned using these statements and moves the rows.
/// </summary>
public static class PostgresPartitioning
{
/// <summary>The clause that makes a <c>CREATE TABLE</c> partitioned by range of <paramref name="column"/>.</summary>
/// <param name="column">The date or timestamp column.</param>
/// <returns>The clause, starting with a space.</returns>
public static string PartitionClause(string column) => " PARTITION BY RANGE (" + PostgresDialect.Instance.Quote(column) + ")";
/// <summary>The name of the partition of a year, for example <c>gl_entry_lines_2026</c>.</summary>
/// <param name="table">The partitioned table.</param>
/// <param name="year">The year.</param>
/// <returns>The partition name.</returns>
public static string PartitionName(string table, int year) => table + "_" + year.ToString(CultureInfo.InvariantCulture);
/// <summary>The statement creating the partition of one year if it does not exist.</summary>
/// <param name="table">The partitioned table.</param>
/// <param name="year">The year.</param>
/// <returns>The statement.</returns>
public static string CreateYearPartition(string table, int year)
{
ArgumentOutOfRangeException.ThrowIfLessThan(year, 1900);
ArgumentOutOfRangeException.ThrowIfGreaterThan(year, 9998);
var dialect = PostgresDialect.Instance;
return string.Create(
CultureInfo.InvariantCulture,
$"CREATE TABLE IF NOT EXISTS {dialect.Quote(PartitionName(table, year))} PARTITION OF {dialect.Quote(table)} FOR VALUES FROM ('{year:D4}-01-01') TO ('{year + 1:D4}-01-01')");
}
/// <summary>The statement creating the default partition, for rows outside the yearly ones.</summary>
/// <param name="table">The partitioned table.</param>
/// <returns>The statement.</returns>
public static string CreateDefaultPartition(string table)
{
var dialect = PostgresDialect.Instance;
return $"CREATE TABLE IF NOT EXISTS {dialect.Quote(table + "_default")} PARTITION OF {dialect.Quote(table)} DEFAULT";
}
}
@@ -0,0 +1,116 @@
using System.Data.Common;
using System.Globalization;
using Khaemhat.Data.Schema;
using Npgsql;
namespace Khaemhat.Data.PostgreSql;
/// <summary>Settings of the PostgreSQL provider (SPEC §5.2), from the instance settings.</summary>
public sealed record PostgresProviderOptions
{
/// <summary>Maximum pooled connections per database (each database has its own pool).</summary>
public int MaxPoolSize { get; init; } = 20;
/// <summary>Server-side limit of a statement (<c>statement_timeout</c> of every session).</summary>
public TimeSpan StatementTimeout { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>The application name shown in <c>pg_stat_activity</c>.</summary>
public string ApplicationName { get; init; } = "khaemhat";
}
/// <summary>
/// The PostgreSQL engine (SPEC §1.3, §5.2), version 16 or later: one connection pool per database, a statement timeout
/// per session, databases created with <c>CREATE DATABASE</c> on the server (the role needs <c>CREATEDB</c>).
/// </summary>
/// <param name="options">The provider settings.</param>
public sealed class PostgresProvider(PostgresProviderOptions options) : IDbProvider
{
/// <summary>The oldest supported major version.</summary>
public const int MinimumMajorVersion = 16;
/// <summary>Creates the provider with default settings.</summary>
public PostgresProvider()
: this(new PostgresProviderOptions())
{
}
/// <inheritdoc />
public DbEngine Engine => DbEngine.PostgreSql;
/// <inheritdoc />
public ISqlDialect Dialect => PostgresDialect.Instance;
/// <inheritdoc />
public DdlGenerator Ddl { get; } = new PostgresSchemaBuilder();
/// <summary>The settings.</summary>
public PostgresProviderOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options));
/// <inheritdoc />
public string BuildConnectionString(DatabaseUrl url)
{
ArgumentNullException.ThrowIfNull(url);
if (url.Engine != DbEngine.PostgreSql)
{
throw new ArgumentException("Not a PostgreSQL URL.", nameof(url));
}
var builder = new NpgsqlConnectionStringBuilder
{
Host = url.Host,
Port = url.Port ?? 5432,
Username = url.UserName,
Password = url.Password,
Database = url.Database.Length == 0 ? "postgres" : url.Database,
MaxPoolSize = Options.MaxPoolSize,
ApplicationName = Options.ApplicationName,
Options = string.Create(CultureInfo.InvariantCulture, $"-c statement_timeout={(long)Options.StatementTimeout.TotalMilliseconds}"),
};
foreach (var (key, value) in url.Options)
{
try
{
builder[key] = value;
}
catch (ArgumentException)
{
throw new FormatException($"The PostgreSQL URL option '{key}' is not supported.");
}
}
return builder.ToString();
}
/// <inheritdoc />
public DbConnection CreateConnection(string connectionString) => new NpgsqlConnection(connectionString);
/// <inheritdoc />
public Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
PostgresDatabaseCreator.EnsureExistsAsync(connectionString, cancellationToken);
/// <inheritdoc />
public Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default) =>
PostgresDatabaseCreator.DropAsync(connectionString, cancellationToken);
/// <inheritdoc />
public Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
PostgresDatabaseCreator.ExistsAsync(connectionString, cancellationToken);
/// <inheritdoc />
public Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default) =>
PostgresServerInfo.ReadAsync(connectionString, cancellationToken);
/// <inheritdoc />
public bool IsTransient(Exception exception) => exception is NpgsqlException { IsTransient: true };
/// <inheritdoc />
public ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default) =>
ValueTask.FromResult<IAsyncDisposable>(NoScope.Instance);
private sealed class NoScope : IAsyncDisposable
{
public static NoScope Instance { get; } = new();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
@@ -0,0 +1,18 @@
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// DDL for PostgreSQL (SPEC §21 <c>PostgresSchemaBuilder</c>): identity keys are
/// <c>bigint GENERATED BY DEFAULT AS IDENTITY</c>, so restores and imports may still write explicit ids.
/// </summary>
public sealed class PostgresSchemaBuilder() : DdlGenerator(PostgresDialect.Instance)
{
/// <inheritdoc />
protected override string IdentityPrimaryKey(ColumnDefinition column)
{
ArgumentNullException.ThrowIfNull(column);
var type = column.Type == ColumnType.Int32 ? "integer" : "bigint";
return Dialect.Quote(column.Name) + " " + type + " GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY";
}
}
@@ -0,0 +1,59 @@
using System.Globalization;
using Npgsql;
namespace Khaemhat.Data.PostgreSql;
/// <summary>Reads version, role, connections, size and extensions of a PostgreSQL database (SPEC §12.1).</summary>
public static class PostgresServerInfo
{
private const string Query = """
SELECT current_setting('server_version'),
current_setting('server_version_num')::int,
current_database(),
pg_database_size(current_database()),
current_user,
(SELECT rolcreatedb FROM pg_roles WHERE rolname = current_user),
(SELECT numbackends FROM pg_stat_database WHERE datname = current_database()),
current_setting('max_connections')::int,
(SELECT coalesce(string_agg(extname || ' ' || extversion, ',' ORDER BY extname), '') FROM pg_extension)
""";
/// <summary>Reads the information.</summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The information, with a warning below version 16 and when the role cannot create databases.</returns>
public static async Task<DbServerInfo> ReadAsync(string connectionString, CancellationToken cancellationToken = default)
{
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
await using var command = new NpgsqlCommand(Query, connection);
await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
var versionNumber = reader.GetInt32(1);
var canCreate = !reader.IsDBNull(5) && reader.GetBoolean(5);
var warnings = new List<string>();
if (versionNumber / 10000 < PostgresProvider.MinimumMajorVersion)
{
warnings.Add(string.Create(
CultureInfo.InvariantCulture,
$"PostgreSQL {reader.GetString(0)} is older than {PostgresProvider.MinimumMajorVersion}, the oldest supported version; upgrade it (17 is recommended)."));
}
if (!canCreate)
{
warnings.Add($"The role {reader.GetString(4)} has no CREATEDB: new company databases must be created by an administrator.");
}
var extensions = reader.GetString(8);
return new DbServerInfo(DbEngine.PostgreSql, reader.GetString(0), versionNumber, reader.GetString(2), reader.GetInt64(3))
{
UserName = reader.GetString(4),
CanCreateDatabases = canCreate,
ActiveConnections = reader.IsDBNull(6) ? null : reader.GetInt32(6),
MaxConnections = reader.GetInt32(7),
Details = extensions.Length == 0 ? [] : extensions.Split(','),
Warnings = warnings,
};
}
}
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>Khaemhat.Data.Sqlite</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" />
</ItemGroup>
</Project>
@@ -0,0 +1,39 @@
namespace Khaemhat.Data.Sqlite;
/// <summary>
/// SQLite has no exact decimal type: <c>Decimal(19,6)</c> values are stored as integers multiplied by 10⁶ (SPEC §5.2).
/// Sums in SQL therefore stay exact integers and are scaled back when read. Values are rounded to 6 decimals half
/// away from zero, like PostgreSQL <c>numeric(19,6)</c>. The usable range is ±9.2 x 10¹².
/// </summary>
public static class SqliteDecimalConverter
{
/// <summary>The scale factor, 10⁶.</summary>
public const long Factor = 1_000_000;
/// <summary>The largest absolute value that can be stored.</summary>
public static readonly decimal MaxValue = long.MaxValue / (decimal)Factor;
/// <summary>Converts a decimal to its scaled integer.</summary>
/// <param name="value">The value.</param>
/// <returns>The scaled integer.</returns>
/// <exception cref="OverflowException">The value is beyond ±9.2 x 10¹².</exception>
public static long ToScaled(decimal value)
{
var scaled = decimal.Round(value * Factor, 0, MidpointRounding.AwayFromZero);
return scaled is > long.MaxValue or < long.MinValue
? throw new OverflowException($"The amount exceeds the SQLite decimal range of ±{MaxValue:N0}.")
: (long)scaled;
}
/// <summary>Converts a scaled integer (or a scaled sum read as integer or real) back to a decimal.</summary>
/// <param name="value">The stored value.</param>
/// <returns>The decimal.</returns>
public static decimal FromScaled(object value) => value switch
{
long l => (decimal)l / Factor,
int i => (decimal)i / Factor,
double d => (decimal)d / Factor,
decimal m => m / Factor,
_ => throw new InvalidCastException($"A {value.GetType().Name} is not a scaled SQLite decimal."),
};
}
+99
View File
@@ -0,0 +1,99 @@
using System.Globalization;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.Sqlite;
/// <summary>
/// The SQLite dialect (SPEC §5.2): <c>STRICT</c> tables with <c>TEXT</c>, <c>INTEGER</c> and <c>BLOB</c>; decimals as
/// integers x10⁶, dates <c>yyyy-MM-dd</c>, timestamps ISO 8601 UTC with microseconds, booleans 0/1, GUIDs as text.
/// Case-insensitive search uses the <c>kh_lower</c> function registered on every connection, which lowers Unicode text
/// (SQLite's own <c>LIKE</c> and <c>lower</c> only fold ASCII).
/// </summary>
public sealed class SqliteDialect : SqlDialectBase
{
/// <summary>The format of stored timestamps: fixed width, so text order is time order.</summary>
public const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'";
/// <summary>The name of the Unicode lower-case function registered on connections.</summary>
public const string LowerFunction = "kh_lower";
/// <summary>The shared instance.</summary>
public static SqliteDialect Instance { get; } = new();
/// <inheritdoc />
public override DbEngine Engine => DbEngine.Sqlite;
/// <inheritdoc />
public override string CurrentTimestampUtc => "strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')";
/// <inheritdoc />
public override SqlFragment CaseInsensitiveLike(SqlFragment column, SqlFragment pattern) =>
SqlFragment.Literal(LowerFunction + "(") + column + SqlFragment.Literal(") LIKE " + LowerFunction + "(") + pattern
+ SqlFragment.Literal(") ESCAPE '\\'");
/// <inheritdoc />
public override SqlFragment AdvisoryLock(string key) => SqlFragment.Empty;
/// <inheritdoc />
public override object ToDbValue(object? value, ColumnType type)
{
if (value is null or DBNull)
{
return DBNull.Value;
}
return type switch
{
ColumnType.String or ColumnType.Text or ColumnType.Json => value as string ?? Convert.ToString(value, CultureInfo.InvariantCulture)!,
ColumnType.Int32 or ColumnType.Int64 => value is Enum ? Convert.ToInt64(value, CultureInfo.InvariantCulture) : ConvertTo<long>(value),
ColumnType.Decimal => SqliteDecimalConverter.ToScaled(ConvertTo<decimal>(value)),
ColumnType.Bool => ConvertTo<bool>(value) ? 1L : 0L,
ColumnType.Date => ToDate(value).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
ColumnType.DateTimeUtc => ToUtc(value).ToString(TimestampFormat, CultureInfo.InvariantCulture),
ColumnType.Guid => (value is Guid g ? g : Guid.Parse((string)value, CultureInfo.InvariantCulture)).ToString("D"),
ColumnType.Bytes => (byte[])value,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
/// <inheritdoc />
public override object? FromDbValue(object? value, ColumnType type)
{
if (value is null or DBNull)
{
return null;
}
return type switch
{
ColumnType.String or ColumnType.Text or ColumnType.Json => value as string ?? Convert.ToString(value, CultureInfo.InvariantCulture),
ColumnType.Int32 => ConvertTo<int>(value),
ColumnType.Int64 => ConvertTo<long>(value),
ColumnType.Decimal => SqliteDecimalConverter.FromScaled(value),
ColumnType.Bool => ConvertTo<long>(value) != 0,
ColumnType.Date => ToDate(value),
ColumnType.DateTimeUtc => value is string s
? DateTime.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal)
: ToUtc(value),
ColumnType.Guid => value is Guid g ? g : Guid.Parse((string)value, CultureInfo.InvariantCulture),
ColumnType.Bytes => (byte[])value,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
/// <inheritdoc />
public override string SqlType(ColumnType type, int? length, int? scale) => type switch
{
ColumnType.Int32 or ColumnType.Int64 or ColumnType.Decimal or ColumnType.Bool => "INTEGER",
ColumnType.Bytes => "BLOB",
_ => "TEXT",
};
/// <inheritdoc />
public override string Literal(object? value, ColumnType type) => value switch
{
bool b => b ? "1" : "0",
decimal d when type == ColumnType.Decimal => SqliteDecimalConverter.ToScaled(d).ToString(CultureInfo.InvariantCulture),
_ => base.Literal(value, type),
};
}
+145
View File
@@ -0,0 +1,145 @@
using System.Data;
using System.Data.Common;
using System.Globalization;
using Khaemhat.Data.Schema;
using Microsoft.Data.Sqlite;
namespace Khaemhat.Data.Sqlite;
/// <summary>
/// The SQLite engine (SPEC §1.3, §5.2): tests, demo, trial and read-only archives. Every connection gets
/// <c>foreign_keys=ON</c> and <c>busy_timeout=5000</c>; file databases use <c>journal_mode=WAL</c>. Databases are files
/// under <c>KHAEMHAT_DATA_DIR</c>, or in-memory databases shared by the connections of the process (tests).
/// </summary>
public sealed class SqliteProvider : IDbProvider
{
private const int BusyTimeoutMilliseconds = 5000;
/// <inheritdoc />
public DbEngine Engine => DbEngine.Sqlite;
/// <inheritdoc />
public ISqlDialect Dialect => SqliteDialect.Instance;
/// <inheritdoc />
public DdlGenerator Ddl { get; } = new SqliteSchemaBuilder();
/// <inheritdoc />
public string BuildConnectionString(DatabaseUrl url)
{
ArgumentNullException.ThrowIfNull(url);
if (url.Engine != DbEngine.Sqlite)
{
throw new ArgumentException("Not a SQLite URL.", nameof(url));
}
var builder = url.IsInMemory
? new SqliteConnectionStringBuilder { DataSource = url.Database, Mode = SqliteOpenMode.Memory, Cache = SqliteCacheMode.Shared }
: new SqliteConnectionStringBuilder { DataSource = Path.GetFullPath(url.Database), Mode = SqliteOpenMode.ReadWriteCreate };
builder.Pooling = true;
builder.DefaultTimeout = 30;
return builder.ToString();
}
/// <inheritdoc />
public DbConnection CreateConnection(string connectionString)
{
var connection = new SqliteConnection(connectionString);
connection.CreateFunction<string?, string?>(SqliteDialect.LowerFunction, static s => s?.ToLowerInvariant(), isDeterministic: true);
var isFile = IsFile(connectionString);
connection.StateChange += (sender, args) =>
{
if (args.CurrentState == ConnectionState.Open && sender is SqliteConnection open)
{
ApplyPragmas(open, isFile);
}
};
return connection;
}
/// <inheritdoc />
public async Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default)
{
if (!IsFile(connectionString))
{
return;
}
var path = new SqliteConnectionStringBuilder(connectionString).DataSource;
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
await using var connection = CreateConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default)
{
if (!IsFile(connectionString))
{
return Task.CompletedTask;
}
using (var connection = new SqliteConnection(connectionString))
{
SqliteConnection.ClearPool(connection);
}
var path = new SqliteConnectionStringBuilder(connectionString).DataSource;
foreach (var file in new[] { path, path + "-wal", path + "-shm", path + "-journal" })
{
File.Delete(file);
}
return Task.CompletedTask;
}
/// <inheritdoc />
public Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
Task.FromResult(!IsFile(connectionString) || File.Exists(new SqliteConnectionStringBuilder(connectionString).DataSource));
/// <inheritdoc />
public async Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default)
{
await using var connection = CreateConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
var version = (string)(await ScalarAsync(connection, "SELECT sqlite_version()", cancellationToken).ConfigureAwait(false))!;
var pages = Convert.ToInt64(await ScalarAsync(connection, "PRAGMA page_count", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
var pageSize = Convert.ToInt64(await ScalarAsync(connection, "PRAGMA page_size", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
var journal = Convert.ToString(await ScalarAsync(connection, "PRAGMA journal_mode", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
var parts = version.Split('.').Select(p => int.Parse(p, CultureInfo.InvariantCulture)).Concat([0, 0, 0]).ToArray();
var source = new SqliteConnectionStringBuilder(connectionString).DataSource;
return new DbServerInfo(
DbEngine.Sqlite, version, (parts[0] * 1_000_000) + (parts[1] * 1_000) + parts[2],
IsFile(connectionString) ? Path.GetFileNameWithoutExtension(source) : source, pages * pageSize)
{
Details = ["journal_mode=" + journal],
};
}
/// <inheritdoc />
public bool IsTransient(Exception exception) =>
exception is SqliteException { SqliteErrorCode: 5 or 6 }; // SQLITE_BUSY, SQLITE_LOCKED
/// <inheritdoc />
public ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default) =>
SqliteWriteLock.AcquireAsync(new SqliteConnectionStringBuilder(connectionString).DataSource, cancellationToken);
private static bool IsFile(string connectionString) =>
new SqliteConnectionStringBuilder(connectionString).Mode != SqliteOpenMode.Memory;
private static void ApplyPragmas(SqliteConnection connection, bool isFile)
{
using var command = connection.CreateCommand();
command.CommandText = isFile
? $"PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMilliseconds};"
: $"PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMilliseconds};";
command.ExecuteNonQuery();
}
private static async Task<object?> ScalarAsync(DbConnection connection, string sql, CancellationToken cancellationToken)
{
await using var command = connection.CreateCommand();
command.CommandText = sql;
return await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,34 @@
using System.Globalization;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.Sqlite;
/// <summary>
/// DDL for SQLite (SPEC §21 <c>SqliteSchemaBuilder</c>): <c>STRICT</c> tables, <c>INTEGER PRIMARY KEY</c> for identity
/// keys, and <c>CHECK</c> constraints that give text lengths and booleans the same limits as on PostgreSQL.
/// </summary>
public sealed class SqliteSchemaBuilder() : DdlGenerator(SqliteDialect.Instance)
{
/// <inheritdoc />
protected override string TableOptions(TableDefinition table) => " STRICT";
/// <inheritdoc />
protected override string IdentityPrimaryKey(ColumnDefinition column)
{
ArgumentNullException.ThrowIfNull(column);
return Dialect.Quote(column.Name) + " INTEGER PRIMARY KEY";
}
/// <inheritdoc />
protected override string ColumnConstraints(ColumnDefinition column)
{
ArgumentNullException.ThrowIfNull(column);
var name = Dialect.Quote(column.Name);
return column.Type switch
{
ColumnType.String => string.Create(CultureInfo.InvariantCulture, $" CHECK (length({name}) <= {column.Length})"),
ColumnType.Bool => $" CHECK ({name} IN (0, 1))",
_ => string.Empty,
};
}
}
@@ -0,0 +1,41 @@
using System.Collections.Concurrent;
namespace Khaemhat.Data.Sqlite;
/// <summary>
/// Serializes the writers of one SQLite database inside the process (SPEC §5.2). SQLite allows a single writer; waiting
/// here is fairer and cheaper than retrying on <c>SQLITE_BUSY</c>. Other processes are kept out by
/// <c>BEGIN IMMEDIATE</c> and <c>busy_timeout</c>. Do not open a second writing unit of work on the same database while
/// holding one in the same flow: it would wait for itself.
/// </summary>
public static class SqliteWriteLock
{
private static readonly ConcurrentDictionary<string, SemaphoreSlim> Locks = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Waits for the write lock of a database.</summary>
/// <param name="database">The database key: full file path, or the in-memory name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The held lock; dispose it to release.</returns>
public static async ValueTask<IAsyncDisposable> AcquireAsync(string database, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(database);
var semaphore = Locks.GetOrAdd(database, static _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
return new Releaser(semaphore);
}
private sealed class Releaser(SemaphoreSlim semaphore) : IAsyncDisposable
{
private int _released;
public ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _released, 1) == 0)
{
semaphore.Release();
}
return ValueTask.CompletedTask;
}
}
}
@@ -0,0 +1,200 @@
using System.Collections.Concurrent;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data.Execution;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Querying;
namespace Khaemhat.Data.Companies;
/// <summary>A company to add to the registry.</summary>
/// <param name="Code">The company code.</param>
/// <param name="Name">The company name.</param>
/// <param name="Database">Where its database is (printed redacted).</param>
/// <param name="IsDefault">Whether it becomes the default company.</param>
/// <param name="Notes">Notes for administrators.</param>
public sealed record CompanyRegistration(string Code, string Name, DatabaseUrl Database, bool IsDefault = false, string? Notes = null);
/// <summary>
/// The company registry in the system database (SPEC §5.4): it resolves <c>company code → (provider, connection
/// string)</c>, decrypting the location stored in <c>sys_companies</c>.
/// </summary>
public interface ICompanyRegistry
{
/// <summary>All companies, by code.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The companies (their location stays encrypted).</returns>
Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default);
/// <summary>A company by code.</summary>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The company, or <see langword="null"/>.</returns>
Task<Company?> FindAsync(string code, CancellationToken cancellationToken = default);
/// <summary>Adds a company whose database already exists or will be created by the caller.</summary>
/// <param name="registration">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The stored company.</returns>
Task<Company> RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default);
/// <summary>The database of a company.</summary>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The target.</returns>
/// <exception cref="KeyNotFoundException">No company has that code.</exception>
Task<DatabaseTarget> ResolveAsync(string code, CancellationToken cancellationToken = default);
/// <summary>Changes the state of a company.</summary>
/// <param name="code">The code.</param>
/// <param name="status">The new state.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default);
}
/// <summary>
/// <see cref="ICompanyRegistry"/> on <c>sys_companies</c>. The database URL is encrypted with
/// <see cref="ISecretProtector"/> for the purpose <c>company:&lt;code&gt;:database</c>, so a row copied to another company
/// cannot be decrypted. Resolved targets are cached until the row changes through this registry.
/// </summary>
public sealed class CompanyRegistry : ICompanyRegistry
{
private readonly DatabaseTarget _system;
private readonly DbProviderCatalog _providers;
private readonly ISecretProtector _protector;
private readonly MapRegistry _maps;
private readonly DataAccessContext _context;
private readonly ConcurrentDictionary<string, DatabaseTarget> _resolved = new(StringComparer.Ordinal);
/// <summary>Creates the registry.</summary>
/// <param name="system">The system database.</param>
/// <param name="providers">The providers by engine.</param>
/// <param name="protector">Encrypts the database locations.</param>
/// <param name="maps">The entity maps, including <see cref="SystemDatabase.CompanyMap"/>.</param>
/// <param name="context">Clock, user and retry policy.</param>
public CompanyRegistry(DatabaseTarget system, DbProviderCatalog providers, ISecretProtector protector, MapRegistry maps, DataAccessContext context)
{
ArgumentNullException.ThrowIfNull(system);
ArgumentNullException.ThrowIfNull(providers);
ArgumentNullException.ThrowIfNull(protector);
ArgumentNullException.ThrowIfNull(maps);
ArgumentNullException.ThrowIfNull(context);
_system = system;
_providers = providers;
_protector = protector;
_maps = maps;
_context = context;
}
/// <summary>The purpose used to encrypt the database location of a company.</summary>
/// <param name="code">The normalized code.</param>
/// <returns>The purpose.</returns>
public static string Purpose(string code) => "company:" + code + ":database";
/// <inheritdoc />
public async Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
var page = await unitOfWork.Repository<Company, long>().ListAsync(Query.For<Company>().OrderBy(c => c.Code), cancellationToken).ConfigureAwait(false);
return page.Items;
}
/// <inheritdoc />
public async Task<Company?> FindAsync(string code, CancellationToken cancellationToken = default)
{
var normalized = CompanyCodes.Normalize(code);
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<Company, long>().FindAsync(Query.For<Company>().Where(c => c.Code == normalized), cancellationToken)
.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<Company> RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(registration);
ArgumentException.ThrowIfNullOrWhiteSpace(registration.Name);
var code = CompanyCodes.Normalize(registration.Code);
_ = _providers.Get(registration.Database.Engine);
var company = new Company
{
Code = code,
Name = registration.Name.Trim(),
Engine = registration.Database.Engine.ToString(),
ConnectionString = _protector.Protect(registration.Database.ToUnredactedString(), Purpose(code)),
Status = CompanyStatus.Active,
IsDefault = registration.IsDefault,
Notes = registration.Notes,
};
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
var companies = unitOfWork.Repository<Company, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await companies.CountAsync(Query.For<Company>().Where(c => c.Code == code), ct).ConfigureAwait(false) > 0)
{
throw new InvalidOperationException($"A company with code {code} already exists.");
}
if (company.IsDefault)
{
await unitOfWork.ExecuteAsync(
SqlFragment.Of($"UPDATE {SqlFragment.Identifier("sys_companies")} SET is_default = {false} WHERE is_default = {true}"), ct)
.ConfigureAwait(false);
}
await companies.InsertAsync(company, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
_resolved.TryRemove(code, out _);
return company;
}
/// <inheritdoc />
public async Task<DatabaseTarget> ResolveAsync(string code, CancellationToken cancellationToken = default)
{
var normalized = CompanyCodes.Normalize(code);
if (_resolved.TryGetValue(normalized, out var cached))
{
return cached;
}
var company = await FindAsync(normalized, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException($"No company has code {normalized}.");
var url = DatabaseUrl.Parse(_protector.Unprotect(company.ConnectionString, Purpose(normalized)));
var target = _providers.Resolve(url);
_resolved[normalized] = target;
return target;
}
/// <inheritdoc />
public async Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default)
{
var normalized = CompanyCodes.Normalize(code);
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
var companies = unitOfWork.Repository<Company, long>();
var company = await companies.FindAsync(Query.For<Company>().Where(c => c.Code == normalized), cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException($"No company has code {normalized}.");
company.Status = status;
await companies.UpdateAsync(company, cancellationToken).ConfigureAwait(false);
_resolved.TryRemove(normalized, out _);
}
private Task<UnitOfWork> OpenAsync(CancellationToken cancellationToken) => UnitOfWork.OpenAsync(_system, _maps, _context, cancellationToken);
}
/// <summary>Finds the system database, or a company database through the registry.</summary>
/// <param name="system">The system database.</param>
/// <param name="companies">The company registry.</param>
public sealed class DatabaseLocator(DatabaseTarget system, ICompanyRegistry companies) : IDatabaseLocator
{
/// <inheritdoc />
public async ValueTask<DatabaseTarget> LocateAsync(DatabaseScope scope, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(scope);
return scope.IsSystem ? system : await companies.ResolveAsync(scope.CompanyCode!, cancellationToken).ConfigureAwait(false);
}
}
+43
View File
@@ -0,0 +1,43 @@
using System.Text.RegularExpressions;
namespace Khaemhat.Data;
/// <summary>
/// Rules for company codes and the names of their databases (SPEC §5.4): the code is 1 to 20 upper-case letters,
/// digits or underscores starting with a letter; the database is <c>khaemhat_&lt;code in lower case&gt;</c>.
/// </summary>
public static partial class CompanyCodes
{
/// <summary>The prefix of every company database name.</summary>
public const string DatabasePrefix = "khaemhat_";
/// <summary>Whether <paramref name="code"/> (already normalized) is a valid company code.</summary>
/// <param name="code">The code.</param>
/// <returns><see langword="true"/> if valid.</returns>
public static bool IsValid(string? code) => code is not null && CodePattern().IsMatch(code);
/// <summary>Trims and upper-cases a code, then validates it.</summary>
/// <param name="code">The code as typed.</param>
/// <returns>The normalized code.</returns>
/// <exception cref="ArgumentException">The code is not valid.</exception>
public static string Normalize(string code)
{
ArgumentNullException.ThrowIfNull(code);
var normalized = code.Trim().ToUpperInvariant();
if (!IsValid(normalized))
{
throw new ArgumentException(
"A company code has 1 to 20 characters: letters, digits or underscore, starting with a letter.", nameof(code));
}
return normalized;
}
/// <summary>The database name of a company, for example <c>khaemhat_demo</c> for <c>DEMO</c>.</summary>
/// <param name="code">The company code.</param>
/// <returns>The database name.</returns>
public static string DatabaseName(string code) => DatabasePrefix + Normalize(code).ToLowerInvariant();
[GeneratedRegex("^[A-Z][A-Z0-9_]{0,19}$", RegexOptions.CultureInvariant)]
private static partial Regex CodePattern();
}
+26
View File
@@ -0,0 +1,26 @@
namespace Khaemhat.Data;
/// <summary>
/// Which database a unit of work opens (SPEC §5.4): the instance system database or the database of one company.
/// </summary>
public sealed record DatabaseScope
{
private DatabaseScope(string? companyCode) => CompanyCode = companyCode;
/// <summary>The system database (<c>KHAEMHAT_SYSTEM_DB</c>).</summary>
public static DatabaseScope System { get; } = new((string?)null);
/// <summary>The company code, or <see langword="null"/> for the system database.</summary>
public string? CompanyCode { get; }
/// <summary>Whether this is the system database.</summary>
public bool IsSystem => CompanyCode is null;
/// <summary>The database of the company with the given code.</summary>
/// <param name="code">The company code (case-insensitive; stored upper-case).</param>
/// <returns>The scope.</returns>
public static DatabaseScope Company(string code) => new(CompanyCodes.Normalize(code));
/// <inheritdoc />
public override string ToString() => CompanyCode is null ? "system" : "company " + CompanyCode;
}
+36
View File
@@ -0,0 +1,36 @@
namespace Khaemhat.Data;
/// <summary>
/// A database ready to be opened: its provider and driver connection string. <see cref="ToString"/> shows only the
/// engine and the database name, never the connection string.
/// </summary>
public sealed class DatabaseTarget
{
/// <summary>Creates a target.</summary>
/// <param name="provider">The provider.</param>
/// <param name="connectionString">The driver connection string.</param>
/// <param name="databaseName">The database name, for messages.</param>
public DatabaseTarget(IDbProvider provider, string connectionString, string databaseName)
{
ArgumentNullException.ThrowIfNull(provider);
ArgumentException.ThrowIfNullOrEmpty(connectionString);
Provider = provider;
ConnectionString = connectionString;
DatabaseName = databaseName ?? string.Empty;
}
/// <summary>The provider.</summary>
public IDbProvider Provider { get; }
/// <summary>The driver connection string. It contains credentials: never log it.</summary>
public string ConnectionString { get; }
/// <summary>The database name.</summary>
public string DatabaseName { get; }
/// <summary>The engine.</summary>
public DbEngine Engine => Provider.Engine;
/// <inheritdoc />
public override string ToString() => Engine + " " + DatabaseName;
}
+259
View File
@@ -0,0 +1,259 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Data;
/// <summary>
/// A database location in URL form, as given by <c>KHAEMHAT_SYSTEM_DB</c>, <c>KHAEMHAT_DB_SERVER</c> and the company
/// registry (SPEC §6):
/// <list type="bullet">
/// <item><c>postgres://user:password@host:5432/database?sslmode=require</c> (also <c>postgresql://</c>; the database
/// may be empty for a server URL);</item>
/// <item><c>sqlite:///absolute/path/file.db</c> (on Windows <c>sqlite:///C:/path/file.db</c>);</item>
/// <item><c>sqlite://memory/name</c>, an in-memory database shared by the connections of the process (tests).</item>
/// </list>
/// <see cref="ToString"/> never shows the password; parsing errors never echo the input.
/// </summary>
public sealed class DatabaseUrl
{
private const string SqliteMemoryPrefix = "sqlite://memory/";
private DatabaseUrl(
DbEngine engine, string database, string? host, int? port, string? userName, string? password,
IReadOnlyDictionary<string, string> options, bool isInMemory)
{
Engine = engine;
Database = database;
Host = host;
Port = port;
UserName = userName;
Password = password;
Options = options;
IsInMemory = isInMemory;
}
/// <summary>The engine.</summary>
public DbEngine Engine { get; }
/// <summary>
/// PostgreSQL: the database name (empty for a server URL). SQLite: the file path, or the name of the in-memory database.
/// </summary>
public string Database { get; }
/// <summary>PostgreSQL host.</summary>
public string? Host { get; }
/// <summary>PostgreSQL port, when given.</summary>
public int? Port { get; }
/// <summary>PostgreSQL user.</summary>
public string? UserName { get; }
/// <summary>PostgreSQL password. Never printed by <see cref="ToString"/>.</summary>
public string? Password { get; }
/// <summary>Query-string options, for example <c>sslmode</c>.</summary>
public IReadOnlyDictionary<string, string> Options { get; }
/// <summary>Whether this is an in-memory SQLite database.</summary>
public bool IsInMemory { get; }
/// <summary>
/// The short database name: the PostgreSQL database, or the SQLite file name without extension (or the in-memory name).
/// </summary>
public string DatabaseName => Engine == DbEngine.PostgreSql || IsInMemory
? Database
: Path.GetFileNameWithoutExtension(Database);
/// <summary>Parses a database URL.</summary>
/// <param name="url">The URL.</param>
/// <returns>The parsed URL.</returns>
/// <exception cref="FormatException">The URL is not valid (the message does not repeat it).</exception>
public static DatabaseUrl Parse(string url)
{
ArgumentNullException.ThrowIfNull(url);
return TryParse(url, out var result, out var error) ? result : throw new FormatException(error);
}
/// <summary>Tries to parse a database URL.</summary>
/// <param name="url">The URL.</param>
/// <param name="result">The parsed URL.</param>
/// <returns><see langword="true"/> if the URL is valid.</returns>
public static bool TryParse(string? url, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out DatabaseUrl? result) =>
TryParse(url, out result, out _);
/// <summary>
/// The same server with another database: on PostgreSQL the database name changes; on SQLite the file
/// <c>&lt;name&gt;.db</c> in the same directory (or another in-memory database).
/// </summary>
/// <param name="databaseName">The database name, for example <c>khaemhat_demo</c>.</param>
/// <returns>The new URL.</returns>
public DatabaseUrl WithDatabase(string databaseName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(databaseName);
if (Engine == DbEngine.PostgreSql || IsInMemory)
{
return new DatabaseUrl(Engine, databaseName, Host, Port, UserName, Password, Options, IsInMemory);
}
var directory = Path.GetDirectoryName(Database) ?? string.Empty;
var path = directory.Length == 0 ? databaseName + ".db" : directory.Replace('\\', '/') + "/" + databaseName + ".db";
return new DatabaseUrl(Engine, path, Host, Port, UserName, Password, Options, IsInMemory);
}
/// <summary>
/// The complete URL including the password, for storing it encrypted. Never log or display the result.
/// </summary>
/// <returns>The URL.</returns>
public string ToUnredactedString() => Format(includePassword: true);
/// <summary>The URL with the password replaced by <c>***</c>.</summary>
/// <returns>The redacted URL.</returns>
public override string ToString() => Format(includePassword: false);
private string Format(bool includePassword)
{
if (Engine == DbEngine.Sqlite)
{
return IsInMemory ? SqliteMemoryPrefix + Database : "sqlite://" + (Database.StartsWith('/') ? Database : "/" + Database);
}
var builder = new StringBuilder("postgres://");
if (UserName is not null)
{
builder.Append(Uri.EscapeDataString(UserName));
if (Password is not null)
{
builder.Append(':').Append(includePassword ? Uri.EscapeDataString(Password) : "***");
}
builder.Append('@');
}
builder.Append(Host);
if (Port is not null)
{
builder.Append(':').Append(Port.Value.ToString(CultureInfo.InvariantCulture));
}
builder.Append('/').Append(Uri.EscapeDataString(Database));
var separator = '?';
foreach (var (key, value) in Options)
{
builder.Append(separator).Append(Uri.EscapeDataString(key)).Append('=').Append(Uri.EscapeDataString(value));
separator = '&';
}
return builder.ToString();
}
private static bool TryParse(string? url, out DatabaseUrl result, out string error)
{
result = null!;
url = url?.Trim();
if (string.IsNullOrEmpty(url))
{
error = "The database URL is empty.";
return false;
}
if (url.StartsWith("sqlite:", StringComparison.OrdinalIgnoreCase))
{
return TryParseSqlite(url, out result, out error);
}
if (url.StartsWith("postgres://", StringComparison.OrdinalIgnoreCase)
|| url.StartsWith("postgresql://", StringComparison.OrdinalIgnoreCase))
{
return TryParsePostgres(url, out result, out error);
}
error = "The database URL must start with postgres:// or sqlite://.";
return false;
}
private static bool TryParseSqlite(string url, out DatabaseUrl result, out string error)
{
result = null!;
var empty = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (url.StartsWith(SqliteMemoryPrefix, StringComparison.OrdinalIgnoreCase))
{
var name = url[SqliteMemoryPrefix.Length..];
if (name.Length == 0 || name.Any(c => !(char.IsAsciiLetterOrDigit(c) || c is '_' or '-')))
{
error = "An in-memory SQLite URL is sqlite://memory/<name> with letters, digits, '-' or '_'.";
return false;
}
result = new DatabaseUrl(DbEngine.Sqlite, name, null, null, null, null, empty, isInMemory: true);
error = string.Empty;
return true;
}
if (!url.StartsWith("sqlite:///", StringComparison.OrdinalIgnoreCase))
{
error = "A SQLite URL is sqlite:///<absolute path> (three slashes).";
return false;
}
var path = url["sqlite://".Length..].Replace('\\', '/');
// sqlite:///C:/data/x.db -> C:/data/x.db
if (path.Length >= 3 && path[0] == '/' && char.IsAsciiLetter(path[1]) && path[2] == ':')
{
path = path[1..];
}
if (path.Length < 2 || path.EndsWith('/'))
{
error = "The SQLite URL has no file name.";
return false;
}
result = new DatabaseUrl(DbEngine.Sqlite, path, null, null, null, null, empty, isInMemory: false);
error = string.Empty;
return true;
}
private static bool TryParsePostgres(string url, out DatabaseUrl result, out string error)
{
result = null!;
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || string.IsNullOrEmpty(uri.Host))
{
error = "The PostgreSQL URL is not valid: expected postgres://user:password@host:port/database.";
return false;
}
string? user = null;
string? password = null;
if (uri.UserInfo.Length > 0)
{
var parts = uri.UserInfo.Split(':', 2);
user = Uri.UnescapeDataString(parts[0]);
password = parts.Length == 2 ? Uri.UnescapeDataString(parts[1]) : null;
}
var database = Uri.UnescapeDataString(uri.AbsolutePath.Trim('/'));
if (database.Contains('/', StringComparison.Ordinal))
{
error = "The PostgreSQL URL path must be a single database name.";
return false;
}
var options = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var query = uri.Query.TrimStart('?');
if (query.Length > 0)
{
foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries))
{
var kv = pair.Split('=', 2);
options[Uri.UnescapeDataString(kv[0])] = kv.Length == 2 ? Uri.UnescapeDataString(kv[1]) : string.Empty;
}
}
result = new DatabaseUrl(
DbEngine.PostgreSql, database, uri.Host, uri.IsDefaultPort || uri.Port < 0 ? null : uri.Port, user, password,
options, isInMemory: false);
error = string.Empty;
return true;
}
}
+11
View File
@@ -0,0 +1,11 @@
namespace Khaemhat.Data;
/// <summary>The database engines Khaemhat supports (SPEC §1.3).</summary>
public enum DbEngine
{
/// <summary>SQLite: tests, demo, trial and read-only archives.</summary>
Sqlite = 0,
/// <summary>PostgreSQL 16 or later (17 recommended): real installations.</summary>
PostgreSql = 1,
}
+37
View File
@@ -0,0 +1,37 @@
namespace Khaemhat.Data;
/// <summary>The providers available to the instance, by engine. The web host registers SQLite and PostgreSQL.</summary>
public sealed class DbProviderCatalog
{
private readonly Dictionary<DbEngine, IDbProvider> _providers = [];
/// <summary>Creates a catalog with the given providers.</summary>
/// <param name="providers">The providers.</param>
public DbProviderCatalog(params IEnumerable<IDbProvider> providers)
{
ArgumentNullException.ThrowIfNull(providers);
foreach (var provider in providers)
{
_providers[provider.Engine] = provider;
}
}
/// <summary>The provider of an engine.</summary>
/// <param name="engine">The engine.</param>
/// <returns>The provider.</returns>
/// <exception cref="InvalidOperationException">No provider is registered for the engine.</exception>
public IDbProvider Get(DbEngine engine) =>
_providers.TryGetValue(engine, out var provider)
? provider
: throw new InvalidOperationException($"No database provider is registered for {engine}.");
/// <summary>The target for a database URL: its provider and connection string.</summary>
/// <param name="url">The URL.</param>
/// <returns>The target.</returns>
public DatabaseTarget Resolve(DatabaseUrl url)
{
ArgumentNullException.ThrowIfNull(url);
var provider = Get(url.Engine);
return new DatabaseTarget(provider, provider.BuildConnectionString(url), url.DatabaseName);
}
}
+28
View File
@@ -0,0 +1,28 @@
namespace Khaemhat.Data;
/// <summary>Information about a database and its server, for the system status page (SPEC §12.1).</summary>
/// <param name="Engine">The engine.</param>
/// <param name="Version">The server version as text, for example <c>17.2</c> or <c>3.46.1</c>.</param>
/// <param name="VersionNumber">The version as a number: PostgreSQL <c>server_version_num</c> (170002), SQLite (3046001).</param>
/// <param name="Database">The database name.</param>
/// <param name="SizeBytes">The database size in bytes, when known.</param>
public sealed record DbServerInfo(DbEngine Engine, string Version, int VersionNumber, string Database, long? SizeBytes)
{
/// <summary>The user the application connects as (PostgreSQL).</summary>
public string? UserName { get; init; }
/// <summary>Whether that user may create databases (PostgreSQL <c>CREATEDB</c>).</summary>
public bool? CanCreateDatabases { get; init; }
/// <summary>Open connections to this database (PostgreSQL).</summary>
public int? ActiveConnections { get; init; }
/// <summary>The server connection limit (PostgreSQL <c>max_connections</c>).</summary>
public int? MaxConnections { get; init; }
/// <summary>Installed extensions (PostgreSQL) or the journal mode (SQLite).</summary>
public IReadOnlyList<string> Details { get; init; } = [];
/// <summary>Problems to show to administrators, for example a PostgreSQL version below 16.</summary>
public IReadOnlyList<string> Warnings { get; init; } = [];
}
@@ -0,0 +1,90 @@
using System.Collections.Concurrent;
using System.Globalization;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.Execution;
/// <summary>The kinds of statements the repositories cache.</summary>
public enum CachedStatementKind
{
/// <summary><c>INSERT</c>, with <c>RETURNING</c> for identity keys.</summary>
Insert = 0,
/// <summary><c>UPDATE … WHERE key = … [AND row_version = …]</c>.</summary>
Update = 1,
/// <summary><c>DELETE … WHERE key = …</c>.</summary>
Delete = 2,
}
/// <summary>A cached statement: SQL text whose parameter <c>p{i}</c> takes the value of <see cref="Parameters"/>[i].</summary>
/// <param name="Text">The SQL text.</param>
/// <param name="Parameters">The columns whose values fill the parameters, in order.</param>
public sealed record CachedStatement(string Text, IReadOnlyList<ColumnMap> Parameters);
/// <summary>
/// The SQL text of the repository statements, built once per entity, statement and dialect and reused (SPEC §21,
/// <c>CommandCache</c>).
/// </summary>
public static class CommandCache
{
private static readonly ConcurrentDictionary<(Type Entity, CachedStatementKind Kind, DbEngine Engine), CachedStatement> Statements = new();
/// <summary>The statement of a kind for an entity map and dialect.</summary>
/// <param name="map">The entity map.</param>
/// <param name="kind">The statement kind.</param>
/// <param name="dialect">The dialect.</param>
/// <returns>The statement.</returns>
public static CachedStatement Get(IEntityMap map, CachedStatementKind kind, ISqlDialect dialect)
{
ArgumentNullException.ThrowIfNull(map);
ArgumentNullException.ThrowIfNull(dialect);
return Statements.GetOrAdd((map.EntityType, kind, dialect.Engine), _ => Build(map, kind, dialect));
}
private static CachedStatement Build(IEntityMap map, CachedStatementKind kind, ISqlDialect dialect)
{
string P(int index) => dialect.Parameter("p" + index.ToString(CultureInfo.InvariantCulture));
switch (kind)
{
case CachedStatementKind.Insert:
{
var columns = map.Columns.Where(c => !(c.IsKey && c.IsIdentity)).ToList();
var names = columns.Select(c => c.ColumnName).ToList();
var placeholders = columns.Select((_, i) => P(i)).ToList();
var text = map.Key.IsIdentity
? dialect.InsertReturningId(map.Table, names, placeholders, map.Key.ColumnName)
: InsertOnly(dialect, map.Table, names, placeholders);
return new CachedStatement(text, columns);
}
case CachedStatementKind.Update:
{
var set = map.Columns
.Where(c => !c.IsKey && c.Audit is not (Mapping.AuditRole.CreatedAt or Mapping.AuditRole.CreatedBy or Mapping.AuditRole.RowVersion))
.ToList();
var assignments = set.Select((c, i) => dialect.Quote(c.ColumnName) + " = " + P(i)).ToList();
var parameters = new List<ColumnMap>(set) { map.Key };
var where = dialect.Quote(map.Key.ColumnName) + " = " + P(set.Count);
if (map.RowVersion is { } version)
{
assignments.Add(dialect.Quote(version.ColumnName) + " = " + dialect.Quote(version.ColumnName) + " + 1");
where += " AND " + dialect.Quote(version.ColumnName) + " = " + P(parameters.Count);
parameters.Add(version);
}
var text = "UPDATE " + dialect.Quote(map.Table) + " SET " + string.Join(", ", assignments) + " WHERE " + where;
return new CachedStatement(text, parameters);
}
case CachedStatementKind.Delete:
return new CachedStatement(
"DELETE FROM " + dialect.Quote(map.Table) + " WHERE " + dialect.Quote(map.Key.ColumnName) + " = " + P(0), [map.Key]);
default:
throw new ArgumentOutOfRangeException(nameof(kind), kind, null);
}
}
private static string InsertOnly(ISqlDialect dialect, string table, IReadOnlyList<string> columns, IReadOnlyList<string> placeholders) =>
"INSERT INTO " + dialect.Quote(table) + " (" + string.Join(", ", columns.Select(dialect.Quote)) + ") VALUES (" + string.Join(", ", placeholders) + ")";
}
@@ -0,0 +1,43 @@
namespace Khaemhat.Data.Execution;
/// <summary>
/// What the data layer needs from the running application: the clock for audit timestamps, the current user for
/// <c>created_by</c>/<c>updated_by</c>, and the retry policy. The web host builds it from <c>ICurrentUser</c> (M2).
/// </summary>
public sealed class DataAccessContext
{
private readonly Func<string?> _currentUser;
/// <summary>Creates a context.</summary>
/// <param name="clock">The clock.</param>
/// <param name="currentUser">Returns the current user name, or <see langword="null"/>.</param>
/// <param name="retryPolicy">The retry policy for transient errors outside transactions.</param>
public DataAccessContext(TimeProvider clock, Func<string?> currentUser, TransientRetryPolicy? retryPolicy = null)
{
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(currentUser);
Clock = clock;
_currentUser = currentUser;
RetryPolicy = retryPolicy ?? TransientRetryPolicy.Default;
}
/// <summary>System clock, no user, default retries.</summary>
public static DataAccessContext Default { get; } = new(TimeProvider.System, static () => null);
/// <summary>The clock.</summary>
public TimeProvider Clock { get; }
/// <summary>The retry policy.</summary>
public TransientRetryPolicy RetryPolicy { get; }
/// <summary>The current user name, or <see langword="null"/>.</summary>
public string? CurrentUser => _currentUser();
/// <summary>The current UTC time, truncated to microseconds (the precision of PostgreSQL and of SQLite storage).</summary>
public DateTime UtcNow => Truncate(Clock.GetUtcNow().UtcDateTime);
/// <summary>Truncates a timestamp to microseconds.</summary>
/// <param name="value">The timestamp.</param>
/// <returns>The truncated timestamp.</returns>
public static DateTime Truncate(DateTime value) => new(value.Ticks - (value.Ticks % 10), value.Kind);
}
+51
View File
@@ -0,0 +1,51 @@
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
namespace Khaemhat.Data.Execution;
/// <summary>
/// Creates driver commands from rendered SQL. This is the only place where command text is assigned: the text comes
/// from <see cref="SqlFragment.Render"/> or from the <see cref="CommandCache"/>, both built from code and mapped
/// names, and every value travels as a parameter.
/// </summary>
/// <param name="dialect">The dialect that configures parameters.</param>
public sealed class DbExecutor(ISqlDialect dialect)
{
/// <summary>Creates a command for a fragment.</summary>
/// <param name="connection">The open connection.</param>
/// <param name="transaction">The transaction, if any.</param>
/// <param name="sql">The fragment.</param>
/// <returns>The command; the caller disposes it.</returns>
public DbCommand CreateCommand(DbConnection connection, DbTransaction? transaction, SqlFragment sql)
{
ArgumentNullException.ThrowIfNull(sql);
var rendered = sql.Render(dialect);
return CreateCommand(connection, transaction, rendered.Text, rendered.Parameters);
}
/// <summary>Creates a command for rendered text and its parameters.</summary>
/// <param name="connection">The open connection.</param>
/// <param name="transaction">The transaction, if any.</param>
/// <param name="text">SQL text produced by the data layer.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>The command; the caller disposes it.</returns>
[SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities",
Justification = "Text comes only from SqlFragment rendering or the command cache; values are always parameters (SPEC §5.2).")]
public DbCommand CreateCommand(DbConnection connection, DbTransaction? transaction, string text, IEnumerable<SqlParameterValue> parameters)
{
ArgumentNullException.ThrowIfNull(connection);
ArgumentNullException.ThrowIfNull(parameters);
var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = text;
foreach (var parameter in parameters)
{
var dbParameter = command.CreateParameter();
dbParameter.ParameterName = parameter.Name;
dialect.ConfigureParameter(dbParameter, parameter.Value, parameter.Type);
command.Parameters.Add(dbParameter);
}
return command;
}
}
+154
View File
@@ -0,0 +1,154 @@
using System.Collections.Concurrent;
using System.Data.Common;
using System.Linq.Expressions;
using System.Reflection;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.Execution;
/// <summary>
/// Maps reader rows to objects (SPEC §21, <c>ReaderMapper&lt;T&gt;</c>). The plan for a type and a column layout is
/// built once and cached; rows are then mapped with compiled delegates. Supported targets:
/// <list type="bullet">
/// <item>scalars (numbers, text, dates, GUIDs, enums, nullable or not): the first column;</item>
/// <item>entities with a registered map: columns matched by column name;</item>
/// <item>other classes and records: settable properties, or the parameters of the public constructor, matched by
/// snake_case name.</item>
/// </list>
/// Values pass through <see cref="ISqlDialect.FromDbValue"/>, so for example scaled SQLite decimals (sums included)
/// come back as <see cref="decimal"/>.
/// </summary>
public static class ReaderMapper
{
private static readonly ConcurrentDictionary<(Type Type, DbEngine Engine, string Layout), Delegate> Plans = new();
/// <summary>The row mapper for <typeparamref name="T"/> and the columns of <paramref name="reader"/>.</summary>
/// <typeparam name="T">The target type.</typeparam>
/// <param name="reader">The reader, positioned before or on a row.</param>
/// <param name="dialect">The dialect.</param>
/// <param name="maps">The entity maps.</param>
/// <returns>A function mapping the current row.</returns>
public static Func<DbDataReader, T> For<T>(DbDataReader reader, ISqlDialect dialect, MapRegistry maps)
{
ArgumentNullException.ThrowIfNull(reader);
ArgumentNullException.ThrowIfNull(dialect);
ArgumentNullException.ThrowIfNull(maps);
var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();
var key = (typeof(T), dialect.Engine, string.Join('|', columns));
return (Func<DbDataReader, T>)Plans.GetOrAdd(key, _ => Build<T>(columns, dialect, maps));
}
private static Func<DbDataReader, T> Build<T>(string[] columns, ISqlDialect dialect, MapRegistry maps)
{
var target = typeof(T);
if (IsScalar(target))
{
var type = LogicalType(target);
return reader => (T)ClrConverter.ConvertTo(dialect.FromDbValue(reader.GetValue(0), type), target)!;
}
if (maps.Find(target) is { } map)
{
return BuildEntity<T>(columns, dialect, map);
}
var constructor = target.GetConstructor(Type.EmptyTypes);
return constructor is not null ? BuildProperties<T>(columns, dialect) : BuildConstructor<T>(columns, dialect);
}
private static Func<DbDataReader, T> BuildEntity<T>(string[] columns, ISqlDialect dialect, IEntityMap map)
{
var slots = columns
.Select((name, ordinal) => (Ordinal: ordinal, Column: map.FindByColumn(name)))
.Where(s => s.Column is not null)
.Select(s => (s.Ordinal, Column: s.Column!))
.ToArray();
return reader =>
{
var entity = map.CreateEntity();
foreach (var (ordinal, column) in slots)
{
column.SetValue(entity, column.FromProvider(dialect.FromDbValue(reader.GetValue(ordinal), column.Type)));
}
return (T)entity;
};
}
private static Func<DbDataReader, T> BuildProperties<T>(string[] columns, ISqlDialect dialect)
{
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite && p.GetSetMethod() is not null)
.ToDictionary(p => SqlNames.ToSnakeCase(p.Name), StringComparer.OrdinalIgnoreCase);
var create = Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile();
var slots = new List<(int Ordinal, ColumnType Type, Type Target, Action<T, object?> Set)>();
for (var ordinal = 0; ordinal < columns.Length; ordinal++)
{
if (!properties.TryGetValue(columns[ordinal], out var property))
{
continue;
}
var instance = Expression.Parameter(typeof(T));
var value = Expression.Parameter(typeof(object));
var set = Expression.Lambda<Action<T, object?>>(
Expression.Assign(Expression.Property(instance, property), Expression.Convert(value, property.PropertyType)), instance, value).Compile();
slots.Add((ordinal, LogicalType(property.PropertyType), property.PropertyType, set));
}
return reader =>
{
var item = create();
foreach (var (ordinal, type, target, set) in slots)
{
set(item, ClrConverter.ConvertTo(dialect.FromDbValue(reader.GetValue(ordinal), type), target));
}
return item;
};
}
private static Func<DbDataReader, T> BuildConstructor<T>(string[] columns, ISqlDialect dialect)
{
var constructor = typeof(T).GetConstructors().OrderByDescending(c => c.GetParameters().Length).FirstOrDefault()
?? throw new InvalidOperationException($"{typeof(T).Name} has no public constructor to map rows to.");
var parameters = constructor.GetParameters();
var ordinals = parameters.Select(p =>
{
var index = Array.FindIndex(columns, c => string.Equals(c, SqlNames.ToSnakeCase(p.Name!), StringComparison.OrdinalIgnoreCase));
return index >= 0
? index
: throw new InvalidOperationException($"{typeof(T).Name}: no column {SqlNames.ToSnakeCase(p.Name!)} for constructor parameter {p.Name}.");
}).ToArray();
var types = parameters.Select(p => LogicalType(p.ParameterType)).ToArray();
var arguments = Expression.Parameter(typeof(object?[]));
var create = Expression.Lambda<Func<object?[], T>>(
Expression.New(constructor, parameters.Select((p, i) =>
(Expression)Expression.Convert(Expression.ArrayIndex(arguments, Expression.Constant(i)), p.ParameterType))),
arguments).Compile();
return reader =>
{
var values = new object?[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
values[i] = ClrConverter.ConvertTo(dialect.FromDbValue(reader.GetValue(ordinals[i]), types[i]), parameters[i].ParameterType);
}
return create(values);
};
}
private static bool IsScalar(Type type)
{
var underlying = Nullable.GetUnderlyingType(type) ?? type;
return underlying.IsEnum || ColumnTypes.FromClrType(underlying) is not null;
}
private static ColumnType LogicalType(Type type)
{
var underlying = Nullable.GetUnderlyingType(type) ?? type;
return underlying.IsEnum ? ColumnType.Text : ColumnTypes.FromClrType(underlying) ?? ColumnType.Text;
}
}
+140
View File
@@ -0,0 +1,140 @@
using System.Globalization;
using Khaemhat.Core.Common;
using Khaemhat.Core.Entities;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Querying;
namespace Khaemhat.Data.Execution;
/// <summary>
/// The repository of SPEC §5.1 for one entity type in one unit of work. Insert, update and delete statements are
/// cached per dialect (<see cref="CommandCache"/>); queries go through <see cref="QueryBuilder{T}"/>.
/// </summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <typeparam name="TKey">The key type.</typeparam>
public sealed class Repository<T, TKey> : IRepository<T, TKey>
where T : class, IEntity<TKey>, new()
{
private readonly UnitOfWork _unitOfWork;
private readonly EntityMap<T> _map;
private readonly QueryBuilder<T> _builder;
internal Repository(UnitOfWork unitOfWork, EntityMap<T> map)
{
_unitOfWork = unitOfWork;
_map = map;
_builder = new QueryBuilder<T>(map, unitOfWork.Dialect);
}
/// <inheritdoc />
public Task<T?> GetAsync(TKey id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(id);
return _unitOfWork.QuerySingleAsync<T>(_builder.SelectByKey(id), cancellationToken);
}
/// <inheritdoc />
public Task<T?> FindAsync(Query<T> query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
return _unitOfWork.QuerySingleAsync<T>(_builder.Select(query.Take(1)), cancellationToken);
}
/// <inheritdoc />
public async Task<PagedResult<T>> ListAsync(Query<T> query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var items = await _unitOfWork.QueryAsync<T>(_builder.Select(query), cancellationToken).ConfigureAwait(false);
long total = query.Limit is null && query.Offset == 0
? items.Count
: await CountAsync(query, cancellationToken).ConfigureAwait(false);
return new PagedResult<T>(items, total, query.Offset, query.Limit);
}
/// <inheritdoc />
public async Task<int> CountAsync(Query<T> query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
return (int)await _unitOfWork.QuerySingleAsync<long>(_builder.Count(query), cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<TKey> InsertAsync(T entity, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(entity);
if (entity is IAuditable audit)
{
audit.CreatedAt = _unitOfWork.Context.UtcNow;
audit.CreatedBy = _unitOfWork.Context.CurrentUser;
audit.UpdatedAt = null;
audit.UpdatedBy = null;
audit.RowVersion = 1;
}
var statement = CommandCache.Get(_map, CachedStatementKind.Insert, _unitOfWork.Dialect);
var parameters = Parameters(statement, entity, overrides: null);
if (!_map.Key.IsIdentity)
{
await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken).ConfigureAwait(false);
return entity.Id;
}
var generated = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteScalarAsync(ct), cancellationToken)
.ConfigureAwait(false);
var key = (TKey)ClrConverter.ConvertTo(_unitOfWork.Dialect.FromDbValue(generated, _map.Key.Type), typeof(TKey))!;
entity.Id = key;
return key;
}
/// <inheritdoc />
public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(entity);
var statement = CommandCache.Get(_map, CachedStatementKind.Update, _unitOfWork.Dialect);
var now = _unitOfWork.Context.UtcNow;
var user = _unitOfWork.Context.CurrentUser;
var overrides = new Dictionary<AuditRole, object?> { [AuditRole.UpdatedAt] = now, [AuditRole.UpdatedBy] = user };
var parameters = Parameters(statement, entity, overrides);
var affected = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken)
.ConfigureAwait(false);
if (affected == 0)
{
var version = entity is IAuditable a ? a.RowVersion : 0;
throw new ConcurrencyException(_map.Table, Convert.ToString(entity.Id, CultureInfo.InvariantCulture) ?? string.Empty, version);
}
if (entity is IAuditable audit)
{
audit.UpdatedAt = now;
audit.UpdatedBy = user;
audit.RowVersion++;
}
}
/// <inheritdoc />
public async Task<bool> DeleteAsync(TKey id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(id);
var statement = CommandCache.Get(_map, CachedStatementKind.Delete, _unitOfWork.Dialect);
var parameters = new[] { new SqlParameterValue("p0", _map.Key.ToProvider(id), _map.Key.Type) };
var affected = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken)
.ConfigureAwait(false);
return affected > 0;
}
private static List<SqlParameterValue> Parameters(CachedStatement statement, T entity, Dictionary<AuditRole, object?>? overrides)
{
var parameters = new List<SqlParameterValue>(statement.Parameters.Count);
for (var i = 0; i < statement.Parameters.Count; i++)
{
var column = statement.Parameters[i];
var value = overrides is not null && column.Audit != AuditRole.None && overrides.TryGetValue(column.Audit, out var replaced)
? replaced
: column.GetValue(entity);
parameters.Add(new SqlParameterValue("p" + i.ToString(CultureInfo.InvariantCulture), column.ToProvider(value), column.Type));
}
return parameters;
}
}
@@ -0,0 +1,45 @@
namespace Khaemhat.Data.Execution;
/// <summary>
/// Retries an operation that failed with a transient error (database busy, connection lost). It is applied only
/// outside transactions: inside one, a retry could repeat half of the work, so the error goes to the caller.
/// </summary>
/// <param name="maxAttempts">Total attempts, at least 1.</param>
/// <param name="baseDelay">Delay before the second attempt; it doubles each time.</param>
public sealed class TransientRetryPolicy(int maxAttempts, TimeSpan baseDelay)
{
/// <summary>Three attempts, 100 ms then 200 ms apart.</summary>
public static TransientRetryPolicy Default { get; } = new(3, TimeSpan.FromMilliseconds(100));
/// <summary>No retries.</summary>
public static TransientRetryPolicy None { get; } = new(1, TimeSpan.Zero);
/// <summary>Total attempts.</summary>
public int MaxAttempts { get; } = maxAttempts >= 1 ? maxAttempts : throw new ArgumentOutOfRangeException(nameof(maxAttempts));
/// <summary>Runs <paramref name="operation"/>, retrying when <paramref name="isTransient"/> says the error is transient.</summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="operation">The operation.</param>
/// <param name="isTransient">Classifies exceptions.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The result.</returns>
public async Task<T> ExecuteAsync<T>(
Func<CancellationToken, Task<T>> operation, Func<Exception, bool> isTransient, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(operation);
ArgumentNullException.ThrowIfNull(isTransient);
var delay = baseDelay;
for (var attempt = 1; ; attempt++)
{
try
{
return await operation(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (attempt < MaxAttempts && !cancellationToken.IsCancellationRequested && isTransient(ex))
{
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
delay += delay;
}
}
}
}
+287
View File
@@ -0,0 +1,287 @@
using System.Data.Common;
using Khaemhat.Core.Entities;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.Execution;
/// <summary>
/// The unit of work of SPEC §5.1 over one open connection. Statements outside a transaction are retried on transient
/// errors; on SQLite every write enters the database write scope (the whole transaction, or the single statement).
/// </summary>
public sealed class UnitOfWork : IUnitOfWork
{
private readonly Dictionary<Type, object> _repositories = [];
private IAsyncDisposable? _writeScope;
private bool _disposed;
private UnitOfWork(DatabaseTarget target, DbConnection connection, MapRegistry maps, DataAccessContext context)
{
Target = target;
Connection = connection;
Maps = maps;
Context = context;
Executor = new DbExecutor(target.Provider.Dialect);
}
/// <summary>The database.</summary>
public DatabaseTarget Target { get; }
/// <summary>The provider.</summary>
public IDbProvider Provider => Target.Provider;
/// <inheritdoc />
public DbConnection Connection { get; }
/// <inheritdoc />
public DbTransaction? Transaction { get; private set; }
/// <inheritdoc />
public ISqlDialect Dialect => Provider.Dialect;
/// <summary>The entity maps.</summary>
public MapRegistry Maps { get; }
/// <summary>Clock, user and retry policy.</summary>
public DataAccessContext Context { get; }
/// <summary>Creates commands.</summary>
public DbExecutor Executor { get; }
/// <summary>Opens a unit of work on a database.</summary>
/// <param name="target">The database.</param>
/// <param name="maps">The entity maps.</param>
/// <param name="context">Clock, user and retry policy.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The open unit of work.</returns>
public static async Task<UnitOfWork> OpenAsync(
DatabaseTarget target, MapRegistry maps, DataAccessContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(maps);
ArgumentNullException.ThrowIfNull(context);
var connection = target.Provider.CreateConnection(target.ConnectionString);
try
{
await context.RetryPolicy.ExecuteAsync(
async ct =>
{
await connection.OpenAsync(ct).ConfigureAwait(false);
return true;
},
target.Provider.IsTransient,
cancellationToken).ConfigureAwait(false);
}
catch
{
await connection.DisposeAsync().ConfigureAwait(false);
throw;
}
return new UnitOfWork(target, connection, maps, context);
}
/// <inheritdoc />
public async Task BeginAsync(CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (Transaction is not null)
{
throw new InvalidOperationException("A transaction is already open on this unit of work.");
}
_writeScope = await Provider.EnterWriteScopeAsync(Target.ConnectionString, cancellationToken).ConfigureAwait(false);
try
{
Transaction = await Connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
await ReleaseWriteScopeAsync().ConfigureAwait(false);
throw;
}
}
/// <inheritdoc />
public async Task CommitAsync(CancellationToken cancellationToken = default)
{
var transaction = Transaction ?? throw new InvalidOperationException("No transaction is open.");
try
{
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
await EndTransactionAsync().ConfigureAwait(false);
}
}
/// <inheritdoc />
public async Task RollbackAsync(CancellationToken cancellationToken = default)
{
var transaction = Transaction ?? throw new InvalidOperationException("No transaction is open.");
try
{
await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
await EndTransactionAsync().ConfigureAwait(false);
}
}
/// <inheritdoc />
public IRepository<T, TKey> Repository<T, TKey>()
where T : class, IEntity<TKey>, new()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_repositories.TryGetValue(typeof(T), out var repository))
{
repository = new Repository<T, TKey>(this, Maps.Get<T>());
_repositories[typeof(T)] = repository;
}
return (IRepository<T, TKey>)repository;
}
/// <inheritdoc />
public Task<int> ExecuteAsync(SqlFragment sql, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(sql);
var rendered = sql.Render(Dialect);
return WriteAsync(rendered.Text, rendered.Parameters, (command, ct) => command.ExecuteNonQueryAsync(ct), cancellationToken);
}
/// <inheritdoc />
public async Task<T?> QuerySingleAsync<T>(SqlFragment sql, CancellationToken cancellationToken = default)
{
var rows = await ReadAsync<T>(sql, single: true, cancellationToken).ConfigureAwait(false);
return rows.Count == 0 ? default : rows[0];
}
/// <inheritdoc />
public Task<IReadOnlyList<T>> QueryAsync<T>(SqlFragment sql, CancellationToken cancellationToken = default) =>
ReadAsync<T>(sql, single: false, cancellationToken);
/// <inheritdoc />
public async Task<DbDataReader> StreamAsync(SqlFragment sql, CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var command = Executor.CreateCommand(Connection, Transaction, sql);
try
{
return await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
await command.DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
if (Transaction is not null)
{
try
{
await Transaction.RollbackAsync().ConfigureAwait(false);
}
catch (DbException)
{
// The connection may already be broken; disposing it releases the transaction anyway.
}
await EndTransactionAsync().ConfigureAwait(false);
}
await Connection.DisposeAsync().ConfigureAwait(false);
}
/// <summary>
/// Runs a writing command: inside the transaction if there is one; otherwise inside the write scope, with retries
/// on transient errors.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="text">The SQL text.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="run">Runs the command.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The result.</returns>
internal async Task<T> WriteAsync<T>(
string text, IEnumerable<SqlParameterValue> parameters, Func<DbCommand, CancellationToken, Task<T>> run, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (Transaction is not null)
{
await using var command = Executor.CreateCommand(Connection, Transaction, text, parameters);
return await run(command, cancellationToken).ConfigureAwait(false);
}
var materialized = parameters.ToList();
return await Context.RetryPolicy.ExecuteAsync(
async ct =>
{
await using var scope = await Provider.EnterWriteScopeAsync(Target.ConnectionString, ct).ConfigureAwait(false);
await using var command = Executor.CreateCommand(Connection, null, text, materialized);
return await run(command, ct).ConfigureAwait(false);
},
Provider.IsTransient,
cancellationToken).ConfigureAwait(false);
}
private async Task<IReadOnlyList<T>> ReadAsync<T>(SqlFragment sql, bool single, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(sql);
async Task<IReadOnlyList<T>> Run(CancellationToken ct)
{
await using var command = Executor.CreateCommand(Connection, Transaction, sql);
await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
var rows = new List<T>();
Func<DbDataReader, T>? map = null;
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
map ??= ReaderMapper.For<T>(reader, Dialect, Maps);
rows.Add(map(reader));
if (single)
{
break;
}
}
return rows;
}
return Transaction is not null
? await Run(cancellationToken).ConfigureAwait(false)
: await Context.RetryPolicy.ExecuteAsync(Run, Provider.IsTransient, cancellationToken).ConfigureAwait(false);
}
private async Task EndTransactionAsync()
{
if (Transaction is not null)
{
await Transaction.DisposeAsync().ConfigureAwait(false);
Transaction = null;
}
await ReleaseWriteScopeAsync().ConfigureAwait(false);
}
private async Task ReleaseWriteScopeAsync()
{
if (_writeScope is not null)
{
await _writeScope.DisposeAsync().ConfigureAwait(false);
_writeScope = null;
}
}
}
@@ -0,0 +1,18 @@
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.Execution;
/// <summary>Opens <see cref="UnitOfWork"/>s on the database of a scope (SPEC §5.1).</summary>
/// <param name="locator">Finds the database of a scope.</param>
/// <param name="maps">The entity maps.</param>
/// <param name="context">Clock, user and retry policy.</param>
public sealed class UnitOfWorkFactory(IDatabaseLocator locator, MapRegistry maps, DataAccessContext context) : IUnitOfWorkFactory
{
/// <inheritdoc />
public async Task<IUnitOfWork> CreateAsync(DatabaseScope scope, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(scope);
var target = await locator.LocateAsync(scope, cancellationToken).ConfigureAwait(false);
return await UnitOfWork.OpenAsync(target, maps, context, cancellationToken).ConfigureAwait(false);
}
}
+5
View File
@@ -0,0 +1,5 @@
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage(
"Naming", "CA1720:Identifier contains type name", Scope = "namespaceanddescendants", Target = "~N:Khaemhat.Data.Schema",
Justification = "The logical column types are named as in SPEC §5.2 (String, Int32, Int64, Decimal, Guid): they are the vocabulary of migrations and docs.")]
+68
View File
@@ -0,0 +1,68 @@
using System.Data.Common;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data;
/// <summary>
/// A database engine (SPEC §5.1): connections, DDL, creation and removal of databases, server information. Implemented
/// by <c>SqliteProvider</c> and <c>PostgresProvider</c>.
/// </summary>
public interface IDbProvider
{
/// <summary>The engine.</summary>
DbEngine Engine { get; }
/// <summary>The SQL dialect.</summary>
ISqlDialect Dialect { get; }
/// <summary>The DDL generator used by migrations.</summary>
DdlGenerator Ddl { get; }
/// <summary>The driver connection string for a database URL.</summary>
/// <param name="url">The database URL (its engine must be <see cref="Engine"/>).</param>
/// <returns>The connection string. It contains credentials: never log it.</returns>
string BuildConnectionString(DatabaseUrl url);
/// <summary>Creates a closed connection. Session settings (pragmas, timeouts) are applied when it opens.</summary>
/// <param name="connectionString">The connection string.</param>
/// <returns>The connection.</returns>
DbConnection CreateConnection(string connectionString);
/// <summary>Creates the database if it does not exist (<c>CREATE DATABASE</c>, or the SQLite file).</summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default);
/// <summary>Drops the database. Only the company registry and the restore service call it.</summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default);
/// <summary>Whether the database exists.</summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> if it exists.</returns>
Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default);
/// <summary>Version, size, connections and warnings of the server and database (SPEC §12.1).</summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The information.</returns>
Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default);
/// <summary>Whether an exception is transient (busy, connection lost) and the statement may be retried outside a transaction.</summary>
/// <param name="exception">The exception.</param>
/// <returns><see langword="true"/> if transient.</returns>
bool IsTransient(Exception exception);
/// <summary>
/// Enters the write scope of a database: on SQLite it serializes writers of the process (<c>SqliteWriteLock</c>);
/// on PostgreSQL it does nothing. Dispose the result to leave.
/// </summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The scope.</returns>
ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default);
}
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more