Compare commits
8 Commits
main-2.0
...
0c3b0e99e8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c3b0e99e8 | ||
|
|
a1a63b11bb | ||
|
|
6db004066f | ||
|
|
a8c1b17095 | ||
|
|
62d682472e | ||
|
|
e07b46fcce | ||
|
|
d896f04274 | ||
|
|
254b2afb9f |
@@ -13,7 +13,6 @@ low-resource language failures.
|
|||||||
- [Model Bias and Language Quality](#model-bias-and-language-quality)
|
- [Model Bias and Language Quality](#model-bias-and-language-quality)
|
||||||
- [Western and Eurocentric Lens](#western-and-eurocentric-lens)
|
- [Western and Eurocentric Lens](#western-and-eurocentric-lens)
|
||||||
- [Wikipedia Enrichment](#wikipedia-enrichment)
|
- [Wikipedia Enrichment](#wikipedia-enrichment)
|
||||||
- [Names-by-Country Dataset](#names-by-country-dataset)
|
|
||||||
- [The "Avoid AI Phrases" Prompt Instruction](#the-avoid-ai-phrases-prompt-instruction)
|
- [The "Avoid AI Phrases" Prompt Instruction](#the-avoid-ai-phrases-prompt-instruction)
|
||||||
- [Known Issues](#known-issues)
|
- [Known Issues](#known-issues)
|
||||||
- [Hallucinated Brewing Techniques](#hallucinated-brewing-techniques)
|
- [Hallucinated Brewing Techniques](#hallucinated-brewing-techniques)
|
||||||
@@ -92,33 +91,6 @@ generated descriptions.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Names-by-Country Dataset
|
|
||||||
|
|
||||||
`tooling/pipeline/forenames-by-country.json` and `surnames-by-country.json`
|
|
||||||
(used to sample a `Name` per ISO 3166-1 country code for user generation) are
|
|
||||||
vendored verbatim, unmodified, from
|
|
||||||
[sigpwned/popular-names-by-country-dataset](https://github.com/sigpwned/popular-names-by-country-dataset)
|
|
||||||
(the `common-forenames-by-country.json` / `common-surnames-by-country.json`
|
|
||||||
release assets), released under **CC0** (public domain). That dataset's own
|
|
||||||
forename/surname lists are pulled from Wikipedia's "Lists of most common
|
|
||||||
surnames" and "List of most popular given names" as of the week of
|
|
||||||
2023-07-08 — see that project's README for full provenance. Names are not
|
|
||||||
LLM-generated; this is curated fixture data per ROADMAP.md §2. Per-forename
|
|
||||||
gender from the source data is preserved through to the sampled `Name`
|
|
||||||
(rather than discarded during loading) so it's available for gender-aware
|
|
||||||
persona/bio generation later.
|
|
||||||
|
|
||||||
The full multinational dataset is kept as-is (106 countries for forenames,
|
|
||||||
75 for surnames) rather than trimmed to `locations.json`'s current country
|
|
||||||
list, so it doesn't need re-sourcing if more countries are added later.
|
|
||||||
`SampleName()` (a free helper in `generate_users.cc`) returns no result for
|
|
||||||
a country present in neither file; of the countries in `locations.json`,
|
|
||||||
that's currently `KE`, `SE`, `SG`, `TH`, `VN`, and `ZA` — `GenerateUsers`
|
|
||||||
skips cities in those countries the same way brewery generation skips
|
|
||||||
cities whose enrichment lookup fails.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## The "Avoid AI Phrases" Prompt Instruction
|
## The "Avoid AI Phrases" Prompt Instruction
|
||||||
|
|
||||||
The system prompt instructs the model to avoid common AI-generated phrasing
|
The system prompt instructs the model to avoid common AI-generated phrasing
|
||||||
@@ -273,7 +245,7 @@ but is semantically incoherent. This comes from limited training-data coverage
|
|||||||
rather than prompt engineering.
|
rather than prompt engineering.
|
||||||
|
|
||||||
Output sample:
|
Output sample:
|
||||||
[./french-cities.example](french-cities.example)
|
[./out-sample/french-cities.example](out-sample/french-cities.example)
|
||||||
|
|
||||||
#### Proposed Mitigations
|
#### Proposed Mitigations
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
# Biergarten Pipeline
|
# Biergarten Pipeline
|
||||||
|
|
||||||
A C++20 command-line pipeline that samples city records from local JSON,
|
A C++20 command-line pipeline that samples city records from local JSON,
|
||||||
enriches each with Wikipedia context, and generates bilingual brewery names
|
enriches each with Wikipedia context, and generates bilingual brewery names and
|
||||||
and descriptions plus locale-grounded user profiles via a local GGUF model or
|
descriptions via a local GGUF model or a deterministic mock.
|
||||||
a deterministic mock.
|
|
||||||
|
|
||||||
> **This pipeline produces AI-generated data.** It is not a source of truth for
|
> **This pipeline produces AI-generated data.** It is not a source of truth for
|
||||||
> brewing techniques, cultural representation, or local-language accuracy. See
|
> brewing techniques, cultural representation, or local-language accuracy. See
|
||||||
@@ -46,7 +45,6 @@ step.
|
|||||||
| Beer reviews and ratings | Stable brewery fixtures with enough context to anchor review pages |
|
| Beer reviews and ratings | Stable brewery fixtures with enough context to anchor review pages |
|
||||||
| Social follow relationships | Repeatable brewery entities for feeds, follows, and saved lists |
|
| Social follow relationships | Repeatable brewery entities for feeds, follows, and saved lists |
|
||||||
| Geospatial brewery experiences | Latitude, longitude, and country-level metadata |
|
| Geospatial brewery experiences | Latitude, longitude, and country-level metadata |
|
||||||
| User accounts and profiles | Locale-grounded names, bios, and an auth-ready email/date-of-birth pair for seeding real accounts |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -96,27 +94,24 @@ Each run writes a fresh dated SQLite file such as
|
|||||||
./biergarten-pipeline \
|
./biergarten-pipeline \
|
||||||
--model ../models/google_gemma-4-E4B-it-Q6_K.gguf \
|
--model ../models/google_gemma-4-E4B-it-Q6_K.gguf \
|
||||||
--prompt-dir prompts \
|
--prompt-dir prompts \
|
||||||
--location-count 25 \
|
|
||||||
--temperature 1.0 --top-p 0.95 --top-k 64 --n-ctx 8192 --seed -1
|
--temperature 1.0 --top-p 0.95 --top-k 64 --n-ctx 8192 --seed -1
|
||||||
```
|
```
|
||||||
|
|
||||||
#### CLI Flags
|
#### CLI Flags
|
||||||
|
|
||||||
| Flag | Purpose |
|
| Flag | Purpose |
|
||||||
| ------------------ | ---------------------------------------------------------------------------------------------------- |
|
| --------------- | ---------------------------------------------------------------------------------------------------- |
|
||||||
| `--mocked` | Deterministic mock generator, no model required. |
|
| `--mocked` | Deterministic mock generator, no model required. |
|
||||||
| `--model, -m` | Path to a GGUF file. Required unless `--mocked` is set. |
|
| `--model, -m` | Path to a GGUF file. Required unless `--mocked` is set. |
|
||||||
| `--prompt-dir` | Directory containing prompt files (e.g. `BREWERY_GENERATION.md`). Required unless `--mocked` is set. |
|
| `--prompt-dir` | Directory containing prompt files (e.g. `BREWERY_GENERATION.md`). Required unless `--mocked` is set. |
|
||||||
| `--output, -o` | Directory for generated SQLite artifacts. Default: `output`. |
|
| `--output, -o` | Directory for generated SQLite artifacts. Default: `output`. |
|
||||||
| `--log-path` | Path for application logs. Default: `pipeline.log`. |
|
| `--log-path` | Path for application logs. Default: `pipeline.log`. |
|
||||||
| `--location-count` | Number of cities to sample from `locations.json` per run. Default: `10`. |
|
| `--temperature` | Sampling temperature. Default: `1.0`. |
|
||||||
| `--temperature` | Sampling temperature. Default: `1.0`. |
|
| `--top-p` | Nucleus sampling. Default: `0.95`. |
|
||||||
| `--top-p` | Nucleus sampling. Default: `0.95`. |
|
| `--top-k` | Top-k sampling. Default: `64`. |
|
||||||
| `--top-k` | Top-k sampling. Default: `64`. |
|
| `--n-ctx` | Context window size. Default: `8192`. |
|
||||||
| `--n-ctx` | Context window size. Default: `8192`. |
|
| `--seed` | Random seed. Default: `-1` (random at runtime). |
|
||||||
| `--seed` | Random seed. Default: `-1` (random at runtime). |
|
| `--help, -h` | Print usage and exit. |
|
||||||
| `--n-gpu-layers` | Number of model layers to offload to GPU. Default: `0`. |
|
|
||||||
| `--help, -h` | Print usage and exit. |
|
|
||||||
|
|
||||||
`--mocked` and `--model` are mutually exclusive. Omitting both exits with an
|
`--mocked` and `--model` are mutually exclusive. Omitting both exits with an
|
||||||
error before the pipeline starts. Sampling flags are ignored when `--mocked` is
|
error before the pipeline starts. Sampling flags are ignored when `--mocked` is
|
||||||
@@ -135,20 +130,17 @@ NVIDIA GPU.
|
|||||||
|
|
||||||
### How it works
|
### How it works
|
||||||
|
|
||||||
The container uses a two-stage build. The builder stage installs CMake/Ninja,
|
The container uses a two-stage build. The first stage pulls prebuilt
|
||||||
clones the matching llama.cpp release tag for its headers only (installed into
|
`libllama`, `libggml`, and backend plugin libraries (including `libggml-cuda.so`
|
||||||
`/usr/local/include`), and copies prebuilt shared libraries (`libllama`,
|
and the CPU variant plugins) from `ghcr.io/ggml-org/llama.cpp:full-cuda`. The
|
||||||
`libggml`, and CUDA/CPU backend plugins) from `ghcr.io/ggml-org/llama.cpp:full-cuda`
|
second stage copies those libraries into `/usr/local/lib` and runs `ldconfig` so
|
||||||
into `/usr/local/lib`. With both headers and libraries present, CMake's
|
the dynamic linker and `dlopen` calls from `ggml_backend_load_all()` can resolve
|
||||||
system-library detection (see [Build](#build) above) finds them and skips the
|
the CUDA backend plugin at runtime. llama.cpp headers are cloned at the matching
|
||||||
FetchContent source build, keeping image build times short.
|
tag and installed into `/usr/local/include`. CMake auto-detects both and skips
|
||||||
|
the FetchContent source build entirely, keeping image build times short.
|
||||||
|
|
||||||
The runtime stage copies the compiled binary, the same prebuilt shared
|
`GGML_BACKEND_PATH` is set to `/usr/local/lib` so llama.cpp knows where to scan
|
||||||
libraries, and config/prompt assets into a slim CUDA runtime image. It sets
|
for backend plugins.
|
||||||
`LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH` so the dynamic linker
|
|
||||||
resolves `libllama`/`libggml` at startup, and also co-locates
|
|
||||||
`libggml-cuda.so` and the CPU backend plugins next to the binary for
|
|
||||||
`ggml_backend_load_all()`'s `dlopen` scan.
|
|
||||||
|
|
||||||
### Build the image
|
### Build the image
|
||||||
|
|
||||||
@@ -173,46 +165,44 @@ docker build \
|
|||||||
Look for `[biergarten] Found system llama.cpp — skipping FetchContent` in the
|
Look for `[biergarten] Found system llama.cpp — skipping FetchContent` in the
|
||||||
output to confirm the fast path was taken.
|
output to confirm the fast path was taken.
|
||||||
|
|
||||||
### Run the container
|
### Run in mocked mode
|
||||||
|
|
||||||
The container always runs the model-backed path; there is no `--mocked`
|
No model or GPU required. Useful for validating the pipeline logic and SQLite
|
||||||
container mode (use a native build for that — see [Quick Start](#quick-start)).
|
export path.
|
||||||
The entrypoint, `runpod/start.sh`, downloads the GGUF model automatically if
|
|
||||||
it is not already present at the configured path.
|
```bash
|
||||||
|
docker run --rm \
|
||||||
|
-e BIERGARTEN_MODE=mocked \
|
||||||
|
-v "$PWD/output:/workspace/output" \
|
||||||
|
-v "$PWD/logs:/workspace/logs" \
|
||||||
|
biergarten-pipeline:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
### Run in live mode
|
||||||
|
|
||||||
|
Mount your GGUF model before starting. The container validates the model path
|
||||||
|
before launching the binary.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
--runtime=nvidia \
|
--runtime=nvidia \
|
||||||
|
-e BIERGARTEN_MODE=live \
|
||||||
|
-e GGML_BACKEND_PATH="/usr/local/lib/libggml-cuda.so" \
|
||||||
-v "$PWD/models:/workspace/models" \
|
-v "$PWD/models:/workspace/models" \
|
||||||
-v "$PWD/output:/workspace/output" \
|
-v "$PWD/output:/workspace/output" \
|
||||||
-v "$PWD/logs:/workspace/logs" \
|
-v "$PWD/logs:/workspace/logs" \
|
||||||
biergarten-pipeline:latest
|
biergarten-pipeline:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
By default this downloads `google_gemma-4-E4B-it-Q6_K.gguf` to
|
The model must be present at `./models/google_gemma-4-E4B-it-Q6_K.gguf` on the
|
||||||
`./models/` on first run if it isn't already there. To use a pre-downloaded
|
host. See [Model](#model) above for the download command.
|
||||||
model, place it at that path first — see [Model](#model) above.
|
|
||||||
|
|
||||||
#### Environment variables
|
|
||||||
|
|
||||||
| Variable | Purpose |
|
|
||||||
| ------------------------- | ----------------------------------------------------------------- |
|
|
||||||
| `BIERGARTEN_MODEL_PATH` | GGUF model path. Default: `/workspace/models/google_gemma-4-E4B-it-Q6_K.gguf`. |
|
|
||||||
| `BIERGARTEN_OUTPUT_DIR` | SQLite output directory. Default: `/workspace/output`. |
|
|
||||||
| `BIERGARTEN_LOG_PATH` | Log file path. Default: `/workspace/logs/pipeline.log`. |
|
|
||||||
| `BIERGARTEN_GL_LAYERS` | GPU layers to offload (`--n-gpu-layers`). Default: `40`. |
|
|
||||||
| `BIERGARTEN_TEMPERATURE`, `BIERGARTEN_TOP_P`, `BIERGARTEN_TOP_K`, `BIERGARTEN_N_CTX`, `BIERGARTEN_SEED` | Optional sampling overrides, unset by default (binary defaults apply). |
|
|
||||||
| `BIERGARTEN_EXTRA_ARGS` | Additional raw CLI args appended verbatim. |
|
|
||||||
|
|
||||||
`--prompt-dir` is hardcoded to `/app/prompts` inside the container and is not
|
|
||||||
configurable via environment variable.
|
|
||||||
|
|
||||||
### RunPod deployment
|
### RunPod deployment
|
||||||
|
|
||||||
Use a GPU pod template. Mount persistent storage for `/workspace/models`,
|
Use a GPU pod template. Mount persistent storage for `/workspace/models`,
|
||||||
`/workspace/output`, and `/workspace/logs`. See
|
`/workspace/output`, and `/workspace/logs`. Set `BIERGARTEN_MODE=live` in the
|
||||||
`tooling/pipeline/runpod/pod-template.yaml` for a starter template — set the
|
template environment. See `tooling/pipeline/runpod/pod-template.yaml` for a
|
||||||
environment variables listed above to match your run.
|
starter template.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -220,77 +210,52 @@ environment variables listed above to match your run.
|
|||||||
|
|
||||||
### Pipeline Stages
|
### Pipeline Stages
|
||||||
|
|
||||||
| Stage | Implementation |
|
| Stage | Implementation |
|
||||||
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
| -------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| Load | `ICuratedDataService` (`CuratedJsonDataService`) reads `locations.json`, `personas.json`, `forenames-by-country.json`, and `surnames-by-country.json` (paths supplied via a `CuratedDataFilePaths` DTO at construction) into typed records, caching each after its first load. `--mocked` runs use `MockCuratedDataService`'s fixed in-memory dataset instead. |
|
| Load | `JsonLoader::LoadLocations()` reads `locations.json` into typed `Location` records. |
|
||||||
| Sample | `BiergartenPipelineOrchestrator::QueryCitiesWithCountries()` samples `--location-count` locations per run (default `10`). |
|
| Sample | `BiergartenDataGenerator::QueryCitiesWithCountries()` samples up to 50 locations per run. |
|
||||||
| Enrich | `WikipediaEnrichmentService` fetches brewing and beer-related context. Keeps going when a lookup fails. `--mocked` runs use `MockEnrichmentService` instead and skip Wikipedia entirely. |
|
| Enrich | `WikipediaService` fetches city and beer context. Keeps going when a lookup fails. |
|
||||||
| Generate Users | `GenerateUsers()` samples a persona and a forename/surname pair per enriched city (skipping countries with no name data), then `MockGenerator` or `LlamaGenerator` produces a username, bio, and activity weight around the sampled name. |
|
| Generate | `MockGenerator` or `LlamaGenerator` produces brewery names and descriptions in English and the local language. |
|
||||||
| Generate Breweries | `MockGenerator` or `LlamaGenerator` produces brewery names and descriptions in English and the local language. |
|
| Store | `SqliteExportService` writes each successful brewery into a fresh dated `.sqlite` database with normalized location and brewery tables. |
|
||||||
| Store | `SqliteExportService` writes each successful user and brewery into a fresh dated `.sqlite` database with normalized `locations`, `users`, and `breweries` tables. |
|
| Log | `spdlog` writes results and warnings to the console. |
|
||||||
| Log | `spdlog` writes results and warnings to the console. |
|
|
||||||
|
|
||||||
If name sampling, enrichment, or generation fails for a city, that city is
|
If enrichment or generation fails for a city, that city is skipped and the
|
||||||
skipped and the pipeline continues. `GenerateUsers()` runs before
|
pipeline continues.
|
||||||
`GenerateBreweries()` in `BiergartenPipelineOrchestrator::Run()`.
|
|
||||||
|
|
||||||
### Key Components
|
### Key Components
|
||||||
|
|
||||||
- `src/main.cc` — argument parsing and Boost.DI composition root.
|
- `src/main.cc` — argument parsing and Boost.DI composition root.
|
||||||
- `CuratedJsonDataService` — implements `ICuratedDataService`; takes a
|
- `JsonLoader` — validates curated location input.
|
||||||
`CuratedDataFilePaths` DTO (locations/personas/forenames/surnames paths) in
|
- `WikipediaService` — queries Wikipedia extracts, caches results, returns empty
|
||||||
its constructor, then parses and validates curated location, persona, and
|
context on failure.
|
||||||
forename/surname JSON, memoizing each result after its first load on a
|
- `LlamaGenerator` — formats prompts for Gemma 4, validates JSON output, retries
|
||||||
given instance. `MockCuratedDataService` is the in-memory substitute (4
|
malformed responses up to three times. If output looks truncated, the retry
|
||||||
fixed locations, 3 personas, and name data for `US`/`DE`/`FR`/`BE`) used in
|
raises the token budget before trying again.
|
||||||
`--mocked` runs.
|
- `MockGenerator` — stable hash-based output so the same city input always
|
||||||
- `WikipediaEnrichmentService` — queries Wikipedia extracts, caches results,
|
produces the same brewery.
|
||||||
returns empty context on failure. `MockEnrichmentService` is the no-op
|
- `SqliteExportService` — creates a dated SQLite file per run and persists each
|
||||||
substitute used in `--mocked` runs.
|
successful brewery into normalized tables.
|
||||||
- `LlamaGenerator` — formats prompts for Gemma 4, validates JSON output for
|
|
||||||
both `GenerateBrewery` and `GenerateUser`, retries malformed responses up
|
|
||||||
to three times with corrective feedback in the retry prompt. The token
|
|
||||||
budget is fixed across attempts; it is not raised automatically on
|
|
||||||
truncation.
|
|
||||||
- `MockGenerator` — stable hash-based output so the same city/persona/name
|
|
||||||
input always produces the same brewery or user.
|
|
||||||
- `SqliteExportService` — creates a dated SQLite file per run and persists
|
|
||||||
each successful user and brewery into normalized tables.
|
|
||||||
- Brewery payloads include English and local-language name and description
|
- Brewery payloads include English and local-language name and description
|
||||||
fields. User payloads carry a sampled first/last name and gender, an
|
fields.
|
||||||
LLM-generated username/bio/activity weight, and a programmatically
|
|
||||||
generated (not LLM-authored) unique email and date of birth.
|
|
||||||
|
|
||||||
### Runtime Behaviour
|
### Runtime Behaviour
|
||||||
|
|
||||||
`WikipediaEnrichmentService` fetches two Wikipedia extracts per city: a
|
`WikipediaService` queries city, country, and beer-related Wikipedia extracts
|
||||||
generic "brewing" extract and a "beer in `{country}`" extract. It does not
|
using its configured lookup, then caches the first successful response per query
|
||||||
currently query a city- or region-specific page. Each query string is cached
|
string. The fetched extract text is included in the prompt as context for
|
||||||
after its first successful (or empty) lookup.
|
generation.
|
||||||
|
|
||||||
`GetLocationContext()` returns an empty string when the web client is
|
`GetLocationContext()` returns an empty string when the web client is
|
||||||
unavailable or when lookup/parsing fails.
|
unavailable or when lookup/parsing fails.
|
||||||
|
|
||||||
`LlamaGenerator` validates model output as structured JSON. On validation
|
`LlamaGenerator` validates model output as structured JSON. The retry path
|
||||||
failure it retries up to three times, replaying the previous error message in
|
exists as a safety hatch for cases where the reasoning block consumes available
|
||||||
the next prompt so the model can self-correct. All runs to date have produced
|
token budget and compresses the JSON output space. All runs to date have
|
||||||
valid output on the first pass; the retry path is kept for resilience.
|
produced valid output on the first pass; the path is kept for resilience.
|
||||||
|
|
||||||
`MockGenerator` uses stable hashes for repeatable output in demos and Storybook
|
`MockGenerator` uses stable hashes for repeatable output in demos and Storybook
|
||||||
runs.
|
runs.
|
||||||
|
|
||||||
`CuratedJsonDataService` memoizes each of `LoadLocations()`, `LoadPersonas()`,
|
|
||||||
`LoadForenamesByCountry()`, and `LoadSurnamesByCountry()` independently the
|
|
||||||
first time each is called, since `BiergartenPipelineOrchestrator` owns a
|
|
||||||
single `ICuratedDataService` instance for the whole run — later calls return
|
|
||||||
the cached result instead of re-parsing.
|
|
||||||
|
|
||||||
`GenerateUsers()` samples a forename/surname pair per city via `SampleName()`,
|
|
||||||
keyed by the city's ISO 3166-1 code. Countries present in `locations.json`
|
|
||||||
but absent from either name fixture (currently `KE`, `SE`, `SG`, `TH`, `VN`,
|
|
||||||
`ZA`) are skipped, the same way a failed enrichment or generation call skips
|
|
||||||
a city — see ETHICS-AND-KNOWN-ISSUES.md's Names-by-Country Dataset section.
|
|
||||||
|
|
||||||
### Process Flow - Activity Diagram
|
### Process Flow - Activity Diagram
|
||||||
|
|
||||||

|

|
||||||
@@ -303,10 +268,9 @@ a city — see ETHICS-AND-KNOWN-ISSUES.md's Names-by-Country Dataset section.
|
|||||||
|
|
||||||
## Generated Output
|
## Generated Output
|
||||||
|
|
||||||
Each successful run stores a `BreweryRecord` pair with the source location
|
Each successful run stores a `GeneratedBrewery` pair with the source location
|
||||||
and a `BreweryResult` payload, and a `UserRecord` pair with the source
|
and a `BreweryResult` payload. The same generated records are also written to a
|
||||||
location and a `UserResult` payload. The same generated records are also
|
fresh SQLite export file named with the current UTC timestamp.
|
||||||
written to a fresh SQLite export file named with the current UTC timestamp.
|
|
||||||
|
|
||||||
| Field | Meaning |
|
| Field | Meaning |
|
||||||
| ------------------- | ------------------------------------------ |
|
| ------------------- | ------------------------------------------ |
|
||||||
@@ -315,17 +279,6 @@ written to a fresh SQLite export file named with the current UTC timestamp.
|
|||||||
| `name_local` | Brewery name in the local language. |
|
| `name_local` | Brewery name in the local language. |
|
||||||
| `description_local` | Brewery description in the local language. |
|
| `description_local` | Brewery description in the local language. |
|
||||||
|
|
||||||
| Field | Meaning |
|
|
||||||
| ----------------- | ----------------------------------------------------------------- |
|
|
||||||
| `first_name` | Sampled forename, copied from the curated name data (not LLM-invented). |
|
|
||||||
| `last_name` | Sampled surname, copied from the curated name data (not LLM-invented). |
|
|
||||||
| `gender` | Gender associated with the sampled forename in the source dataset. |
|
|
||||||
| `username` | LLM-generated handle. |
|
|
||||||
| `bio` | LLM-generated short biography. |
|
|
||||||
| `activity_weight` | Relative check-in/activity weight, reserved for a future J-curve activity profile. |
|
|
||||||
| `email` | Unique `@thebiergarten.app` address, generated programmatically from the sampled name. |
|
|
||||||
| `date_of_birth` | Randomized date of birth (age 19-48), generated programmatically. |
|
|
||||||
|
|
||||||
The log dump also includes city, country, state or province, ISO subdivision
|
The log dump also includes city, country, state or province, ISO subdivision
|
||||||
code, latitude, and longitude for each entry.
|
code, latitude, and longitude for each entry.
|
||||||
|
|
||||||
@@ -339,6 +292,7 @@ code, latitude, and longitude for each entry.
|
|||||||
| `local_languages` | Locale-aware copy selection |
|
| `local_languages` | Locale-aware copy selection |
|
||||||
| `name_en`, `description_en` | Default English display content |
|
| `name_en`, `description_en` | Default English display content |
|
||||||
| `name_local`, `description_local` | Local-language display content |
|
| `name_local`, `description_local` | Local-language display content |
|
||||||
|
| `region_context` | Richer copy for cards and detail pages |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -404,64 +358,47 @@ Silicon; CUDA or HIP/ROCm is detected on Linux when the toolkit is present.
|
|||||||
## Fixture Strategy
|
## Fixture Strategy
|
||||||
|
|
||||||
- `--mocked` for stable fixtures, repeatable screenshots, and Storybook runs.
|
- `--mocked` for stable fixtures, repeatable screenshots, and Storybook runs.
|
||||||
`MockCuratedDataService` swaps in for `CuratedJsonDataService`, so no
|
|
||||||
fixture files need to be present on disk.
|
|
||||||
- `--model` when geographically grounded content matters for demos.
|
- `--model` when geographically grounded content matters for demos.
|
||||||
- Keep `locations.json` structured enough to support discovery and future
|
- Keep `locations.json` structured enough to support discovery and future
|
||||||
filtering.
|
filtering.
|
||||||
- `personas.json`, `forenames-by-country.json`, and
|
- Treat SQLite output as seed material for the app's brewery domain, not
|
||||||
`surnames-by-country.json` are curated/vendored fixture data, not
|
production data.
|
||||||
LLM-generated — see ETHICS-AND-KNOWN-ISSUES.md's Names-by-Country Dataset
|
|
||||||
section for provenance.
|
|
||||||
- Treat SQLite output as seed material for the app's brewery and user
|
|
||||||
domains, not production data.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Repo Layout
|
## Repo Layout
|
||||||
|
|
||||||
| Path | Purpose |
|
| Path | Purpose |
|
||||||
| -------------------------------------- | -------------------------------------------------- |
|
| ---------------------------- | -------------------------------------------------- |
|
||||||
| `tooling/pipeline/includes/` | Public headers and shared models. |
|
| `includes/` | Public headers and shared models. |
|
||||||
| `tooling/pipeline/src/` | Implementation files. |
|
| `src/` | Implementation files. |
|
||||||
| `tooling/pipeline/locations.json` | Curated city input copied into the build tree. |
|
| `locations.json` | Curated city input copied into the build tree. |
|
||||||
| `tooling/pipeline/personas.json` | Curated user persona archetypes copied into the build tree. |
|
| `prompts/` | System prompts used by the model-backed path. |
|
||||||
| `tooling/pipeline/forenames-by-country.json` | Vendored (CC0) forename data by ISO 3166-1 country code. |
|
| `diagrams/` | Architecture and pipeline diagrams. |
|
||||||
| `tooling/pipeline/surnames-by-country.json` | Vendored (CC0) surname data by ISO 3166-1 country code. |
|
| `tooling/pipeline/runpod/` | Dockerfile, launcher, and RunPod pod template. |
|
||||||
| `tooling/pipeline/prompts/` | System prompts used by the model-backed path. |
|
| `ETHICS-AND-KNOWN-ISSUES.md` | Ethics, bias, hallucination analysis, mitigations. |
|
||||||
| `tooling/pipeline/runpod/` | Dockerfile, launcher, and RunPod pod template. |
|
|
||||||
| `docs/pipeline/diagrams/` | Architecture and pipeline diagrams. |
|
|
||||||
| `docs/pipeline/ETHICS-AND-KNOWN-ISSUES.md` | Ethics, bias, hallucination analysis, mitigations. |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Code Tour
|
## Code Tour
|
||||||
|
|
||||||
Paths below are relative to `tooling/pipeline/`.
|
|
||||||
|
|
||||||
- `src/main.cc` — argument parsing and DI composition root.
|
- `src/main.cc` — argument parsing and DI composition root.
|
||||||
- `src/biergarten_pipeline_orchestrator/` — orchestration, sampling, logging,
|
- `src/biergarten_data_generator/` — orchestration, sampling, logging, and
|
||||||
and export.
|
export.
|
||||||
- `src/services/curated_data/` — `CuratedJsonDataService`, the file-backed
|
- `src/services/wikipedia/` — enrichment service and cache.
|
||||||
`ICuratedDataService`, and `MockCuratedDataService`, the in-memory
|
|
||||||
`ICuratedDataService` used in `--mocked` runs.
|
|
||||||
- `src/services/enrichment/wikipedia/` — enrichment service and cache.
|
|
||||||
- `src/services/sqlite/` — SQLite export implementation.
|
- `src/services/sqlite/` — SQLite export implementation.
|
||||||
- `src/data_generation/llama/` — local inference, prompt loading, output
|
- `src/data_generation/llama/` — local inference, prompt loading, output
|
||||||
validation.
|
validation.
|
||||||
- `src/data_generation/mock/` — deterministic fallback.
|
- `src/data_generation/mock/` — deterministic fallback.
|
||||||
- `runpod/` — container build and runtime launcher.
|
- `tooling/pipeline/runpod/` — container build and runtime launcher.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Next Steps
|
## Next Steps
|
||||||
|
|
||||||
The pipeline currently produces city-aware brewery and user records and
|
The pipeline currently produces city-aware brewery records and dated SQLite
|
||||||
dated SQLite exports. The next passes add additional fixture types so the
|
exports. The next passes add additional fixture types so the app can exercise
|
||||||
app can exercise the full brewery and social domains without live data. For
|
the full brewery domain without live data.
|
||||||
the detailed engineering breakdown of what's needed to reach the
|
|
||||||
architecture in [`diagrams/planned/`](./diagrams/planned/), see
|
|
||||||
[ROADMAP.md](./ROADMAP.md).
|
|
||||||
|
|
||||||
### Testing — Very High Priority
|
### Testing — Very High Priority
|
||||||
|
|
||||||
@@ -483,6 +420,12 @@ Generate catalog entries with style, ABV, IBU, color, aroma notes, and food
|
|||||||
pairing hints. Link beers back to breweries and cities. Keep style coverage wide
|
pairing hints. Link beers back to breweries and cities. Keep style coverage wide
|
||||||
enough to exercise search, sort, and category filters.
|
enough to exercise search, sort, and category filters.
|
||||||
|
|
||||||
|
### User Generation
|
||||||
|
|
||||||
|
Generate user profiles with stable names, bios, locale hints, and preference
|
||||||
|
signals. Include stable IDs for downstream fixture joins. Keep output
|
||||||
|
deterministic for screenshots while allowing larger randomized batches.
|
||||||
|
|
||||||
### Check-In System
|
### Check-In System
|
||||||
|
|
||||||
Produce timestamped check-in events between users and breweries. Use a J-curve
|
Produce timestamped check-in events between users and breweries. Use a J-curve
|
||||||
|
|||||||
@@ -1,252 +0,0 @@
|
|||||||
# Pipeline Roadmap — Reaching the Planned Architecture
|
|
||||||
|
|
||||||
This is the engineering breakdown for closing the gap between the **current**
|
|
||||||
pipeline and the **planned** architecture documented in
|
|
||||||
[`diagrams/planned/class.puml`](./diagrams/planned/class.puml) and
|
|
||||||
[`diagrams/planned/activity.puml`](./diagrams/planned/activity.puml). Nothing
|
|
||||||
in `diagrams/planned/` is implemented yet — this file tracks what it would
|
|
||||||
take to get there. For the current implementation, see
|
|
||||||
[README.md](./README.md).
|
|
||||||
|
|
||||||
Items are grouped by layer and roughly ordered by dependency: later groups
|
|
||||||
build on types and services introduced earlier.
|
|
||||||
|
|
||||||
The only concurrency in the current pipeline is the log dispatcher thread
|
|
||||||
(`main.cc` spawns it to drain a `BoundedChannel<LogEntry>` into spdlog for the
|
|
||||||
whole run). Sampling, enrichment, generation, and export all happen
|
|
||||||
synchronously on the main thread inside `BiergartenPipelineOrchestrator::Run()`
|
|
||||||
— §6 below is what introduces the additional worker threads the planned
|
|
||||||
architecture needs.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Domain Models
|
|
||||||
|
|
||||||
`tooling/pipeline/includes/data_model/generated_models.h` and `models.h`.
|
|
||||||
|
|
||||||
- [ ] Add `Completeness` enum (`Full`, `Partial`, `Absent`) and a
|
|
||||||
`LocationContext` struct (`text`, `completeness`, `char_count`).
|
|
||||||
Replace `EnrichedCity::region_context` (currently a plain
|
|
||||||
`std::string`) with `context : LocationContext`.
|
|
||||||
- [ ] Add `BeerStyle` (`name`, `description`, `min_abv`, `max_abv`,
|
|
||||||
`min_ibu`, `max_ibu`).
|
|
||||||
- [ ] Add `BeerResult`, `CheckinResult`, `RatingResult` result payloads.
|
|
||||||
- [ ] Add `GenerationMetadata` (`generation_id`, `generated_time`,
|
|
||||||
`context_provided`, `generated_with`).
|
|
||||||
- [x] Add `first_name`, `last_name`, `gender`, and `activity_weight` to
|
|
||||||
`UserResult` (currently just `username`, `bio`). `first_name`/
|
|
||||||
`last_name`/`gender` are copied from the sampled `Name` (see below),
|
|
||||||
not LLM-invented.
|
|
||||||
- [x] Add `Name` (`first_name`, `last_name`, `gender`) — the sampled result
|
|
||||||
handed to `DataGenerator::GenerateUser`. Add `ForenameEntry` (`name`,
|
|
||||||
`gender`). Landed as a flatter shape than originally planned here: no
|
|
||||||
`NamesByCountry` wrapper class. `curated_data_service.h` instead
|
|
||||||
declares `ForenameList = std::vector<ForenameEntry>` and
|
|
||||||
`SurnameList = std::vector<std::string>`, and
|
|
||||||
`ICuratedDataService` exposes two maps keyed by ISO 3166-1 code —
|
|
||||||
`ForenamesByCountryMap = unordered_map<string, ForenameList>` and
|
|
||||||
`SurnamesByCountryMap = unordered_map<string, SurnameList>` —
|
|
||||||
directly (see §2). Sampling is
|
|
||||||
a free function, `SampleName(forenames_by_country,
|
|
||||||
surnames_by_country, iso3166_1, rng)`, in
|
|
||||||
`generate_users.cc`'s anonymous namespace, not a method on a class.
|
|
||||||
Pairing a forename with a surname happens at sample time so gender
|
|
||||||
(present per-forename in the source data) is never discarded the way a
|
|
||||||
pre-flattened `{first_name, last_name}` list would lose it; see §2.
|
|
||||||
- [ ] Extend `GeneratedBrewery` with `brewery_id`, `context_completeness`,
|
|
||||||
`metadata` (currently just `{location, brewery}`).
|
|
||||||
- [ ] Add `GeneratedBeer`, `GeneratedCheckin`, `GeneratedRating`,
|
|
||||||
`GeneratedFollow` aggregate structs.
|
|
||||||
- [x] Add `UserRecord` (`location`, `user : UserResult`, `email`,
|
|
||||||
`date_of_birth`) as the current stand-in for the planned
|
|
||||||
`GeneratedUser` — `email` and `date_of_birth` are programmatically
|
|
||||||
generated by the orchestrator, never LLM-authored, so a downstream
|
|
||||||
auth-account seeding consumer can register real accounts from the
|
|
||||||
pipeline's SQLite export. No `password`, `user_id`, or `metadata`
|
|
||||||
field yet, matching `BreweryRecord`'s equally pre-`metadata` shape.
|
|
||||||
Already wired into `IExportService`/`SqliteExportService`: a `users`
|
|
||||||
table exists and `GenerateUsers()` exports each successful record via
|
|
||||||
`ProcessRecord(const UserRecord&)` (see §5) in addition to logging and
|
|
||||||
holding `generated_users_` in memory. Still missing vs. the planned
|
|
||||||
`GeneratedUser`: `user_id`, `password`, and `metadata`.
|
|
||||||
- [x] Add `UserPersona` (`name`, `description`, `style_affinities`).
|
|
||||||
|
|
||||||
## 2. Data Preloading
|
|
||||||
|
|
||||||
`tooling/pipeline/includes/services/curated_data/`, fixture files.
|
|
||||||
|
|
||||||
- [x] Extract an interface; have `CuratedJsonDataService` implement it.
|
|
||||||
Landed as `ICuratedDataService`
|
|
||||||
(`services/curated_data/curated_data_service.h`), not `DataPreloader`
|
|
||||||
— `LoadLocations()`, `LoadPersonas()`, `LoadForenamesByCountry()`, and
|
|
||||||
`LoadSurnamesByCountry()` are all virtual methods returning `const&`
|
|
||||||
and take no arguments. `CuratedJsonDataService`
|
|
||||||
(`services/curated_data/curated_json_data_service.h`, originally
|
|
||||||
landed as `JsonLoader` under `json_handling/` before being renamed and
|
|
||||||
moved) takes a `CuratedDataFilePaths` DTO (`locations_path`,
|
|
||||||
`personas_path`, `forenames_path`, `surnames_path`) in its
|
|
||||||
constructor rather than a path per `Load*()` call, and memoizes each
|
|
||||||
result in a private `cache` struct (`locations`, `personas`,
|
|
||||||
`forenames_by_country`, `surnames_by_country`), so a second call on
|
|
||||||
the same instance returns the cached result instead of re-parsing —
|
|
||||||
safe because `CuratedJsonDataService` outlives every call site (owned
|
|
||||||
by `BiergartenPipelineOrchestrator` via
|
|
||||||
`unique_ptr<ICuratedDataService>` for the whole run). `main.cc`'s DI
|
|
||||||
injector also gained a `MockCuratedDataService` (fixed in-memory
|
|
||||||
data: 4 locations across `US`/`DE`/`FR`/`BE`, 3 personas, and
|
|
||||||
matching forename/surname sets for those four countries), bound in
|
|
||||||
place of `CuratedJsonDataService` under `--mocked`, mirroring the
|
|
||||||
existing `MockEnrichmentService`/`MockGenerator` pattern.
|
|
||||||
- [ ] Add `LoadBeerStyles()`. `beer-styles.json` already exists in the repo
|
|
||||||
and is already copied into the Docker image
|
|
||||||
(`runpod/Dockerfile`), but no loader reads it yet, and the native
|
|
||||||
CMake build doesn't copy it into `build/` at all — `CMakeLists.txt`'s
|
|
||||||
"Runtime Assets" step only copies `locations.json` and `prompts/`.
|
|
||||||
- [x] Add `LoadPersonas()` and author `personas.json` (doesn't exist yet).
|
|
||||||
- [x] Add name-by-country loading, parsing
|
|
||||||
`tooling/pipeline/forenames-by-country.json` and
|
|
||||||
`surnames-by-country.json`. Landed as two separate methods —
|
|
||||||
`LoadForenamesByCountry()` and `LoadSurnamesByCountry()` — each
|
|
||||||
returning a flat `ForenamesByCountryMap` / `SurnamesByCountryMap`
|
|
||||||
(aliases for `unordered_map<string, ForenameList>` /
|
|
||||||
`unordered_map<string, SurnameList>`) keyed by ISO 3166-1 code, rather
|
|
||||||
than one combined `LoadNamesByCountry() : NamesByCountry` call. Both
|
|
||||||
files are vendored verbatim (unmodified,
|
|
||||||
full multinational coverage) from
|
|
||||||
`sigpwned/popular-names-by-country-dataset` (CC0) — see
|
|
||||||
ETHICS-AND-KNOWN-ISSUES.md's Names-by-Country Dataset section for
|
|
||||||
provenance. Deliberately not pre-paired or filtered down to just the
|
|
||||||
countries in `locations.json`: keeping the source shape (including
|
|
||||||
per-forename gender) intact means the loader can support more
|
|
||||||
countries later, or gender-aware persona/bio generation, without
|
|
||||||
re-sourcing data.
|
|
||||||
|
|
||||||
## 3. Policy / Strategy Layer
|
|
||||||
|
|
||||||
Entirely new — no `includes/policy/` (or equivalent) directory exists today.
|
|
||||||
|
|
||||||
- [ ] `ContextStrategy` interface + `BreweryContextStrategy` /
|
|
||||||
`BeerContextStrategy`. Today `WikipediaEnrichmentService::GetLocationContext`
|
|
||||||
hardcodes a generic `"brewing"` query and a `"beer in {country}"`
|
|
||||||
query directly — no per-phase strategy selection.
|
|
||||||
- [ ] `SamplingStrategy` interface + `UniformSamplingStrategy`, replacing
|
|
||||||
the inline `std::ranges::sample(...)` call in
|
|
||||||
`BiergartenPipelineOrchestrator::QueryCitiesWithCountries()`.
|
|
||||||
- [ ] `BeerSelectionStrategy` interface + `RandomBeerSelectionStrategy`, to
|
|
||||||
pick styles per brewery from the `BeerStyle` palette (depends on §1
|
|
||||||
and §2).
|
|
||||||
- [ ] `CheckinDistributionStrategy` interface + `JCurveCheckinStrategy` /
|
|
||||||
`RandomCheckinStrategy` — this is the "Check-In System" item already
|
|
||||||
called out in README.md's Next Steps, made concrete.
|
|
||||||
- [ ] `FollowGenerationStrategy` interface + `RandomFollowStrategy` /
|
|
||||||
`ActivityWeightedFollowStrategy`.
|
|
||||||
|
|
||||||
## 4. Data Generation
|
|
||||||
|
|
||||||
`tooling/pipeline/includes/data_generation/`, `src/data_generation/`.
|
|
||||||
|
|
||||||
- [ ] Extend the `DataGenerator` interface with `GenerateBeer`,
|
|
||||||
`GenerateCheckin`, `GenerateRating` (today: only `GenerateBrewery` and
|
|
||||||
`GenerateUser`).
|
|
||||||
- [x] Implement `LlamaGenerator::GenerateUser` for real, with a retry loop
|
|
||||||
mirroring `GenerateBrewery` (GBNF grammar, `ValidateUserJson`, up to 3
|
|
||||||
attempts with corrective feedback) and a new
|
|
||||||
`prompts/USER_GENERATION.md`. Changed the `DataGenerator::GenerateUser`
|
|
||||||
signature to
|
|
||||||
`(city : const EnrichedCity&, persona : const UserPersona&, name : const Name&) : UserResult`,
|
|
||||||
matching what the activity diagram actually passes. `MockGenerator::GenerateUser`
|
|
||||||
updated to match the new signature too.
|
|
||||||
- [ ] Implement `MockGenerator::GenerateBeer` / `GenerateCheckin` /
|
|
||||||
`GenerateRating`.
|
|
||||||
- [ ] Add `IPromptFormatter::ExpectedArchitecture()` and
|
|
||||||
`LlamaGenerator::ValidateModelArchitecture()` so loading a GGUF that
|
|
||||||
doesn't match the configured chat template fails fast instead of
|
|
||||||
silently producing degraded output.
|
|
||||||
- [ ] Add prompt template files for beer/checkin/rating generation next to
|
|
||||||
the existing `prompts/BREWERY_GENERATION.md`.
|
|
||||||
|
|
||||||
## 5. Export Service
|
|
||||||
|
|
||||||
`tooling/pipeline/includes/services/database/`, `src/services/sqlite/`.
|
|
||||||
|
|
||||||
- [x] `IExportService::ProcessRecord(const UserRecord&)` and
|
|
||||||
`SqliteExportService`'s `users` table (see
|
|
||||||
`kCreateUsersTableSql` / `kInsertUserSql` in
|
|
||||||
`includes/services/database/sqlite_statement_helpers.h`) are
|
|
||||||
implemented — `GenerateUsers()` exports every successful user
|
|
||||||
alongside its resolved `location_id`.
|
|
||||||
- [ ] Extend `IExportService` with `ProcessBeer`, `ProcessCheckin`,
|
|
||||||
`ProcessRating`, `ProcessFollow` (today `ProcessRecord(const
|
|
||||||
BreweryRecord&)` and `ProcessRecord(const UserRecord&)` exist).
|
|
||||||
- [ ] Add `beers`, `checkins`, `ratings`, `follows` tables to
|
|
||||||
`SqliteExportService::InitializeSchema()` (`locations`, `breweries`,
|
|
||||||
and `users` already exist) — see `kCreateLocationsTableSql` /
|
|
||||||
`kCreateBreweriesTableSql` / `kCreateUsersTableSql` in
|
|
||||||
`includes/services/database/sqlite_statement_helpers.h` for the
|
|
||||||
existing pattern to follow.
|
|
||||||
- [ ] Add a `brewery_cache_` alongside the existing `location_cache_`, and
|
|
||||||
move from one open transaction for the whole run to per-phase batched
|
|
||||||
commits (`BEGIN` / `COMMIT & BEGIN` on a batch-size threshold), as
|
|
||||||
shown in the planned activity diagram.
|
|
||||||
|
|
||||||
## 6. Concurrency & Orchestration
|
|
||||||
|
|
||||||
`tooling/pipeline/includes/concurrency/`,
|
|
||||||
`src/biergarten_pipeline_orchestrator/`.
|
|
||||||
|
|
||||||
- [ ] `BoundedChannel<T>` already exists and is production-tested — but
|
|
||||||
it's only wired to the single log channel today. Stand up the
|
|
||||||
per-phase producer/consumer channels (`loc_ch`, `exp_ch`, etc.) the
|
|
||||||
planned activity diagram describes, each with a dedicated LLM worker
|
|
||||||
thread and SQLite worker thread.
|
|
||||||
- [ ] Rewrite `BiergartenPipelineOrchestrator::Run()` from one synchronous
|
|
||||||
pass over `generated_breweries_` into phased methods —
|
|
||||||
`RunUserPhase` → `RunBreweryAndBeerPhase` (with a `RunBeerPhase`
|
|
||||||
sub-step once `brewery_pool_` is populated) → `RunCheckinPhase` /
|
|
||||||
`RunFollowPhase` (these two can run in parallel) → `RunRatingPhase` —
|
|
||||||
backed by `user_pool_`, `brewery_pool_`, `beer_pool_`,
|
|
||||||
`checkin_pool_`, `follow_pool_`.
|
|
||||||
- [ ] Honor the structural-concurrency requirement already called out in a
|
|
||||||
comment on `BiergartenPipelineOrchestrator::Run()` in
|
|
||||||
`biergarten_pipeline_orchestrator.h`: once real worker threads exist,
|
|
||||||
they must be structurally joined (e.g. via `std::jthread`) before
|
|
||||||
`Run()` returns, so no worker logs to a closed channel during
|
|
||||||
teardown.
|
|
||||||
|
|
||||||
## 7. Enrichment
|
|
||||||
|
|
||||||
- [ ] Decide whether to restore the city/region-specific Wikipedia query
|
|
||||||
that's currently commented out in
|
|
||||||
`src/services/enrichment/wikipedia/get_summary.cc`
|
|
||||||
(`GetLocationContext`). The `ContextStrategy` work in §3 is a natural
|
|
||||||
place to reintroduce it via `BreweryContextStrategy::QueriesFor()`.
|
|
||||||
- [ ] Pre-warm caches at startup (`PreWarmBeerStyleCache`,
|
|
||||||
`PreWarmLocationCache` in the planned activity diagram) instead of
|
|
||||||
fetching lazily per record, so the streaming phases never block on a
|
|
||||||
cold cache mid-run.
|
|
||||||
|
|
||||||
## 8. Fixtures / Build
|
|
||||||
|
|
||||||
- [x] Author `personas.json`, `forenames-by-country.json`, and
|
|
||||||
`surnames-by-country.json` (see §2).
|
|
||||||
- [ ] Fix the `beer-styles.json` build-tree gap: add it to the "Runtime
|
|
||||||
Assets" `configure_file` step in `CMakeLists.txt` so native builds and
|
|
||||||
the Docker image agree on what's available at runtime.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Suggested build order
|
|
||||||
|
|
||||||
The planned activity diagram's own phase notes ("brewery*pool* is now fully
|
|
||||||
populated. Phase 1b may begin.", etc.) imply a dependency order. Roughly:
|
|
||||||
|
|
||||||
1. Domain models (§1) and data preloading (§2) — nothing else compiles
|
|
||||||
without these.
|
|
||||||
2. Export schema (§5) — so every later generation phase has somewhere to
|
|
||||||
land its output.
|
|
||||||
3. Policy/strategy layer (§3) and generator interface (§4).
|
|
||||||
4. Concurrency/orchestration rewrite (§6), which is the only piece that
|
|
||||||
actually wires §1–§5 into the phased, parallel pipeline shown in the
|
|
||||||
planned diagrams.
|
|
||||||
5. Enrichment cache pre-warming and the city/region query decision (§7) —
|
|
||||||
useful at any point, but most valuable once phases run concurrently.
|
|
||||||
@@ -18,40 +18,23 @@ skinparam ActivityBarColor #628A5B
|
|||||||
skinparam SwimlaneBorderColor #547461
|
skinparam SwimlaneBorderColor #547461
|
||||||
skinparam SwimlaneBorderThickness 0.3
|
skinparam SwimlaneBorderThickness 0.3
|
||||||
|
|
||||||
title The Biergarten Data Pipeline (Current — Synchronous Data Path)
|
title The Biergarten Data Pipeline (Streaming Architecture)
|
||||||
|
|
||||||
|#F2F6F0|main.cc|
|
|#F2F6F0|main.cc|
|
||||||
start
|
start
|
||||||
:Create BoundedChannel<LogEntry> log_channel;
|
|
||||||
:Spawn log dispatcher thread\n(LogDispatcher::Run());
|
|
||||||
note right
|
|
||||||
The only concurrency in the current pipeline:
|
|
||||||
a dedicated thread drains log_channel and
|
|
||||||
forwards entries to spdlog for the entire run.
|
|
||||||
Joined during shutdown after log_channel closes.
|
|
||||||
end note
|
|
||||||
:ParseArguments(argc, argv);
|
:ParseArguments(argc, argv);
|
||||||
if (Are arguments valid?) then (no)
|
if (Are arguments valid?) then (no)
|
||||||
:Log error / usage info;
|
:spdlog::error usage info;
|
||||||
stop
|
stop
|
||||||
else (yes)
|
else (yes)
|
||||||
endif
|
endif
|
||||||
|
|
||||||
:Init OpenSSL global state & LlamaBackendState;
|
:Init OpenSSL global state & LlamaBackendState;
|
||||||
:di::make_injector(...);
|
:di::make_injector(...);
|
||||||
note right
|
:injector.create<std::unique_ptr<BiergartenDataGenerator>>();
|
||||||
Binds ILogger, IEnrichmentService, DataGenerator,
|
:BiergartenDataGenerator::Run();
|
||||||
IExportService, IPromptFormatter, WebClient based
|
|
||||||
on --mocked vs. model-backed mode.
|
|
||||||
end note
|
|
||||||
:injector.create<std::unique_ptr<BiergartenPipelineOrchestrator>>();
|
|
||||||
:BiergartenPipelineOrchestrator::Run();
|
|
||||||
note right
|
|
||||||
Run() itself is synchronous — sampling, enrichment,
|
|
||||||
generation, and export all happen on this thread.
|
|
||||||
end note
|
|
||||||
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|#EAF0E8|BiergartenDataGenerator|
|
||||||
:Initialize SQLite export;
|
:Initialize SQLite export;
|
||||||
|
|
||||||
|#E0EAE0|SqliteExportService|
|
|#E0EAE0|SqliteExportService|
|
||||||
@@ -65,106 +48,23 @@ note right
|
|||||||
Begins Transaction
|
Begins Transaction
|
||||||
end note
|
end note
|
||||||
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|#EAF0E8|BiergartenDataGenerator|
|
||||||
:QueryCitiesWithCountries();
|
:QueryCitiesWithCountries();
|
||||||
|
|
||||||
|#E2EBDC|JsonLoader|
|
|#E2EBDC|JsonLoader|
|
||||||
:JsonLoader::LoadLocations("locations.json");
|
:JsonLoader::LoadLocations("locations.json");
|
||||||
:std::ranges::sample(all_locations, --location-count);
|
:std::ranges::sample(all_locations, 50);
|
||||||
note right
|
|
||||||
--location-count defaults to 10.
|
|
||||||
end note
|
|
||||||
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|#EAF0E8|BiergartenDataGenerator|
|
||||||
while (For each sampled Location?) is (Remaining cities)
|
while (For each sampled Location?) is (Remaining cities)
|
||||||
|#DCE8D8|IEnrichmentService|
|
|#DCE8D8|WikipediaService|
|
||||||
:GetLocationContext(loc);
|
:GetLocationContext(loc);
|
||||||
note right
|
:FetchExtracts(City, Country, Beer);
|
||||||
WikipediaEnrichmentService fetches a generic
|
|#EAF0E8|BiergartenDataGenerator|
|
||||||
"brewing" extract and a "beer in {country}" extract
|
:Store EnrichedCity{Location, region_context};
|
||||||
(not a city/region-specific page). MockEnrichmentService
|
|
||||||
(--mocked) returns an empty string instead.
|
|
||||||
end note
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|
||||||
if (Lookup failed?) then (yes)
|
|
||||||
:Log warning, skip city;
|
|
||||||
else (no)
|
|
||||||
:Store EnrichedCity{Location, region_context};
|
|
||||||
endif
|
|
||||||
endwhile (Done)
|
endwhile (Done)
|
||||||
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|#EAF0E8|BiergartenDataGenerator|
|
||||||
:GenerateUsers(enriched_cities);
|
|
||||||
|
|
||||||
|#E2EBDC|JsonLoader|
|
|
||||||
:LoadPersonas("personas.json");
|
|
||||||
:LoadForenamesByCountry("forenames-by-country.json");
|
|
||||||
:LoadSurnamesByCountry("surnames-by-country.json");
|
|
||||||
note right
|
|
||||||
Each call is cached after its first parse.
|
|
||||||
MockCuratedDataService (--mocked) returns a
|
|
||||||
fixed in-memory dataset instead and skips
|
|
||||||
these three JSON files entirely.
|
|
||||||
end note
|
|
||||||
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|
||||||
while (For each EnrichedCity?) is (Remaining cities)
|
|
||||||
:SampleName(forenames_by_country,\n surnames_by_country, location.iso3166_1);
|
|
||||||
if (Names available for country?) then (no)
|
|
||||||
:Log warning, skip city;
|
|
||||||
else (yes)
|
|
||||||
:Sample UserPersona (uniform random);
|
|
||||||
|
|
||||||
|#E5EDE1|DataGenerator|
|
|
||||||
if (Generator Mode) then (MockGenerator)
|
|
||||||
:DeterministicHash & Format;
|
|
||||||
else (LlamaGenerator)
|
|
||||||
:prompt_directory_->Load("USER_GENERATION");
|
|
||||||
note right
|
|
||||||
Resolves to USER_GENERATION.md inside --prompt-dir.
|
|
||||||
end note
|
|
||||||
repeat
|
|
||||||
:Infer(system_prompt, user_prompt, max_tokens, kUserJsonGrammar);
|
|
||||||
:ValidateUserJson(raw, user);
|
|
||||||
if (Is JSON Valid?) then (yes)
|
|
||||||
break
|
|
||||||
else (no)
|
|
||||||
:Attempt++;
|
|
||||||
:Append validation error to retry prompt;
|
|
||||||
endif
|
|
||||||
repeat while (Attempt < 3?) is (yes)
|
|
||||||
endif
|
|
||||||
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|
||||||
if (Generation successful?) then (yes)
|
|
||||||
:BuildEmail(name, used_email_local_parts);
|
|
||||||
:GenerateDateOfBirth(rng);
|
|
||||||
note right
|
|
||||||
email and date_of_birth are generated
|
|
||||||
programmatically, never LLM-authored.
|
|
||||||
end note
|
|
||||||
|
|
||||||
|#E0EAE0|SqliteExportService|
|
|
||||||
:ProcessRecord(UserRecord);
|
|
||||||
if (Location in cache?) then (yes)
|
|
||||||
:Reuse location_id;
|
|
||||||
else (no)
|
|
||||||
:Insert Location & Cache ID;
|
|
||||||
endif
|
|
||||||
:Insert User (FK: location_id);
|
|
||||||
|
|
||||||
if (Exception caught during insert?) then (yes)
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|
||||||
:Log warning "SQLite export failed";
|
|
||||||
else (no)
|
|
||||||
endif
|
|
||||||
else (no)
|
|
||||||
:Log warning "Generation failed, skipping...";
|
|
||||||
endif
|
|
||||||
endif
|
|
||||||
endwhile (Done)
|
|
||||||
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|
||||||
:GenerateBreweries(enriched_cities);
|
:GenerateBreweries(enriched_cities);
|
||||||
|
|
||||||
|#E5EDE1|DataGenerator|
|
|#E5EDE1|DataGenerator|
|
||||||
@@ -173,10 +73,7 @@ while (For each EnrichedCity?) is (Remaining cities)
|
|||||||
:DeterministicHash & Format;
|
:DeterministicHash & Format;
|
||||||
else (LlamaGenerator)
|
else (LlamaGenerator)
|
||||||
:PrepareRegionContext;
|
:PrepareRegionContext;
|
||||||
:prompt_directory_->Load("BREWERY_GENERATION");
|
:LoadBrewerySystemPrompt("prompts/system.md");
|
||||||
note right
|
|
||||||
Resolves to BREWERY_GENERATION.md inside --prompt-dir.
|
|
||||||
end note
|
|
||||||
repeat
|
repeat
|
||||||
:Infer(system_prompt, user_prompt, max_tokens, kBreweryJsonGrammar);
|
:Infer(system_prompt, user_prompt, max_tokens, kBreweryJsonGrammar);
|
||||||
:ValidateBreweryJson(raw, brewery);
|
:ValidateBreweryJson(raw, brewery);
|
||||||
@@ -184,16 +81,11 @@ while (For each EnrichedCity?) is (Remaining cities)
|
|||||||
break
|
break
|
||||||
else (no)
|
else (no)
|
||||||
:Attempt++;
|
:Attempt++;
|
||||||
:Append validation error to retry prompt;
|
|
||||||
endif
|
endif
|
||||||
repeat while (Attempt < 3?) is (yes)
|
repeat while (Attempt < 3?) is (yes)
|
||||||
note right
|
|
||||||
max_tokens is fixed across retries —
|
|
||||||
it is not raised on truncation.
|
|
||||||
end note
|
|
||||||
endif
|
endif
|
||||||
|
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|#EAF0E8|BiergartenDataGenerator|
|
||||||
if (Generation successful?) then (yes)
|
if (Generation successful?) then (yes)
|
||||||
|#E0EAE0|SqliteExportService|
|
|#E0EAE0|SqliteExportService|
|
||||||
:ProcessRecord(GeneratedBrewery);
|
:ProcessRecord(GeneratedBrewery);
|
||||||
@@ -205,8 +97,8 @@ while (For each EnrichedCity?) is (Remaining cities)
|
|||||||
:Insert Brewery (FK: location_id);
|
:Insert Brewery (FK: location_id);
|
||||||
|
|
||||||
if (Exception caught during insert?) then (yes)
|
if (Exception caught during insert?) then (yes)
|
||||||
|#EAF0E8|BiergartenPipelineOrchestrator|
|
|#EAF0E8|BiergartenDataGenerator|
|
||||||
:Log warning "SQLite export failed";
|
:spdlog::warn "Failed to stream record to SQLite export";
|
||||||
note right
|
note right
|
||||||
Data loss is prevented per-record.
|
Data loss is prevented per-record.
|
||||||
The pipeline continues running.
|
The pipeline continues running.
|
||||||
@@ -214,7 +106,7 @@ while (For each EnrichedCity?) is (Remaining cities)
|
|||||||
else (no)
|
else (no)
|
||||||
endif
|
endif
|
||||||
else (no)
|
else (no)
|
||||||
:Log warning "Generation failed, skipping...";
|
:spdlog::warn "Generation failed, skipping...";
|
||||||
endif
|
endif
|
||||||
|#E5EDE1|DataGenerator|
|
|#E5EDE1|DataGenerator|
|
||||||
endwhile (Done)
|
endwhile (Done)
|
||||||
@@ -227,8 +119,6 @@ note right
|
|||||||
end note
|
end note
|
||||||
|
|
||||||
|#F2F6F0|main.cc|
|
|#F2F6F0|main.cc|
|
||||||
:Close log_channel;
|
|
||||||
:Join log dispatcher thread;
|
|
||||||
:Return 0;
|
:Return 0;
|
||||||
stop
|
stop
|
||||||
|
|
||||||
|
|||||||
@@ -25,19 +25,15 @@ skinparam note {
|
|||||||
|
|
||||||
title The Biergarten Data Pipeline - Class Diagram
|
title The Biergarten Data Pipeline - Class Diagram
|
||||||
|
|
||||||
class BiergartenPipelineOrchestrator {
|
class BiergartenDataGenerator {
|
||||||
- logger_ : std::shared_ptr<ILogger>
|
- logger_ : std::shared_ptr<ILogger>
|
||||||
- context_service_ : std::unique_ptr<IEnrichmentService>
|
- context_service_ : std::unique_ptr<IEnrichmentService>
|
||||||
- generator_ : std::unique_ptr<DataGenerator>
|
- generator_ : std::unique_ptr<DataGenerator>
|
||||||
- exporter_ : std::unique_ptr<IExportService>
|
- exporter_ : std::unique_ptr<IExportService>
|
||||||
- curated_data_service_ : std::unique_ptr<ICuratedDataService>
|
- generated_breweries_ : std::vector<GeneratedBrewery>
|
||||||
- application_options_ : ApplicationOptions
|
|
||||||
- generated_breweries_ : std::vector<BreweryRecord>
|
|
||||||
- generated_users_ : std::vector<UserRecord>
|
|
||||||
+ Run() : bool
|
+ Run() : bool
|
||||||
- QueryCitiesWithCountries() : std::vector<Location>
|
- QueryCitiesWithCountries() : std::vector<Location>
|
||||||
- GenerateBreweries(cities : std::span<const EnrichedCity>) : void
|
- GenerateBreweries(cities : std::span<const EnrichedCity>) : void
|
||||||
- GenerateUsers(cities : std::span<const EnrichedCity>) : void
|
|
||||||
- LogResults() : void
|
- LogResults() : void
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,29 +54,21 @@ class PipelinePhase <<enumeration>> {
|
|||||||
Teardown
|
Teardown
|
||||||
}
|
}
|
||||||
|
|
||||||
struct LogDTO {
|
|
||||||
+ level : LogLevel
|
|
||||||
+ phase : PipelinePhase
|
|
||||||
+ message : std::string
|
|
||||||
}
|
|
||||||
|
|
||||||
struct LogEntry {
|
struct LogEntry {
|
||||||
+ timestamp : std::chrono::system_clock::time_point
|
+ timestamp : std::chrono::system_clock::time_point
|
||||||
+ origin : std::source_location
|
|
||||||
+ thread_id : std::thread::id
|
|
||||||
+ level : LogLevel
|
+ level : LogLevel
|
||||||
+ phase : PipelinePhase
|
+ phase : PipelinePhase
|
||||||
+ message : std::string
|
+ message : std::string
|
||||||
|
+ worker : std::optional<std::string>
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ILogger <<interface>> {
|
interface ILogger <<interface>> {
|
||||||
+ Log(payload : LogDTO) : void
|
+ Log(entry : const LogEntry&) : void
|
||||||
- {abstract} DoLog(entry : LogEntry) : void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class LogProducer {
|
class LogProducer {
|
||||||
- channel_ : BoundedChannel<LogEntry>&
|
- channel_ : BoundedChannel<LogEntry>&
|
||||||
- DoLog(entry : LogEntry) : void
|
+ Log(entry : const LogEntry&) : void
|
||||||
}
|
}
|
||||||
|
|
||||||
class LogDispatcher {
|
class LogDispatcher {
|
||||||
@@ -93,11 +81,7 @@ interface IEnrichmentService <<interface>> {
|
|||||||
+ GetLocationContext(loc : const Location&) : std::string
|
+ GetLocationContext(loc : const Location&) : std::string
|
||||||
}
|
}
|
||||||
|
|
||||||
class MockEnrichmentService {
|
class WikipediaService {
|
||||||
+ GetLocationContext(loc : const Location&) : std::string
|
|
||||||
}
|
|
||||||
|
|
||||||
class WikipediaEnrichmentService {
|
|
||||||
- client_ : std::unique_ptr<WebClient>
|
- client_ : std::unique_ptr<WebClient>
|
||||||
- extract_cache_ : std::unordered_map<std::string, std::string>
|
- extract_cache_ : std::unordered_map<std::string, std::string>
|
||||||
+ GetLocationContext(loc : const Location&) : std::string
|
+ GetLocationContext(loc : const Location&) : std::string
|
||||||
@@ -116,27 +100,26 @@ class HttpWebClient {
|
|||||||
|
|
||||||
interface DataGenerator <<interface>> {
|
interface DataGenerator <<interface>> {
|
||||||
+ GenerateBrewery(location : const Location&, region_context : const std::string&) : BreweryResult
|
+ GenerateBrewery(location : const Location&, region_context : const std::string&) : BreweryResult
|
||||||
+ GenerateUser(city : const EnrichedCity&, persona : const UserPersona&, name : const Name&) : UserResult
|
+ GenerateUser(locale : const std::string&) : UserResult
|
||||||
}
|
}
|
||||||
|
|
||||||
class MockGenerator {
|
class MockGenerator {
|
||||||
+ GenerateBrewery(location : const Location&, region_context : const std::string&) : BreweryResult
|
+ GenerateBrewery(...) : BreweryResult
|
||||||
+ GenerateUser(city : const EnrichedCity&, persona : const UserPersona&, name : const Name&) : UserResult
|
+ GenerateUser(...) : UserResult
|
||||||
- DeterministicHash(location : const Location&) : size_t
|
- DeterministicHash(location : const Location&) : size_t
|
||||||
- DeterministicHash(location : const Location&, persona : const UserPersona&, name : const Name&) : size_t
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class LlamaGenerator {
|
class LlamaGenerator {
|
||||||
- model_ : ModelHandle
|
- model_ : ModelHandle
|
||||||
- context_ : ContextHandle
|
- context_ : ContextHandle
|
||||||
- prompt_formatter_ : std::unique_ptr<IPromptFormatter>
|
- prompt_formatter_ : std::unique_ptr<IPromptFormatter>
|
||||||
- prompt_directory_ : std::unique_ptr<IPromptDirectory>
|
|
||||||
- rng_ : std::mt19937
|
- rng_ : std::mt19937
|
||||||
+ GenerateBrewery(...) : BreweryResult
|
+ GenerateBrewery(...) : BreweryResult
|
||||||
+ GenerateUser(...) : UserResult
|
+ GenerateUser(...) : UserResult
|
||||||
- Load(model_path : const std::string&) : void
|
- Load(model_path : const std::string&) : void
|
||||||
- Infer(...) : std::string
|
- Infer(...) : std::string
|
||||||
- InferFormatted(...) : std::string
|
- InferFormatted(...) : std::string
|
||||||
|
- LoadBrewerySystemPrompt(...) : std::string
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IPromptFormatter <<interface>> {
|
interface IPromptFormatter <<interface>> {
|
||||||
@@ -147,59 +130,13 @@ class Gemma4JinjaPromptFormatter {
|
|||||||
+ Format(system_prompt : std::string_view, user_prompt : std::string_view) : std::string
|
+ Format(system_prompt : std::string_view, user_prompt : std::string_view) : std::string
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IPromptDirectory <<interface>> {
|
|
||||||
+ Load(key : std::string_view) : std::string
|
|
||||||
}
|
|
||||||
|
|
||||||
class PromptDirectory {
|
|
||||||
- prompt_dir_ : std::filesystem::path
|
|
||||||
- cache_ : std::unordered_map<std::string, std::string>
|
|
||||||
+ Load(key : std::string_view) : std::string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ICuratedDataService <<interface>> {
|
|
||||||
+ LoadLocations(filepath : const std::filesystem::path&) : const std::vector<Location>&
|
|
||||||
+ LoadPersonas(filepath : const std::filesystem::path&) : const std::vector<UserPersona>&
|
|
||||||
+ LoadForenamesByCountry(filepath : const std::filesystem::path&) : const std::unordered_map<std::string, forename_list>&
|
|
||||||
+ LoadSurnamesByCountry(filepath : const std::filesystem::path&) : const std::unordered_map<std::string, surname_list>&
|
|
||||||
}
|
|
||||||
|
|
||||||
class JsonLoader {
|
class JsonLoader {
|
||||||
- cache_ : cache
|
+ {static} LoadLocations(filepath : const std::filesystem::path&) : std::vector<Location>
|
||||||
+ LoadLocations(filepath : const std::filesystem::path&) : const std::vector<Location>&
|
|
||||||
+ LoadPersonas(filepath : const std::filesystem::path&) : const std::vector<UserPersona>&
|
|
||||||
+ LoadForenamesByCountry(filepath : const std::filesystem::path&) : const std::unordered_map<std::string, forename_list>&
|
|
||||||
+ LoadSurnamesByCountry(filepath : const std::filesystem::path&) : const std::unordered_map<std::string, surname_list>&
|
|
||||||
}
|
}
|
||||||
|
|
||||||
note right of JsonLoader
|
|
||||||
Each Load* method memoizes its result in
|
|
||||||
cache_ on first call; later calls on the
|
|
||||||
same instance return the cached value
|
|
||||||
without re-parsing.
|
|
||||||
end note
|
|
||||||
|
|
||||||
class MockCuratedDataService {
|
|
||||||
- locations_ : std::vector<Location>
|
|
||||||
- personas_ : std::vector<UserPersona>
|
|
||||||
- forenames_by_country_ : std::unordered_map<std::string, forename_list>
|
|
||||||
- surnames_by_country_ : std::unordered_map<std::string, surname_list>
|
|
||||||
+ LoadLocations(filepath : const std::filesystem::path&) : const std::vector<Location>&
|
|
||||||
+ LoadPersonas(filepath : const std::filesystem::path&) : const std::vector<UserPersona>&
|
|
||||||
+ LoadForenamesByCountry(filepath : const std::filesystem::path&) : const std::unordered_map<std::string, forename_list>&
|
|
||||||
+ LoadSurnamesByCountry(filepath : const std::filesystem::path&) : const std::unordered_map<std::string, surname_list>&
|
|
||||||
}
|
|
||||||
|
|
||||||
note right of MockCuratedDataService
|
|
||||||
Fixed 4-location / 3-persona dataset
|
|
||||||
(US, DE, FR, BE) used in --mocked runs;
|
|
||||||
filepath arguments are ignored.
|
|
||||||
end note
|
|
||||||
|
|
||||||
interface IExportService <<interface>> {
|
interface IExportService <<interface>> {
|
||||||
+ Initialize() : void
|
+ Initialize() : void
|
||||||
+ ProcessRecord(brewery : const BreweryRecord&) : uint64_t
|
+ ProcessRecord(brewery : const GeneratedBrewery&) : void
|
||||||
+ ProcessRecord(user : const UserRecord&) : uint64_t
|
|
||||||
+ Finalize() : void
|
+ Finalize() : void
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,18 +144,15 @@ class SqliteExportService {
|
|||||||
- date_time_provider_ : std::unique_ptr<IDateTimeProvider>
|
- date_time_provider_ : std::unique_ptr<IDateTimeProvider>
|
||||||
- run_timestamp_utc_ : std::string
|
- run_timestamp_utc_ : std::string
|
||||||
- database_path_ : std::filesystem::path
|
- database_path_ : std::filesystem::path
|
||||||
- db_handle_ : SqliteDatabaseHandle
|
- db_handle_ : sqlite3*
|
||||||
- insert_location_stmt_ : SqliteStatementHandle
|
- insert_location_stmt_ : sqlite3_stmt*
|
||||||
- insert_brewery_stmt_ : SqliteStatementHandle
|
- insert_brewery_stmt_ : sqlite3_stmt*
|
||||||
- insert_user_stmt_ : SqliteStatementHandle
|
|
||||||
- transaction_open_ : bool
|
- transaction_open_ : bool
|
||||||
- location_cache_ : std::unordered_map<std::string, sqlite3_int64>
|
- location_cache_ : std::unordered_map<std::string, sqlite3_int64>
|
||||||
+ Initialize() : void
|
+ Initialize() : void
|
||||||
+ ProcessRecord(brewery : const BreweryRecord&) : uint64_t
|
+ ProcessRecord(brewery : const GeneratedBrewery&) : void
|
||||||
+ ProcessRecord(user : const UserRecord&) : uint64_t
|
|
||||||
+ Finalize() : void
|
+ Finalize() : void
|
||||||
- InitializeSchema() : void
|
- InitializeSchema() : void
|
||||||
- ResolveLocationId(location : const Location&) : sqlite3_int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IDateTimeProvider <<interface>> {
|
interface IDateTimeProvider <<interface>> {
|
||||||
@@ -230,23 +164,19 @@ class SystemDateTimeProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
' Structural Relationships / Dependency Injection
|
' Structural Relationships / Dependency Injection
|
||||||
BiergartenPipelineOrchestrator *-- ILogger : owns
|
BiergartenDataGenerator *-- ILogger : owns
|
||||||
BiergartenPipelineOrchestrator *-- IEnrichmentService : owns
|
BiergartenDataGenerator *-- IEnrichmentService : owns
|
||||||
BiergartenPipelineOrchestrator *-- DataGenerator : owns
|
BiergartenDataGenerator *-- DataGenerator : owns
|
||||||
BiergartenPipelineOrchestrator *-- IExportService : owns
|
BiergartenDataGenerator *-- IExportService : owns
|
||||||
BiergartenPipelineOrchestrator *-- ICuratedDataService : owns
|
|
||||||
|
|
||||||
LogEntry *-- LogLevel
|
LogEntry *-- LogLevel
|
||||||
LogEntry *-- PipelinePhase
|
LogEntry *-- PipelinePhase
|
||||||
LogDTO *-- LogLevel
|
|
||||||
LogDTO *-- PipelinePhase
|
|
||||||
ILogger <|.. LogProducer : implements
|
ILogger <|.. LogProducer : implements
|
||||||
LogProducer ..> LogEntry : emits
|
LogProducer ..> LogEntry : emits
|
||||||
LogDispatcher ..> LogEntry : consumes
|
LogDispatcher ..> LogEntry : consumes
|
||||||
|
|
||||||
IEnrichmentService <|.. WikipediaEnrichmentService : implements
|
IEnrichmentService <|.. WikipediaService : implements
|
||||||
IEnrichmentService <|.. MockEnrichmentService : implements
|
WikipediaService *-- WebClient : owns
|
||||||
WikipediaEnrichmentService *-- WebClient : owns
|
|
||||||
|
|
||||||
WebClient <|.. HttpWebClient : implements
|
WebClient <|.. HttpWebClient : implements
|
||||||
|
|
||||||
@@ -254,13 +184,10 @@ DataGenerator <|.. MockGenerator : implements
|
|||||||
DataGenerator <|.. LlamaGenerator : implements
|
DataGenerator <|.. LlamaGenerator : implements
|
||||||
|
|
||||||
LlamaGenerator *-- IPromptFormatter : uses
|
LlamaGenerator *-- IPromptFormatter : uses
|
||||||
LlamaGenerator *-- IPromptDirectory : uses
|
|
||||||
|
|
||||||
IPromptFormatter <|.. Gemma4JinjaPromptFormatter : implements
|
IPromptFormatter <|.. Gemma4JinjaPromptFormatter : implements
|
||||||
IPromptDirectory <|.. PromptDirectory : implements
|
|
||||||
|
|
||||||
ICuratedDataService <|.. JsonLoader : implements
|
BiergartenDataGenerator ..> JsonLoader : uses
|
||||||
ICuratedDataService <|.. MockCuratedDataService : implements
|
|
||||||
|
|
||||||
IExportService <|.. SqliteExportService : implements
|
IExportService <|.. SqliteExportService : implements
|
||||||
SqliteExportService *-- IDateTimeProvider : owns
|
SqliteExportService *-- IDateTimeProvider : owns
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 86 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 44 KiB |
@@ -43,18 +43,10 @@ fork again
|
|||||||
:EnrichmentService::PreWarmLocationCache(sampled_locations);
|
:EnrichmentService::PreWarmLocationCache(sampled_locations);
|
||||||
end fork
|
end fork
|
||||||
fork
|
fork
|
||||||
:JsonLoader::LoadForenamesByCountry(\n "forenames-by-country.json");
|
:JsonLoader::LoadNamesByCountry("names-by-country.json");
|
||||||
fork again
|
|
||||||
:JsonLoader::LoadSurnamesByCountry(\n "surnames-by-country.json");
|
|
||||||
fork again
|
fork again
|
||||||
:JsonLoader::LoadPersonas("personas.json");
|
:JsonLoader::LoadPersonas("personas.json");
|
||||||
end fork
|
end fork
|
||||||
note right
|
|
||||||
Each call is memoized after its first parse
|
|
||||||
(implemented today). MockCuratedDataService
|
|
||||||
returns a fixed in-memory dataset instead
|
|
||||||
under --mocked, skipping these JSON files.
|
|
||||||
end note
|
|
||||||
|
|
||||||
' ═══════════════════════════════════════════
|
' ═══════════════════════════════════════════
|
||||||
' PHASE 0 — USER GENERATION
|
' PHASE 0 — USER GENERATION
|
||||||
@@ -90,15 +82,11 @@ fork again
|
|||||||
ibu_preference, checkin_weight.
|
ibu_preference, checkin_weight.
|
||||||
end note
|
end note
|
||||||
|
|
||||||
:SampleName(forenames_by_country,\n surnames_by_country, location.iso3166_1, rng);
|
:NamesByCountry::SampleName(\n location.iso3166_1);
|
||||||
note right
|
note right
|
||||||
Deterministic lookup -- no LLM involved.
|
Deterministic lookup -- no LLM involved.
|
||||||
Free function (implemented today in
|
Name selected from pre-keyed table
|
||||||
generate_users.cc), not a class method.
|
|
||||||
Name selected from pre-keyed maps
|
|
||||||
and passed into the generation prompt.
|
and passed into the generation prompt.
|
||||||
Skips the city if either map has no
|
|
||||||
entry for iso3166_1.
|
|
||||||
end note
|
end note
|
||||||
|
|
||||||
:GenerateUser(enriched_city, persona, sampled_name)\nvia DataGenerator;
|
:GenerateUser(enriched_city, persona, sampled_name)\nvia DataGenerator;
|
||||||
|
|||||||
@@ -67,50 +67,11 @@ package "Domain: Models" {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class UserResult {
|
class UserResult {
|
||||||
+ first_name : std::string
|
|
||||||
+ last_name : std::string
|
|
||||||
+ gender : std::string
|
|
||||||
+ username : std::string
|
+ username : std::string
|
||||||
+ bio : std::string
|
+ bio : std::string
|
||||||
+ activity_weight : float
|
+ activity_weight : float
|
||||||
}
|
}
|
||||||
|
|
||||||
class Name {
|
|
||||||
+ first_name : std::string
|
|
||||||
+ last_name : std::string
|
|
||||||
+ gender : std::string
|
|
||||||
}
|
|
||||||
|
|
||||||
class ForenameEntry {
|
|
||||||
+ name : std::string
|
|
||||||
+ gender : std::string
|
|
||||||
}
|
|
||||||
|
|
||||||
note right of ForenameEntry
|
|
||||||
forename_list = std::unordered_set<ForenameEntry>
|
|
||||||
surname_list = std::unordered_set<std::string>
|
|
||||||
(aliases declared in curated_data_service.h).
|
|
||||||
ICuratedDataService::LoadForenamesByCountry() /
|
|
||||||
LoadSurnamesByCountry() each return a flat
|
|
||||||
std::unordered_map<std::string, forename_list>
|
|
||||||
or <std::string, surname_list> keyed by ISO
|
|
||||||
3166-1 country code -- no NamesByCountry
|
|
||||||
wrapper class. SampleName(forenames_by_country,
|
|
||||||
surnames_by_country, iso3166_1, rng) is a free
|
|
||||||
function, not a method, so it can be called by
|
|
||||||
any per-city worker without owning the maps.
|
|
||||||
Sourced from popular-names-by-country-dataset
|
|
||||||
(CC0) -- see ETHICS-AND-KNOWN-ISSUES.md. Gender
|
|
||||||
is preserved per forename so it can be threaded
|
|
||||||
through to persona/bio generation later; surnames
|
|
||||||
carry no gender in the source data. Pairing
|
|
||||||
happens at sample time, not at fixture-authoring
|
|
||||||
time, so no information from the source dataset
|
|
||||||
is discarded up front.
|
|
||||||
end note
|
|
||||||
|
|
||||||
ForenameEntry ..> Name : SampleName() produces
|
|
||||||
|
|
||||||
class CheckinResult {
|
class CheckinResult {
|
||||||
+ checked_in_at : std::string
|
+ checked_in_at : std::string
|
||||||
+ note : std::string
|
+ note : std::string
|
||||||
@@ -149,20 +110,9 @@ package "Domain: Models" {
|
|||||||
+ user_id : uint64_t
|
+ user_id : uint64_t
|
||||||
+ location : Location
|
+ location : Location
|
||||||
+ user : UserResult
|
+ user : UserResult
|
||||||
+ email : std::string
|
|
||||||
+ date_of_birth : std::string
|
|
||||||
+ password : std::string
|
|
||||||
+ metadata : GenerationMetadata
|
+ metadata : GenerationMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
note right of GeneratedUser
|
|
||||||
email, date_of_birth, and password are
|
|
||||||
programmatically generated by the orchestrator
|
|
||||||
(not LLM-authored) so a downstream auth-account
|
|
||||||
seeding consumer can register real accounts from
|
|
||||||
this export. See ROADMAP.md §1.
|
|
||||||
end note
|
|
||||||
|
|
||||||
class GeneratedCheckin {
|
class GeneratedCheckin {
|
||||||
+ checkin_id : uint64_t
|
+ checkin_id : uint64_t
|
||||||
+ user_id : uint64_t
|
+ user_id : uint64_t
|
||||||
@@ -368,43 +318,20 @@ package "Infrastructure: Pipeline Channel" {
|
|||||||
|
|
||||||
package "Infrastructure: Data Preloading" {
|
package "Infrastructure: Data Preloading" {
|
||||||
|
|
||||||
interface ICuratedDataService <<interface>> {
|
interface DataPreloader <<interface>> {
|
||||||
+ LoadLocations(filepath : const std::filesystem::path&) : const std::vector<Location>&
|
+ LoadLocations(filepath : const std::filesystem::path&) : std::vector<Location>
|
||||||
+ LoadBeerStyles(filepath : const std::filesystem::path&) : const std::vector<BeerStyle>&
|
+ LoadBeerStyles(filepath : const std::filesystem::path&) : std::vector<BeerStyle>
|
||||||
+ LoadPersonas(filepath : const std::filesystem::path&) : const std::vector<UserPersona>&
|
+ LoadPersonas(filepath : const std::filesystem::path&) : std::vector<Persona>
|
||||||
+ LoadForenamesByCountry(forenames_filepath : const std::filesystem::path&) : const std::unordered_map<std::string, forename_list>&
|
+ LoadNamesByCountry(filepath : const std::filesystem::path&) : NamesByCountry
|
||||||
+ LoadSurnamesByCountry(surnames_filepath : const std::filesystem::path&) : const std::unordered_map<std::string, surname_list>&
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class JsonLoader {
|
class JsonLoader {
|
||||||
+ LoadLocations(filepath : const std::filesystem::path&) : const std::vector<Location>&
|
+ LoadLocations(filepath : const std::filesystem::path&) : std::vector<Location>
|
||||||
+ LoadBeerStyles(filepath : const std::filesystem::path&) : const std::vector<BeerStyle>&
|
+ LoadBeerStyles(filepath : const std::filesystem::path&) : std::vector<BeerStyle>
|
||||||
+ LoadPersonas(filepath : const std::filesystem::path&) : const std::vector<UserPersona>&
|
+ LoadPersonas(filepath : const std::filesystem::path&) : std::vector<Persona>
|
||||||
+ LoadForenamesByCountry(forenames_filepath : const std::filesystem::path&) : const std::unordered_map<std::string, forename_list>&
|
+ LoadNamesByCountry(filepath : const std::filesystem::path&) : NamesByCountry
|
||||||
+ LoadSurnamesByCountry(surnames_filepath : const std::filesystem::path&) : const std::unordered_map<std::string, surname_list>&
|
|
||||||
}
|
}
|
||||||
|
|
||||||
note right of JsonLoader
|
|
||||||
Each Load* call is memoized after its first
|
|
||||||
parse -- implemented today, ahead of the rest
|
|
||||||
of this package (LoadBeerStyles is still planned).
|
|
||||||
end note
|
|
||||||
|
|
||||||
class MockCuratedDataService {
|
|
||||||
+ LoadLocations(filepath : const std::filesystem::path&) : const std::vector<Location>&
|
|
||||||
+ LoadBeerStyles(filepath : const std::filesystem::path&) : const std::vector<BeerStyle>&
|
|
||||||
+ LoadPersonas(filepath : const std::filesystem::path&) : const std::vector<UserPersona>&
|
|
||||||
+ LoadForenamesByCountry(forenames_filepath : const std::filesystem::path&) : const std::unordered_map<std::string, forename_list>&
|
|
||||||
+ LoadSurnamesByCountry(surnames_filepath : const std::filesystem::path&) : const std::unordered_map<std::string, surname_list>&
|
|
||||||
}
|
|
||||||
|
|
||||||
note right of MockCuratedDataService
|
|
||||||
Fixed in-memory dataset used in --mocked mode,
|
|
||||||
implemented today for Locations/Personas/
|
|
||||||
Forenames/Surnames; would need a LoadBeerStyles
|
|
||||||
fixture too once that method is implemented.
|
|
||||||
end note
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
package "Infrastructure: Enrichment" {
|
package "Infrastructure: Enrichment" {
|
||||||
@@ -453,7 +380,7 @@ package "Infrastructure: Data Generation" {
|
|||||||
interface DataGenerator <<interface>> {
|
interface DataGenerator <<interface>> {
|
||||||
+ GenerateBrewery(location : const Location&,\n context : const LocationContext&) : BreweryResult
|
+ GenerateBrewery(location : const Location&,\n context : const LocationContext&) : BreweryResult
|
||||||
+ GenerateBeer(brewery_id : uint64_t,\n location : const Location&,\n context : const LocationContext&,\n style : const BeerStyle&) : BeerResult
|
+ GenerateBeer(brewery_id : uint64_t,\n location : const Location&,\n context : const LocationContext&,\n style : const BeerStyle&) : BeerResult
|
||||||
+ GenerateUser(city : const EnrichedCity&,\n persona : const UserPersona&,\n name : const Name&) : UserResult
|
+ GenerateUser(location : const Location&) : UserResult
|
||||||
+ GenerateCheckin(user : const GeneratedUser&,\n brewery : const GeneratedBrewery&,\n timestamp : const std::string&) : CheckinResult
|
+ GenerateCheckin(user : const GeneratedUser&,\n brewery : const GeneratedBrewery&,\n timestamp : const std::string&) : CheckinResult
|
||||||
+ GenerateRating(user : const GeneratedUser&,\n beer : const GeneratedBeer&,\n checkin_id : uint64_t) : RatingResult
|
+ GenerateRating(user : const GeneratedUser&,\n beer : const GeneratedBeer&,\n checkin_id : uint64_t) : RatingResult
|
||||||
}
|
}
|
||||||
@@ -546,7 +473,7 @@ package "Infrastructure: Data Export" {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class BiergartenPipelineOrchestrator {
|
class BiergartenPipelineOrchestrator {
|
||||||
- curated_data_service_ : std::unique_ptr<ICuratedDataService>
|
- preloader_ : std::unique_ptr<DataPreloader>
|
||||||
- enrichment_service_ : std::unique_ptr<EnrichmentService>
|
- enrichment_service_ : std::unique_ptr<EnrichmentService>
|
||||||
- generator_ : std::unique_ptr<DataGenerator>
|
- generator_ : std::unique_ptr<DataGenerator>
|
||||||
- logger_ : std::unique_ptr<Logger>
|
- logger_ : std::unique_ptr<Logger>
|
||||||
@@ -574,7 +501,7 @@ class BiergartenPipelineOrchestrator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
' --- Orchestration Aggregations (Services & Strategies) ---
|
' --- Orchestration Aggregations (Services & Strategies) ---
|
||||||
BiergartenPipelineOrchestrator *-- ICuratedDataService
|
BiergartenPipelineOrchestrator *-- DataPreloader
|
||||||
BiergartenPipelineOrchestrator *-- EnrichmentService
|
BiergartenPipelineOrchestrator *-- EnrichmentService
|
||||||
BiergartenPipelineOrchestrator *-- DataGenerator
|
BiergartenPipelineOrchestrator *-- DataGenerator
|
||||||
BiergartenPipelineOrchestrator *-- ExportService
|
BiergartenPipelineOrchestrator *-- ExportService
|
||||||
@@ -593,8 +520,7 @@ BiergartenPipelineOrchestrator *-- "0..*" GeneratedCheckin : checkin_pool_
|
|||||||
BiergartenPipelineOrchestrator *-- "0..*" GeneratedFollow : follow_pool_
|
BiergartenPipelineOrchestrator *-- "0..*" GeneratedFollow : follow_pool_
|
||||||
|
|
||||||
' --- Interfaces & Implementations ---
|
' --- Interfaces & Implementations ---
|
||||||
ICuratedDataService <|.. JsonLoader
|
DataPreloader <|.. JsonLoader
|
||||||
ICuratedDataService <|.. MockCuratedDataService
|
|
||||||
Logger <|.. PipelineLogger
|
Logger <|.. PipelineLogger
|
||||||
ContextStrategy <|.. BreweryContextStrategy
|
ContextStrategy <|.. BreweryContextStrategy
|
||||||
ContextStrategy <|.. BeerContextStrategy
|
ContextStrategy <|.. BeerContextStrategy
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 142 KiB After Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 240 KiB After Width: | Height: | Size: 184 KiB |
24
tooling/pipeline-results-viewer/.gitignore
vendored
@@ -1,24 +0,0 @@
|
|||||||
# Logs
|
|
||||||
logs
|
|
||||||
*.log
|
|
||||||
npm-debug.log*
|
|
||||||
yarn-debug.log*
|
|
||||||
yarn-error.log*
|
|
||||||
pnpm-debug.log*
|
|
||||||
lerna-debug.log*
|
|
||||||
|
|
||||||
node_modules
|
|
||||||
dist
|
|
||||||
dist-ssr
|
|
||||||
*.local
|
|
||||||
|
|
||||||
# Editor directories and files
|
|
||||||
.vscode/*
|
|
||||||
!.vscode/extensions.json
|
|
||||||
.idea
|
|
||||||
.DS_Store
|
|
||||||
*.suo
|
|
||||||
*.ntvs*
|
|
||||||
*.njsproj
|
|
||||||
*.sln
|
|
||||||
*.sw?
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>Pipeline Results Viewer</title>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="dialog" id="window">
|
|
||||||
<div class="dialog-header">
|
|
||||||
<p>Pipeline Results Viewer</p>
|
|
||||||
</div>
|
|
||||||
<div class="tab-strip" role="tablist">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="tab is-active"
|
|
||||||
id="tab-tables"
|
|
||||||
role="tab"
|
|
||||||
aria-selected="true"
|
|
||||||
aria-controls="panel-tables"
|
|
||||||
>
|
|
||||||
Tables
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="tab"
|
|
||||||
id="tab-query"
|
|
||||||
role="tab"
|
|
||||||
aria-selected="false"
|
|
||||||
aria-controls="panel-query"
|
|
||||||
>
|
|
||||||
Query
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="dialog-body">
|
|
||||||
<div
|
|
||||||
class="tab-panel"
|
|
||||||
id="panel-tables"
|
|
||||||
role="tabpanel"
|
|
||||||
aria-labelledby="tab-tables"
|
|
||||||
>
|
|
||||||
<div class="field-group">
|
|
||||||
<label for="table-select">Table</label>
|
|
||||||
<select id="table-select"></select>
|
|
||||||
</div>
|
|
||||||
<p id="status"></p>
|
|
||||||
<div id="table-container"></div>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="tab-panel"
|
|
||||||
id="panel-query"
|
|
||||||
role="tabpanel"
|
|
||||||
aria-labelledby="tab-query"
|
|
||||||
hidden
|
|
||||||
>
|
|
||||||
<div class="field-group field-group--stacked">
|
|
||||||
<label for="query-input">SQL Query</label>
|
|
||||||
<textarea
|
|
||||||
id="query-input"
|
|
||||||
rows="4"
|
|
||||||
spellcheck="false"
|
|
||||||
placeholder="SELECT * FROM ..."
|
|
||||||
></textarea>
|
|
||||||
</div>
|
|
||||||
<button type="button" id="query-run" class="btn">Run Query</button>
|
|
||||||
<p id="query-status"></p>
|
|
||||||
<div id="query-container"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<script type="module" src="/src/main.ts"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
1334
tooling/pipeline-results-viewer/package-lock.json
generated
@@ -1,20 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "pipeline-results-viewer",
|
|
||||||
"version": "0.0.0",
|
|
||||||
"private": true,
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"dev": "vite",
|
|
||||||
"build": "tsc && vite build",
|
|
||||||
"preview": "vite preview"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/sql.js": "^1.4.11",
|
|
||||||
"sass": "^1.101.0",
|
|
||||||
"typescript": "^6.0.3",
|
|
||||||
"vite": "^8.0.12"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"sql.js": "^1.14.1"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
Before Width: | Height: | Size: 9.3 KiB |
@@ -1,147 +0,0 @@
|
|||||||
import initSqlJs, { type Database, type SqlValue } from "sql.js";
|
|
||||||
import sqlWasmUrl from "sql.js/dist/sql-wasm.wasm?url";
|
|
||||||
import "./style.scss";
|
|
||||||
|
|
||||||
const DB_URL = "/biergarten.sqlite";
|
|
||||||
|
|
||||||
const tabs = document.querySelectorAll<HTMLButtonElement>("[role='tab']");
|
|
||||||
const panels = document.querySelectorAll<HTMLDivElement>("[role='tabpanel']");
|
|
||||||
|
|
||||||
const tableSelect = document.querySelector<HTMLSelectElement>("#table-select")!;
|
|
||||||
const tableContainer =
|
|
||||||
document.querySelector<HTMLDivElement>("#table-container")!;
|
|
||||||
const status = document.querySelector<HTMLParagraphElement>("#status")!;
|
|
||||||
|
|
||||||
const queryInput = document.querySelector<HTMLTextAreaElement>("#query-input")!;
|
|
||||||
const queryRun = document.querySelector<HTMLButtonElement>("#query-run")!;
|
|
||||||
const queryStatus = document.querySelector<HTMLParagraphElement>("#query-status")!;
|
|
||||||
const queryContainer =
|
|
||||||
document.querySelector<HTMLDivElement>("#query-container")!;
|
|
||||||
|
|
||||||
for (const tab of tabs) {
|
|
||||||
tab.addEventListener("click", () => {
|
|
||||||
for (const otherTab of tabs) {
|
|
||||||
const isActive = otherTab === tab;
|
|
||||||
otherTab.classList.toggle("is-active", isActive);
|
|
||||||
otherTab.setAttribute("aria-selected", String(isActive));
|
|
||||||
}
|
|
||||||
for (const panel of panels) {
|
|
||||||
panel.hidden = panel.id !== tab.getAttribute("aria-controls");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const renderResultTable = (
|
|
||||||
container: HTMLDivElement,
|
|
||||||
columns: string[],
|
|
||||||
values: SqlValue[][],
|
|
||||||
) => {
|
|
||||||
const table = document.createElement("table");
|
|
||||||
|
|
||||||
const head = table.createTHead().insertRow();
|
|
||||||
for (const column of columns) {
|
|
||||||
const th = document.createElement("th");
|
|
||||||
th.textContent = column;
|
|
||||||
head.append(th);
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = table.createTBody();
|
|
||||||
for (const row of values) {
|
|
||||||
const tr = body.insertRow();
|
|
||||||
for (const cell of row) {
|
|
||||||
const td = document.createElement("td");
|
|
||||||
td.textContent = String(cell ?? "");
|
|
||||||
tr.append(td);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
container.append(table);
|
|
||||||
};
|
|
||||||
|
|
||||||
const renderTable = (db: Database, name: string) => {
|
|
||||||
const result = db.exec(`SELECT * FROM "${name}"`);
|
|
||||||
tableContainer.replaceChildren();
|
|
||||||
|
|
||||||
if (result.length === 0) {
|
|
||||||
tableContainer.append(
|
|
||||||
Object.assign(document.createElement("p"), { textContent: "No rows." }),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { columns, values } = result[0];
|
|
||||||
renderResultTable(tableContainer, columns, values);
|
|
||||||
};
|
|
||||||
|
|
||||||
const runQuery = (db: Database) => {
|
|
||||||
const sql = queryInput.value.trim();
|
|
||||||
queryContainer.replaceChildren();
|
|
||||||
|
|
||||||
if (!sql) {
|
|
||||||
queryStatus.textContent = "Enter a query to run.";
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const results = db.exec(sql);
|
|
||||||
|
|
||||||
if (results.length === 0) {
|
|
||||||
queryStatus.textContent = "Query executed. No rows returned.";
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { columns, values } = results[results.length - 1];
|
|
||||||
renderResultTable(queryContainer, columns, values);
|
|
||||||
queryStatus.textContent = `${values.length} row${values.length === 1 ? "" : "s"} returned.`;
|
|
||||||
} catch (error) {
|
|
||||||
queryStatus.textContent = `Error: ${error instanceof Error ? error.message : String(error)}`;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
async function main(): Promise<void> {
|
|
||||||
status.textContent = "Loading database...";
|
|
||||||
|
|
||||||
const sqlJs = await initSqlJs({ locateFile: () => sqlWasmUrl });
|
|
||||||
const response = await fetch(DB_URL);
|
|
||||||
const buffer = await response.arrayBuffer();
|
|
||||||
const db = new sqlJs.Database(new Uint8Array(buffer));
|
|
||||||
|
|
||||||
const tables =
|
|
||||||
db
|
|
||||||
.exec(
|
|
||||||
`SELECT name
|
|
||||||
FROM sqlite_master
|
|
||||||
WHERE
|
|
||||||
type = 'table'
|
|
||||||
AND
|
|
||||||
name NOT LIKE 'sqlite_%'
|
|
||||||
ORDER BY name`,
|
|
||||||
)[0]
|
|
||||||
?.values.map((row) => String(row[0])) ?? [];
|
|
||||||
|
|
||||||
for (const name of tables) {
|
|
||||||
tableSelect.append(new Option(name, name));
|
|
||||||
}
|
|
||||||
|
|
||||||
tableSelect.addEventListener("change", () =>
|
|
||||||
renderTable(db, tableSelect.value),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (tables.length > 0) {
|
|
||||||
renderTable(db, tables[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
status.textContent = "";
|
|
||||||
|
|
||||||
queryRun.addEventListener("click", () => runQuery(db));
|
|
||||||
queryInput.addEventListener("keydown", (event) => {
|
|
||||||
if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
|
|
||||||
event.preventDefault();
|
|
||||||
runQuery(db);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch((error: unknown) => {
|
|
||||||
status.textContent = `Failed to load database: ${String(error)}`;
|
|
||||||
});
|
|
||||||
@@ -1,267 +0,0 @@
|
|||||||
$gray-100: #dedede;
|
|
||||||
$gray-300: #c3c3c3;
|
|
||||||
$gray-500: #808080;
|
|
||||||
$white: #ffffff;
|
|
||||||
$black: #000000;
|
|
||||||
$navy: #000080;
|
|
||||||
$blue: #1084d0;
|
|
||||||
$teal: #008080;
|
|
||||||
|
|
||||||
$color-surface: $gray-300;
|
|
||||||
$color-surface-alt: $gray-100;
|
|
||||||
$color-surface-sunken: $white;
|
|
||||||
$color-border-highlight: $gray-100;
|
|
||||||
$color-border-lowlight: $gray-500;
|
|
||||||
$color-border-light: $white;
|
|
||||||
$color-border-dark: $black;
|
|
||||||
$color-text: $black;
|
|
||||||
$color-text-on-accent: $white;
|
|
||||||
$color-text-status: $navy;
|
|
||||||
$color-accent-start: $navy;
|
|
||||||
$color-accent-end: $blue;
|
|
||||||
$color-desktop-bg: $teal;
|
|
||||||
$color-row-stripe: $gray-100;
|
|
||||||
$color-shadow: rgba($black, 0.4);
|
|
||||||
$color-focus-ring: $black;
|
|
||||||
|
|
||||||
$bevel-size: 2px;
|
|
||||||
$font-stack: Tahoma, "MS Sans Serif", Verdana, sans-serif;
|
|
||||||
|
|
||||||
@mixin bevel-raised($size: $bevel-size) {
|
|
||||||
border-style: solid;
|
|
||||||
border-width: $size;
|
|
||||||
border-top-color: $color-border-highlight;
|
|
||||||
border-left-color: $color-border-highlight;
|
|
||||||
border-right-color: $color-border-dark;
|
|
||||||
border-bottom-color: $color-border-dark;
|
|
||||||
box-shadow:
|
|
||||||
inset $size $size 0 0 $color-border-light,
|
|
||||||
inset (-$size) (-$size) 0 0 $color-border-lowlight;
|
|
||||||
}
|
|
||||||
|
|
||||||
@mixin bevel-sunken($size: $bevel-size) {
|
|
||||||
border-style: solid;
|
|
||||||
border-width: $size;
|
|
||||||
border-top-color: $color-border-lowlight;
|
|
||||||
border-left-color: $color-border-lowlight;
|
|
||||||
border-right-color: $color-border-light;
|
|
||||||
border-bottom-color: $color-border-light;
|
|
||||||
box-shadow:
|
|
||||||
inset $size $size 0 0 $color-border-dark,
|
|
||||||
inset (-$size) (-$size) 0 0 $color-surface-alt;
|
|
||||||
}
|
|
||||||
|
|
||||||
* {
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
|
|
||||||
body {
|
|
||||||
margin: 0;
|
|
||||||
padding: 24px;
|
|
||||||
background: $color-desktop-bg;
|
|
||||||
font-family: $font-stack;
|
|
||||||
color: $color-text;
|
|
||||||
min-height: 100vh;
|
|
||||||
}
|
|
||||||
|
|
||||||
#window {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 1600px;
|
|
||||||
margin: 0 auto;
|
|
||||||
background: $color-surface;
|
|
||||||
padding: 6px;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 6px;
|
|
||||||
@include bevel-raised(3px);
|
|
||||||
box-shadow: 8px 8px 0 0 $color-shadow;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dialog-header {
|
|
||||||
background: linear-gradient(90deg, $color-accent-start, $color-accent-end);
|
|
||||||
color: $color-text-on-accent;
|
|
||||||
padding: 6px 8px;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
|
|
||||||
p {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 14px;
|
|
||||||
font-weight: bold;
|
|
||||||
letter-spacing: 0.5px;
|
|
||||||
text-transform: uppercase;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-strip {
|
|
||||||
display: flex;
|
|
||||||
gap: 4px;
|
|
||||||
padding: 8px 8px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab {
|
|
||||||
position: relative;
|
|
||||||
top: 3px;
|
|
||||||
margin-bottom: -2px;
|
|
||||||
font-family: $font-stack;
|
|
||||||
font-size: 12px;
|
|
||||||
font-weight: bold;
|
|
||||||
text-transform: uppercase;
|
|
||||||
padding: 6px 14px;
|
|
||||||
background: $color-surface;
|
|
||||||
color: $color-text;
|
|
||||||
border-style: solid;
|
|
||||||
border-width: 2px;
|
|
||||||
border-top-color: $color-border-light;
|
|
||||||
border-left-color: $color-border-light;
|
|
||||||
border-right-color: $color-border-dark;
|
|
||||||
border-bottom-color: $color-border-dark;
|
|
||||||
border-radius: 0;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&.is-active {
|
|
||||||
top: 0;
|
|
||||||
z-index: 1;
|
|
||||||
border-bottom-color: $color-surface;
|
|
||||||
}
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: 1px dotted $color-focus-ring;
|
|
||||||
outline-offset: -4px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.dialog-body {
|
|
||||||
border-top: 2px solid $color-border-dark;
|
|
||||||
padding: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tab-panel {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 12px;
|
|
||||||
|
|
||||||
&[hidden] {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.field-group {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
|
|
||||||
label {
|
|
||||||
font-size: 12px;
|
|
||||||
font-weight: bold;
|
|
||||||
text-transform: uppercase;
|
|
||||||
}
|
|
||||||
|
|
||||||
&.field-group--stacked {
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: stretch;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
select#table-select {
|
|
||||||
font-family: $font-stack;
|
|
||||||
font-size: 13px;
|
|
||||||
padding: 3px 6px;
|
|
||||||
background: $color-surface-sunken;
|
|
||||||
color: $color-text;
|
|
||||||
border-radius: 0;
|
|
||||||
@include bevel-sunken();
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: 1px dotted $color-focus-ring;
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
textarea#query-input {
|
|
||||||
font-family: $font-stack;
|
|
||||||
font-size: 13px;
|
|
||||||
padding: 6px;
|
|
||||||
background: $color-surface-sunken;
|
|
||||||
color: $color-text;
|
|
||||||
border-radius: 0;
|
|
||||||
resize: vertical;
|
|
||||||
@include bevel-sunken();
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: 1px dotted $color-focus-ring;
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn {
|
|
||||||
align-self: flex-start;
|
|
||||||
font-family: $font-stack;
|
|
||||||
font-size: 12px;
|
|
||||||
font-weight: bold;
|
|
||||||
text-transform: uppercase;
|
|
||||||
padding: 6px 16px;
|
|
||||||
background: $color-surface;
|
|
||||||
color: $color-text;
|
|
||||||
cursor: pointer;
|
|
||||||
@include bevel-raised();
|
|
||||||
|
|
||||||
&:active {
|
|
||||||
@include bevel-sunken();
|
|
||||||
}
|
|
||||||
|
|
||||||
&:focus {
|
|
||||||
outline: 1px dotted $color-focus-ring;
|
|
||||||
outline-offset: -4px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#status,
|
|
||||||
#query-status {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 12px;
|
|
||||||
font-style: italic;
|
|
||||||
color: $color-text-status;
|
|
||||||
}
|
|
||||||
|
|
||||||
#table-container,
|
|
||||||
#query-container {
|
|
||||||
background: $color-surface-sunken;
|
|
||||||
padding: 4px;
|
|
||||||
overflow-x: auto;
|
|
||||||
@include bevel-sunken();
|
|
||||||
}
|
|
||||||
|
|
||||||
table {
|
|
||||||
border-collapse: collapse;
|
|
||||||
margin: 0 auto;
|
|
||||||
font-family: $font-stack;
|
|
||||||
}
|
|
||||||
|
|
||||||
th,
|
|
||||||
td {
|
|
||||||
border: 1px solid $color-border-lowlight;
|
|
||||||
padding: 4px 8px;
|
|
||||||
text-align: left;
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
th {
|
|
||||||
background: $color-surface;
|
|
||||||
white-space: nowrap;
|
|
||||||
font-weight: bold;
|
|
||||||
text-transform: uppercase;
|
|
||||||
@include bevel-raised(1px);
|
|
||||||
}
|
|
||||||
|
|
||||||
td {
|
|
||||||
min-width: 120px;
|
|
||||||
max-width: 800px;
|
|
||||||
white-space: normal;
|
|
||||||
word-break: break-word;
|
|
||||||
background: $color-surface-sunken;
|
|
||||||
}
|
|
||||||
|
|
||||||
tbody tr:nth-child(even) td {
|
|
||||||
background: $color-row-stripe;
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "es2023",
|
|
||||||
"module": "esnext",
|
|
||||||
"lib": ["ES2023", "DOM"],
|
|
||||||
"types": ["vite/client"],
|
|
||||||
"skipLibCheck": true,
|
|
||||||
|
|
||||||
/* Bundler mode */
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"allowImportingTsExtensions": true,
|
|
||||||
"verbatimModuleSyntax": true,
|
|
||||||
"moduleDetection": "force",
|
|
||||||
"noEmit": true,
|
|
||||||
|
|
||||||
/* Linting */
|
|
||||||
"noUnusedLocals": true,
|
|
||||||
"noUnusedParameters": true,
|
|
||||||
"erasableSyntaxOnly": true,
|
|
||||||
"noFallthroughCasesInSwitch": true
|
|
||||||
},
|
|
||||||
"include": ["src"]
|
|
||||||
}
|
|
||||||
@@ -139,7 +139,6 @@ FetchContent_MakeAvailable(cpp-httplib)
|
|||||||
# 5. Executable & Sources
|
# 5. Executable & Sources
|
||||||
add_executable(${PROJECT_NAME}
|
add_executable(${PROJECT_NAME}
|
||||||
includes/services/enrichment/mock_enrichment.h
|
includes/services/enrichment/mock_enrichment.h
|
||||||
includes/services/curated_data/mock_curated_data_service.h
|
|
||||||
includes/json_handling/pretty_print.h)
|
includes/json_handling/pretty_print.h)
|
||||||
|
|
||||||
# --- Entry point ---
|
# --- Entry point ---
|
||||||
@@ -149,12 +148,7 @@ target_sources(${PROJECT_NAME} PRIVATE
|
|||||||
|
|
||||||
# --- json_handling ---
|
# --- json_handling ---
|
||||||
target_sources(${PROJECT_NAME} PRIVATE
|
target_sources(${PROJECT_NAME} PRIVATE
|
||||||
src/services/curated_data/curated_json_data_service.cc
|
src/json_handling/json_loader.cc
|
||||||
)
|
|
||||||
|
|
||||||
# --- services: curated_data ---
|
|
||||||
target_sources(${PROJECT_NAME} PRIVATE
|
|
||||||
src/services/curated_data/mock_curated_data_service.cc
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# --- application_options ---
|
# --- application_options ---
|
||||||
@@ -167,7 +161,6 @@ target_sources(${PROJECT_NAME} PRIVATE
|
|||||||
src/biergarten_pipeline_orchestrator/log_results.cc
|
src/biergarten_pipeline_orchestrator/log_results.cc
|
||||||
src/biergarten_pipeline_orchestrator/biergarten_pipeline_orchestrator.cc
|
src/biergarten_pipeline_orchestrator/biergarten_pipeline_orchestrator.cc
|
||||||
src/biergarten_pipeline_orchestrator/generate_breweries.cc
|
src/biergarten_pipeline_orchestrator/generate_breweries.cc
|
||||||
src/biergarten_pipeline_orchestrator/generate_users.cc
|
|
||||||
src/biergarten_pipeline_orchestrator/run.cc
|
src/biergarten_pipeline_orchestrator/run.cc
|
||||||
src/biergarten_pipeline_orchestrator/query_cities_with_countries.cc
|
src/biergarten_pipeline_orchestrator/query_cities_with_countries.cc
|
||||||
)
|
)
|
||||||
@@ -211,7 +204,6 @@ target_sources(${PROJECT_NAME} PRIVATE
|
|||||||
# --- services: sqlite ---
|
# --- services: sqlite ---
|
||||||
target_sources(${PROJECT_NAME} PRIVATE
|
target_sources(${PROJECT_NAME} PRIVATE
|
||||||
src/services/sqlite/process_record.cc
|
src/services/sqlite/process_record.cc
|
||||||
src/services/sqlite/process_user_record.cc
|
|
||||||
src/services/sqlite/sqlite_export_service.cc
|
src/services/sqlite/sqlite_export_service.cc
|
||||||
src/services/sqlite/finalize.cc
|
src/services/sqlite/finalize.cc
|
||||||
src/services/sqlite/initialize.cc
|
src/services/sqlite/initialize.cc
|
||||||
@@ -268,21 +260,6 @@ configure_file(
|
|||||||
${CMAKE_BINARY_DIR}/locations.json
|
${CMAKE_BINARY_DIR}/locations.json
|
||||||
COPYONLY
|
COPYONLY
|
||||||
)
|
)
|
||||||
configure_file(
|
|
||||||
${CMAKE_SOURCE_DIR}/personas.json
|
|
||||||
${CMAKE_BINARY_DIR}/personas.json
|
|
||||||
COPYONLY
|
|
||||||
)
|
|
||||||
configure_file(
|
|
||||||
${CMAKE_SOURCE_DIR}/forenames-by-country.json
|
|
||||||
${CMAKE_BINARY_DIR}/forenames-by-country.json
|
|
||||||
COPYONLY
|
|
||||||
)
|
|
||||||
configure_file(
|
|
||||||
${CMAKE_SOURCE_DIR}/surnames-by-country.json
|
|
||||||
${CMAKE_BINARY_DIR}/surnames-by-country.json
|
|
||||||
COPYONLY
|
|
||||||
)
|
|
||||||
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
|
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
|
||||||
COMMAND ${CMAKE_COMMAND} -E copy_directory
|
COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||||
${CMAKE_SOURCE_DIR}/prompts
|
${CMAKE_SOURCE_DIR}/prompts
|
||||||
|
|||||||
@@ -1,72 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# Walks every directory under src/ and includes/ (including nested
|
|
||||||
# subdirectories), runs clang-format on the C/C++ files in that directory
|
|
||||||
# only (non-recursive), and commits the result with its own commit.
|
|
||||||
#
|
|
||||||
# Usage: ./format-per-directory.sh [-y]
|
|
||||||
# -y skip the confirmation prompt
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SKIP_CONFIRM=false
|
|
||||||
if [[ "${1:-}" == "-y" ]]; then
|
|
||||||
SKIP_CONFIRM=true
|
|
||||||
fi
|
|
||||||
|
|
||||||
cd "$(dirname "$0")"
|
|
||||||
|
|
||||||
if [ ! -f .clang-format ]; then
|
|
||||||
echo "ERROR: .clang-format file not found."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if ! command -v clang-format &>/dev/null; then
|
|
||||||
echo "ERROR: clang-format not found."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if ! command -v git &>/dev/null; then
|
|
||||||
echo "ERROR: git not found."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "WARNING: This script will format .cpp, .h, .cxx, .cc, .c, .hpp files"
|
|
||||||
echo "directory-by-directory under src/ and includes/, committing after each"
|
|
||||||
echo "directory is formatted."
|
|
||||||
|
|
||||||
if [[ "$SKIP_CONFIRM" == false ]]; then
|
|
||||||
read -p "Do you want to continue? (y/n) " -n 1 -r
|
|
||||||
echo
|
|
||||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
|
||||||
echo "Aborted."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ -n "$(git status --porcelain)" ]]; then
|
|
||||||
echo "ERROR: working tree is not clean. Commit or stash your changes first."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
dirs=$(find src includes -type d | sort)
|
|
||||||
|
|
||||||
for dir in $dirs; do
|
|
||||||
files=$(find "$dir" -maxdepth 1 -type f \( -name "*.cpp" -o -name "*.hpp" -o -name "*.h" -o -name "*.c" -o -name "*.cc" -o -name "*.cxx" \))
|
|
||||||
|
|
||||||
if [[ -z "$files" ]]; then
|
|
||||||
continue
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Formatting $dir..."
|
|
||||||
echo "$files" | xargs clang-format -i
|
|
||||||
|
|
||||||
if [[ -n "$(git status --porcelain -- "$dir")" ]]; then
|
|
||||||
git add -- "$dir"
|
|
||||||
git commit -m "Formatted $dir"
|
|
||||||
else
|
|
||||||
echo "No changes in $dir, skipping commit."
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "Done."
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_PIPELINE_H_
|
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_PIPELINE_H_
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @file biergarten_pipeline.h
|
|
||||||
* @brief Master umbrella header — includes every public header in the
|
|
||||||
* Biergarten pipeline.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// --- orchestrator ---
|
|
||||||
#include "biergarten_pipeline_orchestrator.h"
|
|
||||||
|
|
||||||
// --- concurrency ---
|
|
||||||
#include "concurrency/bounded_channel.h"
|
|
||||||
|
|
||||||
// --- data_generation ---
|
|
||||||
#include "data_generation/data_generator.h"
|
|
||||||
#include "data_generation/json_grammars.h"
|
|
||||||
#ifndef BIERGARTEN_MOCK_ONLY
|
|
||||||
#include "data_generation/llama_generator.h"
|
|
||||||
#include "data_generation/llama_generator_helpers.h"
|
|
||||||
#endif
|
|
||||||
#include "data_generation/mock_generator.h"
|
|
||||||
#include "data_generation/prompt_formatting/gemma4_jinja_prompt_formatter.h"
|
|
||||||
#include "data_generation/prompt_formatting/prompt_formatter.h"
|
|
||||||
|
|
||||||
// --- data_model ---
|
|
||||||
#include "data_model/generated_models.h"
|
|
||||||
#include "data_model/models.h"
|
|
||||||
|
|
||||||
// --- json_handling ---
|
|
||||||
#include "json_handling/pretty_print.h"
|
|
||||||
#include "services/curated_data/curated_json_data_service.h"
|
|
||||||
|
|
||||||
// --- llama backend ---
|
|
||||||
#ifndef BIERGARTEN_MOCK_ONLY
|
|
||||||
#include "llama_backend_state.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// --- services: curated_data ---
|
|
||||||
#include "services/curated_data/curated_data_service.h"
|
|
||||||
#include "services/curated_data/mock_curated_data_service.h"
|
|
||||||
|
|
||||||
// --- services: database ---
|
|
||||||
#include "services/database/export_service.h"
|
|
||||||
#include "services/database/sqlite_connection_helpers.h"
|
|
||||||
#include "services/database/sqlite_export_service.h"
|
|
||||||
#include "services/database/sqlite_export_service_helpers.h"
|
|
||||||
#include "services/database/sqlite_handle_types.h"
|
|
||||||
#include "services/database/sqlite_statement_helpers.h"
|
|
||||||
|
|
||||||
// --- services: datetime ---
|
|
||||||
#include "services/datetime/date_time_provider.h"
|
|
||||||
#include "services/datetime/timer.h"
|
|
||||||
|
|
||||||
// --- services: enrichment ---
|
|
||||||
#include "services/enrichment/enrichment_service.h"
|
|
||||||
#include "services/enrichment/mock_enrichment.h"
|
|
||||||
#include "services/enrichment/wikipedia_service.h"
|
|
||||||
|
|
||||||
// --- services: logging ---
|
|
||||||
#include "services/logging/log_dispatcher.h"
|
|
||||||
#include "services/logging/log_entry.h"
|
|
||||||
#include "services/logging/log_producer.h"
|
|
||||||
#include "services/logging/logger.h"
|
|
||||||
|
|
||||||
// --- services: prompting ---
|
|
||||||
#include "services/prompting/prompt_directory.h"
|
|
||||||
|
|
||||||
// --- web_client ---
|
|
||||||
#include "web_client/http_web_client.h"
|
|
||||||
#include "web_client/web_client.h"
|
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_PIPELINE_H_
|
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_PIPELINE_ORCHESTRATOR_H_
|
#ifndef BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_DATA_GENERATOR_H_
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_PIPELINE_ORCHESTRATOR_H_
|
#define BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_DATA_GENERATOR_H_
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @file biergarten_pipeline_orchestrator.h
|
* @file biergarten_data_generator.h
|
||||||
* @brief Orchestration for end-to-end brewery and user data generation.
|
* @brief Orchestration for end-to-end brewery data generation pipeline.
|
||||||
|
*
|
||||||
|
* Intent: Coordinates location loading, enrichment, and generation phases
|
||||||
|
* to produce a complete dataset. Coordinates dependencies via composition root.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
@@ -12,36 +15,32 @@
|
|||||||
|
|
||||||
#include "data_generation/data_generator.h"
|
#include "data_generation/data_generator.h"
|
||||||
#include "data_model/generated_models.h"
|
#include "data_model/generated_models.h"
|
||||||
#include "services/curated_data/curated_data_service.h"
|
|
||||||
#include "services/database/export_service.h"
|
#include "services/database/export_service.h"
|
||||||
#include "services/enrichment/enrichment_service.h"
|
#include "services/enrichment/enrichment_service.h"
|
||||||
|
|
||||||
#include "services/logging/logger.h"
|
#include "services/logging/logger.h"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Main orchestrator for the Biergarten data generation pipeline.
|
* @brief Main data generator class for the Biergarten pipeline.
|
||||||
*
|
*
|
||||||
* Handles location loading, city enrichment, and brewery/user generation.
|
* This class encapsulates the core logic for generating brewery data.
|
||||||
|
* It handles location loading, city enrichment, and brewery generation.
|
||||||
*/
|
*/
|
||||||
class BiergartenPipelineOrchestrator {
|
class BiergartenPipelineOrchestrator {
|
||||||
public:
|
public:
|
||||||
/**
|
/**
|
||||||
* @brief Constructs the orchestrator with injected pipeline dependencies.
|
* @brief Constructs the orchestrator with injected pipeline dependencies.
|
||||||
*
|
*
|
||||||
* @param logger Sink for pipeline diagnostics.
|
* @param context_service Provides regional context for locations.
|
||||||
* @param context_service Provides regional context for locations.
|
* @param generator Implementation (Llama or Mock) for brewery/user generation.
|
||||||
* @param generator Implementation (Llama or Mock) for brewery/user
|
* @param exporter Database backend for persisting generated records.
|
||||||
* generation.
|
* @param application_options CLI configuration and paths.
|
||||||
* @param exporter Database backend for persisting generated records.
|
*/
|
||||||
* @param curated_data_service Loads curated location, persona, and name
|
|
||||||
* data used to seed generation.
|
|
||||||
* @param application_options CLI configuration and paths.
|
|
||||||
*/
|
|
||||||
BiergartenPipelineOrchestrator(
|
BiergartenPipelineOrchestrator(
|
||||||
std::shared_ptr<ILogger> logger,
|
std::shared_ptr<ILogger> logger,
|
||||||
std::unique_ptr<IEnrichmentService> context_service,
|
std::unique_ptr<IEnrichmentService> context_service,
|
||||||
std::unique_ptr<DataGenerator> generator,
|
std::unique_ptr<DataGenerator> generator,
|
||||||
std::unique_ptr<IExportService> exporter,
|
std::unique_ptr<IExportService> exporter,
|
||||||
std::unique_ptr<ICuratedDataService> curated_data_service,
|
|
||||||
const ApplicationOptions& application_options);
|
const ApplicationOptions& application_options);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -50,42 +49,38 @@ class BiergartenPipelineOrchestrator {
|
|||||||
* Performs the following steps:
|
* Performs the following steps:
|
||||||
* 1. Load curated locations from JSON
|
* 1. Load curated locations from JSON
|
||||||
* 2. Resolve context for each city using the injected context service
|
* 2. Resolve context for each city using the injected context service
|
||||||
* 3. Generate brewery and user data for sampled cities
|
* 3. Generate brewery data for sampled cities
|
||||||
*
|
*
|
||||||
* @note STRUCTURAL CONCURRENCY REQUIREMENT:
|
* @note STRUCTURAL CONCURRENCY REQUIREMENT:
|
||||||
* When transitioned to a multithreaded design, this method MUST
|
* When transitioned to a multithreaded design, this method MUST structurally
|
||||||
* structurally enforce that all deployed worker threads are joined before
|
* enforce that all deployed worker threads are joined before returning (e.g.
|
||||||
* returning (e.g. by using std::jthread or a structured concurrency
|
* by using std::jthread or a structured concurrency primitive). This ensures
|
||||||
* primitive). This ensures workers do not attempt to log to a closed
|
* workers do not attempt to log to a closed channel during application teardown.
|
||||||
* channel during application teardown.
|
|
||||||
*
|
*
|
||||||
* @return true if successful, false if not
|
* @return true if successful, false if not
|
||||||
*/
|
*/
|
||||||
bool Run();
|
bool Run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
/// @brief Logger instance for emitting pipeline messages.
|
||||||
std::shared_ptr<ILogger> logger_;
|
std::shared_ptr<ILogger> logger_;
|
||||||
|
|
||||||
|
/// @brief Owning context provider dependency.
|
||||||
std::unique_ptr<IEnrichmentService> context_service_;
|
std::unique_ptr<IEnrichmentService> context_service_;
|
||||||
|
|
||||||
/**
|
/// @brief Generator dependency selected in the composition root.
|
||||||
* @brief Generator implementation selected at the composition root (Llama
|
|
||||||
* or Mock).
|
|
||||||
*/
|
|
||||||
std::unique_ptr<DataGenerator> generator_;
|
std::unique_ptr<DataGenerator> generator_;
|
||||||
|
|
||||||
/**
|
/// @brief Storage backend for generated brewery records.
|
||||||
* @brief Storage backend for generated brewery and user records.
|
std::unique_ptr<IExportService> exporter_;
|
||||||
*/
|
|
||||||
std::unique_ptr<IExportService> exporter_;
|
|
||||||
std::unique_ptr<ICuratedDataService> curated_data_service_;
|
|
||||||
|
|
||||||
ApplicationOptions application_options_;
|
/// @brief CLI configuration: paths, model settings, generation parameters.
|
||||||
|
ApplicationOptions application_options_;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Load locations from JSON and sample cities.
|
* @brief Load locations from JSON and sample cities.
|
||||||
*
|
*
|
||||||
* @return Vector of locations randomly sampled per
|
* @return Vector of sampled locations capped at 50 entries.
|
||||||
* PipelineOptions::location_count.
|
|
||||||
*/
|
*/
|
||||||
std::vector<Location> QueryCitiesWithCountries();
|
std::vector<Location> QueryCitiesWithCountries();
|
||||||
|
|
||||||
@@ -97,20 +92,11 @@ class BiergartenPipelineOrchestrator {
|
|||||||
void GenerateBreweries(std::span<const EnrichedCity> cities);
|
void GenerateBreweries(std::span<const EnrichedCity> cities);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Generate users grounded in sampled names and personas for
|
* @brief Log the generated brewery results.
|
||||||
* enriched cities.
|
|
||||||
*
|
|
||||||
* @param cities Span of enriched city data.
|
|
||||||
*/
|
|
||||||
void GenerateUsers(std::span<const EnrichedCity> cities);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Log the generated brewery and user results.
|
|
||||||
*/
|
*/
|
||||||
void LogResults() const;
|
void LogResults() const;
|
||||||
|
|
||||||
std::vector<BreweryRecord> generated_breweries_;
|
/// @brief Stores generated brewery data.
|
||||||
std::vector<UserRecord> generated_users_;
|
std::vector<GeneratedBrewery> generated_breweries_;
|
||||||
};
|
};
|
||||||
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_DATA_GENERATOR_H_
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_BIERGARTEN_PIPELINE_ORCHESTRATOR_H_
|
|
||||||
|
|||||||
@@ -9,12 +9,10 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @file bounded_channel.h
|
* @file bounded_channel.h
|
||||||
* @brief Thread-safe, bounded multi-producer/multi-consumer synchronous
|
* @brief Thread-safe, bounded multi-producer/multi-consumer synchronous channel.
|
||||||
* channel.
|
|
||||||
*
|
*
|
||||||
* Intent: Enables asynchronous inter-thread communication with backpressure.
|
* Intent: Enables asynchronous inter-thread communication with backpressure.
|
||||||
* Models a synchronous channel where producers/consumers block on capacity
|
* Models a synchronous channel where producers/consumers block on capacity limits.
|
||||||
* limits.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "concurrency/bounded_channel.h"
|
#include "bounded_channel.h"
|
||||||
|
|
||||||
template <typename T>
|
template <typename T>
|
||||||
void BoundedChannel<T>::Send(T item) {
|
void BoundedChannel<T>::Send(T item) {
|
||||||
|
|||||||
@@ -28,16 +28,12 @@ class DataGenerator {
|
|||||||
const std::string& region_context) = 0;
|
const std::string& region_context) = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Generates a user profile grounded in a sampled name and persona.
|
* @brief Generates a user profile for a locale.
|
||||||
*
|
*
|
||||||
* @param city Enriched city the user is associated with.
|
* @param locale Locale hint used by generator.
|
||||||
* @param persona Persona archetype grounding the generated bio.
|
|
||||||
* @param name Sampled first/last name (and gender)
|
|
||||||
* @return User generation result.
|
* @return User generation result.
|
||||||
*/
|
*/
|
||||||
virtual UserResult GenerateUser(const EnrichedCity& city,
|
virtual UserResult GenerateUser(const std::string& locale) = 0;
|
||||||
const UserPersona& persona,
|
|
||||||
const Name& name) = 0;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_DATA_GENERATOR_H_
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_DATA_GENERATOR_H_
|
||||||
|
|||||||
@@ -1,52 +0,0 @@
|
|||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_JSON_GRAMMARS_H_
|
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_JSON_GRAMMARS_H_
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @file data_generation/json_grammars.h
|
|
||||||
* @brief GBNF grammars constraining structured JSON output from
|
|
||||||
* LlamaGenerator inference calls.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <string_view>
|
|
||||||
|
|
||||||
// GBNF grammar for structured user JSON output.
|
|
||||||
// thought-block permits the model to emit free-form reasoning before the
|
|
||||||
// JSON object (the prompts explicitly invite this); only the "{...}" tail is
|
|
||||||
// constrained to the expected shape.
|
|
||||||
inline constexpr std::string_view kUserJsonGrammar = R"json_user(
|
|
||||||
root ::= thought-block (
|
|
||||||
"{" ws
|
|
||||||
"\"username\"" ws ":" ws string ws "," ws
|
|
||||||
"\"bio\"" ws ":" ws string ws "," ws
|
|
||||||
"\"activity_weight\"" ws ":" ws number ws
|
|
||||||
"}" ws
|
|
||||||
)
|
|
||||||
thought-block ::= [^{]*
|
|
||||||
ws ::= [ \t\n\r]*
|
|
||||||
string ::= "\"" char+ "\""
|
|
||||||
char ::= [^"\\\x7F\x00-\x1F] | [\\] escape
|
|
||||||
escape ::= ["\\/bfnrt] | "u" hex hex hex hex
|
|
||||||
hex ::= [0-9a-fA-F]
|
|
||||||
number ::= "-"? ("0" | [1-9] [0-9]*) ("." [0-9]+)?
|
|
||||||
)json_user";
|
|
||||||
|
|
||||||
// GBNF grammar for structured brewery JSON output (see thought-block note
|
|
||||||
// above).
|
|
||||||
inline constexpr std::string_view kBreweryJsonGrammar = R"json_brewery(
|
|
||||||
root ::= thought-block (
|
|
||||||
"{" ws
|
|
||||||
"\"name_en\"" ws ":" ws string ws "," ws
|
|
||||||
"\"description_en\"" ws ":" ws string ws "," ws
|
|
||||||
"\"name_local\"" ws ":" ws string ws "," ws
|
|
||||||
"\"description_local\"" ws ":" ws string ws
|
|
||||||
"}" ws
|
|
||||||
)
|
|
||||||
thought-block ::= [^{]*
|
|
||||||
ws ::= [ \t\n\r]*
|
|
||||||
string ::= "\"" char+ "\""
|
|
||||||
char ::= [^"\\\x7F\x00-\x1F] | [\\] escape
|
|
||||||
escape ::= ["\\/bfnrt] | "u" hex hex hex hex
|
|
||||||
hex ::= [0-9a-fA-F]
|
|
||||||
)json_brewery";
|
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_JSON_GRAMMARS_H_
|
|
||||||
@@ -1,23 +1,24 @@
|
|||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_LLAMA_GENERATOR_H_
|
#ifndef BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_LLAMA_GENERATOR_H_
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_LLAMA_GENERATOR_H_
|
#define BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_LLAMA_GENERATOR_H_
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @file data_generation/llama_generator.h
|
* @file data_generation/llama_generator.h
|
||||||
* @brief llama.cpp-backed implementation of DataGenerator.
|
* @brief llama.cpp-backed implementation of DataGenerator.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <filesystem>
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
|
||||||
|
#include "../services/prompting/prompt_directory.h"
|
||||||
#include "data_generation/data_generator.h"
|
#include "data_generation/data_generator.h"
|
||||||
#include "data_generation/prompt_formatting/prompt_formatter.h"
|
#include "data_generation/prompt_formatting/prompt_formatter.h"
|
||||||
#include "data_model/models.h"
|
#include "data_model/models.h"
|
||||||
#include "services/logging/logger.h"
|
#include "services/logging/logger.h"
|
||||||
#include "services/prompting/prompt_directory.h"
|
|
||||||
|
|
||||||
struct llama_model;
|
struct llama_model;
|
||||||
struct llama_context;
|
struct llama_context;
|
||||||
@@ -43,9 +44,14 @@ class LlamaGenerator final : public DataGenerator {
|
|||||||
|
|
||||||
~LlamaGenerator() override;
|
~LlamaGenerator() override;
|
||||||
|
|
||||||
|
// disable copy constructor
|
||||||
LlamaGenerator(const LlamaGenerator&) = delete;
|
LlamaGenerator(const LlamaGenerator&) = delete;
|
||||||
|
|
||||||
|
// disable copy assignment operator
|
||||||
LlamaGenerator& operator=(const LlamaGenerator&) = delete;
|
LlamaGenerator& operator=(const LlamaGenerator&) = delete;
|
||||||
|
// disable move constructor
|
||||||
LlamaGenerator(LlamaGenerator&&) = delete;
|
LlamaGenerator(LlamaGenerator&&) = delete;
|
||||||
|
// disable move assignment operator
|
||||||
LlamaGenerator& operator=(LlamaGenerator&&) = delete;
|
LlamaGenerator& operator=(LlamaGenerator&&) = delete;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,15 +65,12 @@ class LlamaGenerator final : public DataGenerator {
|
|||||||
const std::string& region_context) override;
|
const std::string& region_context) override;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Generates a user profile grounded in a sampled name and persona.
|
* @brief Generates a user profile for the provided locale.
|
||||||
*
|
*
|
||||||
* @param city Enriched city the user is associated with.
|
* @param locale Locale hint.
|
||||||
* @param persona Persona archetype grounding the generated bio.
|
|
||||||
* @param name Sampled first/last name -- not LLM-invented.
|
|
||||||
* @return Generated user profile.
|
* @return Generated user profile.
|
||||||
*/
|
*/
|
||||||
UserResult GenerateUser(const EnrichedCity& city, const UserPersona& persona,
|
UserResult GenerateUser(const std::string& locale) override;
|
||||||
const Name& name) override;
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static constexpr int32_t kDefaultMaxTokens = 10000;
|
static constexpr int32_t kDefaultMaxTokens = 10000;
|
||||||
|
|||||||
@@ -47,18 +47,4 @@ void AppendTokenPiece(const llama_vocab* vocab, llama_token token,
|
|||||||
std::optional<std::string> ValidateBreweryJson(const std::string& raw,
|
std::optional<std::string> ValidateBreweryJson(const std::string& raw,
|
||||||
BreweryResult& brewery_out);
|
BreweryResult& brewery_out);
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Validates and parses user JSON output.
|
|
||||||
*
|
|
||||||
* Only populates `username`, `bio`, and `activity_weight` -- `first_name`
|
|
||||||
* and `last_name` are not LLM-authored and are set separately from the
|
|
||||||
* sampled Name.
|
|
||||||
*
|
|
||||||
* @param raw Raw model output.
|
|
||||||
* @param user_out Parsed user payload.
|
|
||||||
* @return Validation error message if invalid, or std::nullopt on success.
|
|
||||||
*/
|
|
||||||
std::optional<std::string> ValidateUserJson(const std::string& raw,
|
|
||||||
UserResult& user_out);
|
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_LLAMA_GENERATOR_HELPERS_H_
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_LLAMA_GENERATOR_HELPERS_H_
|
||||||
|
|||||||
@@ -28,16 +28,12 @@ class MockGenerator final : public DataGenerator {
|
|||||||
const std::string& region_context) override;
|
const std::string& region_context) override;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Generates deterministic user data grounded in a sampled name and
|
* @brief Generates deterministic user data for a locale.
|
||||||
* persona.
|
|
||||||
*
|
*
|
||||||
* @param city Enriched city the user is associated with.
|
* @param locale Locale hint.
|
||||||
* @param persona Persona archetype.
|
|
||||||
* @param name Sampled first/last name, copied directly into the result.
|
|
||||||
* @return Generated user result.
|
* @return Generated user result.
|
||||||
*/
|
*/
|
||||||
UserResult GenerateUser(const EnrichedCity& city, const UserPersona& persona,
|
UserResult GenerateUser(const std::string& locale) override;
|
||||||
const Name& name) override;
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/**
|
/**
|
||||||
@@ -48,25 +44,12 @@ class MockGenerator final : public DataGenerator {
|
|||||||
*/
|
*/
|
||||||
static size_t DeterministicHash(const Location& location);
|
static size_t DeterministicHash(const Location& location);
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Combines city, persona, and name into a stable hash value.
|
|
||||||
*
|
|
||||||
* @param location City and country names.
|
|
||||||
* @param persona Persona archetype.
|
|
||||||
* @param name Sampled first/last name.
|
|
||||||
* @return Deterministic hash value.
|
|
||||||
*/
|
|
||||||
static size_t DeterministicHash(const Location& location,
|
|
||||||
const UserPersona& persona, const Name& name);
|
|
||||||
|
|
||||||
// Hash stride constants for deterministic distribution across fixed-size
|
// Hash stride constants for deterministic distribution across fixed-size
|
||||||
// arrays. These coprime strides spread hash values uniformly without
|
// arrays. These coprime strides spread hash values uniformly without
|
||||||
// clustering, ensuring diverse output across different hash inputs.
|
// clustering, ensuring diverse output across different hash inputs.
|
||||||
static constexpr size_t kNounHashStride = 7;
|
static constexpr size_t kNounHashStride = 7;
|
||||||
static constexpr size_t kDescriptionHashStride = 13;
|
static constexpr size_t kDescriptionHashStride = 13;
|
||||||
static constexpr size_t kBioHashStride = 11;
|
static constexpr size_t kBioHashStride = 11;
|
||||||
static constexpr size_t kActivityWeightHashStride = 17;
|
|
||||||
static constexpr size_t kActivityWeightHashRange = 1000;
|
|
||||||
|
|
||||||
static constexpr std::array<std::string_view, 18> kBreweryAdjectives = {
|
static constexpr std::array<std::string_view, 18> kBreweryAdjectives = {
|
||||||
"Craft", "Heritage", "Local", "Artisan", "Pioneer", "Golden",
|
"Craft", "Heritage", "Local", "Artisan", "Pioneer", "Golden",
|
||||||
@@ -141,8 +124,7 @@ class MockGenerator final : public DataGenerator {
|
|||||||
"Visits breweries for the stories, stays for the flagship pours.",
|
"Visits breweries for the stories, stays for the flagship pours.",
|
||||||
"Craft beer fan mapping tasting notes and favorite brew routes.",
|
"Craft beer fan mapping tasting notes and favorite brew routes.",
|
||||||
"Always ready to trade recommendations for underrated local breweries.",
|
"Always ready to trade recommendations for underrated local breweries.",
|
||||||
"Keeping a running list of must-try collab releases and tap "
|
"Keeping a running list of must-try collab releases and tap takeovers."};
|
||||||
"takeovers."};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_MOCK_GENERATOR_H_
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_GENERATION_MOCK_GENERATOR_H_
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @file data_model/generated_models.h
|
* @file data_model/generated_models.h
|
||||||
* @brief Generated output models from the pipeline: brewery/user results,
|
* @brief Generated output models from the pipeline: brewery/user results, enriched data,
|
||||||
* enriched data, and complete generation results.
|
* and complete generation results.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
@@ -19,24 +19,16 @@
|
|||||||
* @brief Generated brewery payload.
|
* @brief Generated brewery payload.
|
||||||
*/
|
*/
|
||||||
struct BreweryResult {
|
struct BreweryResult {
|
||||||
/**
|
/// @brief Brewery display name in English.
|
||||||
* @brief Brewery display name in English.
|
|
||||||
*/
|
|
||||||
std::string name_en;
|
std::string name_en;
|
||||||
|
|
||||||
/**
|
/// @brief Brewery description text in English.
|
||||||
* @brief Brewery description text in English.
|
|
||||||
*/
|
|
||||||
std::string description_en;
|
std::string description_en;
|
||||||
|
|
||||||
/**
|
/// @brief Brewery display name in the local language.
|
||||||
* @brief Brewery display name in the local language.
|
|
||||||
*/
|
|
||||||
std::string name_local;
|
std::string name_local;
|
||||||
|
|
||||||
/**
|
/// @brief Brewery description text in the local language.
|
||||||
* @brief Brewery description text in the local language.
|
|
||||||
*/
|
|
||||||
std::string description_local;
|
std::string description_local;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -44,39 +36,11 @@ struct BreweryResult {
|
|||||||
* @brief Generated user profile payload.
|
* @brief Generated user profile payload.
|
||||||
*/
|
*/
|
||||||
struct UserResult {
|
struct UserResult {
|
||||||
/**
|
/// @brief Username handle.
|
||||||
* @brief First (given) name, copied from the sampled Name -- not
|
|
||||||
* LLM-invented.
|
|
||||||
*/
|
|
||||||
std::string first_name{};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Last (family) name, copied from the sampled Name -- not
|
|
||||||
* LLM-invented.
|
|
||||||
*/
|
|
||||||
std::string last_name{};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Gender associated with the sampled first name, copied from the
|
|
||||||
* sampled Name -- not LLM-invented.
|
|
||||||
*/
|
|
||||||
std::string gender{};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Username handle.
|
|
||||||
*/
|
|
||||||
std::string username{};
|
std::string username{};
|
||||||
|
|
||||||
/**
|
/// @brief Short user biography.
|
||||||
* @brief Short user biography.
|
|
||||||
*/
|
|
||||||
std::string bio{};
|
std::string bio{};
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Relative check-in/activity weight for this user, used to drive
|
|
||||||
* a J-curve activity profile in later pipeline phases.
|
|
||||||
*/
|
|
||||||
float activity_weight{};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -94,23 +58,9 @@ struct EnrichedCity {
|
|||||||
/**
|
/**
|
||||||
* @brief Helper struct to store generated brewery data.
|
* @brief Helper struct to store generated brewery data.
|
||||||
*/
|
*/
|
||||||
struct BreweryRecord {
|
struct GeneratedBrewery {
|
||||||
Location location;
|
Location location;
|
||||||
BreweryResult brewery;
|
BreweryResult brewery;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Helper struct to store generated user data.
|
|
||||||
*
|
|
||||||
* `email` and `date_of_birth` are programmatically generated by the
|
|
||||||
* orchestrator (never LLM-authored) so a downstream auth-account seeding
|
|
||||||
* consumer can register real accounts from the pipeline's SQLite export.
|
|
||||||
*/
|
|
||||||
struct UserRecord {
|
|
||||||
Location location;
|
|
||||||
UserResult user;
|
|
||||||
std::string email{};
|
|
||||||
std::string date_of_birth{};
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_MODEL_GENERATED_MODELS_H_
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_MODEL_GENERATED_MODELS_H_
|
||||||
|
|||||||
@@ -10,7 +10,6 @@
|
|||||||
#include <boost/program_options.hpp>
|
#include <boost/program_options.hpp>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <functional>
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
@@ -29,106 +28,40 @@ namespace prog_opts = boost::program_options;
|
|||||||
* @brief Canonical location record for city-level generation.
|
* @brief Canonical location record for city-level generation.
|
||||||
*/
|
*/
|
||||||
struct Location {
|
struct Location {
|
||||||
|
/// @brief City name.
|
||||||
std::string city{};
|
std::string city{};
|
||||||
|
|
||||||
|
/// @brief State or province name.
|
||||||
std::string state_province{};
|
std::string state_province{};
|
||||||
|
|
||||||
/**
|
/// @brief ISO 3166-2 subdivision code.
|
||||||
* @brief ISO 3166-2 subdivision code.
|
|
||||||
*/
|
|
||||||
std::string iso3166_2{};
|
std::string iso3166_2{};
|
||||||
|
|
||||||
|
/// @brief Country name.
|
||||||
std::string country{};
|
std::string country{};
|
||||||
|
|
||||||
/**
|
/// @brief ISO 3166-1 country code.
|
||||||
* @brief ISO 3166-1 country code.
|
|
||||||
*/
|
|
||||||
std::string iso3166_1{};
|
std::string iso3166_1{};
|
||||||
|
|
||||||
/**
|
/// @brief Local language codes in priority order.
|
||||||
* @brief Local language codes in priority order.
|
|
||||||
*/
|
|
||||||
std::vector<std::string> local_languages{};
|
std::vector<std::string> local_languages{};
|
||||||
|
|
||||||
/**
|
/// @brief Latitude in decimal degrees.
|
||||||
* @brief Latitude in decimal degrees.
|
|
||||||
*/
|
|
||||||
double latitude{};
|
double latitude{};
|
||||||
|
|
||||||
/**
|
/// @brief Longitude in decimal degrees.
|
||||||
* @brief Longitude in decimal degrees.
|
|
||||||
*/
|
|
||||||
double longitude{};
|
double longitude{};
|
||||||
};
|
};
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Name / Persona Models
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief A sampled first/last name pair, with the source forename's gender.
|
* @brief Non-owning brewery location input.
|
||||||
*
|
|
||||||
* Produced by the SampleName() helper in generate_users.cc.
|
|
||||||
*/
|
*/
|
||||||
struct Name {
|
struct BreweryLocation {
|
||||||
std::string first_name{};
|
/// @brief City name.
|
||||||
std::string last_name{};
|
std::string_view city_name;
|
||||||
|
|
||||||
/**
|
/// @brief Country name.
|
||||||
* @brief Gender associated with the sampled forename (e.g. "M", "F"), as
|
std::string_view country_name;
|
||||||
* reported by the source dataset.
|
|
||||||
*/
|
|
||||||
std::string gender{};
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief A single forename entry from the names-by-country fixture data.
|
|
||||||
*/
|
|
||||||
struct ForenameEntry {
|
|
||||||
/**
|
|
||||||
* @brief Romanized forename.
|
|
||||||
*/
|
|
||||||
std::string name{};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Gender associated with this forename, as reported by the source
|
|
||||||
* dataset (e.g. "M", "F").
|
|
||||||
*/
|
|
||||||
std::string gender{};
|
|
||||||
|
|
||||||
bool operator==(const ForenameEntry& other) const {
|
|
||||||
return name == other.name && gender == other.gender;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
namespace std {
|
|
||||||
template <>
|
|
||||||
struct hash<ForenameEntry> {
|
|
||||||
size_t operator()(const ForenameEntry& entry) const noexcept {
|
|
||||||
const size_t name_hash = std::hash<std::string>{}(entry.name);
|
|
||||||
const size_t gender_hash = std::hash<std::string>{}(entry.gender);
|
|
||||||
return name_hash ^ (gender_hash << 1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} // namespace std
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief A persona archetype used to ground LLM-generated user bios.
|
|
||||||
*/
|
|
||||||
struct UserPersona {
|
|
||||||
/**
|
|
||||||
* @brief Persona display name (e.g. "Hophead Explorer").
|
|
||||||
*/
|
|
||||||
std::string name{};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Short description of the persona's interests and voice.
|
|
||||||
*/
|
|
||||||
std::string description{};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Beer styles this persona gravitates toward.
|
|
||||||
*/
|
|
||||||
std::vector<std::string> style_affinities{};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -139,34 +72,22 @@ struct UserPersona {
|
|||||||
* @brief LLM sampling parameters.
|
* @brief LLM sampling parameters.
|
||||||
*/
|
*/
|
||||||
struct SamplingOptions {
|
struct SamplingOptions {
|
||||||
/**
|
/// @brief LLM sampling temperature (0.0 to 1.0, higher = more random).
|
||||||
* @brief LLM sampling temperature (higher = more random).
|
|
||||||
*/
|
|
||||||
float temperature = 1.0F;
|
float temperature = 1.0F;
|
||||||
|
|
||||||
/**
|
/// @brief LLM nucleus sampling top-p parameter.
|
||||||
* @brief LLM nucleus sampling top-p parameter.
|
|
||||||
*/
|
|
||||||
float top_p = 0.95F;
|
float top_p = 0.95F;
|
||||||
|
|
||||||
/**
|
/// @brief LLM top-k sampling parameter.
|
||||||
* @brief LLM top-k sampling parameter.
|
|
||||||
*/
|
|
||||||
uint32_t top_k = 64;
|
uint32_t top_k = 64;
|
||||||
|
|
||||||
/**
|
/// @brief Context window size (tokens).
|
||||||
* @brief Context window size (tokens).
|
|
||||||
*/
|
|
||||||
uint32_t n_ctx = 8192;
|
uint32_t n_ctx = 8192;
|
||||||
|
|
||||||
/**
|
/// @brief Random seed (-1 for random, otherwise non-negative).
|
||||||
* @brief Random seed (-1 for random, otherwise non-negative).
|
|
||||||
*/
|
|
||||||
int seed = -1;
|
int seed = -1;
|
||||||
|
|
||||||
/**
|
/// @brief Number of layers to offload to GPU.
|
||||||
* @brief Number of layers to offload to GPU.
|
|
||||||
*/
|
|
||||||
int n_gpu_layers = 0;
|
int n_gpu_layers = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -174,20 +95,16 @@ struct SamplingOptions {
|
|||||||
* @brief Configuration for the LLM generator component.
|
* @brief Configuration for the LLM generator component.
|
||||||
*/
|
*/
|
||||||
struct GeneratorOptions {
|
struct GeneratorOptions {
|
||||||
/**
|
/// @brief Path to the LLM model file (gguf format).
|
||||||
* @brief Path to the LLM model file (gguf format).
|
|
||||||
*/
|
|
||||||
std::filesystem::path model_path;
|
std::filesystem::path model_path;
|
||||||
|
|
||||||
/**
|
/// @brief Use mocked generator instead of actual LLM inference.
|
||||||
* @brief Use mocked generator instead of actual LLM inference.
|
|
||||||
*/
|
|
||||||
bool use_mocked = false;
|
bool use_mocked = false;
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Specific sampling parameters for this generator.
|
|
||||||
* If nullopt, the application should use global defaults.
|
/// @brief Specific sampling parameters for this generator.
|
||||||
*/
|
/// If nullopt, the application should use global defaults.
|
||||||
std::optional<SamplingOptions> sampling;
|
std::optional<SamplingOptions> sampling;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -195,23 +112,18 @@ struct GeneratorOptions {
|
|||||||
* @brief Configuration for the pipeline execution and output.
|
* @brief Configuration for the pipeline execution and output.
|
||||||
*/
|
*/
|
||||||
struct PipelineOptions {
|
struct PipelineOptions {
|
||||||
/**
|
/// @brief Directory for generated artifacts.
|
||||||
* @brief Directory for generated artifacts.
|
|
||||||
*/
|
|
||||||
std::filesystem::path output_path;
|
std::filesystem::path output_path;
|
||||||
|
|
||||||
/**
|
/// @brief Directory that contains named prompt files (e.g.
|
||||||
* @brief Directory that contains named prompt files (e.g.
|
/// BREWERY_GENERATION.md).
|
||||||
* BREWERY_GENERATION.md).
|
|
||||||
*/
|
|
||||||
std::filesystem::path prompt_dir;
|
std::filesystem::path prompt_dir;
|
||||||
|
|
||||||
|
/// @brief Path for application logs.
|
||||||
std::filesystem::path log_path;
|
std::filesystem::path log_path;
|
||||||
|
|
||||||
/**
|
/// @brief Number of locations to sample from the dataset
|
||||||
* @brief Number of locations to sample from the dataset
|
/// More locations -> more users/more breweries
|
||||||
* More locations -> more users/more breweries
|
|
||||||
*/
|
|
||||||
uint32_t location_count;
|
uint32_t location_count;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -227,7 +139,7 @@ struct ApplicationOptions {
|
|||||||
// Function Declarations
|
// Function Declarations
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
std::optional<ApplicationOptions> ParseArguments(
|
std::optional<ApplicationOptions> ParseArguments(const int argc, char** argv,
|
||||||
const int argc, char** argv, std::shared_ptr<ILogger> logger = nullptr);
|
std::shared_ptr<ILogger> logger = nullptr);
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_MODEL_MODELS_H_
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_DATA_MODEL_MODELS_H_
|
||||||
|
|||||||
25
tooling/pipeline/includes/json_handling/json_loader.h
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
#ifndef BIERGARTEN_PIPELINE_INCLUDES_JSON_HANDLING_JSON_LOADER_H_
|
||||||
|
#define BIERGARTEN_PIPELINE_INCLUDES_JSON_HANDLING_JSON_LOADER_H_
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @file json_handling/json_loader.h
|
||||||
|
* @brief Loader API for curated location data.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "data_model/models.h"
|
||||||
|
#include "services/logging/logger.h"
|
||||||
|
|
||||||
|
/// @brief Loads curated world locations from a JSON file into memory.
|
||||||
|
class JsonLoader {
|
||||||
|
public:
|
||||||
|
/// @brief Parses a JSON array file and returns all location records.
|
||||||
|
static std::vector<Location> LoadLocations(
|
||||||
|
const std::filesystem::path& filepath,
|
||||||
|
std::shared_ptr<ILogger> logger = nullptr);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_JSON_HANDLING_JSON_LOADER_H_
|
||||||
@@ -106,4 +106,4 @@ inline void PrettyPrint(std::ostream& outstream,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_JSON_HANDLING_PRETTY_PRINT_H_
|
#endif
|
||||||
|
|||||||
@@ -16,10 +16,16 @@
|
|||||||
*/
|
*/
|
||||||
class LlamaBackendState {
|
class LlamaBackendState {
|
||||||
public:
|
public:
|
||||||
|
/// @brief Initializes global llama backend state.
|
||||||
LlamaBackendState() { llama_backend_init(); }
|
LlamaBackendState() { llama_backend_init(); }
|
||||||
|
|
||||||
|
/// @brief Cleans up global llama backend state.
|
||||||
~LlamaBackendState() { llama_backend_free(); }
|
~LlamaBackendState() { llama_backend_free(); }
|
||||||
|
|
||||||
|
/// @brief Non-copyable type.
|
||||||
LlamaBackendState(const LlamaBackendState&) = delete;
|
LlamaBackendState(const LlamaBackendState&) = delete;
|
||||||
|
|
||||||
|
/// @brief Non-copyable type.
|
||||||
LlamaBackendState& operator=(const LlamaBackendState&) = delete;
|
LlamaBackendState& operator=(const LlamaBackendState&) = delete;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_SERVICES_CURATED_DATA_CURATED_DATA_SERVICE_H_
|
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_SERVICES_CURATED_DATA_CURATED_DATA_SERVICE_H_
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @file services/curated_data/curated_data_service.h
|
|
||||||
* @brief Abstraction for loading curated location, persona, and name data.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <filesystem>
|
|
||||||
#include <unordered_map>
|
|
||||||
#include <unordered_set>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include "data_model/models.h"
|
|
||||||
|
|
||||||
using ForenameList = std::vector<ForenameEntry>;
|
|
||||||
using SurnameList = std::vector<std::string>;
|
|
||||||
using LocationsList = std::vector<Location>;
|
|
||||||
using PersonasList = std::vector<UserPersona>;
|
|
||||||
using ForenamesByCountryMap = std::unordered_map<std::string, ForenameList>;
|
|
||||||
using SurnamesByCountryMap = std::unordered_map<std::string, SurnameList>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Interface for services that load curated data used to seed
|
|
||||||
* brewery/user generation.
|
|
||||||
*/
|
|
||||||
class ICuratedDataService {
|
|
||||||
public:
|
|
||||||
ICuratedDataService() = default;
|
|
||||||
virtual ~ICuratedDataService() = default;
|
|
||||||
|
|
||||||
ICuratedDataService(const ICuratedDataService&) = delete;
|
|
||||||
ICuratedDataService& operator=(const ICuratedDataService&) = delete;
|
|
||||||
ICuratedDataService(ICuratedDataService&&) = delete;
|
|
||||||
ICuratedDataService& operator=(ICuratedDataService&&) = delete;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Loads all curated location records.
|
|
||||||
*/
|
|
||||||
virtual const LocationsList& LoadLocations() = 0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Loads all curated persona records.
|
|
||||||
*/
|
|
||||||
virtual const PersonasList& LoadPersonas() = 0;
|
|
||||||
virtual const ForenamesByCountryMap& LoadForenamesByCountry() = 0;
|
|
||||||
virtual const SurnamesByCountryMap& LoadSurnamesByCountry() = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_SERVICES_CURATED_DATA_CURATED_DATA_SERVICE_H_
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_JSON_HANDLING_JSON_LOADER_H_
|
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_JSON_HANDLING_JSON_LOADER_H_
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @file json_handling/json_loader.h
|
|
||||||
* @brief JSON-backed implementation of ICuratedDataService.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <filesystem>
|
|
||||||
|
|
||||||
#include "data_model/models.h"
|
|
||||||
#include "services/curated_data/curated_data_service.h"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief File locations for the curated JSON fixtures consumed by
|
|
||||||
* CuratedJsonDataService.
|
|
||||||
*/
|
|
||||||
struct CuratedDataFilePaths {
|
|
||||||
std::filesystem::path locations_path;
|
|
||||||
std::filesystem::path personas_path;
|
|
||||||
std::filesystem::path forenames_path;
|
|
||||||
std::filesystem::path surnames_path;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Loads curated location, persona, and name data from JSON files.
|
|
||||||
*/
|
|
||||||
class CuratedJsonDataService final : public ICuratedDataService {
|
|
||||||
struct cache {
|
|
||||||
LocationsList locations;
|
|
||||||
PersonasList personas;
|
|
||||||
ForenamesByCountryMap forenames_by_country;
|
|
||||||
SurnamesByCountryMap surnames_by_country;
|
|
||||||
|
|
||||||
cache() = default;
|
|
||||||
~cache() = default;
|
|
||||||
};
|
|
||||||
|
|
||||||
CuratedDataFilePaths filepaths_;
|
|
||||||
cache cache_;
|
|
||||||
|
|
||||||
public:
|
|
||||||
explicit CuratedJsonDataService(CuratedDataFilePaths filepaths);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Parses a JSON array file and returns all location records.
|
|
||||||
*/
|
|
||||||
const LocationsList& LoadLocations() override;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Parses a JSON array file and returns all persona records.
|
|
||||||
*/
|
|
||||||
const PersonasList& LoadPersonas() override;
|
|
||||||
|
|
||||||
const ForenamesByCountryMap& LoadForenamesByCountry() override;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Parses a JSON file and returns all the forenames per country.
|
|
||||||
*/
|
|
||||||
const SurnamesByCountryMap& LoadSurnamesByCountry() override;
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_JSON_HANDLING_JSON_LOADER_H_
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_SERVICES_CURATED_DATA_MOCK_CURATED_DATA_SERVICE_H_
|
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_SERVICES_CURATED_DATA_MOCK_CURATED_DATA_SERVICE_H_
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @file services/curated_data/mock_curated_data_service.h
|
|
||||||
* @brief In-memory ICuratedDataService backed by a small fixed dataset, used
|
|
||||||
* when file-backed curated data is disabled (mock mode).
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <filesystem>
|
|
||||||
|
|
||||||
#include "data_model/models.h"
|
|
||||||
#include "services/curated_data/curated_data_service.h"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Curated data service returning a small fixed in-memory dataset in
|
|
||||||
* place of the JSON fixture files used by JsonLoader.
|
|
||||||
*/
|
|
||||||
class MockCuratedDataService final : public ICuratedDataService {
|
|
||||||
public:
|
|
||||||
MockCuratedDataService();
|
|
||||||
|
|
||||||
const LocationsList& LoadLocations() override;
|
|
||||||
|
|
||||||
const PersonasList& LoadPersonas() override;
|
|
||||||
|
|
||||||
const ForenamesByCountryMap& LoadForenamesByCountry() override;
|
|
||||||
|
|
||||||
const SurnamesByCountryMap& LoadSurnamesByCountry() override;
|
|
||||||
|
|
||||||
private:
|
|
||||||
LocationsList locations_;
|
|
||||||
PersonasList personas_;
|
|
||||||
ForenamesByCountryMap forenames_by_country_;
|
|
||||||
SurnamesByCountryMap surnames_by_country_;
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_SERVICES_CURATED_DATA_MOCK_CURATED_DATA_SERVICE_H_
|
|
||||||
@@ -16,6 +16,8 @@
|
|||||||
class IExportService {
|
class IExportService {
|
||||||
public:
|
public:
|
||||||
IExportService() = default;
|
IExportService() = default;
|
||||||
|
|
||||||
|
/// @brief Virtual destructor for polymorphic cleanup.
|
||||||
virtual ~IExportService() = default;
|
virtual ~IExportService() = default;
|
||||||
|
|
||||||
IExportService(const IExportService&) = delete;
|
IExportService(const IExportService&) = delete;
|
||||||
@@ -23,9 +25,7 @@ class IExportService {
|
|||||||
IExportService(IExportService&&) = delete;
|
IExportService(IExportService&&) = delete;
|
||||||
IExportService& operator=(IExportService&&) = delete;
|
IExportService& operator=(IExportService&&) = delete;
|
||||||
|
|
||||||
/**
|
/// @brief Prepares the export destination for a new run.
|
||||||
* @brief Prepares the export destination for a new run.
|
|
||||||
*/
|
|
||||||
virtual void Initialize() = 0;
|
virtual void Initialize() = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -33,18 +33,9 @@ class IExportService {
|
|||||||
*
|
*
|
||||||
* @param brewery Generated brewery payload to store.
|
* @param brewery Generated brewery payload to store.
|
||||||
*/
|
*/
|
||||||
virtual uint64_t ProcessRecord(const BreweryRecord& brewery) = 0;
|
virtual uint64_t ProcessRecord(const GeneratedBrewery& brewery) = 0;
|
||||||
|
|
||||||
/**
|
/// @brief Finalizes the export destination.
|
||||||
* @brief Persists one generated user record.
|
|
||||||
*
|
|
||||||
* @param user Generated user payload to store.
|
|
||||||
*/
|
|
||||||
virtual uint64_t ProcessRecord(const UserRecord& user) = 0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Finalizes the export destination.
|
|
||||||
*/
|
|
||||||
virtual void Finalize() = 0;
|
virtual void Finalize() = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
|
||||||
#include "services/database/sqlite_handle_types.h"
|
#include "sqlite_handle_types.h"
|
||||||
|
|
||||||
namespace sqlite_export_service_internal {
|
namespace sqlite_export_service_internal {
|
||||||
|
|
||||||
|
|||||||
@@ -12,9 +12,9 @@
|
|||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|
||||||
#include "data_model/models.h"
|
#include "data_model/models.h"
|
||||||
#include "services/database/export_service.h"
|
#include "../datetime/date_time_provider.h"
|
||||||
#include "services/database/sqlite_export_service_helpers.h"
|
#include "export_service.h"
|
||||||
#include "services/datetime/date_time_provider.h"
|
#include "sqlite_export_service_helpers.h"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Persists generated brewery records into a fresh SQLite database.
|
* @brief Persists generated brewery records into a fresh SQLite database.
|
||||||
@@ -30,8 +30,7 @@ class SqliteExportService final : public IExportService {
|
|||||||
SqliteExportService& operator=(SqliteExportService&&) = delete;
|
SqliteExportService& operator=(SqliteExportService&&) = delete;
|
||||||
|
|
||||||
void Initialize() override;
|
void Initialize() override;
|
||||||
uint64_t ProcessRecord(const BreweryRecord& brewery) override;
|
uint64_t ProcessRecord(const GeneratedBrewery& brewery) override;
|
||||||
uint64_t ProcessRecord(const UserRecord& user) override;
|
|
||||||
void Finalize() override;
|
void Finalize() override;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -47,15 +46,6 @@ class SqliteExportService final : public IExportService {
|
|||||||
[[nodiscard]] std::filesystem::path BuildDatabasePath() const;
|
[[nodiscard]] std::filesystem::path BuildDatabasePath() const;
|
||||||
[[nodiscard]] static std::string BuildLocationKey(const Location& location);
|
[[nodiscard]] static std::string BuildLocationKey(const Location& location);
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Returns the row id for @p location, inserting it first if it has
|
|
||||||
* not already been seen during this run.
|
|
||||||
*
|
|
||||||
* Shared by both ProcessRecord() overloads so breweries and users
|
|
||||||
* referencing the same location resolve to the same row.
|
|
||||||
*/
|
|
||||||
[[nodiscard]] sqlite3_int64 ResolveLocationId(const Location& location);
|
|
||||||
|
|
||||||
std::unique_ptr<IDateTimeProvider> date_time_provider_;
|
std::unique_ptr<IDateTimeProvider> date_time_provider_;
|
||||||
std::filesystem::path output_path_;
|
std::filesystem::path output_path_;
|
||||||
std::string run_timestamp_utc_;
|
std::string run_timestamp_utc_;
|
||||||
@@ -63,7 +53,6 @@ class SqliteExportService final : public IExportService {
|
|||||||
SqliteDatabaseHandle db_handle_;
|
SqliteDatabaseHandle db_handle_;
|
||||||
SqliteStatementHandle insert_location_stmt_;
|
SqliteStatementHandle insert_location_stmt_;
|
||||||
SqliteStatementHandle insert_brewery_stmt_;
|
SqliteStatementHandle insert_brewery_stmt_;
|
||||||
SqliteStatementHandle insert_user_stmt_;
|
|
||||||
bool transaction_open_ = false;
|
bool transaction_open_ = false;
|
||||||
std::unordered_map<std::string, sqlite3_int64> location_cache_;
|
std::unordered_map<std::string, sqlite3_int64> location_cache_;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
|
|
||||||
/* Umbrella header for backward compatibility. */
|
/* Umbrella header for backward compatibility. */
|
||||||
|
|
||||||
#include "services/database/sqlite_connection_helpers.h"
|
#include "sqlite_connection_helpers.h"
|
||||||
#include "services/database/sqlite_handle_types.h"
|
#include "sqlite_handle_types.h"
|
||||||
#include "services/database/sqlite_statement_helpers.h"
|
#include "sqlite_statement_helpers.h"
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_SERVICES_DATABASE_SQLITE_EXPORT_SERVICE_HELPERS_H_
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_SERVICES_DATABASE_SQLITE_EXPORT_SERVICE_HELPERS_H_
|
||||||
|
|||||||
@@ -24,10 +24,8 @@ using SqliteDatabaseHandle = std::unique_ptr<sqlite3, SqliteDatabaseDeleter>;
|
|||||||
using SqliteStatementHandle =
|
using SqliteStatementHandle =
|
||||||
std::unique_ptr<sqlite3_stmt, SqliteStatementDeleter>;
|
std::unique_ptr<sqlite3_stmt, SqliteStatementDeleter>;
|
||||||
|
|
||||||
// Represents a parameter that is bound to a prepared SQLite statement.
|
|
||||||
// N.B. indices are 1 based.
|
|
||||||
template <typename T>
|
template <typename T>
|
||||||
struct BoundParam {
|
struct BindParam {
|
||||||
int index;
|
int index;
|
||||||
T value;
|
T value;
|
||||||
std::string_view action;
|
std::string_view action;
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "services/database/sqlite_handle_types.h"
|
#include "sqlite_handle_types.h"
|
||||||
|
|
||||||
namespace sqlite_export_service_internal {
|
namespace sqlite_export_service_internal {
|
||||||
|
|
||||||
@@ -50,26 +50,6 @@ CREATE INDEX IF NOT EXISTS idx_breweries_location_id ON breweries(location_id);
|
|||||||
|
|
||||||
)sql";
|
)sql";
|
||||||
|
|
||||||
inline constexpr std::string_view kCreateUsersTableSql = R"sql(
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
location_id INTEGER NOT NULL,
|
|
||||||
first_name TEXT NOT NULL,
|
|
||||||
last_name TEXT NOT NULL,
|
|
||||||
gender TEXT NOT NULL,
|
|
||||||
username TEXT NOT NULL,
|
|
||||||
bio TEXT NOT NULL,
|
|
||||||
activity_weight REAL NOT NULL,
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
date_of_birth TEXT NOT NULL,
|
|
||||||
FOREIGN KEY(location_id) REFERENCES locations(id) ON DELETE CASCADE
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_users_location_id ON users(location_id);
|
|
||||||
|
|
||||||
)sql";
|
|
||||||
|
|
||||||
inline constexpr std::string_view kInsertLocationSql = R"sql(
|
inline constexpr std::string_view kInsertLocationSql = R"sql(
|
||||||
INSERT INTO locations (
|
INSERT INTO locations (
|
||||||
city,
|
city,
|
||||||
@@ -93,52 +73,20 @@ INSERT INTO breweries (
|
|||||||
) VALUES (?, ?, ?, ?, ?);
|
) VALUES (?, ?, ?, ?, ?);
|
||||||
)sql";
|
)sql";
|
||||||
|
|
||||||
inline constexpr std::string_view kInsertUserSql = R"sql(
|
inline constexpr int kLocationCityBindIndex = 1;
|
||||||
INSERT INTO users (
|
inline constexpr int kLocationStateProvinceBindIndex = 2;
|
||||||
location_id,
|
inline constexpr int kLocationIso31662BindIndex = 3;
|
||||||
first_name,
|
inline constexpr int kLocationCountryBindIndex = 4;
|
||||||
last_name,
|
inline constexpr int kLocationIso31661BindIndex = 5;
|
||||||
gender,
|
inline constexpr int kLocationLanguagesBindIndex = 6;
|
||||||
username,
|
inline constexpr int kLocationLatitudeBindIndex = 7;
|
||||||
bio,
|
inline constexpr int kLocationLongitudeBindIndex = 8;
|
||||||
activity_weight,
|
|
||||||
email,
|
|
||||||
date_of_birth
|
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);
|
|
||||||
)sql";
|
|
||||||
|
|
||||||
// sqlite3_bind_*() parameter indices are 1-based, matching the "?"
|
inline constexpr int kBreweryLocationIdBindIndex = 1;
|
||||||
// placeholder order in the SQL above.
|
inline constexpr int kBreweryEnglishNameBindIndex = 2;
|
||||||
enum LocationBindIndex {
|
inline constexpr int kBreweryEnglishDescriptionBindIndex = 3;
|
||||||
kLocationCityBindIndex = 1,
|
inline constexpr int kBreweryLocalNameBindIndex = 4;
|
||||||
kLocationStateProvinceBindIndex,
|
inline constexpr int kBreweryLocalDescriptionBindIndex = 5;
|
||||||
kLocationIso31662BindIndex,
|
|
||||||
kLocationCountryBindIndex,
|
|
||||||
kLocationIso31661BindIndex,
|
|
||||||
kLocationLanguagesBindIndex,
|
|
||||||
kLocationLatitudeBindIndex,
|
|
||||||
kLocationLongitudeBindIndex,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum BreweryBindIndex {
|
|
||||||
kBreweryLocationIdBindIndex = 1,
|
|
||||||
kBreweryEnglishNameBindIndex,
|
|
||||||
kBreweryEnglishDescriptionBindIndex,
|
|
||||||
kBreweryLocalNameBindIndex,
|
|
||||||
kBreweryLocalDescriptionBindIndex,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum UserBindIndex {
|
|
||||||
kUserLocationIdBindIndex = 1,
|
|
||||||
kUserFirstNameBindIndex,
|
|
||||||
kUserLastNameBindIndex,
|
|
||||||
kUserGenderBindIndex,
|
|
||||||
kUserUsernameBindIndex,
|
|
||||||
kUserBioBindIndex,
|
|
||||||
kUserActivityWeightBindIndex,
|
|
||||||
kUserEmailBindIndex,
|
|
||||||
kUserDateOfBirthBindIndex,
|
|
||||||
};
|
|
||||||
|
|
||||||
SqliteStatementHandle PrepareStatement(const SqliteDatabaseHandle& db_handle,
|
SqliteStatementHandle PrepareStatement(const SqliteDatabaseHandle& db_handle,
|
||||||
std::string_view sql,
|
std::string_view sql,
|
||||||
@@ -147,13 +95,13 @@ SqliteStatementHandle PrepareStatement(const SqliteDatabaseHandle& db_handle,
|
|||||||
void ResetStatement(SqliteStatementHandle& statement);
|
void ResetStatement(SqliteStatementHandle& statement);
|
||||||
|
|
||||||
void Bind(const SqliteStatementHandle& statement,
|
void Bind(const SqliteStatementHandle& statement,
|
||||||
const BoundParam<std::string_view>& param);
|
const BindParam<std::string_view>& param);
|
||||||
|
|
||||||
void Bind(const SqliteStatementHandle& statement,
|
void Bind(const SqliteStatementHandle& statement,
|
||||||
const BoundParam<double>& param);
|
const BindParam<double>& param);
|
||||||
|
|
||||||
void Bind(const SqliteStatementHandle& statement,
|
void Bind(const SqliteStatementHandle& statement,
|
||||||
const BoundParam<sqlite3_int64>& param);
|
const BindParam<sqlite3_int64>& param);
|
||||||
|
|
||||||
void StepStatement(const SqliteDatabaseHandle& db_handle,
|
void StepStatement(const SqliteDatabaseHandle& db_handle,
|
||||||
const SqliteStatementHandle& statement,
|
const SqliteStatementHandle& statement,
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
*/
|
*/
|
||||||
class IDateTimeProvider {
|
class IDateTimeProvider {
|
||||||
public:
|
public:
|
||||||
|
/// @brief Virtual destructor for polymorphic cleanup.
|
||||||
virtual ~IDateTimeProvider() = default;
|
virtual ~IDateTimeProvider() = default;
|
||||||
|
|
||||||
IDateTimeProvider() = default;
|
IDateTimeProvider() = default;
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
*/
|
*/
|
||||||
class IEnrichmentService {
|
class IEnrichmentService {
|
||||||
public:
|
public:
|
||||||
|
/// @brief Virtual destructor for polymorphic cleanup.
|
||||||
virtual ~IEnrichmentService() = default;
|
virtual ~IEnrichmentService() = default;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,18 +1,13 @@
|
|||||||
|
//
|
||||||
|
// Created by aaronpo on 13/05/2026.
|
||||||
|
//
|
||||||
|
|
||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_SERVICES_ENRICHMENT_MOCK_ENRICHMENT_H_
|
#ifndef BIERGARTEN_PIPELINE_INCLUDES_SERVICES_ENRICHMENT_MOCK_ENRICHMENT_H_
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_SERVICES_ENRICHMENT_MOCK_ENRICHMENT_H_
|
#define BIERGARTEN_PIPELINE_INCLUDES_SERVICES_ENRICHMENT_MOCK_ENRICHMENT_H_
|
||||||
|
|
||||||
/**
|
|
||||||
* @file services/enrichment/mock_enrichment.h
|
|
||||||
* @brief No-op IEnrichmentService used when network enrichment is disabled.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
#include "services/enrichment/enrichment_service.h"
|
#include "enrichment_service.h"
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Enrichment service that returns no context for any location.
|
|
||||||
*/
|
|
||||||
class MockEnrichmentService final : public IEnrichmentService {
|
class MockEnrichmentService final : public IEnrichmentService {
|
||||||
public:
|
public:
|
||||||
std::string GetLocationContext(const Location& /*loc*/) override {
|
std::string GetLocationContext(const Location& /*loc*/) override {
|
||||||
|
|||||||
@@ -11,37 +11,25 @@
|
|||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|
||||||
#include "services/enrichment/enrichment_service.h"
|
#include "enrichment_service.h"
|
||||||
#include "services/logging/logger.h"
|
#include "services/logging/logger.h"
|
||||||
#include "web_client/web_client.h"
|
#include "web_client/web_client.h"
|
||||||
|
|
||||||
/**
|
/// @brief Provides Wikipedia summary lookups backed by cached raw extracts.
|
||||||
* @brief Provides Wikipedia summary lookups backed by cached raw extracts.
|
|
||||||
*/
|
|
||||||
class WikipediaEnrichmentService final : public IEnrichmentService {
|
class WikipediaEnrichmentService final : public IEnrichmentService {
|
||||||
public:
|
public:
|
||||||
/**
|
/// @brief Creates a new Wikipedia service with the provided web client.
|
||||||
* @brief Creates a new Wikipedia service with the provided web client.
|
|
||||||
*/
|
|
||||||
explicit WikipediaEnrichmentService(std::unique_ptr<WebClient> client,
|
explicit WikipediaEnrichmentService(std::unique_ptr<WebClient> client,
|
||||||
std::shared_ptr<ILogger> logger);
|
std::shared_ptr<ILogger> logger);
|
||||||
|
|
||||||
/**
|
/// @brief Returns the Wikipedia-derived context for a location.
|
||||||
* @brief Returns the Wikipedia-derived context for a location.
|
|
||||||
*/
|
|
||||||
[[nodiscard]] std::string GetLocationContext(const Location& loc) override;
|
[[nodiscard]] std::string GetLocationContext(const Location& loc) override;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::string FetchExtract(std::string_view query);
|
std::string FetchExtract(std::string_view query);
|
||||||
std::unique_ptr<WebClient> client_;
|
std::unique_ptr<WebClient> client_;
|
||||||
std::shared_ptr<ILogger> logger_;
|
std::shared_ptr<ILogger> logger_;
|
||||||
/**
|
/// @brief Canonical cache for raw Wikipedia query extracts.
|
||||||
* @brief Cache for raw Wikipedia query extracts, keyed by query string.
|
|
||||||
*
|
|
||||||
* GetLocationContext() always queries "brewing" and reuses "beer in
|
|
||||||
* {country}" for every city in that country, so caching avoids refetching
|
|
||||||
* the same extract across locations in a run.
|
|
||||||
*/
|
|
||||||
std::unordered_map<std::string, std::string> extract_cache_;
|
std::unordered_map<std::string, std::string> extract_cache_;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -20,22 +20,10 @@
|
|||||||
* @brief Severity levels supported by the logging infra.
|
* @brief Severity levels supported by the logging infra.
|
||||||
*/
|
*/
|
||||||
enum class LogLevel {
|
enum class LogLevel {
|
||||||
/**
|
Debug, ///< Development/debugging information.
|
||||||
* @brief Development/debugging information.
|
Info, ///< General informational messages.
|
||||||
*/
|
Warn, ///< Warning conditions.
|
||||||
Debug,
|
Error, ///< Error conditions.
|
||||||
/**
|
|
||||||
* @brief General informational messages.
|
|
||||||
*/
|
|
||||||
Info,
|
|
||||||
/**
|
|
||||||
* @brief Warning conditions.
|
|
||||||
*/
|
|
||||||
Warn,
|
|
||||||
/**
|
|
||||||
* @brief Error conditions.
|
|
||||||
*/
|
|
||||||
Error,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,44 +34,18 @@ enum class LogLevel {
|
|||||||
* pipeline that emitted it.
|
* pipeline that emitted it.
|
||||||
*/
|
*/
|
||||||
enum class PipelinePhase {
|
enum class PipelinePhase {
|
||||||
/**
|
Startup, ///< Initialization and validation.
|
||||||
* @brief Initialization and validation.
|
UserGeneration, ///< User profile generation.
|
||||||
*/
|
BreweryAndBeerGeneration, ///< Brewery and beer data generation.
|
||||||
Startup,
|
CheckinGeneration, ///< Checkin (visit) record generation.
|
||||||
/**
|
RatingGeneration, ///< Rating and review generation.
|
||||||
* @brief Location/context enrichment (e.g. Wikipedia lookups).
|
FollowGeneration, ///< Follow relationship generation.
|
||||||
*/
|
Teardown, ///< Finalization and cleanup.
|
||||||
Enrichment,
|
|
||||||
/**
|
|
||||||
* @brief User profile generation.
|
|
||||||
*/
|
|
||||||
UserGeneration,
|
|
||||||
/**
|
|
||||||
* @brief Brewery and beer data generation.
|
|
||||||
*/
|
|
||||||
BreweryAndBeerGeneration,
|
|
||||||
/**
|
|
||||||
* @brief Checkin (visit) record generation.
|
|
||||||
*/
|
|
||||||
CheckinGeneration,
|
|
||||||
/**
|
|
||||||
* @brief Rating and review generation.
|
|
||||||
*/
|
|
||||||
RatingGeneration,
|
|
||||||
/**
|
|
||||||
* @brief Follow relationship generation.
|
|
||||||
*/
|
|
||||||
FollowGeneration,
|
|
||||||
/**
|
|
||||||
* @brief Finalization and cleanup.
|
|
||||||
*/
|
|
||||||
Teardown,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @struct LogDTO
|
* @struct LogDTO
|
||||||
* @brief User-provided subset of log fields. Used to capture call-site info
|
* @brief User-provided subset of log fields. Used to capture call-site info transparently.
|
||||||
* transparently.
|
|
||||||
*/
|
*/
|
||||||
struct LogDTO {
|
struct LogDTO {
|
||||||
LogLevel level;
|
LogLevel level;
|
||||||
@@ -102,35 +64,25 @@ struct LogDTO {
|
|||||||
* before the entry is dispatched.
|
* before the entry is dispatched.
|
||||||
*/
|
*/
|
||||||
struct LogEntry {
|
struct LogEntry {
|
||||||
/**
|
/// @brief Timestamp when the entry was created.
|
||||||
* @brief Timestamp when the entry was created.
|
|
||||||
*/
|
|
||||||
std::chrono::system_clock::time_point timestamp{};
|
std::chrono::system_clock::time_point timestamp{};
|
||||||
|
|
||||||
/**
|
/// @brief Source location where the log call was made.
|
||||||
* @brief Source location where the log call was made.
|
|
||||||
*/
|
|
||||||
std::source_location origin{};
|
std::source_location origin{};
|
||||||
|
|
||||||
/**
|
/// @brief Thread responsible for emitting the log.
|
||||||
* @brief Thread responsible for emitting the log.
|
|
||||||
*/
|
|
||||||
std::thread::id thread_id{};
|
std::thread::id thread_id{};
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Severity level of this entry.
|
/// @brief Severity level of this entry.
|
||||||
*/
|
|
||||||
LogLevel level;
|
LogLevel level;
|
||||||
|
|
||||||
/**
|
/// @brief Pipeline phase associated with the entry.
|
||||||
* @brief Pipeline phase associated with the entry.
|
|
||||||
*/
|
|
||||||
PipelinePhase phase;
|
PipelinePhase phase;
|
||||||
|
|
||||||
/**
|
/// @brief Log message text.
|
||||||
* @brief Log message text.
|
|
||||||
*/
|
|
||||||
std::string message;
|
std::string message;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_SERVICES_LOGGING_LOG_ENTRY_H_
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_SERVICES_LOGGING_LOG_ENTRY_H_
|
||||||
|
|||||||
@@ -6,8 +6,8 @@
|
|||||||
* a bounded channel for later processing by the dispatcher.
|
* a bounded channel for later processing by the dispatcher.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_SERVICES_LOGGING_LOG_PRODUCER_H_
|
#ifndef BIERGARTEN_PIPELINE_INCLUDES_SERVICES_LOGGING_CHANNEL_LOGGER_H_
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_SERVICES_LOGGING_LOG_PRODUCER_H_
|
#define BIERGARTEN_PIPELINE_INCLUDES_SERVICES_LOGGING_CHANNEL_LOGGER_H_
|
||||||
|
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
|
||||||
@@ -50,4 +50,4 @@ class LogProducer final : public ILogger {
|
|||||||
BoundedChannel<LogEntry>& channel_;
|
BoundedChannel<LogEntry>& channel_;
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_SERVICES_LOGGING_LOG_PRODUCER_H_
|
#endif // BIERGARTEN_PIPELINE_INCLUDES_SERVICES_LOGGING_CHANNEL_LOGGER_H_
|
||||||
|
|||||||
@@ -39,8 +39,7 @@ class ILogger {
|
|||||||
*/
|
*/
|
||||||
void Log(LogDTO payload,
|
void Log(LogDTO payload,
|
||||||
std::source_location origin = std::source_location::current(),
|
std::source_location origin = std::source_location::current(),
|
||||||
std::chrono::system_clock::time_point timestamp =
|
std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(),
|
||||||
std::chrono::system_clock::now(),
|
|
||||||
std::thread::id thread_id = std::this_thread::get_id()) {
|
std::thread::id thread_id = std::this_thread::get_id()) {
|
||||||
LogEntry entry;
|
LogEntry entry;
|
||||||
entry.timestamp = timestamp;
|
entry.timestamp = timestamp;
|
||||||
|
|||||||
@@ -1,18 +1,19 @@
|
|||||||
/**
|
/**
|
||||||
* @file web_client/http_web_client.h
|
* @file web_client/http_web_client.h
|
||||||
* @brief cpp-httplib implementation of the WebClient interface.
|
* @brief cpp-httplib implementation of the WebClient interface.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef BIERGARTEN_PIPELINE_INCLUDES_WEB_CLIENT_HTTP_WEB_CLIENT_H_
|
#ifndef BIERGARTEN_PIPELINE_INCLUDES_WEB_CLIENT_HTTP_WEB_CLIENT_H_
|
||||||
#define BIERGARTEN_PIPELINE_INCLUDES_WEB_CLIENT_HTTP_WEB_CLIENT_H_
|
#define BIERGARTEN_PIPELINE_INCLUDES_WEB_CLIENT_HTTP_WEB_CLIENT_H_
|
||||||
|
|
||||||
|
|
||||||
|
#include "web_client/web_client.h"
|
||||||
|
#include "services/logging/logger.h"
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#include "services/logging/logger.h"
|
|
||||||
#include "web_client/web_client.h"
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief WebClient implementation backed by cpp-httplib.
|
* @brief WebClient implementation backed by cpp-httplib.
|
||||||
*
|
*
|
||||||
@@ -25,7 +26,7 @@
|
|||||||
* bound to a single origin at construction time.
|
* bound to a single origin at construction time.
|
||||||
*/
|
*/
|
||||||
class HttpWebClient final : public WebClient {
|
class HttpWebClient final : public WebClient {
|
||||||
public:
|
public:
|
||||||
explicit HttpWebClient(std::shared_ptr<ILogger> logger)
|
explicit HttpWebClient(std::shared_ptr<ILogger> logger)
|
||||||
: logger_(std::move(logger)) {}
|
: logger_(std::move(logger)) {}
|
||||||
~HttpWebClient() override = default;
|
~HttpWebClient() override = default;
|
||||||
@@ -33,8 +34,7 @@ class HttpWebClient final : public WebClient {
|
|||||||
/**
|
/**
|
||||||
* @brief Executes a blocking HTTP/HTTPS GET request against a full URL.
|
* @brief Executes a blocking HTTP/HTTPS GET request against a full URL.
|
||||||
*
|
*
|
||||||
* @param url Fully-qualified URL, e.g.
|
* @param url Fully-qualified URL, e.g. "https://en.wikipedia.org/api/rest_v1/page/summary/Berlin"
|
||||||
* "https://en.wikipedia.org/api/rest_v1/page/summary/Berlin"
|
|
||||||
* @return Response body on HTTP 2xx; throws std::runtime_error otherwise.
|
* @return Response body on HTTP 2xx; throws std::runtime_error otherwise.
|
||||||
*/
|
*/
|
||||||
std::string Get(const std::string& url) override;
|
std::string Get(const std::string& url) override;
|
||||||
@@ -52,4 +52,5 @@ class HttpWebClient final : public WebClient {
|
|||||||
std::shared_ptr<ILogger> logger_;
|
std::shared_ptr<ILogger> logger_;
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // BIERGARTEN_PIPELINE_INCLUDES_WEB_CLIENT_HTTP_WEB_CLIENT_H_
|
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
*/
|
*/
|
||||||
class WebClient {
|
class WebClient {
|
||||||
public:
|
public:
|
||||||
|
/// @brief Virtual destructor for polymorphic cleanup.
|
||||||
virtual ~WebClient() = default;
|
virtual ~WebClient() = default;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"name": "Hophead Explorer",
|
|
||||||
"description": "Chases the newest hop varieties and double-digit IBUs, tracking hazy releases and limited tap takeovers across town.",
|
|
||||||
"style_affinities": ["American IPA", "Double IPA", "New England IPA", "Black IPA"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Malt & Tradition Loyalist",
|
|
||||||
"description": "Prefers clean, balanced lagers brewed the way their region has brewed them for generations, and is quick to defend a well-made Helles.",
|
|
||||||
"style_affinities": ["Munich Helles", "Vienna Lager", "Märzen", "Festbier"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Dark & Roasty Devotee",
|
|
||||||
"description": "Orders the darkest beer on the board year-round, drawn to roasted malt, coffee, and chocolate notes over carbonated lightness.",
|
|
||||||
"style_affinities": ["Imperial Stout", "Robust Porter", "Baltic Porter", "Oatmeal Stout"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Sour & Wild Forager",
|
|
||||||
"description": "Seeks out barrel-aged, spontaneously fermented, and funky beers, and will travel for a fresh bottling of something wild.",
|
|
||||||
"style_affinities": ["Lambic", "Gueuze", "Flanders Red Ale", "Wild Ale"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Session Sipper",
|
|
||||||
"description": "Values an easy-drinking pint that holds up over a long afternoon at the taproom more than raw intensity or novelty.",
|
|
||||||
"style_affinities": ["Session IPA", "Ordinary Bitter", "Cream Ale", "Blonde Ale"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Belgian Abbey Pilgrim",
|
|
||||||
"description": "Collects abbey and trappist releases, drawn to the dried-fruit esters and warming strength of classic Belgian ales.",
|
|
||||||
"style_affinities": ["Belgian Tripel", "Belgian Dubbel", "Belgian Quadrupel", "Trappist Single"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Wheat & Citrus Casual",
|
|
||||||
"description": "Reaches for something light, cloudy, and refreshing, usually with a citrus or coriander note, especially on a patio in summer.",
|
|
||||||
"style_affinities": ["Hefeweizen", "Witbier", "American Wheat Beer", "Berliner Weisse"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Big & Boozy Connoisseur",
|
|
||||||
"description": "Sips slowly from a snifter, seeking out high-ABV releases meant for aging and savoring rather than quick refreshment.",
|
|
||||||
"style_affinities": ["English Barleywine", "Wee Heavy", "Doppelbock", "Old Ale"]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
# FULL SYSTEM PROMPT
|
|
||||||
|
|
||||||
You are a craft beer community profile writer. You write short, first-person
|
|
||||||
biographies for fictional users of a brewery-discovery app, grounded in the
|
|
||||||
exact name, locale, and persona provided. You do not invent the user's name --
|
|
||||||
it is given to you and must not be altered, translated, or abbreviated beyond
|
|
||||||
forming a username.
|
|
||||||
|
|
||||||
You will receive the inputs like this:
|
|
||||||
|
|
||||||
## NAME:
|
|
||||||
|
|
||||||
[First name] [Last name]
|
|
||||||
|
|
||||||
## GENDER:
|
|
||||||
|
|
||||||
[Gender associated with the given first name]
|
|
||||||
|
|
||||||
## CITY:
|
|
||||||
|
|
||||||
[City Name]
|
|
||||||
|
|
||||||
## COUNTRY:
|
|
||||||
|
|
||||||
[Country Name]
|
|
||||||
|
|
||||||
## PERSONA:
|
|
||||||
|
|
||||||
[Persona archetype name]
|
|
||||||
|
|
||||||
## PERSONA DESCRIPTION:
|
|
||||||
|
|
||||||
[What this persona cares about and how they talk about beer]
|
|
||||||
|
|
||||||
## STYLE AFFINITIES:
|
|
||||||
|
|
||||||
[Comma-separated beer styles this persona favors]
|
|
||||||
|
|
||||||
## CRITICAL OUTPUT FORMAT (READ CAREFULLY):
|
|
||||||
|
|
||||||
ABSOLUTELY NO MARKDOWN FORMATTING. Do NOT wrap your response in json or ```
|
|
||||||
blocks.
|
|
||||||
|
|
||||||
Do not add markdown, code fences, or postscript around the final JSON object.
|
|
||||||
Do not say "Here is the JSON" or "Enjoy!".
|
|
||||||
|
|
||||||
The JSON must contain exactly three keys ("username", "bio",
|
|
||||||
"activity_weight") in that order. Do not rename or add any other keys.
|
|
||||||
|
|
||||||
ESCAPE ALL QUOTES inside the bio field using \", or use single quotes (' ')
|
|
||||||
instead.
|
|
||||||
|
|
||||||
DO NOT use actual line breaks (\n) inside any string. Keep the bio as one
|
|
||||||
continuous string.
|
|
||||||
|
|
||||||
The bio must be between 25 and 60 words, written in first person, and must
|
|
||||||
read as something this specific person would write about themselves -- not a
|
|
||||||
generic profile blurb.
|
|
||||||
|
|
||||||
`activity_weight` is a number between 0 and 1 (inclusive) representing how
|
|
||||||
often this persona checks in at breweries relative to other users. Persona
|
|
||||||
archetypes implying frequent, habitual brewery visits should skew higher;
|
|
||||||
casual or occasional-visitor personas should skew lower. Do not default to
|
|
||||||
0.5 -- vary it meaningfully based on the persona description.
|
|
||||||
|
|
||||||
Expected JSON format:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"username": "a handle derived from the given name",
|
|
||||||
"bio": "The first-person bio goes here.",
|
|
||||||
"activity_weight": 0.62
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## CONTENT RULES AND CONSTRAINTS:
|
|
||||||
|
|
||||||
### THE USERNAME:
|
|
||||||
|
|
||||||
Derive the username from the given first and/or last name (e.g. lowercase,
|
|
||||||
abbreviated, or combined with a short word or number tied to the persona's
|
|
||||||
style affinities). Do not invent an unrelated handle. Do not include spaces.
|
|
||||||
|
|
||||||
### THE BIO:
|
|
||||||
|
|
||||||
Ground the bio in the supplied persona description and style affinities --
|
|
||||||
mention at least one specific beer style from the style affinities list, in a
|
|
||||||
way that sounds like a personal preference rather than a list. Reference the
|
|
||||||
city or country naturally if it fits, but do not force it.
|
|
||||||
|
|
||||||
### VOICE & PERSPECTIVE:
|
|
||||||
|
|
||||||
Write in the first person ("I"/"my"). The tone should match the persona:
|
|
||||||
an enthusiastic explorer sounds different from a relaxed, easy-drinking
|
|
||||||
regular. Do not write in second or third person.
|
|
||||||
|
|
||||||
### THE BLOCKLIST (FORBIDDEN CONCEPTS):
|
|
||||||
|
|
||||||
You absolutely cannot use the following words and phrases. Make sure your
|
|
||||||
final output doesn't have any of these:
|
|
||||||
|
|
||||||
- "hidden gem"
|
|
||||||
- "passion"
|
|
||||||
- "authentic"
|
|
||||||
- "craft beer enthusiast"
|
|
||||||
- "beer connoisseur"
|
|
||||||
- "journey"
|
|
||||||
|
|
||||||
#### FORBIDDEN WRITING PATTERNS
|
|
||||||
|
|
||||||
The following patterns are common AI writing pitfalls and must not appear in
|
|
||||||
the bio:
|
|
||||||
|
|
||||||
- Negative parallelism constructions: "It's not X, it's Y"
|
|
||||||
- Inflated significance phrases: "stands as a testament," "plays a vital
|
|
||||||
role," "deeply rooted"
|
|
||||||
- Superficial trailing analyses: sentences ending in -ing words that add
|
|
||||||
opinion without content
|
|
||||||
- Promotional travel-copy tone: "breathtaking," "must-visit," "vibrant"
|
|
||||||
- Overused conjunctive transitions used as sentence openers: "Moreover,"
|
|
||||||
"Furthermore," "In addition"
|
|
||||||
- Rule of three: do not consistently organise ideas or examples in triplets
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
./biergarten-pipeline \
|
|
||||||
--model ../models/google_gemma-4-E4B-it-Q6_K.gguf \
|
|
||||||
--temperature 1.0 \
|
|
||||||
--top-p 0.95 \
|
|
||||||
--top-k 64 \
|
|
||||||
--n-ctx 8192 \
|
|
||||||
--location-count 15 \
|
|
||||||
--prompt-dir ../prompts
|
|
||||||
@@ -10,10 +10,11 @@ dockerStartCmd: []
|
|||||||
isPublic: false
|
isPublic: false
|
||||||
isServerless: false
|
isServerless: false
|
||||||
env:
|
env:
|
||||||
|
BIERGARTEN_MODE: live
|
||||||
BIERGARTEN_MODEL_PATH: /workspace/models/google_gemma-4-E4B-it-Q6_K.gguf
|
BIERGARTEN_MODEL_PATH: /workspace/models/google_gemma-4-E4B-it-Q6_K.gguf
|
||||||
|
BIERGARTEN_PROMPT_DIR: /workspace/app/build/prompts
|
||||||
BIERGARTEN_OUTPUT_DIR: /workspace/output
|
BIERGARTEN_OUTPUT_DIR: /workspace/output
|
||||||
BIERGARTEN_LOG_PATH: /workspace/logs/pipeline.log
|
BIERGARTEN_LOG_PATH: /workspace/logs/pipeline.log
|
||||||
BIERGARTEN_GL_LAYERS: "40"
|
|
||||||
BIERGARTEN_TEMPERATURE: "1.0"
|
BIERGARTEN_TEMPERATURE: "1.0"
|
||||||
BIERGARTEN_TOP_P: "0.95"
|
BIERGARTEN_TOP_P: "0.95"
|
||||||
BIERGARTEN_TOP_K: "64"
|
BIERGARTEN_TOP_K: "64"
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
|
|
||||||
opt("help,h", "Produce help message");
|
opt("help,h", "Produce help message");
|
||||||
|
|
||||||
|
// Defaults sourced from SamplingOptions{} so the CLI and LlamaGenerator
|
||||||
|
// share a single source of truth — changing the struct updates both.
|
||||||
auto add_sampling_options = [&]() -> void {
|
auto add_sampling_options = [&]() -> void {
|
||||||
const SamplingOptions sampling_defaults{};
|
const SamplingOptions sampling_defaults{};
|
||||||
opt("temperature",
|
opt("temperature",
|
||||||
@@ -51,8 +53,7 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
prog_opts::value<std::string>()->default_value("pipeline.log"),
|
prog_opts::value<std::string>()->default_value("pipeline.log"),
|
||||||
"Path for application logs");
|
"Path for application logs");
|
||||||
opt("prompt-dir", prog_opts::value<std::string>()->default_value(""),
|
opt("prompt-dir", prog_opts::value<std::string>()->default_value(""),
|
||||||
"Directory containing named prompt files (e.g. "
|
"Directory containing named prompt files (e.g. BREWERY_GENERATION.md)."
|
||||||
"BREWERY_GENERATION.md)."
|
|
||||||
" Required when not using --mocked.");
|
" Required when not using --mocked.");
|
||||||
opt("location-count", prog_opts::value<uint32_t>()->default_value(10));
|
opt("location-count", prog_opts::value<uint32_t>()->default_value(10));
|
||||||
};
|
};
|
||||||
@@ -71,11 +72,11 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
})();
|
})();
|
||||||
if (logger) {
|
if (logger) {
|
||||||
logger->Log(LogDTO{.level = LogLevel::Info,
|
logger->Log(LogDTO{.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = title});
|
.message = title});
|
||||||
logger->Log(LogDTO{.level = LogLevel::Info,
|
logger->Log(LogDTO{.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = usage});
|
.message = usage});
|
||||||
}
|
}
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
}
|
}
|
||||||
@@ -90,8 +91,8 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
help_stream << "\n" << desc;
|
help_stream << "\n" << desc;
|
||||||
if (logger) {
|
if (logger) {
|
||||||
logger->Log(LogDTO{.level = LogLevel::Info,
|
logger->Log(LogDTO{.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = help_stream.str()});
|
.message = help_stream.str()});
|
||||||
}
|
}
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
}
|
}
|
||||||
@@ -107,16 +108,14 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
const std::string model_path = var_map["model"].as<std::string>();
|
const std::string model_path = var_map["model"].as<std::string>();
|
||||||
const int n_gpu_layers = var_map["n-gpu-layers"].as<int>();
|
const int n_gpu_layers = var_map["n-gpu-layers"].as<int>();
|
||||||
|
|
||||||
// Enforce mutual exclusivity before any further configuration is
|
// Enforce mutual exclusivity before any further configuration is applied.
|
||||||
// applied.
|
|
||||||
if (use_mocked && !model_path.empty()) {
|
if (use_mocked && !model_path.empty()) {
|
||||||
const std::string msg =
|
const std::string msg =
|
||||||
"Invalid arguments: --mocked and --model are mutually "
|
"Invalid arguments: --mocked and --model are mutually exclusive";
|
||||||
"exclusive";
|
|
||||||
if (logger) {
|
if (logger) {
|
||||||
logger->Log(LogDTO{.level = LogLevel::Error,
|
logger->Log(LogDTO{.level = LogLevel::Error,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = msg});
|
.message = msg});
|
||||||
} else {
|
} else {
|
||||||
std::cerr << msg << std::endl;
|
std::cerr << msg << std::endl;
|
||||||
}
|
}
|
||||||
@@ -125,12 +124,11 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
|
|
||||||
if (!use_mocked && model_path.empty()) {
|
if (!use_mocked && model_path.empty()) {
|
||||||
const std::string msg =
|
const std::string msg =
|
||||||
"Invalid arguments: either --mocked or --model must be "
|
"Invalid arguments: either --mocked or --model must be specified";
|
||||||
"specified";
|
|
||||||
if (logger) {
|
if (logger) {
|
||||||
logger->Log(LogDTO{.level = LogLevel::Error,
|
logger->Log(LogDTO{.level = LogLevel::Error,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = msg});
|
.message = msg});
|
||||||
} else {
|
} else {
|
||||||
std::cerr << msg << std::endl;
|
std::cerr << msg << std::endl;
|
||||||
}
|
}
|
||||||
@@ -141,8 +139,7 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
// generator has no use for it and should not require it to be present.
|
// generator has no use for it and should not require it to be present.
|
||||||
if (!use_mocked && options.pipeline.prompt_dir.empty()) {
|
if (!use_mocked && options.pipeline.prompt_dir.empty()) {
|
||||||
const std::string msg =
|
const std::string msg =
|
||||||
"Invalid arguments: --prompt-dir is required when not using "
|
"Invalid arguments: --prompt-dir is required when not using --mocked";
|
||||||
"--mocked";
|
|
||||||
if (logger) {
|
if (logger) {
|
||||||
logger->Log({.level = LogLevel::Error,
|
logger->Log({.level = LogLevel::Error,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
@@ -155,6 +152,7 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
|
|
||||||
options.generator.use_mocked = use_mocked;
|
options.generator.use_mocked = use_mocked;
|
||||||
options.generator.model_path = model_path;
|
options.generator.model_path = model_path;
|
||||||
|
// options.generator.n_gpu_layers = n_gpu_layers;
|
||||||
|
|
||||||
// Only populate sampling config when the user explicitly overrides at
|
// Only populate sampling config when the user explicitly overrides at
|
||||||
// least one value. Leaving it as std::nullopt lets LlamaGenerator fall
|
// least one value. Leaving it as std::nullopt lets LlamaGenerator fall
|
||||||
@@ -173,8 +171,8 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
"Sampling parameters are ignored when using --mocked";
|
"Sampling parameters are ignored when using --mocked";
|
||||||
if (logger) {
|
if (logger) {
|
||||||
logger->Log(LogDTO{.level = LogLevel::Warn,
|
logger->Log(LogDTO{.level = LogLevel::Warn,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = msg});
|
.message = msg});
|
||||||
} else {
|
} else {
|
||||||
std::cerr << msg << std::endl;
|
std::cerr << msg << std::endl;
|
||||||
}
|
}
|
||||||
@@ -199,8 +197,8 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
exception.what();
|
exception.what();
|
||||||
if (logger) {
|
if (logger) {
|
||||||
logger->Log(LogDTO{.level = LogLevel::Error,
|
logger->Log(LogDTO{.level = LogLevel::Error,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = msg});
|
.message = msg});
|
||||||
}
|
}
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
} catch (...) {
|
} catch (...) {
|
||||||
@@ -208,8 +206,8 @@ std::optional<ApplicationOptions> ParseArguments(
|
|||||||
"Failed to parse command-line arguments: unknown error";
|
"Failed to parse command-line arguments: unknown error";
|
||||||
if (logger) {
|
if (logger) {
|
||||||
logger->Log(LogDTO{.level = LogLevel::Error,
|
logger->Log(LogDTO{.level = LogLevel::Error,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = msg});
|
.message = msg});
|
||||||
}
|
}
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* @file biergarten_pipeline_orchestrator/biergarten_pipeline_orchestrator.cc
|
* @file biergarten_pipeline_orchestrator/biergarten_pipeline_orchestrator.cc
|
||||||
* @brief BiergartenPipelineOrchestrator constructor implementation.
|
* @brief BiergartenDataGenerator constructor implementation.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "biergarten_pipeline_orchestrator.h"
|
#include "biergarten_pipeline_orchestrator.h"
|
||||||
@@ -12,11 +12,9 @@ BiergartenPipelineOrchestrator::BiergartenPipelineOrchestrator(
|
|||||||
std::unique_ptr<IEnrichmentService> context_service,
|
std::unique_ptr<IEnrichmentService> context_service,
|
||||||
std::unique_ptr<DataGenerator> generator,
|
std::unique_ptr<DataGenerator> generator,
|
||||||
std::unique_ptr<IExportService> exporter,
|
std::unique_ptr<IExportService> exporter,
|
||||||
std::unique_ptr<ICuratedDataService> curated_data_service,
|
const ApplicationOptions &app_options)
|
||||||
const ApplicationOptions& application_options)
|
|
||||||
: logger_(std::move(logger)),
|
: logger_(std::move(logger)),
|
||||||
context_service_(std::move(context_service)),
|
context_service_(std::move(context_service)),
|
||||||
generator_(std::move(generator)),
|
generator_(std::move(generator)),
|
||||||
exporter_(std::move(exporter)),
|
exporter_(std::move(exporter)),
|
||||||
curated_data_service_(std::move(curated_data_service)),
|
application_options_(app_options) {}
|
||||||
application_options_(application_options) {}
|
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
/**
|
/**
|
||||||
* @file biergarten_pipeline_orchestrator/generate_breweries.cc
|
* @file biergarten_pipeline_orchestrator/generate_breweries.cc
|
||||||
* @brief BiergartenPipelineOrchestrator::GenerateBreweries() implementation.
|
* @brief BiergartenDataGenerator::GenerateBreweries() implementation.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <format>
|
#include <format>
|
||||||
#include <optional>
|
|
||||||
|
|
||||||
#include "biergarten_pipeline_orchestrator.h"
|
#include "biergarten_pipeline_orchestrator.h"
|
||||||
#include "services/logging/logger.h"
|
#include "services/logging/logger.h"
|
||||||
@@ -20,69 +19,50 @@ void BiergartenPipelineOrchestrator::GenerateBreweries(
|
|||||||
size_t skipped_count = 0;
|
size_t skipped_count = 0;
|
||||||
size_t export_failed_count = 0;
|
size_t export_failed_count = 0;
|
||||||
|
|
||||||
const auto generate_record =
|
for (const auto& [location, region_context] : cities) {
|
||||||
[this, &skipped_count](
|
|
||||||
const Location& location,
|
|
||||||
const std::string& region_context) -> std::optional<BreweryRecord> {
|
|
||||||
try {
|
try {
|
||||||
const BreweryResult brewery =
|
const BreweryResult brewery =
|
||||||
generator_->GenerateBrewery(location, region_context);
|
generator_->GenerateBrewery(location, region_context);
|
||||||
return BreweryRecord{.location = location, .brewery = brewery};
|
|
||||||
|
const GeneratedBrewery gen{.location = location, .brewery = brewery};
|
||||||
|
|
||||||
|
generated_breweries_.push_back(gen);
|
||||||
|
|
||||||
|
try {
|
||||||
|
exporter_->ProcessRecord(gen);
|
||||||
|
} catch (const std::exception& export_exception) {
|
||||||
|
++export_failed_count;
|
||||||
|
|
||||||
|
logger_->Log(
|
||||||
|
{.level = LogLevel::Warn,
|
||||||
|
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
||||||
|
.message =
|
||||||
|
std::format("[Pipeline] Generated brewery for '{}' ({}) but SQLite export failed: {}",
|
||||||
|
location.city, location.country, export_exception.what())});
|
||||||
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
++skipped_count;
|
++skipped_count;
|
||||||
|
|
||||||
logger_->Log(
|
logger_->Log({.level = LogLevel::Warn,
|
||||||
{.level = LogLevel::Warn,
|
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
||||||
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
.message = std::format("[Pipeline] Skipping city '{}' ({}): brewery generation failed: {}",
|
||||||
.message = std::format("[Pipeline] Skipping city '{}' ({}): brewery "
|
location.city, location.country, e.what())});
|
||||||
"generation failed: {}",
|
|
||||||
location.city, location.country, e.what())});
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
const auto export_record = [this, &export_failed_count](
|
|
||||||
const BreweryRecord& record) {
|
|
||||||
try {
|
|
||||||
exporter_->ProcessRecord(record);
|
|
||||||
} catch (const std::exception& export_exception) {
|
|
||||||
++export_failed_count;
|
|
||||||
logger_->Log(
|
|
||||||
{.level = LogLevel::Warn,
|
|
||||||
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
|
||||||
.message = std::format("[Pipeline] Generated brewery for '{}' ({}) "
|
|
||||||
"but SQLite export failed: {}",
|
|
||||||
record.location.city, record.location.country,
|
|
||||||
export_exception.what())});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const auto& [location, region_context] : cities) {
|
|
||||||
const std::optional<BreweryRecord> record =
|
|
||||||
generate_record(location, region_context);
|
|
||||||
if (!record.has_value()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
generated_breweries_.push_back(*record);
|
|
||||||
export_record(*record);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (skipped_count > 0) {
|
if (skipped_count > 0) {
|
||||||
logger_->Log(
|
logger_->Log({.level = LogLevel::Warn,
|
||||||
{.level = LogLevel::Warn,
|
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
||||||
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
.message = std::format(
|
||||||
.message = std::format(
|
"[Pipeline] Skipped {} city/cities due to generation errors",
|
||||||
"[Pipeline] Skipped {} city/cities due to generation errors",
|
skipped_count)});
|
||||||
skipped_count)});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (export_failed_count > 0) {
|
if (export_failed_count > 0) {
|
||||||
logger_->Log(
|
logger_->Log({.level = LogLevel::Warn,
|
||||||
{.level = LogLevel::Warn,
|
.phase = PipelinePhase::Teardown,
|
||||||
.phase = PipelinePhase::Teardown,
|
.message = std::format(
|
||||||
.message = std::format("[Pipeline] Failed to export {} generated "
|
"[Pipeline] Failed to export {} generated brewery/breweries to SQLite",
|
||||||
"brewery/breweries to SQLite",
|
export_failed_count)});
|
||||||
export_failed_count)});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,219 +0,0 @@
|
|||||||
/**
|
|
||||||
* @file biergarten_pipeline_orchestrator/generate_users.cc
|
|
||||||
* @brief BiergartenPipelineOrchestrator::GenerateUsers() implementation.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <cctype>
|
|
||||||
#include <chrono>
|
|
||||||
#include <format>
|
|
||||||
#include <iterator>
|
|
||||||
#include <optional>
|
|
||||||
#include <random>
|
|
||||||
#include <stdexcept>
|
|
||||||
#include <string>
|
|
||||||
#include <string_view>
|
|
||||||
#include <unordered_set>
|
|
||||||
|
|
||||||
#include "biergarten_pipeline_orchestrator.h"
|
|
||||||
#include "services/curated_data/curated_json_data_service.h"
|
|
||||||
#include "services/logging/logger.h"
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
std::string Sanitize(std::string_view value) {
|
|
||||||
std::string out;
|
|
||||||
out.reserve(value.size());
|
|
||||||
for (const char character : value) {
|
|
||||||
if (std::isalnum(static_cast<unsigned char>(character)) != 0) {
|
|
||||||
out.push_back(static_cast<char>(
|
|
||||||
std::tolower(static_cast<unsigned char>(character))));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string BuildEmail(const Name& name,
|
|
||||||
std::unordered_set<std::string>& used_local_parts) {
|
|
||||||
const std::string base =
|
|
||||||
std::format("{}.{}", Sanitize(name.first_name), Sanitize(name.last_name));
|
|
||||||
|
|
||||||
std::string local_part = base;
|
|
||||||
uint32_t suffix = 1;
|
|
||||||
|
|
||||||
while (used_local_parts.contains(local_part)) {
|
|
||||||
local_part = std::format("{}{}", base, suffix);
|
|
||||||
++suffix;
|
|
||||||
}
|
|
||||||
|
|
||||||
used_local_parts.insert(local_part);
|
|
||||||
|
|
||||||
return std::format("{}@thebiergarten.app", local_part);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string GenerateDateOfBirth(std::mt19937& rng) {
|
|
||||||
using namespace std::chrono;
|
|
||||||
|
|
||||||
constexpr int kMinAge = 19;
|
|
||||||
constexpr int kMaxAge = 48;
|
|
||||||
constexpr int kMaxDayOffset = 364;
|
|
||||||
|
|
||||||
std::uniform_int_distribution<int> age_dist(kMinAge, kMaxAge);
|
|
||||||
std::uniform_int_distribution<int> day_offset_dist(0, kMaxDayOffset);
|
|
||||||
|
|
||||||
const year_month_day today{floor<days>(system_clock::now())};
|
|
||||||
const year_month_day birth_year_anchor{today.year() - years{age_dist(rng)},
|
|
||||||
today.month(), today.day()};
|
|
||||||
const sys_days birth_date =
|
|
||||||
sys_days{birth_year_anchor} - days{day_offset_dist(rng)};
|
|
||||||
const year_month_day birth_ymd{birth_date};
|
|
||||||
|
|
||||||
return std::format("{:04}-{:02}-{:02}", static_cast<int>(birth_ymd.year()),
|
|
||||||
static_cast<unsigned>(birth_ymd.month()),
|
|
||||||
static_cast<unsigned>(birth_ymd.day()));
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<Name> SampleName(
|
|
||||||
const ForenamesByCountryMap& forenames_by_country,
|
|
||||||
const SurnamesByCountryMap& surnames_by_country,
|
|
||||||
const std::string& iso3166_1, std::mt19937& rng) {
|
|
||||||
const auto forenames_it = forenames_by_country.find(iso3166_1);
|
|
||||||
const auto surnames_it = surnames_by_country.find(iso3166_1);
|
|
||||||
|
|
||||||
if (forenames_it == forenames_by_country.end() ||
|
|
||||||
surnames_it == surnames_by_country.end() ||
|
|
||||||
forenames_it->second.empty() || surnames_it->second.empty()) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ForenameList& forenames = forenames_it->second;
|
|
||||||
const SurnameList& surnames = surnames_it->second;
|
|
||||||
|
|
||||||
std::uniform_int_distribution<size_t> forename_dist(0, forenames.size() - 1);
|
|
||||||
std::uniform_int_distribution<size_t> surname_dist(0, surnames.size() - 1);
|
|
||||||
|
|
||||||
auto forename_it = forenames.begin();
|
|
||||||
std::advance(forename_it, forename_dist(rng));
|
|
||||||
|
|
||||||
auto surname_it = surnames.begin();
|
|
||||||
std::advance(surname_it, surname_dist(rng));
|
|
||||||
|
|
||||||
return Name{.first_name = forename_it->name,
|
|
||||||
.last_name = *surname_it,
|
|
||||||
.gender = forename_it->gender};
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
void BiergartenPipelineOrchestrator::GenerateUsers(
|
|
||||||
std::span<const EnrichedCity> cities) {
|
|
||||||
logger_->Log({.level = LogLevel::Info,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = "=== SAMPLE USER GENERATION ==="});
|
|
||||||
|
|
||||||
const PersonasList& personas = curated_data_service_->LoadPersonas();
|
|
||||||
|
|
||||||
if (personas.empty()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
"No personas available in personas.json for user generation");
|
|
||||||
}
|
|
||||||
|
|
||||||
const ForenamesByCountryMap& forenames_by_country =
|
|
||||||
curated_data_service_->LoadForenamesByCountry();
|
|
||||||
const SurnamesByCountryMap& surnames_by_country =
|
|
||||||
curated_data_service_->LoadSurnamesByCountry();
|
|
||||||
|
|
||||||
std::mt19937 rng(std::random_device{}());
|
|
||||||
std::uniform_int_distribution<size_t> persona_dist(0, personas.size() - 1);
|
|
||||||
|
|
||||||
generated_users_.clear();
|
|
||||||
size_t skipped_count = 0;
|
|
||||||
size_t export_failed_count = 0;
|
|
||||||
std::unordered_set<std::string> used_email_local_parts;
|
|
||||||
|
|
||||||
const auto generate_record =
|
|
||||||
[this, &rng, &skipped_count, &used_email_local_parts](
|
|
||||||
const EnrichedCity& city, const UserPersona& persona,
|
|
||||||
const Name& sampled_name) -> std::optional<UserRecord> {
|
|
||||||
try {
|
|
||||||
const UserResult user =
|
|
||||||
generator_->GenerateUser(city, persona, sampled_name);
|
|
||||||
|
|
||||||
return UserRecord{
|
|
||||||
.location = city.location,
|
|
||||||
.user = user,
|
|
||||||
.email = BuildEmail(sampled_name, used_email_local_parts),
|
|
||||||
.date_of_birth = GenerateDateOfBirth(rng),
|
|
||||||
};
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
++skipped_count;
|
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = std::format(
|
|
||||||
"[Pipeline] Skipping city '{}' ({}): "
|
|
||||||
"user generation failed: {}",
|
|
||||||
city.location.city, city.location.country, e.what())});
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const auto export_record = [this,
|
|
||||||
&export_failed_count](const UserRecord& record) {
|
|
||||||
try {
|
|
||||||
exporter_->ProcessRecord(record);
|
|
||||||
} catch (const std::exception& export_exception) {
|
|
||||||
++export_failed_count;
|
|
||||||
|
|
||||||
logger_->Log(
|
|
||||||
{.level = LogLevel::Warn,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = std::format("[Pipeline] Generated user for '{}' ({}) but "
|
|
||||||
"SQLite export failed: {}",
|
|
||||||
record.location.city, record.location.country,
|
|
||||||
export_exception.what())});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const auto& city : cities) {
|
|
||||||
const std::optional<Name> sampled_name =
|
|
||||||
SampleName(forenames_by_country, surnames_by_country,
|
|
||||||
city.location.iso3166_1, rng);
|
|
||||||
|
|
||||||
if (!sampled_name.has_value()) {
|
|
||||||
++skipped_count;
|
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = std::format(
|
|
||||||
"[Pipeline] Skipping city '{}' ({}): no names "
|
|
||||||
"available for country '{}'",
|
|
||||||
city.location.city, city.location.country,
|
|
||||||
city.location.iso3166_1)});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const UserPersona& persona = personas[persona_dist(rng)];
|
|
||||||
|
|
||||||
const std::optional<UserRecord> record =
|
|
||||||
generate_record(city, persona, *sampled_name);
|
|
||||||
if (!record.has_value()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
generated_users_.push_back(*record);
|
|
||||||
export_record(*record);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (skipped_count > 0) {
|
|
||||||
logger_->Log(
|
|
||||||
{.level = LogLevel::Warn,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = std::format(
|
|
||||||
"[Pipeline] Skipped {} city/cities during user generation",
|
|
||||||
skipped_count)});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (export_failed_count > 0) {
|
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
|
||||||
.phase = PipelinePhase::Teardown,
|
|
||||||
.message = std::format("[Pipeline] Failed to export {} "
|
|
||||||
"generated user/users to SQLite",
|
|
||||||
export_failed_count)});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,20 @@
|
|||||||
/**
|
/**
|
||||||
* @file biergarten_pipeline_orchestrator/log_results.cc
|
* @file biergarten_pipeline_orchestrator/log_results.cc
|
||||||
* @brief BiergartenPipelineOrchestrator::LogResults() implementation.
|
* @brief BiergartenDataGenerator::LogResults() implementation.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <boost/json/array.hpp>
|
#include <boost/json/array.hpp>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <format>
|
#include <format>
|
||||||
|
|
||||||
|
#include "../../includes/json_handling/pretty_print.h"
|
||||||
#include "biergarten_pipeline_orchestrator.h"
|
#include "biergarten_pipeline_orchestrator.h"
|
||||||
#include "json_handling/pretty_print.h"
|
|
||||||
#include "services/logging/logger.h"
|
#include "services/logging/logger.h"
|
||||||
|
|
||||||
void BiergartenPipelineOrchestrator::LogResults() const {
|
void BiergartenPipelineOrchestrator::LogResults() const {
|
||||||
boost::json::array brewery_output;
|
boost::json::array output;
|
||||||
|
|
||||||
for (const auto& [location, brewery] : generated_breweries_) {
|
for (const auto& [location, brewery] : generated_breweries_) {
|
||||||
brewery_output.push_back(boost::json::object{
|
output.push_back(boost::json::object{
|
||||||
{"name_en", brewery.name_en},
|
{"name_en", brewery.name_en},
|
||||||
{"description_en", brewery.description_en},
|
{"description_en", brewery.description_en},
|
||||||
{"name_local", brewery.name_local},
|
{"name_local", brewery.name_local},
|
||||||
@@ -30,30 +29,9 @@ void BiergartenPipelineOrchestrator::LogResults() const {
|
|||||||
}}});
|
}}});
|
||||||
}
|
}
|
||||||
|
|
||||||
std::ostringstream brewery_oss;
|
std::ostringstream oss;
|
||||||
PrettyPrint(brewery_oss, brewery_output);
|
PrettyPrint(oss, output);
|
||||||
logger_->Log({.level = LogLevel::Info,
|
logger_->Log({.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Teardown,
|
.phase = PipelinePhase::Teardown,
|
||||||
.message = brewery_oss.str()});
|
.message = oss.str()});
|
||||||
|
|
||||||
boost::json::array user_output;
|
|
||||||
|
|
||||||
for (const auto& generated_user : generated_users_) {
|
|
||||||
user_output.push_back(boost::json::object{
|
|
||||||
{"first_name", generated_user.user.first_name},
|
|
||||||
{"last_name", generated_user.user.last_name},
|
|
||||||
{"gender", generated_user.user.gender},
|
|
||||||
{"username", generated_user.user.username},
|
|
||||||
{"bio", generated_user.user.bio},
|
|
||||||
{"activity_weight", generated_user.user.activity_weight},
|
|
||||||
{"email", generated_user.email},
|
|
||||||
{"date_of_birth", generated_user.date_of_birth},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
std::ostringstream user_oss;
|
|
||||||
PrettyPrint(user_oss, user_output);
|
|
||||||
logger_->Log({.level = LogLevel::Info,
|
|
||||||
.phase = PipelinePhase::Teardown,
|
|
||||||
.message = user_oss.str()});
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
/**
|
/**
|
||||||
* @file biergarten_pipeline_orchestrator/query_cities_with_countries.cc
|
* @file biergarten_pipeline_orchestrator/query_cities_with_countries.cc
|
||||||
* @brief BiergartenPipelineOrchestrator::QueryCitiesWithCountries()
|
* @brief BiergartenDataGenerator::QueryCitiesWithCountries() implementation.
|
||||||
* implementation.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
|
#include <filesystem>
|
||||||
#include <format>
|
#include <format>
|
||||||
#include <iterator>
|
#include <iterator>
|
||||||
#include <random>
|
#include <random>
|
||||||
|
|
||||||
#include "biergarten_pipeline_orchestrator.h"
|
#include "biergarten_pipeline_orchestrator.h"
|
||||||
#include "services/curated_data/curated_json_data_service.h"
|
#include "json_handling/json_loader.h"
|
||||||
#include "services/logging/logger.h"
|
#include "services/logging/logger.h"
|
||||||
|
|
||||||
std::vector<Location>
|
std::vector<Location>
|
||||||
@@ -20,8 +20,9 @@ BiergartenPipelineOrchestrator::QueryCitiesWithCountries() {
|
|||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = "=== GEOGRAPHIC DATA OVERVIEW ==="});
|
.message = "=== GEOGRAPHIC DATA OVERVIEW ==="});
|
||||||
|
|
||||||
const std::vector<Location>& all_locations =
|
const std::filesystem::path locations_path = "locations.json";
|
||||||
curated_data_service_->LoadLocations();
|
|
||||||
|
auto all_locations = JsonLoader::LoadLocations(locations_path, logger_);
|
||||||
|
|
||||||
const size_t sample_count = std::min(
|
const size_t sample_count = std::min(
|
||||||
static_cast<size_t>(application_options_.pipeline.location_count),
|
static_cast<size_t>(application_options_.pipeline.location_count),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* @file biergarten_pipeline_orchestrator/run.cc
|
* @file biergarten_pipeline_orchestrator/run.cc
|
||||||
* @brief BiergartenPipelineOrchestrator::Run() implementation.
|
* @brief BiergartenDataGenerator::Run() implementation.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
@@ -22,40 +22,42 @@ bool BiergartenPipelineOrchestrator::Run() {
|
|||||||
for (auto& city : cities) {
|
for (auto& city : cities) {
|
||||||
try {
|
try {
|
||||||
std::string region_context = context_service_->GetLocationContext(city);
|
std::string region_context = context_service_->GetLocationContext(city);
|
||||||
|
// logger_->Log(LogLevel::Debug, PipelinePhase::UserGeneration,
|
||||||
|
// "[Pipeline] Context for '" + city.city + "' (" +
|
||||||
|
// city.iso3166_2 + ") gathered:\n" + region_context);
|
||||||
|
|
||||||
enriched.push_back(
|
enriched.push_back(
|
||||||
EnrichedCity{.location = std::move(city),
|
EnrichedCity{.location = std::move(city),
|
||||||
.region_context = std::move(region_context)});
|
.region_context = std::move(region_context)});
|
||||||
} catch (const std::exception& exception) {
|
} catch (const std::exception& exception) {
|
||||||
++skipped_count;
|
++skipped_count;
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Enrichment,
|
{.level = LogLevel::Warn,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::UserGeneration,
|
||||||
"[Pipeline] Skipping city '{}' ({}): context "
|
.message = std::format(
|
||||||
"lookup failed: {}",
|
"[Pipeline] Skipping city '{}' ({}): context lookup failed: {}",
|
||||||
city.city, city.country, exception.what())});
|
city.city, city.country, exception.what())});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (skipped_count > 0) {
|
if (skipped_count > 0) {
|
||||||
logger_->Log(
|
logger_->Log({.level = LogLevel::Warn,
|
||||||
{.level = LogLevel::Warn,
|
.phase = PipelinePhase::UserGeneration,
|
||||||
.phase = PipelinePhase::Enrichment,
|
.message = std::format(
|
||||||
.message = std::format("[Pipeline] Skipped {} city/cities due "
|
"[Pipeline] Skipped {} city/cities due to context lookup errors",
|
||||||
"to context lookup errors",
|
skipped_count)});
|
||||||
skipped_count)});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this->GenerateUsers(enriched);
|
|
||||||
this->GenerateBreweries(enriched);
|
this->GenerateBreweries(enriched);
|
||||||
exporter_->Finalize();
|
exporter_->Finalize();
|
||||||
this->LogResults();
|
this->LogResults();
|
||||||
return true;
|
return true;
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
logger_->Log({.level = LogLevel::Error,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Teardown,
|
{.level = LogLevel::Error,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::Teardown,
|
||||||
"Pipeline execution failed with error: {}", e.what())});
|
.message =
|
||||||
|
std::format("Pipeline execution failed with error: {}", e.what())});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,6 @@
|
|||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "data_generation/json_grammars.h"
|
|
||||||
#include "data_generation/llama_generator.h"
|
#include "data_generation/llama_generator.h"
|
||||||
#include "data_generation/llama_generator_helpers.h"
|
#include "data_generation/llama_generator_helpers.h"
|
||||||
|
|
||||||
@@ -33,6 +32,19 @@ static std::string FormatLocalLanguageCodes(
|
|||||||
return formatted;
|
return formatted;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GBNF grammar for structured brewery JSON output.
|
||||||
|
// @TODO move to a separate gbnf file if it grows in complexity or is shared
|
||||||
|
// across modules.
|
||||||
|
static constexpr std::string_view kBreweryJsonGrammar = R"json_brewery(
|
||||||
|
root ::= thought-block "{" ws "\"name_en\"" ws ":" ws string ws "," ws "\"description_en\"" ws ":" ws string ws "," ws "\"name_local\"" ws ":" ws string ws "," ws "\"description_local\"" ws ":" ws string ws "}" ws
|
||||||
|
thought-block ::= [^{]*
|
||||||
|
ws ::= [ \t\n\r]*
|
||||||
|
string ::= "\"" char+ "\""
|
||||||
|
char ::= [^"\\\x7F\x00-\x1F] | [\\] escape
|
||||||
|
escape ::= ["\\/bfnrt] | "u" hex hex hex hex
|
||||||
|
hex ::= [0-9a-fA-F]
|
||||||
|
)json_brewery";
|
||||||
|
|
||||||
static constexpr int kBreweryInitialMaxTokens = 2800;
|
static constexpr int kBreweryInitialMaxTokens = 2800;
|
||||||
|
|
||||||
BreweryResult LlamaGenerator::GenerateBrewery(
|
BreweryResult LlamaGenerator::GenerateBrewery(
|
||||||
@@ -71,14 +83,15 @@ BreweryResult LlamaGenerator::GenerateBrewery(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* RETRY LOOP with validation and error correction
|
* RETRY LOOP with validation and error correction
|
||||||
* Attempts to generate valid brewery data up to 3 times, with
|
* Attempts to generate valid brewery data up to 3 times, with feedback-based
|
||||||
* feedback-based refinement
|
* refinement
|
||||||
*/
|
*/
|
||||||
constexpr int max_attempts = 3;
|
constexpr int max_attempts = 3;
|
||||||
std::string raw;
|
std::string raw;
|
||||||
std::string last_error;
|
std::string last_error;
|
||||||
|
|
||||||
// Token budget: too small risks truncating valid JSON mid-string.
|
// Token budget: too small risks truncating valid JSON mid-string.
|
||||||
|
// Start conservatively but allow adaptive increases on truncation.
|
||||||
int max_tokens = kBreweryInitialMaxTokens;
|
int max_tokens = kBreweryInitialMaxTokens;
|
||||||
|
|
||||||
// Limit output length to keep it concise and focused
|
// Limit output length to keep it concise and focused
|
||||||
@@ -91,7 +104,7 @@ BreweryResult LlamaGenerator::GenerateBrewery(
|
|||||||
{.level = LogLevel::Debug,
|
{.level = LogLevel::Debug,
|
||||||
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
||||||
.message = std::format("LlamaGenerator: raw output (attempt {}): {}",
|
.message = std::format("LlamaGenerator: raw output (attempt {}): {}",
|
||||||
attempt + 1, raw)});
|
attempt + 1, raw)});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate output: parse JSON and check required fields
|
// Validate output: parse JSON and check required fields
|
||||||
@@ -107,9 +120,8 @@ BreweryResult LlamaGenerator::GenerateBrewery(
|
|||||||
logger_->Log(
|
logger_->Log(
|
||||||
{.level = LogLevel::Info,
|
{.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
||||||
.message = std::format("LlamaGenerator: successfully generated "
|
.message = std::format("LlamaGenerator: successfully generated brewery data on attempt {}",
|
||||||
"brewery data on attempt {}",
|
attempt + 1)});
|
||||||
attempt + 1)});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return brewery;
|
return brewery;
|
||||||
@@ -122,38 +134,33 @@ BreweryResult LlamaGenerator::GenerateBrewery(
|
|||||||
logger_->Log(
|
logger_->Log(
|
||||||
{.level = LogLevel::Warn,
|
{.level = LogLevel::Warn,
|
||||||
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
||||||
.message = std::format(
|
.message =
|
||||||
"LlamaGenerator: malformed brewery JSON (attempt {}): {}",
|
std::format("LlamaGenerator: malformed brewery JSON (attempt {}): {}",
|
||||||
attempt + 1, *validation_error)});
|
attempt + 1, *validation_error)});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update prompt with error details to guide LLM toward correct output.
|
// Update prompt with error details to guide LLM toward correct output.
|
||||||
user_prompt = std::format(
|
user_prompt = std::format(
|
||||||
"Your previous response was invalid. Error: {}\nReturn the thought "
|
"Your previous response was invalid. Error: {}\nReturn the thought "
|
||||||
"process before the JSON if needed, then return ONLY valid JSON "
|
"process before the JSON if needed, then return ONLY valid JSON with "
|
||||||
"with "
|
"exactly these keys, in this exact order: {{\"name_en\": \"<English "
|
||||||
"exactly these keys, in this exact order: {{\"name_en\": "
|
|
||||||
"\"<English "
|
|
||||||
"brewery name>\", \"description_en\": \"<English single-paragraph "
|
"brewery name>\", \"description_en\": \"<English single-paragraph "
|
||||||
"description>\", \"name_local\": \"<local-language brewery "
|
"description>\", \"name_local\": \"<local-language brewery name>\", "
|
||||||
"name>\", "
|
|
||||||
"\"description_local\": \"<local-language single-paragraph "
|
"\"description_local\": \"<local-language single-paragraph "
|
||||||
"description>\"}}.\nDo not include markdown, comments, extra keys, "
|
"description>\"}}.\nDo not include markdown, comments, extra keys, or "
|
||||||
"or "
|
"literal placeholder values.\n\nKeep the JSON strings concise enough "
|
||||||
"literal placeholder values.\n\nKeep the JSON strings concise "
|
|
||||||
"enough "
|
|
||||||
"to fit within the token budget.\n\n{}",
|
"to fit within the token budget.\n\n{}",
|
||||||
*validation_error, retry_location);
|
*validation_error, retry_location);
|
||||||
}
|
}
|
||||||
|
|
||||||
// All retry attempts exhausted: log failure and throw exception
|
// All retry attempts exhausted: log failure and throw exception
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Error,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
{.level = LogLevel::Error,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::BreweryAndBeerGeneration,
|
||||||
"LlamaGenerator: malformed brewery "
|
.message = std::format(
|
||||||
"response after {} attempts: {}",
|
"LlamaGenerator: malformed brewery response after {} attempts: {}",
|
||||||
max_attempts, last_error.empty() ? raw : last_error)});
|
max_attempts, last_error.empty() ? raw : last_error)});
|
||||||
}
|
}
|
||||||
throw std::runtime_error("LlamaGenerator: malformed brewery response");
|
throw std::runtime_error("LlamaGenerator: malformed brewery response");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,115 +1,24 @@
|
|||||||
/**
|
/**
|
||||||
* @file data_generation/llama/generate_user.cc
|
* @file data_generation/llama/generate_user.cc
|
||||||
* @brief Builds persona/name-grounded user prompts, performs retry-based
|
* @brief Generates locale-aware user profiles with strict two-line formatting,
|
||||||
* inference, and validates structured JSON output for user records.
|
* retry handling, and output sanitization for downstream parsing.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <format>
|
|
||||||
#include <optional>
|
|
||||||
#include <stdexcept>
|
|
||||||
#include <string>
|
|
||||||
#include <string_view>
|
|
||||||
|
|
||||||
#include "data_generation/json_grammars.h"
|
#include <format>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
#include "data_generation/llama_generator.h"
|
#include "data_generation/llama_generator.h"
|
||||||
#include "data_generation/llama_generator_helpers.h"
|
#include "data_generation/llama_generator_helpers.h"
|
||||||
|
|
||||||
static constexpr int kUserInitialMaxTokens = 1200;
|
// TODO: Implement locale-aware user profile generation.
|
||||||
|
// Current implementation returns a hardcoded test value and ignores the
|
||||||
UserResult LlamaGenerator::GenerateUser(const EnrichedCity& city,
|
// locale parameter. Future implementation should:
|
||||||
const UserPersona& persona,
|
// 1. Load a USER_GENERATION.md prompt template with locale context
|
||||||
const Name& name) {
|
// 2. Perform LLM inference with locale-specific username/bio generation
|
||||||
std::string style_affinities;
|
// 3. Parse and validate JSON output with retry handling (similar to brewery)
|
||||||
for (const std::string& style : persona.style_affinities) {
|
// 4. Return locale-aware username and biography
|
||||||
if (!style_affinities.empty()) {
|
UserResult LlamaGenerator::GenerateUser(const std::string& locale) {
|
||||||
style_affinities += ", ";
|
return {.username = "test_user",
|
||||||
}
|
.bio = std::format("This is a test user profile from {}.", locale)};
|
||||||
style_affinities += style;
|
|
||||||
}
|
|
||||||
|
|
||||||
const std::string system_prompt = prompt_directory_->Load("USER_GENERATION");
|
|
||||||
|
|
||||||
std::string user_prompt = std::format(
|
|
||||||
"## NAME:\n\n{} {}\n\n"
|
|
||||||
"## GENDER:\n\n{}\n\n"
|
|
||||||
"## CITY:\n\n{}\n\n"
|
|
||||||
"## COUNTRY:\n\n{}\n\n"
|
|
||||||
"## PERSONA:\n\n{}\n\n"
|
|
||||||
"## PERSONA DESCRIPTION:\n\n{}\n\n"
|
|
||||||
"## STYLE AFFINITIES:\n\n{}",
|
|
||||||
name.first_name, name.last_name, name.gender, city.location.city,
|
|
||||||
city.location.country, persona.name, persona.description,
|
|
||||||
style_affinities);
|
|
||||||
|
|
||||||
const std::string retry_context = std::format(
|
|
||||||
"Name: {} {}\nCity: {}, {}\nPersona: {}", name.first_name, name.last_name,
|
|
||||||
city.location.city, city.location.country, persona.name);
|
|
||||||
|
|
||||||
constexpr int max_attempts = 3;
|
|
||||||
std::string raw;
|
|
||||||
std::string last_error;
|
|
||||||
int max_tokens = kUserInitialMaxTokens;
|
|
||||||
|
|
||||||
for (int attempt = 0; attempt < max_attempts; ++attempt) {
|
|
||||||
raw = this->Infer(system_prompt, user_prompt, max_tokens, kUserJsonGrammar);
|
|
||||||
if (logger_) {
|
|
||||||
logger_->Log(
|
|
||||||
{.level = LogLevel::Debug,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = std::format("LlamaGenerator: raw output (attempt {}): {}",
|
|
||||||
attempt + 1, raw)});
|
|
||||||
}
|
|
||||||
|
|
||||||
UserResult user;
|
|
||||||
const std::optional<std::string> validation_error =
|
|
||||||
ValidateUserJson(raw, user);
|
|
||||||
|
|
||||||
if (!validation_error.has_value()) {
|
|
||||||
if (logger_) {
|
|
||||||
logger_->Log(
|
|
||||||
{.level = LogLevel::Info,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = std::format("LlamaGenerator: successfully "
|
|
||||||
"generated user data on attempt {}",
|
|
||||||
attempt + 1)});
|
|
||||||
}
|
|
||||||
|
|
||||||
user.first_name = name.first_name;
|
|
||||||
user.last_name = name.last_name;
|
|
||||||
user.gender = name.gender;
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
last_error = *validation_error;
|
|
||||||
if (logger_) {
|
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = std::format(
|
|
||||||
"LlamaGenerator: malformed user JSON (attempt {}): {}",
|
|
||||||
attempt + 1, *validation_error)});
|
|
||||||
}
|
|
||||||
|
|
||||||
user_prompt = std::format(
|
|
||||||
"Your previous response was invalid. Error: {}\nReturn the thought "
|
|
||||||
"process before the JSON if needed, then return ONLY valid JSON "
|
|
||||||
"with "
|
|
||||||
"exactly these keys, in this exact order: {{\"username\": "
|
|
||||||
"\"<handle "
|
|
||||||
"derived from the given name>\", \"bio\": \"<first-person bio "
|
|
||||||
"grounded in the persona>\", \"activity_weight\": <number between "
|
|
||||||
"0 "
|
|
||||||
"and 1>}}.\nDo not include markdown, comments, extra keys, or "
|
|
||||||
"literal placeholder values.\n\n{}",
|
|
||||||
*validation_error, retry_context);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (logger_) {
|
|
||||||
logger_->Log({.level = LogLevel::Error,
|
|
||||||
.phase = PipelinePhase::UserGeneration,
|
|
||||||
.message = std::format(
|
|
||||||
"LlamaGenerator: malformed user response "
|
|
||||||
"after {} attempts: {}",
|
|
||||||
max_attempts, last_error.empty() ? raw : last_error)});
|
|
||||||
}
|
|
||||||
throw std::runtime_error("LlamaGenerator: malformed user response");
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,16 +9,13 @@
|
|||||||
#include <boost/json.hpp>
|
#include <boost/json.hpp>
|
||||||
#include <cctype>
|
#include <cctype>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <span>
|
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include <llama.h>
|
|
||||||
|
|
||||||
#include "data_generation/llama_generator_helpers.h"
|
#include "data_generation/llama_generator_helpers.h"
|
||||||
|
#include "llama.h"
|
||||||
namespace {
|
namespace {
|
||||||
/**
|
/**
|
||||||
* String trimming: removes leading and trailing whitespace
|
* String trimming: removes leading and trailing whitespace
|
||||||
@@ -79,7 +76,7 @@ bool ReadRequiredTrimmedStringField(const boost::json::object& obj,
|
|||||||
return !out.empty();
|
return !out.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool HasSchemaPlaceholder(std::span<std::string* const> values) {
|
bool HasSchemaPlaceholder(const std::array<std::string*, 4>& values) {
|
||||||
for (const std::string* value : values) {
|
for (const std::string* value : values) {
|
||||||
std::string lowered = *value;
|
std::string lowered = *value;
|
||||||
std::ranges::transform(lowered, lowered.begin(),
|
std::ranges::transform(lowered, lowered.begin(),
|
||||||
@@ -210,58 +207,3 @@ std::optional<std::string> ValidateBreweryJson(const std::string& raw,
|
|||||||
|
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::optional<std::string> ValidateUserJson(const std::string& raw,
|
|
||||||
UserResult& user_out) {
|
|
||||||
boost::system::error_code error_code;
|
|
||||||
const std::string_view raw_view(raw);
|
|
||||||
const size_t opening_brace = raw_view.find('{');
|
|
||||||
if (opening_brace == std::string_view::npos) {
|
|
||||||
return "JSON parse error: missing opening brace '{'";
|
|
||||||
}
|
|
||||||
|
|
||||||
const std::string_view json_payload = raw_view.substr(opening_brace);
|
|
||||||
boost::json::value json_value = boost::json::parse(json_payload, error_code);
|
|
||||||
if (error_code) {
|
|
||||||
return "JSON parse error: " + error_code.message();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!json_value.is_object()) {
|
|
||||||
return "JSON root must be an object";
|
|
||||||
}
|
|
||||||
|
|
||||||
const auto& obj = json_value.get_object();
|
|
||||||
if (obj.size() != 3) {
|
|
||||||
return "JSON object must contain exactly three keys";
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string validation_error;
|
|
||||||
if (!ReadRequiredTrimmedStringField(obj, "username", user_out.username,
|
|
||||||
&validation_error)) {
|
|
||||||
return validation_error;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!ReadRequiredTrimmedStringField(obj, "bio", user_out.bio,
|
|
||||||
&validation_error)) {
|
|
||||||
return validation_error;
|
|
||||||
}
|
|
||||||
|
|
||||||
const boost::json::value* activity_weight_field =
|
|
||||||
obj.if_contains("activity_weight");
|
|
||||||
if (activity_weight_field == nullptr || !activity_weight_field->is_number()) {
|
|
||||||
return "Missing or invalid numeric field: activity_weight";
|
|
||||||
}
|
|
||||||
|
|
||||||
const double activity_weight = activity_weight_field->to_number<double>();
|
|
||||||
if (activity_weight < 0.0 || activity_weight > 1.0) {
|
|
||||||
return "activity_weight must be between 0 and 1";
|
|
||||||
}
|
|
||||||
user_out.activity_weight = static_cast<float>(activity_weight);
|
|
||||||
|
|
||||||
const std::array schema_placeholders = {&user_out.username, &user_out.bio};
|
|
||||||
if (HasSchemaPlaceholder(schema_placeholders)) {
|
|
||||||
return "JSON appears to be a schema placeholder, not content";
|
|
||||||
}
|
|
||||||
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -14,10 +14,9 @@
|
|||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include <llama.h>
|
|
||||||
|
|
||||||
#include "data_generation/llama_generator.h"
|
#include "data_generation/llama_generator.h"
|
||||||
#include "data_generation/llama_generator_helpers.h"
|
#include "data_generation/llama_generator_helpers.h"
|
||||||
|
#include "llama.h"
|
||||||
|
|
||||||
static constexpr size_t kPromptTokenSlack = 8;
|
static constexpr size_t kPromptTokenSlack = 8;
|
||||||
// Minimum tokens to keep when using top-p sampling. Ensures at least one
|
// Minimum tokens to keep when using top-p sampling. Ensures at least one
|
||||||
|
|||||||
@@ -11,9 +11,8 @@
|
|||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
#include <llama.h>
|
|
||||||
|
|
||||||
#include "data_model/models.h"
|
#include "data_model/models.h"
|
||||||
|
#include "llama.h"
|
||||||
|
|
||||||
static constexpr uint32_t kMaxContextSize = 32768U;
|
static constexpr uint32_t kMaxContextSize = 32768U;
|
||||||
|
|
||||||
|
|||||||
@@ -10,10 +10,9 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#include <ggml-backend.h>
|
|
||||||
#include <llama.h>
|
|
||||||
|
|
||||||
#include "data_generation/llama_generator.h"
|
#include "data_generation/llama_generator.h"
|
||||||
|
#include "ggml-backend.h"
|
||||||
|
#include "llama.h"
|
||||||
|
|
||||||
// Maximum batch size for decode operations. Capping the batch prevents
|
// Maximum batch size for decode operations. Capping the batch prevents
|
||||||
// excessive memory allocation while maintaining inference performance.
|
// excessive memory allocation while maintaining inference performance.
|
||||||
|
|||||||
@@ -14,13 +14,3 @@ size_t MockGenerator::DeterministicHash(const Location& location) {
|
|||||||
boost::hash_combine(seed, location.country);
|
boost::hash_combine(seed, location.country);
|
||||||
return seed;
|
return seed;
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t MockGenerator::DeterministicHash(const Location& location,
|
|
||||||
const UserPersona& persona,
|
|
||||||
const Name& name) {
|
|
||||||
size_t seed = DeterministicHash(location);
|
|
||||||
boost::hash_combine(seed, persona.name);
|
|
||||||
boost::hash_combine(seed, name.first_name);
|
|
||||||
boost::hash_combine(seed, name.last_name);
|
|
||||||
return seed;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,31 +1,22 @@
|
|||||||
/**
|
/**
|
||||||
* @file data_generation/mock/generate_user.cc
|
* @file data_generation/mock/generate_user.cc
|
||||||
* @brief Generates deterministic mock user profiles by hashing city, persona,
|
* @brief Generates deterministic mock user profiles by hashing locale values
|
||||||
* and sampled name into predefined username and bio collections.
|
* into predefined username and bio collections.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <functional>
|
||||||
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
|
||||||
#include "data_generation/mock_generator.h"
|
#include "data_generation/mock_generator.h"
|
||||||
|
|
||||||
UserResult MockGenerator::GenerateUser(const EnrichedCity& city,
|
UserResult MockGenerator::GenerateUser(const std::string& locale) {
|
||||||
const UserPersona& persona,
|
const size_t hash = std::hash<std::string>{}(locale);
|
||||||
const Name& name) {
|
|
||||||
const size_t hash = DeterministicHash(city.location, persona, name);
|
|
||||||
|
|
||||||
|
UserResult result;
|
||||||
const std::string_view username = kUsernames[hash % kUsernames.size()];
|
const std::string_view username = kUsernames[hash % kUsernames.size()];
|
||||||
const std::string_view bio = kBios[hash / kBioHashStride % kBios.size()];
|
const std::string_view bio = kBios[hash / kBioHashStride % kBios.size()];
|
||||||
const float activity_weight =
|
result.username = username;
|
||||||
static_cast<float>(hash / kActivityWeightHashStride %
|
result.bio = bio;
|
||||||
kActivityWeightHashRange) /
|
return result;
|
||||||
static_cast<float>(kActivityWeightHashRange);
|
|
||||||
|
|
||||||
return {
|
|
||||||
.first_name = name.first_name,
|
|
||||||
.last_name = name.last_name,
|
|
||||||
.gender = name.gender,
|
|
||||||
.username = std::string(username),
|
|
||||||
.bio = std::string(bio),
|
|
||||||
.activity_weight = activity_weight,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|||||||
110
tooling/pipeline/src/json_handling/json_loader.cc
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
/**
|
||||||
|
* @file json_handling/json_loader.cc
|
||||||
|
* @brief Parses curated location JSON input into strongly typed Location
|
||||||
|
* records with strict field validation and descriptive error reporting.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "json_handling/json_loader.h"
|
||||||
|
|
||||||
|
#include <format>
|
||||||
|
#include "services/logging/logger.h"
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
#include <boost/json.hpp>
|
||||||
|
#include <fstream>
|
||||||
|
#include <sstream>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
static std::string ReadRequiredString(const boost::json::object& object,
|
||||||
|
const char* key) {
|
||||||
|
const boost::json::value* value = object.if_contains(key);
|
||||||
|
if (value == nullptr || !value->is_string()) {
|
||||||
|
throw std::runtime_error(
|
||||||
|
std::format("Missing or invalid string field: {}", key));
|
||||||
|
}
|
||||||
|
const std::string_view text = value->as_string();
|
||||||
|
return std::string(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
static double ReadRequiredNumber(const boost::json::object& object,
|
||||||
|
const char* key) {
|
||||||
|
const boost::json::value* value = object.if_contains(key);
|
||||||
|
if (value == nullptr || !value->is_number()) {
|
||||||
|
throw std::runtime_error(
|
||||||
|
std::format("Missing or invalid numeric field: {}", key));
|
||||||
|
}
|
||||||
|
return value->to_number<double>();
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::vector<std::string> ReadRequiredStringArray(
|
||||||
|
const boost::json::object& object, const char* key) {
|
||||||
|
const boost::json::value* value = object.if_contains(key);
|
||||||
|
if (value == nullptr || !value->is_array()) {
|
||||||
|
throw std::runtime_error(
|
||||||
|
std::format("Missing or invalid string array field: {}", key));
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& array = value->as_array();
|
||||||
|
std::vector<std::string> items;
|
||||||
|
items.reserve(array.size());
|
||||||
|
for (const auto& item : array) {
|
||||||
|
if (!item.is_string()) {
|
||||||
|
throw std::runtime_error(
|
||||||
|
std::format("Missing or invalid string array field: {}", key));
|
||||||
|
}
|
||||||
|
items.emplace_back(item.as_string());
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<Location> JsonLoader::LoadLocations(
|
||||||
|
const std::filesystem::path& filepath, std::shared_ptr<ILogger> logger) {
|
||||||
|
std::ifstream input(filepath);
|
||||||
|
if (!input.is_open()) {
|
||||||
|
throw std::runtime_error("Failed to open locations file: " +
|
||||||
|
filepath.string());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::stringstream buffer;
|
||||||
|
buffer << input.rdbuf();
|
||||||
|
const std::string content = buffer.str();
|
||||||
|
|
||||||
|
boost::system::error_code error;
|
||||||
|
boost::json::value root = boost::json::parse(content, error);
|
||||||
|
if (error) {
|
||||||
|
throw std::runtime_error("Failed to parse locations JSON: " +
|
||||||
|
error.message());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!root.is_array()) {
|
||||||
|
throw std::runtime_error(
|
||||||
|
"Invalid locations JSON: root element must be an array");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<Location> locations;
|
||||||
|
const auto& items = root.as_array();
|
||||||
|
locations.reserve(items.size());
|
||||||
|
|
||||||
|
for (const auto& item : items) {
|
||||||
|
if (!item.is_object()) {
|
||||||
|
throw std::runtime_error(
|
||||||
|
"Invalid locations JSON: each entry must be an object");
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto& object = item.as_object();
|
||||||
|
locations.push_back(Location{
|
||||||
|
.city = ReadRequiredString(object, "city"),
|
||||||
|
.state_province = ReadRequiredString(object, "state_province"),
|
||||||
|
.iso3166_2 = ReadRequiredString(object, "iso3166_2"),
|
||||||
|
.country = ReadRequiredString(object, "country"),
|
||||||
|
.iso3166_1 = ReadRequiredString(object, "iso3166_1"),
|
||||||
|
.local_languages = ReadRequiredStringArray(object, "local_languages"),
|
||||||
|
.latitude = ReadRequiredNumber(object, "latitude"),
|
||||||
|
.longitude = ReadRequiredNumber(object, "longitude"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return locations;
|
||||||
|
}
|
||||||
@@ -18,7 +18,25 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
#include "biergarten_pipeline.h"
|
#include "biergarten_pipeline_orchestrator.h"
|
||||||
|
#include "concurrency/bounded_channel.h"
|
||||||
|
#include "data_generation/llama_generator.h"
|
||||||
|
#include "data_generation/mock_generator.h"
|
||||||
|
#include "data_generation/prompt_formatting/gemma4_jinja_prompt_formatter.h"
|
||||||
|
#include "data_model/models.h"
|
||||||
|
#include "llama_backend_state.h"
|
||||||
|
#include "services/database/export_service.h"
|
||||||
|
#include "services/database/sqlite_export_service.h"
|
||||||
|
#include "services/datetime/timer.h"
|
||||||
|
#include "services/enrichment/enrichment_service.h"
|
||||||
|
#include "services/enrichment/mock_enrichment.h"
|
||||||
|
#include "services/enrichment/wikipedia_service.h"
|
||||||
|
#include "services/logging/log_dispatcher.h"
|
||||||
|
#include "services/logging/log_entry.h"
|
||||||
|
#include "services/logging/log_producer.h"
|
||||||
|
#include "services/logging/logger.h"
|
||||||
|
#include "services/prompting/prompt_directory.h"
|
||||||
|
#include "web_client/http_web_client.h"
|
||||||
|
|
||||||
namespace di = boost::di;
|
namespace di = boost::di;
|
||||||
|
|
||||||
@@ -35,7 +53,6 @@ int main(const int argc, char** argv) {
|
|||||||
std::make_shared<LogProducer>(log_channel);
|
std::make_shared<LogProducer>(log_channel);
|
||||||
|
|
||||||
std::thread log_thread([&log_dispatcher] { log_dispatcher->Run(); });
|
std::thread log_thread([&log_dispatcher] { log_dispatcher->Run(); });
|
||||||
|
|
||||||
auto shutdown = [&](const int exit_code) {
|
auto shutdown = [&](const int exit_code) {
|
||||||
log_channel.Close();
|
log_channel.Close();
|
||||||
log_thread.join();
|
log_thread.join();
|
||||||
@@ -49,8 +66,8 @@ int main(const int argc, char** argv) {
|
|||||||
const LlamaBackendState llama_backend_state;
|
const LlamaBackendState llama_backend_state;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
log_producer->Log({.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = "STARTING PIPELINE"});
|
.message = "STARTING PIPELINE"});
|
||||||
|
|
||||||
const std::optional<ApplicationOptions> parsed_options =
|
const std::optional<ApplicationOptions> parsed_options =
|
||||||
@@ -72,8 +89,8 @@ int main(const int argc, char** argv) {
|
|||||||
prompt_directory = std::make_unique<PromptDirectory>(
|
prompt_directory = std::make_unique<PromptDirectory>(
|
||||||
options.pipeline.prompt_dir, log_producer);
|
options.pipeline.prompt_dir, log_producer);
|
||||||
} catch (const std::exception& dir_error) {
|
} catch (const std::exception& dir_error) {
|
||||||
log_producer->Log({.level = LogLevel::Error,
|
log_producer->Log({.level = LogLevel::Error,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = std::format("Invalid --prompt-dir: {}",
|
.message = std::format("Invalid --prompt-dir: {}",
|
||||||
dir_error.what())});
|
dir_error.what())});
|
||||||
|
|
||||||
@@ -86,34 +103,12 @@ int main(const int argc, char** argv) {
|
|||||||
di::bind<ApplicationOptions>().to(options),
|
di::bind<ApplicationOptions>().to(options),
|
||||||
di::bind<std::string>().to(model_path),
|
di::bind<std::string>().to(model_path),
|
||||||
di::bind<IExportService>().to<SqliteExportService>(),
|
di::bind<IExportService>().to<SqliteExportService>(),
|
||||||
di::bind<ICuratedDataService>().to(
|
|
||||||
[options, &log_producer]() -> std::unique_ptr<ICuratedDataService> {
|
|
||||||
if (options.generator.use_mocked) {
|
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
|
||||||
.phase = PipelinePhase::Startup,
|
|
||||||
.message = "Curated data: mock"});
|
|
||||||
|
|
||||||
return std::make_unique<MockCuratedDataService>();
|
|
||||||
}
|
|
||||||
|
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
|
||||||
.phase = PipelinePhase::Startup,
|
|
||||||
.message = "Curated data: JsonLoader"});
|
|
||||||
|
|
||||||
return std::make_unique<CuratedJsonDataService>(
|
|
||||||
CuratedDataFilePaths{
|
|
||||||
.locations_path = "locations.json",
|
|
||||||
.personas_path = "personas.json",
|
|
||||||
.forenames_path = "forenames-by-country.json",
|
|
||||||
.surnames_path = "surnames-by-country.json",
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
di::bind<IPromptFormatter>().to([options, log_producer] {
|
di::bind<IPromptFormatter>().to([options, log_producer] {
|
||||||
if (options.generator.use_mocked) {
|
if (options.generator.use_mocked) {
|
||||||
{
|
{
|
||||||
log_producer->Log(
|
log_producer->Log(
|
||||||
{.level = LogLevel::Info,
|
{.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = "Prompt formatter: none (mock mode)"});
|
.message = "Prompt formatter: none (mock mode)"});
|
||||||
}
|
}
|
||||||
return std::unique_ptr<IPromptFormatter>(nullptr);
|
return std::unique_ptr<IPromptFormatter>(nullptr);
|
||||||
@@ -121,7 +116,7 @@ int main(const int argc, char** argv) {
|
|||||||
{
|
{
|
||||||
log_producer->Log(
|
log_producer->Log(
|
||||||
{.level = LogLevel::Info,
|
{.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = "Prompt formatter: Gemma4JinjaPromptFormatter"});
|
.message = "Prompt formatter: Gemma4JinjaPromptFormatter"});
|
||||||
}
|
}
|
||||||
return std::unique_ptr<IPromptFormatter>(
|
return std::unique_ptr<IPromptFormatter>(
|
||||||
@@ -130,17 +125,17 @@ int main(const int argc, char** argv) {
|
|||||||
di::bind<WebClient>().to([options, log_producer] {
|
di::bind<WebClient>().to([options, log_producer] {
|
||||||
if (options.generator.use_mocked) {
|
if (options.generator.use_mocked) {
|
||||||
{
|
{
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
log_producer->Log({.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = "Web client: none (mock mode)"});
|
.message = "Web client: none (mock mode)"});
|
||||||
}
|
}
|
||||||
return std::unique_ptr<WebClient>(nullptr);
|
return std::unique_ptr<WebClient>(nullptr);
|
||||||
}
|
}
|
||||||
|
{
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
log_producer->Log({.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = "Web client: HttpWebClient"});
|
.message = "Web client: HttpWebClient"});
|
||||||
|
}
|
||||||
return std::unique_ptr<WebClient>(
|
return std::unique_ptr<WebClient>(
|
||||||
std::make_unique<HttpWebClient>(log_producer));
|
std::make_unique<HttpWebClient>(log_producer));
|
||||||
}),
|
}),
|
||||||
@@ -148,17 +143,18 @@ int main(const int argc, char** argv) {
|
|||||||
[options, &log_producer](
|
[options, &log_producer](
|
||||||
const auto& inj) -> std::unique_ptr<IEnrichmentService> {
|
const auto& inj) -> std::unique_ptr<IEnrichmentService> {
|
||||||
if (options.generator.use_mocked) {
|
if (options.generator.use_mocked) {
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
{
|
||||||
.phase = PipelinePhase::Startup,
|
log_producer->Log({.level = LogLevel::Info,
|
||||||
.message = "Enrichment: mock"});
|
.phase = PipelinePhase::Startup,
|
||||||
|
.message = "Enrichment: mock"});
|
||||||
|
}
|
||||||
return std::make_unique<MockEnrichmentService>();
|
return std::make_unique<MockEnrichmentService>();
|
||||||
}
|
}
|
||||||
|
{
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
log_producer->Log({.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Startup,
|
.phase = PipelinePhase::Startup,
|
||||||
.message = "Enrichment: Wikipedia"});
|
.message = "Enrichment: Wikipedia"});
|
||||||
|
}
|
||||||
return std::make_unique<WikipediaEnrichmentService>(
|
return std::make_unique<WikipediaEnrichmentService>(
|
||||||
inj.template create<std::unique_ptr<WebClient>>(),
|
inj.template create<std::unique_ptr<WebClient>>(),
|
||||||
log_producer);
|
log_producer);
|
||||||
@@ -167,57 +163,50 @@ int main(const int argc, char** argv) {
|
|||||||
[&options, &model_path, &sampling, &prompt_directory,
|
[&options, &model_path, &sampling, &prompt_directory,
|
||||||
&log_producer](const auto& inj) -> std::unique_ptr<DataGenerator> {
|
&log_producer](const auto& inj) -> std::unique_ptr<DataGenerator> {
|
||||||
if (options.generator.use_mocked) {
|
if (options.generator.use_mocked) {
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
{
|
||||||
.phase = PipelinePhase::Startup,
|
log_producer->Log({.level = LogLevel::Info,
|
||||||
.message = "Generator: mock"});
|
.phase = PipelinePhase::Startup,
|
||||||
|
.message = "Generator: mock"});
|
||||||
|
}
|
||||||
return std::make_unique<MockGenerator>();
|
return std::make_unique<MockGenerator>();
|
||||||
}
|
}
|
||||||
|
{
|
||||||
#ifdef BIERGARTEN_MOCK_ONLY
|
log_producer->Log(
|
||||||
// Unreachable: ParseArguments requires --mocked when
|
{.level = LogLevel::Info,
|
||||||
// BIERGARTEN_MOCK_ONLY is compiled in, so LlamaGenerator is
|
.phase = PipelinePhase::Startup,
|
||||||
// never constructed and is not linked into this binary.
|
.message = std::format(
|
||||||
throw std::runtime_error(
|
"Generator: LlamaGenerator | model={} | temp={:.2f} "
|
||||||
"LlamaGenerator is unavailable in a BIERGARTEN_MOCK_ONLY "
|
"top_p={:.2f} top_k={} n_ctx={} seed={}",
|
||||||
"build");
|
model_path, sampling.temperature, sampling.top_p,
|
||||||
#else
|
sampling.top_k, sampling.n_ctx, sampling.seed)});
|
||||||
log_producer->Log(
|
}
|
||||||
{.level = LogLevel::Info,
|
|
||||||
.phase = PipelinePhase::Startup,
|
|
||||||
.message = std::format(
|
|
||||||
"Generator: LlamaGenerator | model={} | "
|
|
||||||
"temp={:.2f} top_p={:.2f} top_k={} n_ctx={} seed={}",
|
|
||||||
model_path, sampling.temperature, sampling.top_p,
|
|
||||||
sampling.top_k, sampling.n_ctx, sampling.seed)});
|
|
||||||
|
|
||||||
return std::make_unique<LlamaGenerator>(
|
return std::make_unique<LlamaGenerator>(
|
||||||
options, model_path, log_producer,
|
options, model_path, log_producer,
|
||||||
inj.template create<std::unique_ptr<IPromptFormatter>>(),
|
inj.template create<std::unique_ptr<IPromptFormatter>>(),
|
||||||
std::move(prompt_directory));
|
std::move(prompt_directory));
|
||||||
#endif
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const auto orchestrator =
|
const auto orchestrator =
|
||||||
injector.create<std::unique_ptr<BiergartenPipelineOrchestrator>>();
|
injector.create<std::unique_ptr<BiergartenPipelineOrchestrator>>();
|
||||||
|
|
||||||
if (!orchestrator->Run()) {
|
if (!orchestrator->Run()) {
|
||||||
log_producer->Log({.level = LogLevel::Error,
|
log_producer->Log({.level = LogLevel::Error,
|
||||||
.phase = PipelinePhase::Teardown,
|
.phase = PipelinePhase::Teardown,
|
||||||
.message = "Pipeline execution failed"});
|
.message = "Pipeline execution failed"});
|
||||||
return shutdown(EXIT_FAILURE);
|
return shutdown(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
|
|
||||||
log_producer->Log({.level = LogLevel::Info,
|
log_producer->Log({.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Teardown,
|
.phase = PipelinePhase::Teardown,
|
||||||
.message = std::format("Pipeline complete in {} ms",
|
.message = std::format("Pipeline complete in {} ms",
|
||||||
timer.Elapsed())});
|
timer.Elapsed())});
|
||||||
|
|
||||||
return shutdown(EXIT_SUCCESS);
|
return shutdown(EXIT_SUCCESS);
|
||||||
|
|
||||||
} catch (const std::exception& exception) {
|
} catch (const std::exception& exception) {
|
||||||
const LogDTO log_entry{.level = LogLevel::Error,
|
const LogDTO log_entry{.level = LogLevel::Error,
|
||||||
.phase = PipelinePhase::Teardown,
|
.phase = PipelinePhase::Teardown,
|
||||||
.message = exception.what()};
|
.message = exception.what()};
|
||||||
if (log_producer) {
|
if (log_producer) {
|
||||||
log_producer->Log(log_entry);
|
log_producer->Log(log_entry);
|
||||||
} else {
|
} else {
|
||||||
@@ -226,4 +215,4 @@ int main(const int argc, char** argv) {
|
|||||||
|
|
||||||
return shutdown(EXIT_FAILURE);
|
return shutdown(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,264 +0,0 @@
|
|||||||
/**
|
|
||||||
* @file json_handling/json_loader.cc
|
|
||||||
* @brief Parses curated location JSON input into strongly typed Location
|
|
||||||
* records with strict field validation and descriptive error reporting.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "services/curated_data/curated_json_data_service.h"
|
|
||||||
|
|
||||||
#include <boost/json.hpp>
|
|
||||||
#include <format>
|
|
||||||
#include <fstream>
|
|
||||||
#include <iostream>
|
|
||||||
#include <sstream>
|
|
||||||
#include <stdexcept>
|
|
||||||
#include <string>
|
|
||||||
#include <string_view>
|
|
||||||
#include <utility>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include "services/logging/logger.h"
|
|
||||||
|
|
||||||
static std::string ReadRequiredString(const boost::json::object& object,
|
|
||||||
const char* key) {
|
|
||||||
const boost::json::value* value = object.if_contains(key);
|
|
||||||
if (value == nullptr || !value->is_string()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
std::format("Missing or invalid string field: {}", key));
|
|
||||||
}
|
|
||||||
const std::string_view text = value->as_string();
|
|
||||||
return std::string(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static double ReadRequiredNumber(const boost::json::object& object,
|
|
||||||
const char* key) {
|
|
||||||
const boost::json::value* value = object.if_contains(key);
|
|
||||||
if (value == nullptr || !value->is_number()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
std::format("Missing or invalid numeric field: {}", key));
|
|
||||||
}
|
|
||||||
return value->to_number<double>();
|
|
||||||
}
|
|
||||||
|
|
||||||
static std::vector<std::string> ReadRequiredStringArray(
|
|
||||||
const boost::json::object& object, const char* key) {
|
|
||||||
const boost::json::value* value = object.if_contains(key);
|
|
||||||
if (value == nullptr || !value->is_array()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
std::format("Missing or invalid string array field: {}", key));
|
|
||||||
}
|
|
||||||
|
|
||||||
const auto& array = value->as_array();
|
|
||||||
std::vector<std::string> items;
|
|
||||||
items.reserve(array.size());
|
|
||||||
for (const auto& item : array) {
|
|
||||||
if (!item.is_string()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
std::format("Missing or invalid string array field: {}", key));
|
|
||||||
}
|
|
||||||
items.emplace_back(item.as_string());
|
|
||||||
}
|
|
||||||
return items;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
|
|
||||||
boost::json::value ParseJsonFile(const std::filesystem::path& filepath,
|
|
||||||
const char* what) {
|
|
||||||
std::ifstream input(filepath);
|
|
||||||
if (!input.is_open()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
std::format("Failed to open {} file: {}", what, filepath.string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
std::stringstream buffer;
|
|
||||||
buffer << input.rdbuf();
|
|
||||||
|
|
||||||
boost::system::error_code error;
|
|
||||||
boost::json::value root = boost::json::parse(buffer.str(), error);
|
|
||||||
if (error) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
std::format("Failed to parse {} JSON: {}", what, error.message()));
|
|
||||||
}
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Returns the first element of a string array field, falling back to
|
|
||||||
* `fallback_key` if `key` is missing/empty (some source entries only have a
|
|
||||||
* "localized" form and no "romanized" form).
|
|
||||||
*/
|
|
||||||
std::string ReadFirstOfStringArray(const boost::json::object& object,
|
|
||||||
const char* key, const char* fallback_key) {
|
|
||||||
for (const char* candidate_key : {key, fallback_key}) {
|
|
||||||
const boost::json::value* value = object.if_contains(candidate_key);
|
|
||||||
if (value == nullptr || !value->is_array()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const auto& array = value->as_array();
|
|
||||||
if (!array.empty() && array.front().is_string()) {
|
|
||||||
return std::string(array.front().as_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw std::runtime_error(
|
|
||||||
std::format("Missing or invalid string array field: {}", key));
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
CuratedJsonDataService::CuratedJsonDataService(CuratedDataFilePaths filepaths)
|
|
||||||
: filepaths_(std::move(filepaths)) {}
|
|
||||||
|
|
||||||
const LocationsList& CuratedJsonDataService::LoadLocations() {
|
|
||||||
if (!cache_.locations.empty()) {
|
|
||||||
return cache_.locations;
|
|
||||||
}
|
|
||||||
|
|
||||||
const boost::json::value root =
|
|
||||||
ParseJsonFile(filepaths_.locations_path, "locations");
|
|
||||||
|
|
||||||
if (!root.is_array()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Invalid locations JSON: root element must be an array");
|
|
||||||
}
|
|
||||||
|
|
||||||
LocationsList locations;
|
|
||||||
const auto& items = root.as_array();
|
|
||||||
locations.reserve(items.size());
|
|
||||||
|
|
||||||
for (const auto& item : items) {
|
|
||||||
if (!item.is_object()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Invalid locations JSON: each entry must be an object");
|
|
||||||
}
|
|
||||||
|
|
||||||
const auto& object = item.as_object();
|
|
||||||
locations.push_back(Location{
|
|
||||||
.city = ReadRequiredString(object, "city"),
|
|
||||||
.state_province = ReadRequiredString(object, "state_province"),
|
|
||||||
.iso3166_2 = ReadRequiredString(object, "iso3166_2"),
|
|
||||||
.country = ReadRequiredString(object, "country"),
|
|
||||||
.iso3166_1 = ReadRequiredString(object, "iso3166_1"),
|
|
||||||
.local_languages = ReadRequiredStringArray(object, "local_languages"),
|
|
||||||
.latitude = ReadRequiredNumber(object, "latitude"),
|
|
||||||
.longitude = ReadRequiredNumber(object, "longitude"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
cache_.locations = std::move(locations);
|
|
||||||
return cache_.locations;
|
|
||||||
}
|
|
||||||
|
|
||||||
const PersonasList& CuratedJsonDataService::LoadPersonas() {
|
|
||||||
if (!cache_.personas.empty()) {
|
|
||||||
return cache_.personas;
|
|
||||||
}
|
|
||||||
|
|
||||||
const boost::json::value root =
|
|
||||||
ParseJsonFile(filepaths_.personas_path, "personas");
|
|
||||||
|
|
||||||
if (!root.is_array()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Invalid personas JSON: root element must be an array");
|
|
||||||
}
|
|
||||||
|
|
||||||
PersonasList personas;
|
|
||||||
const auto& items = root.as_array();
|
|
||||||
personas.reserve(items.size());
|
|
||||||
|
|
||||||
for (const auto& item : items) {
|
|
||||||
if (!item.is_object()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Invalid personas JSON: each entry must be an object");
|
|
||||||
}
|
|
||||||
|
|
||||||
const auto& object = item.as_object();
|
|
||||||
personas.push_back(UserPersona{
|
|
||||||
.name = ReadRequiredString(object, "name"),
|
|
||||||
.description = ReadRequiredString(object, "description"),
|
|
||||||
.style_affinities = ReadRequiredStringArray(object, "style_affinities"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
cache_.personas = std::move(personas);
|
|
||||||
return cache_.personas;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ForenamesByCountryMap& CuratedJsonDataService::LoadForenamesByCountry() {
|
|
||||||
if (!cache_.forenames_by_country.empty()) {
|
|
||||||
return cache_.forenames_by_country;
|
|
||||||
}
|
|
||||||
|
|
||||||
const boost::json::value root =
|
|
||||||
ParseJsonFile(filepaths_.forenames_path, "forenames-by-country");
|
|
||||||
|
|
||||||
if (!root.is_object()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Invalid forenames-by-country JSON: root element must be an object "
|
|
||||||
"keyed by ISO 3166-1 country code");
|
|
||||||
}
|
|
||||||
|
|
||||||
ForenamesByCountryMap forenames_by_country;
|
|
||||||
for (const auto& [country_code, regions] : root.as_object()) {
|
|
||||||
if (!regions.is_array()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
ForenameList entries;
|
|
||||||
for (const auto& region : regions.as_array()) {
|
|
||||||
if (!region.is_object()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const boost::json::value* names = region.as_object().if_contains("names");
|
|
||||||
if (names == nullptr || !names->is_array()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
for (const auto& name_value : names->as_array()) {
|
|
||||||
if (!name_value.is_object()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const auto& name_object = name_value.as_object();
|
|
||||||
entries.emplace_back(ForenameEntry{
|
|
||||||
.name =
|
|
||||||
ReadFirstOfStringArray(name_object, "romanized", "localized"),
|
|
||||||
.gender = ReadRequiredString(name_object, "gender"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
forenames_by_country.emplace(country_code, std::move(entries));
|
|
||||||
}
|
|
||||||
|
|
||||||
cache_.forenames_by_country = std::move(forenames_by_country);
|
|
||||||
return cache_.forenames_by_country;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SurnamesByCountryMap& CuratedJsonDataService::LoadSurnamesByCountry() {
|
|
||||||
if (!cache_.surnames_by_country.empty()) {
|
|
||||||
return cache_.surnames_by_country;
|
|
||||||
}
|
|
||||||
|
|
||||||
const boost::json::value root =
|
|
||||||
ParseJsonFile(filepaths_.surnames_path, "surnames-by-country");
|
|
||||||
|
|
||||||
if (!root.is_object()) {
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Invalid surnames-by-country JSON: root element must be an object "
|
|
||||||
"keyed by ISO 3166-1 country code");
|
|
||||||
}
|
|
||||||
|
|
||||||
SurnamesByCountryMap surnames_by_country;
|
|
||||||
for (const auto& [country_code, name_entries] : root.as_object()) {
|
|
||||||
if (!name_entries.is_array()) continue;
|
|
||||||
|
|
||||||
SurnameList surnames;
|
|
||||||
for (const auto& name_value : name_entries.as_array()) {
|
|
||||||
if (!name_value.is_object()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
surnames.emplace_back(ReadFirstOfStringArray(name_value.as_object(),
|
|
||||||
"romanized", "localized"));
|
|
||||||
}
|
|
||||||
surnames_by_country.emplace(country_code, std::move(surnames));
|
|
||||||
}
|
|
||||||
|
|
||||||
cache_.surnames_by_country = std::move(surnames_by_country);
|
|
||||||
return cache_.surnames_by_country;
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
/**
|
|
||||||
* @file services/curated_data/mock_curated_data_service.cc
|
|
||||||
* @brief Fixed in-memory location, persona, and name dataset for mock mode.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "services/curated_data/mock_curated_data_service.h"
|
|
||||||
|
|
||||||
MockCuratedDataService::MockCuratedDataService()
|
|
||||||
: locations_{
|
|
||||||
Location{.city = "Portland",
|
|
||||||
.state_province = "Oregon",
|
|
||||||
.iso3166_2 = "US-OR",
|
|
||||||
.country = "United States",
|
|
||||||
.iso3166_1 = "US",
|
|
||||||
.local_languages = {"en"},
|
|
||||||
.latitude = 45.5152,
|
|
||||||
.longitude = -122.6784},
|
|
||||||
Location{.city = "Munich",
|
|
||||||
.state_province = "Bavaria",
|
|
||||||
.iso3166_2 = "DE-BY",
|
|
||||||
.country = "Germany",
|
|
||||||
.iso3166_1 = "DE",
|
|
||||||
.local_languages = {"de"},
|
|
||||||
.latitude = 48.1351,
|
|
||||||
.longitude = 11.5820},
|
|
||||||
Location{.city = "Lyon",
|
|
||||||
.state_province = "Auvergne-Rhone-Alpes",
|
|
||||||
.iso3166_2 = "FR-ARA",
|
|
||||||
.country = "France",
|
|
||||||
.iso3166_1 = "FR",
|
|
||||||
.local_languages = {"fr"},
|
|
||||||
.latitude = 45.7640,
|
|
||||||
.longitude = 4.8357},
|
|
||||||
Location{.city = "Brussels",
|
|
||||||
.state_province = "Brussels-Capital",
|
|
||||||
.iso3166_2 = "BE-BRU",
|
|
||||||
.country = "Belgium",
|
|
||||||
.iso3166_1 = "BE",
|
|
||||||
.local_languages = {"nl", "fr"},
|
|
||||||
.latitude = 50.8503,
|
|
||||||
.longitude = 4.3517},
|
|
||||||
},
|
|
||||||
personas_{
|
|
||||||
UserPersona{.name = "Hophead Explorer",
|
|
||||||
.description = "Chases hop-forward IPAs and seeks out "
|
|
||||||
"taprooms with rotating drafts.",
|
|
||||||
.style_affinities = {"IPA", "Pale Ale"}},
|
|
||||||
UserPersona{.name = "Lager Traditionalist",
|
|
||||||
.description = "Prefers clean, balanced lagers and "
|
|
||||||
"classic pub styles.",
|
|
||||||
.style_affinities = {"Lager", "Pilsner"}},
|
|
||||||
UserPersona{.name = "Sour Curious",
|
|
||||||
.description = "Seeks out wild ales, sours, and "
|
|
||||||
"barrel-aged experiments.",
|
|
||||||
.style_affinities = {"Sour", "Wild Ale"}},
|
|
||||||
},
|
|
||||||
forenames_by_country_{
|
|
||||||
{"US",
|
|
||||||
ForenameList{
|
|
||||||
ForenameEntry{.name = "James", .gender = "M"},
|
|
||||||
ForenameEntry{.name = "Mary", .gender = "F"},
|
|
||||||
}},
|
|
||||||
{"DE",
|
|
||||||
ForenameList{
|
|
||||||
ForenameEntry{.name = "Lukas", .gender = "M"},
|
|
||||||
ForenameEntry{.name = "Anna", .gender = "F"},
|
|
||||||
}},
|
|
||||||
{"FR",
|
|
||||||
ForenameList{
|
|
||||||
ForenameEntry{.name = "Lucas", .gender = "M"},
|
|
||||||
ForenameEntry{.name = "Camille", .gender = "F"},
|
|
||||||
}},
|
|
||||||
{"BE",
|
|
||||||
ForenameList{
|
|
||||||
ForenameEntry{.name = "Noah", .gender = "M"},
|
|
||||||
ForenameEntry{.name = "Emma", .gender = "F"},
|
|
||||||
}},
|
|
||||||
},
|
|
||||||
surnames_by_country_{
|
|
||||||
{"US", SurnameList{"Smith", "Johnson"}},
|
|
||||||
{"DE", SurnameList{"Muller", "Schmidt"}},
|
|
||||||
{"FR", SurnameList{"Martin", "Bernard"}},
|
|
||||||
{"BE", SurnameList{"Peeters", "Janssens"}},
|
|
||||||
} {}
|
|
||||||
|
|
||||||
const LocationsList& MockCuratedDataService::LoadLocations() {
|
|
||||||
return locations_;
|
|
||||||
}
|
|
||||||
|
|
||||||
const PersonasList& MockCuratedDataService::LoadPersonas() { return personas_; }
|
|
||||||
|
|
||||||
const ForenamesByCountryMap& MockCuratedDataService::LoadForenamesByCountry() {
|
|
||||||
return forenames_by_country_;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SurnamesByCountryMap& MockCuratedDataService::LoadSurnamesByCountry() {
|
|
||||||
return surnames_by_country_;
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* @file wikipedia/fetch_extract.cc
|
* @file wikipedia/fetch_extract.cc
|
||||||
* @brief WikipediaEnrichmentService::FetchExtract() implementation.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <boost/json.hpp>
|
#include <boost/json.hpp>
|
||||||
@@ -21,10 +20,9 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
if (const auto cache_it = this->extract_cache_.find(cache_key);
|
if (const auto cache_it = this->extract_cache_.find(cache_key);
|
||||||
cache_it != this->extract_cache_.end()) {
|
cache_it != this->extract_cache_.end()) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log(
|
logger_->Log({.level = LogLevel::Debug,
|
||||||
{.level = LogLevel::Debug,
|
.phase = PipelinePhase::UserGeneration,
|
||||||
.phase = PipelinePhase::Enrichment,
|
.message = std::format("Wikipedia: Cache hit for {}!", cache_key)});
|
||||||
.message = std::format("Wikipedia: Cache hit for {}!", cache_key)});
|
|
||||||
}
|
}
|
||||||
return cache_it->second;
|
return cache_it->second;
|
||||||
}
|
}
|
||||||
@@ -32,8 +30,7 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
const std::string encoded = this->client_->EncodeURL(cache_key);
|
const std::string encoded = this->client_->EncodeURL(cache_key);
|
||||||
const std::string url = std::format(
|
const std::string url = std::format(
|
||||||
"https://en.wikipedia.org/w/"
|
"https://en.wikipedia.org/w/"
|
||||||
"api.php?action=query&titles={}&prop=extracts&explaintext=1&format="
|
"api.php?action=query&titles={}&prop=extracts&explaintext=1&format=json",
|
||||||
"json",
|
|
||||||
encoded);
|
encoded);
|
||||||
|
|
||||||
const std::string body = this->client_->Get(url);
|
const std::string body = this->client_->Get(url);
|
||||||
@@ -48,11 +45,11 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
|
|
||||||
if (ec) {
|
if (ec) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Enrichment,
|
{.level = LogLevel::Warn,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::UserGeneration,
|
||||||
"WikipediaService: JSON parse error for '{}': {}",
|
.message = std::format("WikipediaService: JSON parse error for '{}': {}",
|
||||||
std::string(query), ec.message())});
|
std::string(query), ec.message())});
|
||||||
}
|
}
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -61,11 +58,12 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
const json::object* obj = doc.if_object();
|
const json::object* obj = doc.if_object();
|
||||||
if (obj == nullptr) {
|
if (obj == nullptr) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Enrichment,
|
{.level = LogLevel::Warn,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::UserGeneration,
|
||||||
"WikipediaService: Expected root object for '{}'",
|
.message =
|
||||||
std::string(query))});
|
std::format("WikipediaService: Expected root object for '{}'",
|
||||||
|
std::string(query))});
|
||||||
}
|
}
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -78,11 +76,12 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
|
|
||||||
if ((pages_ptr == nullptr) || !pages_ptr->is_object()) {
|
if ((pages_ptr == nullptr) || !pages_ptr->is_object()) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Enrichment,
|
{.level = LogLevel::Warn,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::UserGeneration,
|
||||||
"WikipediaService: Missing query.pages for '{}'",
|
.message =
|
||||||
std::string(query))});
|
std::format("WikipediaService: Missing query.pages for '{}'",
|
||||||
|
std::string(query))});
|
||||||
}
|
}
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -91,11 +90,11 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
|
|
||||||
if (pages.empty()) {
|
if (pages.empty()) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Enrichment,
|
{.level = LogLevel::Warn,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::UserGeneration,
|
||||||
"WikipediaService: No pages returned for '{}'",
|
.message = std::format("WikipediaService: No pages returned for '{}'",
|
||||||
std::string(query))});
|
std::string(query))});
|
||||||
}
|
}
|
||||||
this->extract_cache_.emplace(cache_key, "");
|
this->extract_cache_.emplace(cache_key, "");
|
||||||
return {};
|
return {};
|
||||||
@@ -107,11 +106,12 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
|
|
||||||
if (!page_val.is_object()) {
|
if (!page_val.is_object()) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Enrichment,
|
{.level = LogLevel::Warn,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::UserGeneration,
|
||||||
"WikipediaService: Unexpected page format for '{}'",
|
.message =
|
||||||
std::string(query))});
|
std::format("WikipediaService: Unexpected page format for '{}'",
|
||||||
|
std::string(query))});
|
||||||
}
|
}
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -121,11 +121,10 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
// Handle 404/Missing status
|
// Handle 404/Missing status
|
||||||
if (page.contains("missing")) {
|
if (page.contains("missing")) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log(
|
logger_->Log({.level = LogLevel::Warn,
|
||||||
{.level = LogLevel::Warn,
|
.phase = PipelinePhase::UserGeneration,
|
||||||
.phase = PipelinePhase::Enrichment,
|
.message = std::format("WikipediaService: Page '{}' does not exist",
|
||||||
.message = std::format("WikipediaService: Page '{}' does not exist",
|
std::string(query))});
|
||||||
std::string(query))});
|
|
||||||
}
|
}
|
||||||
this->extract_cache_.emplace(cache_key, "");
|
this->extract_cache_.emplace(cache_key, "");
|
||||||
return {};
|
return {};
|
||||||
@@ -135,11 +134,12 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
|
|
||||||
if ((extract_ptr == nullptr) || !extract_ptr->is_string()) {
|
if ((extract_ptr == nullptr) || !extract_ptr->is_string()) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Enrichment,
|
{.level = LogLevel::Warn,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::UserGeneration,
|
||||||
"WikipediaService: No extract string found for '{}'",
|
.message =
|
||||||
std::string(query))});
|
std::format("WikipediaService: No extract string found for '{}'",
|
||||||
|
std::string(query))});
|
||||||
}
|
}
|
||||||
this->extract_cache_.emplace(cache_key, "");
|
this->extract_cache_.emplace(cache_key, "");
|
||||||
return {};
|
return {};
|
||||||
@@ -148,11 +148,10 @@ std::string WikipediaEnrichmentService::FetchExtract(std::string_view query) {
|
|||||||
// 4. Success
|
// 4. Success
|
||||||
std::string extract(extract_ptr->as_string());
|
std::string extract(extract_ptr->as_string());
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log(
|
logger_->Log({.level = LogLevel::Info,
|
||||||
{.level = LogLevel::Info,
|
.phase = PipelinePhase::UserGeneration,
|
||||||
.phase = PipelinePhase::Enrichment,
|
.message = std::format("WikipediaService: Fetched {} chars for '{}'",
|
||||||
.message = std::format("WikipediaService: Fetched {} chars for '{}'",
|
extract.size(), std::string(query))});
|
||||||
extract.size(), std::string(query))});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this->extract_cache_.insert_or_assign(cache_key, extract);
|
this->extract_cache_.insert_or_assign(cache_key, extract);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* @file wikipedia/get_summary.cc
|
* @file wikipedia/get_summary.cc
|
||||||
* @brief WikipediaEnrichmentService::GetLocationContext() implementation.
|
* @brief WikipediaService::GetLocationContext() implementation.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
@@ -16,7 +16,7 @@ std::string WikipediaEnrichmentService::GetLocationContext(
|
|||||||
if (!this->client_) {
|
if (!this->client_) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Warn,
|
logger_->Log({.level = LogLevel::Warn,
|
||||||
.phase = PipelinePhase::Enrichment,
|
.phase = PipelinePhase::UserGeneration,
|
||||||
.message = "Wikipedia client is nullptr."});
|
.message = "Wikipedia client is nullptr."});
|
||||||
}
|
}
|
||||||
return {};
|
return {};
|
||||||
@@ -24,6 +24,13 @@ std::string WikipediaEnrichmentService::GetLocationContext(
|
|||||||
|
|
||||||
std::string result;
|
std::string result;
|
||||||
|
|
||||||
|
// std::string region_query(loc.city);
|
||||||
|
// if (!loc.country.empty()) {
|
||||||
|
// region_query += loc.state_province,
|
||||||
|
// region_query += ", ";
|
||||||
|
// region_query += loc.country;
|
||||||
|
// }
|
||||||
|
|
||||||
constexpr std::string_view brewing_query = "brewing";
|
constexpr std::string_view brewing_query = "brewing";
|
||||||
const std::string location_query =
|
const std::string location_query =
|
||||||
std::format("{}, {}", loc.city, loc.iso3166_2);
|
std::format("{}, {}", loc.city, loc.iso3166_2);
|
||||||
@@ -44,10 +51,9 @@ std::string WikipediaEnrichmentService::GetLocationContext(
|
|||||||
append_extract(FetchExtract(beer_query));
|
append_extract(FetchExtract(beer_query));
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Info,
|
logger_->Log({.level = LogLevel::Info,
|
||||||
.phase = PipelinePhase::Enrichment,
|
.phase = PipelinePhase::UserGeneration,
|
||||||
.message = std::format(
|
.message = std::format("Done fetching for {}. Sleeping for 10 seconds.",
|
||||||
"Done fetching for {}. Sleeping for 10 seconds.",
|
location_query)});
|
||||||
location_query)});
|
|
||||||
}
|
}
|
||||||
std::this_thread::sleep_for(10s);
|
std::this_thread::sleep_for(10s);
|
||||||
|
|
||||||
@@ -55,9 +61,9 @@ std::string WikipediaEnrichmentService::GetLocationContext(
|
|||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log(
|
logger_->Log(
|
||||||
{.level = LogLevel::Debug,
|
{.level = LogLevel::Debug,
|
||||||
.phase = PipelinePhase::Enrichment,
|
.phase = PipelinePhase::UserGeneration,
|
||||||
.message = std::format("WikipediaService lookup failed for '{}': {}",
|
.message = std::format("WikipediaService lookup failed for '{}': {}",
|
||||||
location_query, e.what())});
|
location_query, e.what())});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* @file services/wikipedia/wikipedia_service.cc
|
* @file services/wikipedia/wikipedia_service.cc
|
||||||
* @brief WikipediaEnrichmentService constructor implementation.
|
* @brief WikipediaService constructor implementation.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "services/enrichment/wikipedia_service.h"
|
#include "services/enrichment/wikipedia_service.h"
|
||||||
|
|||||||
@@ -19,8 +19,6 @@ namespace {
|
|||||||
switch (phase) {
|
switch (phase) {
|
||||||
case PipelinePhase::Startup:
|
case PipelinePhase::Startup:
|
||||||
return "Startup";
|
return "Startup";
|
||||||
case PipelinePhase::Enrichment:
|
|
||||||
return "Enrichment";
|
|
||||||
case PipelinePhase::UserGeneration:
|
case PipelinePhase::UserGeneration:
|
||||||
return "User Generation";
|
return "User Generation";
|
||||||
case PipelinePhase::BreweryAndBeerGeneration:
|
case PipelinePhase::BreweryAndBeerGeneration:
|
||||||
|
|||||||
@@ -44,8 +44,8 @@ PromptDirectory::PromptDirectory(const std::filesystem::path& prompt_dir,
|
|||||||
// Scenario 4: directory must be readable (probe with directory_iterator).
|
// Scenario 4: directory must be readable (probe with directory_iterator).
|
||||||
std::filesystem::directory_iterator probe(prompt_dir_, ec);
|
std::filesystem::directory_iterator probe(prompt_dir_, ec);
|
||||||
if (ec) {
|
if (ec) {
|
||||||
throw std::runtime_error(std::format(
|
throw std::runtime_error(
|
||||||
"PromptDirectory: prompt directory is not readable: {} ({})",
|
std::format("PromptDirectory: prompt directory is not readable: {} ({})",
|
||||||
prompt_dir_.string(), ec.message()));
|
prompt_dir_.string(), ec.message()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ std::string PromptDirectory::Load(std::string_view key) {
|
|||||||
if (!file.is_open()) {
|
if (!file.is_open()) {
|
||||||
throw std::runtime_error(
|
throw std::runtime_error(
|
||||||
std::format("PromptDirectory: prompt file not found for key '{}': {}",
|
std::format("PromptDirectory: prompt file not found for key '{}': {}",
|
||||||
key_str, file_path.string()));
|
key_str, file_path.string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string content((std::istreambuf_iterator<char>(file)),
|
std::string content((std::istreambuf_iterator<char>(file)),
|
||||||
@@ -84,18 +84,15 @@ std::string PromptDirectory::Load(std::string_view key) {
|
|||||||
file.close();
|
file.close();
|
||||||
|
|
||||||
if (content.empty()) {
|
if (content.empty()) {
|
||||||
throw std::runtime_error(
|
throw std::runtime_error(std::format("PromptDirectory: prompt file for key '{}' is empty: {}",
|
||||||
std::format("PromptDirectory: prompt file for key '{}' is empty: {}",
|
key_str, file_path.string()));
|
||||||
key_str, file_path.string()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log(
|
logger_->Log({.level = LogLevel::Info,
|
||||||
{.level = LogLevel::Info,
|
.phase = PipelinePhase::Startup,
|
||||||
.phase = PipelinePhase::Startup,
|
.message = std::format("[PromptDirectory] Loaded prompt '{}' from '{}' ({} chars)",
|
||||||
.message = std::format(
|
key_str, file_path.string(), content.size())});
|
||||||
"[PromptDirectory] Loaded prompt '{}' from '{}' ({} chars)",
|
|
||||||
key_str, file_path.string(), content.size())});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cache_.emplace(key_str, content);
|
cache_.emplace(key_str, content);
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ void SqliteExportService::Finalize() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
insert_user_stmt_.reset();
|
|
||||||
insert_brewery_stmt_.reset();
|
insert_brewery_stmt_.reset();
|
||||||
insert_location_stmt_.reset();
|
insert_location_stmt_.reset();
|
||||||
if (transaction_open_) {
|
if (transaction_open_) {
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ void ResetStatement(SqliteStatementHandle& statement) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Bind(const SqliteStatementHandle& statement,
|
void Bind(const SqliteStatementHandle& statement,
|
||||||
const BoundParam<std::string_view>& param) {
|
const BindParam<std::string_view>& param) {
|
||||||
const auto byte_count = param.value.size();
|
const auto byte_count = param.value.size();
|
||||||
if (byte_count > static_cast<std::size_t>(std::numeric_limits<int>::max())) {
|
if (byte_count > static_cast<std::size_t>(std::numeric_limits<int>::max())) {
|
||||||
ThrowSqliteError(sqlite3_db_handle(statement.get()), param.action);
|
ThrowSqliteError(sqlite3_db_handle(statement.get()), param.action);
|
||||||
@@ -60,7 +60,7 @@ void Bind(const SqliteStatementHandle& statement,
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Bind(const SqliteStatementHandle& statement,
|
void Bind(const SqliteStatementHandle& statement,
|
||||||
const BoundParam<double>& param) {
|
const BindParam<double>& param) {
|
||||||
if (sqlite3_bind_double(statement.get(), param.index, param.value) !=
|
if (sqlite3_bind_double(statement.get(), param.index, param.value) !=
|
||||||
SQLITE_OK) {
|
SQLITE_OK) {
|
||||||
ThrowSqliteError(sqlite3_db_handle(statement.get()), param.action);
|
ThrowSqliteError(sqlite3_db_handle(statement.get()), param.action);
|
||||||
@@ -68,7 +68,7 @@ void Bind(const SqliteStatementHandle& statement,
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Bind(const SqliteStatementHandle& statement,
|
void Bind(const SqliteStatementHandle& statement,
|
||||||
const BoundParam<sqlite3_int64>& param) {
|
const BindParam<sqlite3_int64>& param) {
|
||||||
if (sqlite3_bind_int64(statement.get(), param.index, param.value) !=
|
if (sqlite3_bind_int64(statement.get(), param.index, param.value) !=
|
||||||
SQLITE_OK) {
|
SQLITE_OK) {
|
||||||
ThrowSqliteError(sqlite3_db_handle(statement.get()), param.action);
|
ThrowSqliteError(sqlite3_db_handle(statement.get()), param.action);
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ std::filesystem::path SqliteExportService::BuildDatabasePath() const {
|
|||||||
std::filesystem::path candidate = output_path_ / base_filename;
|
std::filesystem::path candidate = output_path_ / base_filename;
|
||||||
|
|
||||||
for (int suffix = 1; std::filesystem::exists(candidate); ++suffix) {
|
for (int suffix = 1; std::filesystem::exists(candidate); ++suffix) {
|
||||||
candidate = output_path_ / std::filesystem::path(
|
candidate = output_path_ /
|
||||||
std::format("biergarten_seed_{}-{}.sqlite",
|
std::filesystem::path(std::format("biergarten_seed_{}-{}.sqlite",
|
||||||
run_timestamp_utc_, suffix));
|
run_timestamp_utc_, suffix));
|
||||||
}
|
}
|
||||||
|
|
||||||
return candidate;
|
return candidate;
|
||||||
@@ -33,9 +33,6 @@ void SqliteExportService::InitializeSchema() const {
|
|||||||
sqlite_export_service_internal::ExecSql(
|
sqlite_export_service_internal::ExecSql(
|
||||||
db_handle_, sqlite_export_service_internal::kCreateBreweriesTableSql,
|
db_handle_, sqlite_export_service_internal::kCreateBreweriesTableSql,
|
||||||
"Failed to create SQLite breweries table");
|
"Failed to create SQLite breweries table");
|
||||||
sqlite_export_service_internal::ExecSql(
|
|
||||||
db_handle_, sqlite_export_service_internal::kCreateUsersTableSql,
|
|
||||||
"Failed to create SQLite users table");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void SqliteExportService::PrepareStatements() {
|
void SqliteExportService::PrepareStatements() {
|
||||||
@@ -45,9 +42,6 @@ void SqliteExportService::PrepareStatements() {
|
|||||||
insert_brewery_stmt_ = sqlite_export_service_internal::PrepareStatement(
|
insert_brewery_stmt_ = sqlite_export_service_internal::PrepareStatement(
|
||||||
db_handle_, sqlite_export_service_internal::kInsertBrewerySql,
|
db_handle_, sqlite_export_service_internal::kInsertBrewerySql,
|
||||||
"Failed to prepare SQLite brewery insert statement");
|
"Failed to prepare SQLite brewery insert statement");
|
||||||
insert_user_stmt_ = sqlite_export_service_internal::PrepareStatement(
|
|
||||||
db_handle_, sqlite_export_service_internal::kInsertUserSql,
|
|
||||||
"Failed to prepare SQLite user insert statement");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void SqliteExportService::RollbackAndCloseNoThrow() noexcept {
|
void SqliteExportService::RollbackAndCloseNoThrow() noexcept {
|
||||||
@@ -60,7 +54,6 @@ void SqliteExportService::RollbackAndCloseNoThrow() noexcept {
|
|||||||
transaction_open_ = false;
|
transaction_open_ = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
insert_user_stmt_.reset();
|
|
||||||
insert_brewery_stmt_.reset();
|
insert_brewery_stmt_.reset();
|
||||||
insert_location_stmt_.reset();
|
insert_location_stmt_.reset();
|
||||||
db_handle_.reset();
|
db_handle_.reset();
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* @file services/sqlite/process_record.cc
|
* @file services/sqlite/process_record.cc
|
||||||
* @brief SqliteExportService::ProcessRecord() implementation
|
* @brief SqliteExportService::ProcessRecord() implementation.
|
||||||
* and the shared location-resolution helper.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
@@ -30,117 +29,111 @@ std::string SqliteExportService::BuildLocationKey(const Location& location) {
|
|||||||
return key_stream.str();
|
return key_stream.str();
|
||||||
}
|
}
|
||||||
|
|
||||||
sqlite3_int64 SqliteExportService::ResolveLocationId(const Location& location) {
|
uint64_t SqliteExportService::ProcessRecord(const GeneratedBrewery& brewery) {
|
||||||
const std::string location_key = BuildLocationKey(location);
|
|
||||||
const auto cached_location = location_cache_.find(location_key);
|
|
||||||
if (cached_location != location_cache_.end()) {
|
|
||||||
return cached_location->second;
|
|
||||||
}
|
|
||||||
|
|
||||||
const std::string local_languages_json =
|
|
||||||
sqlite_export_service_internal::SerializeVector(location.local_languages);
|
|
||||||
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_location_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kLocationCityBindIndex,
|
|
||||||
.value = location.city,
|
|
||||||
.action = "Failed to bind SQLite location city"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_location_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index =
|
|
||||||
sqlite_export_service_internal::kLocationStateProvinceBindIndex,
|
|
||||||
.value = location.state_province,
|
|
||||||
.action = "Failed to bind SQLite location state/province"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_location_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kLocationIso31662BindIndex,
|
|
||||||
.value = location.iso3166_2,
|
|
||||||
.action = "Failed to bind SQLite location ISO 3166-2 code"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_location_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kLocationCountryBindIndex,
|
|
||||||
.value = location.country,
|
|
||||||
.action = "Failed to bind SQLite location country"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_location_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kLocationIso31661BindIndex,
|
|
||||||
.value = location.iso3166_1,
|
|
||||||
.action = "Failed to bind SQLite location ISO 3166-1 code"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_location_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kLocationLanguagesBindIndex,
|
|
||||||
.value = local_languages_json,
|
|
||||||
.action = "Failed to bind SQLite location languages"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_location_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam{
|
|
||||||
.index = sqlite_export_service_internal::kLocationLatitudeBindIndex,
|
|
||||||
.value = location.latitude,
|
|
||||||
.action = "Failed to bind SQLite location latitude"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_location_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam{
|
|
||||||
.index = sqlite_export_service_internal::kLocationLongitudeBindIndex,
|
|
||||||
.value = location.longitude,
|
|
||||||
.action = "Failed to bind SQLite location longitude"});
|
|
||||||
|
|
||||||
sqlite_export_service_internal::StepStatement(
|
|
||||||
db_handle_, insert_location_stmt_,
|
|
||||||
"Failed to insert SQLite location row");
|
|
||||||
|
|
||||||
const sqlite3_int64 location_id =
|
|
||||||
sqlite_export_service_internal::LastInsertRowId(db_handle_);
|
|
||||||
location_cache_.emplace(location_key, location_id);
|
|
||||||
sqlite_export_service_internal::ResetStatement(insert_location_stmt_);
|
|
||||||
|
|
||||||
return location_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
uint64_t SqliteExportService::ProcessRecord(const BreweryRecord& brewery) {
|
|
||||||
if (db_handle_ == nullptr || !transaction_open_) {
|
if (db_handle_ == nullptr || !transaction_open_) {
|
||||||
throw std::runtime_error("SQLite export service is not initialized");
|
throw std::runtime_error("SQLite export service is not initialized");
|
||||||
}
|
}
|
||||||
|
|
||||||
const sqlite3_int64 location_id = ResolveLocationId(brewery.location);
|
const std::string location_key = BuildLocationKey(brewery.location);
|
||||||
|
const auto cached_location = location_cache_.find(location_key);
|
||||||
|
sqlite3_int64 location_id = 0;
|
||||||
|
|
||||||
|
if (cached_location != location_cache_.end()) {
|
||||||
|
location_id = cached_location->second;
|
||||||
|
} else {
|
||||||
|
const std::string local_languages_json =
|
||||||
|
sqlite_export_service_internal::SerializeVector(
|
||||||
|
brewery.location.local_languages);
|
||||||
|
|
||||||
|
sqlite_export_service_internal::Bind(
|
||||||
|
insert_location_stmt_,
|
||||||
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
|
.index = sqlite_export_service_internal::kLocationCityBindIndex,
|
||||||
|
.value = brewery.location.city,
|
||||||
|
.action = "Failed to bind SQLite location city"});
|
||||||
|
sqlite_export_service_internal::Bind(
|
||||||
|
insert_location_stmt_,
|
||||||
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
|
.index =
|
||||||
|
sqlite_export_service_internal::kLocationStateProvinceBindIndex,
|
||||||
|
.value = brewery.location.state_province,
|
||||||
|
.action = "Failed to bind SQLite location state/province"});
|
||||||
|
sqlite_export_service_internal::Bind(
|
||||||
|
insert_location_stmt_,
|
||||||
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
|
.index = sqlite_export_service_internal::kLocationIso31662BindIndex,
|
||||||
|
.value = brewery.location.iso3166_2,
|
||||||
|
.action = "Failed to bind SQLite location ISO 3166-2 code"});
|
||||||
|
sqlite_export_service_internal::Bind(
|
||||||
|
insert_location_stmt_,
|
||||||
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
|
.index = sqlite_export_service_internal::kLocationCountryBindIndex,
|
||||||
|
.value = brewery.location.country,
|
||||||
|
.action = "Failed to bind SQLite location country"});
|
||||||
|
sqlite_export_service_internal::Bind(
|
||||||
|
insert_location_stmt_,
|
||||||
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
|
.index = sqlite_export_service_internal::kLocationIso31661BindIndex,
|
||||||
|
.value = brewery.location.iso3166_1,
|
||||||
|
.action = "Failed to bind SQLite location ISO 3166-1 code"});
|
||||||
|
sqlite_export_service_internal::Bind(
|
||||||
|
insert_location_stmt_,
|
||||||
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
|
.index =
|
||||||
|
sqlite_export_service_internal::kLocationLanguagesBindIndex,
|
||||||
|
.value = local_languages_json,
|
||||||
|
.action = "Failed to bind SQLite location languages"});
|
||||||
|
sqlite_export_service_internal::Bind(
|
||||||
|
insert_location_stmt_,
|
||||||
|
sqlite_export_service_internal::BindParam{
|
||||||
|
.index = sqlite_export_service_internal::kLocationLatitudeBindIndex,
|
||||||
|
.value = brewery.location.latitude,
|
||||||
|
.action = "Failed to bind SQLite location latitude"});
|
||||||
|
sqlite_export_service_internal::Bind(
|
||||||
|
insert_location_stmt_,
|
||||||
|
sqlite_export_service_internal::BindParam{
|
||||||
|
.index =
|
||||||
|
sqlite_export_service_internal::kLocationLongitudeBindIndex,
|
||||||
|
.value = brewery.location.longitude,
|
||||||
|
.action = "Failed to bind SQLite location longitude"});
|
||||||
|
|
||||||
|
sqlite_export_service_internal::StepStatement(
|
||||||
|
db_handle_, insert_location_stmt_,
|
||||||
|
"Failed to insert SQLite location row");
|
||||||
|
|
||||||
|
location_id = sqlite_export_service_internal::LastInsertRowId(db_handle_);
|
||||||
|
location_cache_.emplace(location_key, location_id);
|
||||||
|
sqlite_export_service_internal::ResetStatement(insert_location_stmt_);
|
||||||
|
}
|
||||||
|
|
||||||
sqlite_export_service_internal::Bind(
|
sqlite_export_service_internal::Bind(
|
||||||
insert_brewery_stmt_,
|
insert_brewery_stmt_,
|
||||||
sqlite_export_service_internal::BoundParam<sqlite3_int64>{
|
sqlite_export_service_internal::BindParam<sqlite3_int64>{
|
||||||
.index = sqlite_export_service_internal::kBreweryLocationIdBindIndex,
|
.index = sqlite_export_service_internal::kBreweryLocationIdBindIndex,
|
||||||
.value = location_id,
|
.value = location_id,
|
||||||
.action = "Failed to bind SQLite brewery location id"});
|
.action = "Failed to bind SQLite brewery location id"});
|
||||||
|
|
||||||
sqlite_export_service_internal::Bind(
|
sqlite_export_service_internal::Bind(
|
||||||
insert_brewery_stmt_,
|
insert_brewery_stmt_,
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
.index = sqlite_export_service_internal::kBreweryEnglishNameBindIndex,
|
.index = sqlite_export_service_internal::kBreweryEnglishNameBindIndex,
|
||||||
.value = brewery.brewery.name_en,
|
.value = brewery.brewery.name_en,
|
||||||
.action = "Failed to bind SQLite brewery English name"});
|
.action = "Failed to bind SQLite brewery English name"});
|
||||||
|
|
||||||
sqlite_export_service_internal::Bind(
|
sqlite_export_service_internal::Bind(
|
||||||
insert_brewery_stmt_,
|
insert_brewery_stmt_,
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
.index = sqlite_export_service_internal::
|
.index = sqlite_export_service_internal::
|
||||||
kBreweryEnglishDescriptionBindIndex,
|
kBreweryEnglishDescriptionBindIndex,
|
||||||
.value = brewery.brewery.description_en,
|
.value = brewery.brewery.description_en,
|
||||||
.action = "Failed to bind SQLite brewery English description"});
|
.action = "Failed to bind SQLite brewery English description"});
|
||||||
|
|
||||||
sqlite_export_service_internal::Bind(
|
sqlite_export_service_internal::Bind(
|
||||||
insert_brewery_stmt_,
|
insert_brewery_stmt_,
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
.index = sqlite_export_service_internal::kBreweryLocalNameBindIndex,
|
.index = sqlite_export_service_internal::kBreweryLocalNameBindIndex,
|
||||||
.value = brewery.brewery.name_local,
|
.value = brewery.brewery.name_local,
|
||||||
.action = "Failed to bind SQLite brewery local name"});
|
.action = "Failed to bind SQLite brewery local name"});
|
||||||
|
|
||||||
sqlite_export_service_internal::Bind(
|
sqlite_export_service_internal::Bind(
|
||||||
insert_brewery_stmt_,
|
insert_brewery_stmt_,
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
sqlite_export_service_internal::BindParam<std::string_view>{
|
||||||
.index =
|
.index =
|
||||||
sqlite_export_service_internal::kBreweryLocalDescriptionBindIndex,
|
sqlite_export_service_internal::kBreweryLocalDescriptionBindIndex,
|
||||||
.value = brewery.brewery.description_local,
|
.value = brewery.brewery.description_local,
|
||||||
|
|||||||
@@ -1,79 +0,0 @@
|
|||||||
/**
|
|
||||||
* @file services/sqlite/process_user_record.cc
|
|
||||||
* @brief SqliteExportService::ProcessRecord(UserRecord) implementation.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
#include "services/database/sqlite_export_service.h"
|
|
||||||
#include "services/database/sqlite_export_service_helpers.h"
|
|
||||||
|
|
||||||
uint64_t SqliteExportService::ProcessRecord(const UserRecord& user) {
|
|
||||||
if (db_handle_ == nullptr || !transaction_open_) {
|
|
||||||
throw std::runtime_error("SQLite export service is not initialized");
|
|
||||||
}
|
|
||||||
|
|
||||||
const sqlite3_int64 location_id = ResolveLocationId(user.location);
|
|
||||||
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<sqlite3_int64>{
|
|
||||||
.index = sqlite_export_service_internal::kUserLocationIdBindIndex,
|
|
||||||
.value = location_id,
|
|
||||||
.action = "Failed to bind SQLite user location id"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kUserFirstNameBindIndex,
|
|
||||||
.value = user.user.first_name,
|
|
||||||
.action = "Failed to bind SQLite user first name"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kUserLastNameBindIndex,
|
|
||||||
.value = user.user.last_name,
|
|
||||||
.action = "Failed to bind SQLite user last name"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kUserGenderBindIndex,
|
|
||||||
.value = user.user.gender,
|
|
||||||
.action = "Failed to bind SQLite user gender"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kUserUsernameBindIndex,
|
|
||||||
.value = user.user.username,
|
|
||||||
.action = "Failed to bind SQLite user username"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kUserBioBindIndex,
|
|
||||||
.value = user.user.bio,
|
|
||||||
.action = "Failed to bind SQLite user bio"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<double>{
|
|
||||||
.index = sqlite_export_service_internal::kUserActivityWeightBindIndex,
|
|
||||||
.value = static_cast<double>(user.user.activity_weight),
|
|
||||||
.action = "Failed to bind SQLite user activity weight"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kUserEmailBindIndex,
|
|
||||||
.value = user.email,
|
|
||||||
.action = "Failed to bind SQLite user email"});
|
|
||||||
sqlite_export_service_internal::Bind(
|
|
||||||
insert_user_stmt_,
|
|
||||||
sqlite_export_service_internal::BoundParam<std::string_view>{
|
|
||||||
.index = sqlite_export_service_internal::kUserDateOfBirthBindIndex,
|
|
||||||
.value = user.date_of_birth,
|
|
||||||
.action = "Failed to bind SQLite user date of birth"});
|
|
||||||
|
|
||||||
sqlite_export_service_internal::StepStatement(
|
|
||||||
db_handle_, insert_user_stmt_, "Failed to insert SQLite user row");
|
|
||||||
|
|
||||||
sqlite_export_service_internal::ResetStatement(insert_user_stmt_);
|
|
||||||
|
|
||||||
return sqlite_export_service_internal::LastInsertRowId(db_handle_);
|
|
||||||
}
|
|
||||||
@@ -48,20 +48,21 @@ std::string HttpWebClient::Get(const std::string& url) {
|
|||||||
const httplib::Result result = client.Get(path);
|
const httplib::Result result = client.Get(path);
|
||||||
|
|
||||||
if (!result) {
|
if (!result) {
|
||||||
throw std::runtime_error(
|
throw std::runtime_error(std::format(
|
||||||
std::format("[HttpWebClient] Request failed for URL: {} — {}", url,
|
"[HttpWebClient] Request failed for URL: {} — {}", url,
|
||||||
httplib::to_string(result.error())));
|
httplib::to_string(result.error())));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result->status < kSuccessMin || result->status >= kSuccessMax) {
|
if (result->status < kSuccessMin || result->status >= kSuccessMax) {
|
||||||
if (logger_) {
|
if (logger_) {
|
||||||
logger_->Log({.level = LogLevel::Error,
|
logger_->Log(
|
||||||
.phase = PipelinePhase::Enrichment,
|
{.level = LogLevel::Error,
|
||||||
.message = std::format(
|
.phase = PipelinePhase::UserGeneration,
|
||||||
"[HttpWebClient] Request failed for URL: {}", url)});
|
.message =
|
||||||
|
std::format("[HttpWebClient] Request failed for URL: {}", url)});
|
||||||
}
|
}
|
||||||
throw std::runtime_error(std::format("[HttpWebClient] HTTP {} for URL: {}",
|
throw std::runtime_error(std::format("[HttpWebClient] HTTP {} for URL: {}",
|
||||||
result->status, url));
|
result->status, url));
|
||||||
}
|
}
|
||||||
|
|
||||||
return result->body;
|
return result->body;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"printWidth": 100,
|
"printWidth": 80,
|
||||||
"useTabs": false,
|
"useTabs": false,
|
||||||
"indentSize": 4,
|
"indentSize": 4,
|
||||||
"endOfLine": "lf",
|
"endOfLine": "lf",
|
||||||
|
|||||||
@@ -8,9 +8,15 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.11" />
|
<PackageReference
|
||||||
|
Include="Microsoft.AspNetCore.OpenApi"
|
||||||
|
Version="9.0.11"
|
||||||
|
/>
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
||||||
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
|
<PackageReference
|
||||||
|
Include="FluentValidation.AspNetCore"
|
||||||
|
Version="11.3.0"
|
||||||
|
/>
|
||||||
<PackageReference Include="MediatR" Version="12.4.1" />
|
<PackageReference Include="MediatR" Version="12.4.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text.Encodings.Web;
|
using System.Text.Encodings.Web;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Shared.Contracts;
|
||||||
using Infrastructure.Jwt;
|
using Infrastructure.Jwt;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Microsoft.Extensions.Primitives;
|
|
||||||
using Shared.Contracts;
|
|
||||||
|
|
||||||
namespace API.Core.Authentication;
|
namespace API.Core.Authentication;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Custom ASP.NET Core authentication handler that validates bearer JWT access tokens
|
/// Custom ASP.NET Core authentication handler that validates bearer JWT access tokens
|
||||||
/// supplied in the <c>Authorization</c> header against the <c>JWT</c> authentication scheme.
|
/// supplied in the <c>Authorization</c> header against the <c>JWT</c> authentication scheme.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="options">The monitored options for the <c>JWT</c> authentication scheme.</param>
|
/// <param name="options">The monitored options for the <c>JWT</c> authentication scheme.</param>
|
||||||
/// <param name="logger">The logger factory used by the base <see cref="AuthenticationHandler{TOptions}" />.</param>
|
/// <param name="logger">The logger factory used by the base <see cref="AuthenticationHandler{TOptions}"/>.</param>
|
||||||
/// <param name="encoder">The URL encoder used by the base <see cref="AuthenticationHandler{TOptions}" />.</param>
|
/// <param name="encoder">The URL encoder used by the base <see cref="AuthenticationHandler{TOptions}"/>.</param>
|
||||||
/// <param name="tokenInfrastructure">The infrastructure service used to validate JWT access tokens.</param>
|
/// <param name="tokenInfrastructure">The infrastructure service used to validate JWT access tokens.</param>
|
||||||
/// <param name="configuration">The application configuration, used as a fallback source for the JWT secret key.</param>
|
/// <param name="configuration">The application configuration, used as a fallback source for the JWT secret key.</param>
|
||||||
public class JwtAuthenticationHandler(
|
public class JwtAuthenticationHandler(
|
||||||
@@ -26,57 +26,78 @@ public class JwtAuthenticationHandler(
|
|||||||
) : AuthenticationHandler<JwtAuthenticationOptions>(options, logger, encoder)
|
) : AuthenticationHandler<JwtAuthenticationOptions>(options, logger, encoder)
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Validates the incoming request's bearer JWT access token and produces an authentication result.
|
/// Validates the incoming request's bearer JWT access token and produces an authentication result.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// The signing secret is resolved first from the <c>ACCESS_TOKEN_SECRET</c> environment variable, falling
|
/// The signing secret is resolved first from the <c>ACCESS_TOKEN_SECRET</c> environment variable, falling
|
||||||
/// back to the <c>Jwt:SecretKey</c> configuration value, to stay consistent with the secret source used
|
/// back to the <c>Jwt:SecretKey</c> configuration value, to stay consistent with the secret source used
|
||||||
/// when tokens are issued. Authentication fails if the secret is not configured, the
|
/// when tokens are issued. Authentication fails if the secret is not configured, the
|
||||||
/// <c>Authorization</c> header is missing, the header does not use the <c>Bearer</c> scheme, or the
|
/// <c>Authorization</c> header is missing, the header does not use the <c>Bearer</c> scheme, or the
|
||||||
/// token fails validation.
|
/// token fails validation.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <returns>
|
/// <returns>
|
||||||
/// A successful <see cref="AuthenticateResult" /> containing the validated
|
/// A successful <see cref="AuthenticateResult"/> containing the validated <see cref="System.Security.Claims.ClaimsPrincipal"/>
|
||||||
/// <see cref="System.Security.Claims.ClaimsPrincipal" />
|
/// on success, or a failure result describing why authentication could not be completed.
|
||||||
/// on success, or a failure result describing why authentication could not be completed.
|
|
||||||
/// </returns>
|
/// </returns>
|
||||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||||
{
|
{
|
||||||
// Use the same access-token secret source as TokenService to avoid mismatched validation.
|
// Use the same access-token secret source as TokenService to avoid mismatched validation.
|
||||||
string? secret = Environment.GetEnvironmentVariable("ACCESS_TOKEN_SECRET");
|
var secret = Environment.GetEnvironmentVariable("ACCESS_TOKEN_SECRET");
|
||||||
if (string.IsNullOrWhiteSpace(secret))
|
if (string.IsNullOrWhiteSpace(secret))
|
||||||
|
{
|
||||||
secret = configuration["Jwt:SecretKey"];
|
secret = configuration["Jwt:SecretKey"];
|
||||||
|
}
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(secret))
|
if (string.IsNullOrWhiteSpace(secret))
|
||||||
|
{
|
||||||
return AuthenticateResult.Fail("JWT secret is not configured");
|
return AuthenticateResult.Fail("JWT secret is not configured");
|
||||||
|
}
|
||||||
|
|
||||||
// Check if Authorization header exists
|
// Check if Authorization header exists
|
||||||
if (!Request.Headers.TryGetValue("Authorization", out StringValues authHeaderValue))
|
if (
|
||||||
|
!Request.Headers.TryGetValue(
|
||||||
|
"Authorization",
|
||||||
|
out var authHeaderValue
|
||||||
|
)
|
||||||
|
)
|
||||||
|
{
|
||||||
return AuthenticateResult.Fail("Authorization header is missing");
|
return AuthenticateResult.Fail("Authorization header is missing");
|
||||||
|
}
|
||||||
|
|
||||||
string authHeader = authHeaderValue.ToString();
|
var authHeader = authHeaderValue.ToString();
|
||||||
if (!authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
if (
|
||||||
return AuthenticateResult.Fail("Invalid authorization header format");
|
!authHeader.StartsWith(
|
||||||
|
"Bearer ",
|
||||||
|
StringComparison.OrdinalIgnoreCase
|
||||||
|
)
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return AuthenticateResult.Fail(
|
||||||
|
"Invalid authorization header format"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
string token = authHeader.Substring("Bearer ".Length).Trim();
|
var token = authHeader.Substring("Bearer ".Length).Trim();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
ClaimsPrincipal claimsPrincipal = await tokenInfrastructure.ValidateJwtAsync(
|
var claimsPrincipal = await tokenInfrastructure.ValidateJwtAsync(
|
||||||
token,
|
token,
|
||||||
secret
|
secret
|
||||||
);
|
);
|
||||||
AuthenticationTicket ticket = new(claimsPrincipal, Scheme.Name);
|
var ticket = new AuthenticationTicket(claimsPrincipal, Scheme.Name);
|
||||||
return AuthenticateResult.Success(ticket);
|
return AuthenticateResult.Success(ticket);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
return AuthenticateResult.Fail($"Token validation failed: {ex.Message}");
|
return AuthenticateResult.Fail(
|
||||||
|
$"Token validation failed: {ex.Message}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Writes a JSON 401 Unauthorized response when authentication fails or is required but not supplied.
|
/// Writes a JSON 401 Unauthorized response when authentication fails or is required but not supplied.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="properties">The authentication properties associated with the challenge.</param>
|
/// <param name="properties">The authentication properties associated with the challenge.</param>
|
||||||
/// <returns>A task that completes once the response body has been written.</returns>
|
/// <returns>A task that completes once the response body has been written.</returns>
|
||||||
@@ -85,16 +106,13 @@ public class JwtAuthenticationHandler(
|
|||||||
Response.ContentType = "application/json";
|
Response.ContentType = "application/json";
|
||||||
Response.StatusCode = 401;
|
Response.StatusCode = 401;
|
||||||
|
|
||||||
ResponseBody response = new()
|
var response = new ResponseBody { Message = "Unauthorized: Invalid or missing authentication token" };
|
||||||
{
|
|
||||||
Message = "Unauthorized: Invalid or missing authentication token",
|
|
||||||
};
|
|
||||||
await Response.WriteAsJsonAsync(response);
|
await Response.WriteAsJsonAsync(response);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Options for the <c>JWT</c> authentication scheme handled by <see cref="JwtAuthenticationHandler" />.
|
/// Options for the <c>JWT</c> authentication scheme handled by <see cref="JwtAuthenticationHandler"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>No additional options are defined beyond those provided by <see cref="AuthenticationSchemeOptions" />.</remarks>
|
/// <remarks>No additional options are defined beyond those provided by <see cref="AuthenticationSchemeOptions"/>.</remarks>
|
||||||
public class JwtAuthenticationOptions : AuthenticationSchemeOptions { }
|
public class JwtAuthenticationOptions : AuthenticationSchemeOptions { }
|
||||||
|
|||||||
@@ -1,27 +1,27 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace API.Core.Controllers;
|
namespace API.Core.Controllers
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Handles requests that do not match any other route, used as the application's fallback controller.
|
|
||||||
/// </summary>
|
|
||||||
/// <remarks>
|
|
||||||
/// Excluded from API explorer/Swagger output via <c>[ApiExplorerSettings(IgnoreApi = true)]</c>.
|
|
||||||
/// Wired up as the fallback target via <c>app.MapFallbackToController("Handle404", "NotFound")</c> in
|
|
||||||
/// <c>Program.cs</c>.
|
|
||||||
/// </remarks>
|
|
||||||
[ApiController]
|
|
||||||
[ApiExplorerSettings(IgnoreApi = true)]
|
|
||||||
[Route("error")] // required
|
|
||||||
public class NotFoundController : ControllerBase
|
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns a generic 404 response for any request that did not match a defined route.
|
/// Handles requests that do not match any other route, used as the application's fallback controller.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>A <c>404 Not Found</c> result with a JSON body containing a "Route not found." message.</returns>
|
/// <remarks>
|
||||||
[HttpGet("404")] //required
|
/// Excluded from API explorer/Swagger output via <c>[ApiExplorerSettings(IgnoreApi = true)]</c>.
|
||||||
public IActionResult Handle404()
|
/// Wired up as the fallback target via <c>app.MapFallbackToController("Handle404", "NotFound")</c> in <c>Program.cs</c>.
|
||||||
|
/// </remarks>
|
||||||
|
[ApiController]
|
||||||
|
[ApiExplorerSettings(IgnoreApi = true)]
|
||||||
|
[Route("error")] // required
|
||||||
|
public class NotFoundController : ControllerBase
|
||||||
{
|
{
|
||||||
return NotFound(new { message = "Route not found." });
|
/// <summary>
|
||||||
|
/// Returns a generic 404 response for any request that did not match a defined route.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A <c>404 Not Found</c> result with a JSON body containing a "Route not found." message.</returns>
|
||||||
|
[HttpGet("404")] //required
|
||||||
|
public IActionResult Handle404()
|
||||||
|
{
|
||||||
|
return NotFound(new { message = "Route not found." });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
using Shared.Contracts;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Shared.Contracts;
|
|
||||||
|
|
||||||
namespace API.Core.Controllers;
|
namespace API.Core.Controllers;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sample controller demonstrating an endpoint that requires JWT authentication.
|
/// Sample controller demonstrating an endpoint that requires JWT authentication.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/[controller]")]
|
[Route("api/[controller]")]
|
||||||
@@ -14,18 +14,18 @@ namespace API.Core.Controllers;
|
|||||||
public class ProtectedController : ControllerBase
|
public class ProtectedController : ControllerBase
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns the authenticated caller's user ID and username, extracted from the JWT claims.
|
/// Returns the authenticated caller's user ID and username, extracted from the JWT claims.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>
|
/// <returns>
|
||||||
/// A <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}" /> whose payload contains the
|
/// A <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}"/> whose payload contains the
|
||||||
/// caller's <c>userId</c> (from <see cref="ClaimTypes.NameIdentifier" />) and <c>username</c>
|
/// caller's <c>userId</c> (from <see cref="ClaimTypes.NameIdentifier"/>) and <c>username</c>
|
||||||
/// (from <see cref="ClaimTypes.Name" />), either of which may be <c>null</c> if not present in the token.
|
/// (from <see cref="ClaimTypes.Name"/>), either of which may be <c>null</c> if not present in the token.
|
||||||
/// </returns>
|
/// </returns>
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public ActionResult<ResponseBody<object>> Get()
|
public ActionResult<ResponseBody<object>> Get()
|
||||||
{
|
{
|
||||||
string? userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
string? username = User.FindFirst(ClaimTypes.Name)?.Value;
|
var username = User.FindFirst(ClaimTypes.Name)?.Value;
|
||||||
|
|
||||||
return Ok(
|
return Ok(
|
||||||
new ResponseBody<object>
|
new ResponseBody<object>
|
||||||
|
|||||||
@@ -1,89 +1,53 @@
|
|||||||
// API.Core/Filters/GlobalExceptionFilter.cs
|
// API.Core/Filters/GlobalExceptionFilter.cs
|
||||||
|
|
||||||
|
using Shared.Contracts;
|
||||||
using Domain.Exceptions;
|
using Domain.Exceptions;
|
||||||
|
using FluentValidation;
|
||||||
|
using Microsoft.Data.SqlClient;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.Mvc.Filters;
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
using Microsoft.Data.SqlClient;
|
|
||||||
using Shared.Contracts;
|
|
||||||
using ValidationException = FluentValidation.ValidationException;
|
|
||||||
|
|
||||||
namespace API.Core;
|
namespace API.Core;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// MVC exception filter that converts unhandled exceptions raised by controller actions into
|
/// MVC exception filter that converts unhandled exceptions raised by controller actions into
|
||||||
/// consistent JSON error responses with appropriate HTTP status codes.
|
/// consistent JSON error responses with appropriate HTTP status codes.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="logger">Logger used to record unhandled exceptions before they are translated into a response.</param>
|
/// <param name="logger">Logger used to record unhandled exceptions before they are translated into a response.</param>
|
||||||
public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExceptionFilter
|
public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
|
||||||
|
: IExceptionFilter
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Logs the exception and sets <see cref="ExceptionContext.Result" /> to an appropriate error response,
|
/// Logs the exception and sets <see cref="ExceptionContext.Result"/> to an appropriate error response,
|
||||||
/// marking the exception as handled.
|
/// marking the exception as handled.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// Maps exception types to responses as follows:
|
/// Maps exception types to responses as follows:
|
||||||
/// <list type="bullet">
|
/// <list type="bullet">
|
||||||
/// <item>
|
/// <item><description><see cref="FluentValidation.ValidationException"/> → <c>400 Bad Request</c> with per-property validation error messages.</description></item>
|
||||||
/// <description>
|
/// <item><description><see cref="ConflictException"/> → <c>409 Conflict</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||||
/// <see cref="FluentValidation.ValidationException" /> → <c>400 Bad Request</c> with per-property
|
/// <item><description><see cref="NotFoundException"/> → <c>404 Not Found</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||||
/// validation error messages.
|
/// <item><description><see cref="UnauthorizedException"/> → <c>401 Unauthorized</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||||
/// </description>
|
/// <item><description><see cref="ForbiddenException"/> → <c>403 Forbidden</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||||
/// </item>
|
/// <item><description><see cref="SqlException"/> → <c>503 Service Unavailable</c> with a generic database error message.</description></item>
|
||||||
/// <item>
|
/// <item><description><see cref="Domain.Exceptions.ValidationException"/> → <c>400 Bad Request</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||||
/// <description>
|
/// <item><description>Any other exception → <c>500 Internal Server Error</c> with a generic error message.</description></item>
|
||||||
/// <see cref="ConflictException" /> → <c>409 Conflict</c> with a <see cref="ResponseBody" />
|
/// </list>
|
||||||
/// message.
|
|
||||||
/// </description>
|
|
||||||
/// </item>
|
|
||||||
/// <item>
|
|
||||||
/// <description>
|
|
||||||
/// <see cref="NotFoundException" /> → <c>404 Not Found</c> with a <see cref="ResponseBody" />
|
|
||||||
/// message.
|
|
||||||
/// </description>
|
|
||||||
/// </item>
|
|
||||||
/// <item>
|
|
||||||
/// <description>
|
|
||||||
/// <see cref="UnauthorizedException" /> → <c>401 Unauthorized</c> with a
|
|
||||||
/// <see cref="ResponseBody" /> message.
|
|
||||||
/// </description>
|
|
||||||
/// </item>
|
|
||||||
/// <item>
|
|
||||||
/// <description>
|
|
||||||
/// <see cref="ForbiddenException" /> → <c>403 Forbidden</c> with a <see cref="ResponseBody" />
|
|
||||||
/// message.
|
|
||||||
/// </description>
|
|
||||||
/// </item>
|
|
||||||
/// <item>
|
|
||||||
/// <description>
|
|
||||||
/// <see cref="SqlException" /> → <c>503 Service Unavailable</c> with a generic database error
|
|
||||||
/// message.
|
|
||||||
/// </description>
|
|
||||||
/// </item>
|
|
||||||
/// <item>
|
|
||||||
/// <description>
|
|
||||||
/// <see cref="Domain.Exceptions.ValidationException" /> → <c>400 Bad Request</c> with a
|
|
||||||
/// <see cref="ResponseBody" /> message.
|
|
||||||
/// </description>
|
|
||||||
/// </item>
|
|
||||||
/// <item>
|
|
||||||
/// <description>Any other exception → <c>500 Internal Server Error</c> with a generic error message.</description>
|
|
||||||
/// </item>
|
|
||||||
/// </list>
|
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <param name="context">
|
/// <param name="context">The context for the unhandled exception, including the exception itself and the result to populate.</param>
|
||||||
/// The context for the unhandled exception, including the exception itself and the result to
|
|
||||||
/// populate.
|
|
||||||
/// </param>
|
|
||||||
public void OnException(ExceptionContext context)
|
public void OnException(ExceptionContext context)
|
||||||
{
|
{
|
||||||
logger.LogError(context.Exception, "Unhandled exception occurred");
|
logger.LogError(context.Exception, "Unhandled exception occurred");
|
||||||
|
|
||||||
switch (context.Exception)
|
switch (context.Exception)
|
||||||
{
|
{
|
||||||
case ValidationException fluentValidationException:
|
case FluentValidation.ValidationException fluentValidationException:
|
||||||
Dictionary<string, string[]> errors = fluentValidationException
|
var errors = fluentValidationException
|
||||||
.Errors.GroupBy(e => e.PropertyName)
|
.Errors.GroupBy(e => e.PropertyName)
|
||||||
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray());
|
.ToDictionary(
|
||||||
|
g => g.Key,
|
||||||
|
g => g.Select(e => e.ErrorMessage).ToArray()
|
||||||
|
);
|
||||||
|
|
||||||
context.Result = new BadRequestObjectResult(
|
context.Result = new BadRequestObjectResult(
|
||||||
new { message = "Validation failed", errors }
|
new { message = "Validation failed", errors }
|
||||||
@@ -92,7 +56,9 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExc
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case ConflictException ex:
|
case ConflictException ex:
|
||||||
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
|
context.Result = new ObjectResult(
|
||||||
|
new ResponseBody { Message = ex.Message }
|
||||||
|
)
|
||||||
{
|
{
|
||||||
StatusCode = 409,
|
StatusCode = 409,
|
||||||
};
|
};
|
||||||
@@ -100,7 +66,9 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExc
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case NotFoundException ex:
|
case NotFoundException ex:
|
||||||
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
|
context.Result = new ObjectResult(
|
||||||
|
new ResponseBody { Message = ex.Message }
|
||||||
|
)
|
||||||
{
|
{
|
||||||
StatusCode = 404,
|
StatusCode = 404,
|
||||||
};
|
};
|
||||||
@@ -108,7 +76,9 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExc
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case UnauthorizedException ex:
|
case UnauthorizedException ex:
|
||||||
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
|
context.Result = new ObjectResult(
|
||||||
|
new ResponseBody { Message = ex.Message }
|
||||||
|
)
|
||||||
{
|
{
|
||||||
StatusCode = 401,
|
StatusCode = 401,
|
||||||
};
|
};
|
||||||
@@ -116,7 +86,9 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExc
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case ForbiddenException ex:
|
case ForbiddenException ex:
|
||||||
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
|
context.Result = new ObjectResult(
|
||||||
|
new ResponseBody { Message = ex.Message }
|
||||||
|
)
|
||||||
{
|
{
|
||||||
StatusCode = 403,
|
StatusCode = 403,
|
||||||
};
|
};
|
||||||
@@ -134,7 +106,9 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExc
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case Domain.Exceptions.ValidationException ex:
|
case Domain.Exceptions.ValidationException ex:
|
||||||
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
|
context.Result = new ObjectResult(
|
||||||
|
new ResponseBody { Message = ex.Message }
|
||||||
|
)
|
||||||
{
|
{
|
||||||
StatusCode = 400,
|
StatusCode = 400,
|
||||||
};
|
};
|
||||||
@@ -143,7 +117,10 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExc
|
|||||||
|
|
||||||
default:
|
default:
|
||||||
context.Result = new ObjectResult(
|
context.Result = new ObjectResult(
|
||||||
new ResponseBody { Message = "An unexpected error occurred" }
|
new ResponseBody
|
||||||
|
{
|
||||||
|
Message = "An unexpected error occurred",
|
||||||
|
}
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
StatusCode = 500,
|
StatusCode = 500,
|
||||||
|
|||||||
@@ -14,14 +14,13 @@ using Infrastructure.Jwt;
|
|||||||
using Infrastructure.Sql;
|
using Infrastructure.Sql;
|
||||||
using Shared.Application.Behaviors;
|
using Shared.Application.Behaviors;
|
||||||
|
|
||||||
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
// Global Exception Filter
|
// Global Exception Filter
|
||||||
builder
|
builder.Services.AddControllers(options =>
|
||||||
.Services.AddControllers(options =>
|
{
|
||||||
{
|
options.Filters.Add<GlobalExceptionFilter>();
|
||||||
options.Filters.Add<GlobalExceptionFilter>();
|
})
|
||||||
})
|
|
||||||
.AddApplicationPart(typeof(BreweryController).Assembly)
|
.AddApplicationPart(typeof(BreweryController).Assembly)
|
||||||
.AddApplicationPart(typeof(UserController).Assembly)
|
.AddApplicationPart(typeof(UserController).Assembly)
|
||||||
.AddApplicationPart(typeof(AuthController).Assembly);
|
.AddApplicationPart(typeof(AuthController).Assembly);
|
||||||
@@ -56,11 +55,16 @@ builder.Services.AddHealthChecks();
|
|||||||
builder.Logging.ClearProviders();
|
builder.Logging.ClearProviders();
|
||||||
builder.Logging.AddConsole();
|
builder.Logging.AddConsole();
|
||||||
if (!builder.Environment.IsProduction())
|
if (!builder.Environment.IsProduction())
|
||||||
|
{
|
||||||
builder.Logging.AddDebug();
|
builder.Logging.AddDebug();
|
||||||
|
}
|
||||||
|
|
||||||
// Configure Dependency Injection -------------------------------------------------------------------------------------
|
// Configure Dependency Injection -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
builder.Services.AddSingleton<ISqlConnectionFactory, DefaultSqlConnectionFactory>();
|
builder.Services.AddSingleton<
|
||||||
|
ISqlConnectionFactory,
|
||||||
|
DefaultSqlConnectionFactory
|
||||||
|
>();
|
||||||
|
|
||||||
builder.Services.AddFeaturesBreweries();
|
builder.Services.AddFeaturesBreweries();
|
||||||
builder.Services.AddFeaturesUserManagement();
|
builder.Services.AddFeaturesUserManagement();
|
||||||
@@ -77,11 +81,14 @@ builder.Services.AddScoped<GlobalExceptionFilter>();
|
|||||||
// Configure JWT Authentication
|
// Configure JWT Authentication
|
||||||
builder
|
builder
|
||||||
.Services.AddAuthentication("JWT")
|
.Services.AddAuthentication("JWT")
|
||||||
.AddScheme<JwtAuthenticationOptions, JwtAuthenticationHandler>("JWT", options => { });
|
.AddScheme<JwtAuthenticationOptions, JwtAuthenticationHandler>(
|
||||||
|
"JWT",
|
||||||
|
options => { }
|
||||||
|
);
|
||||||
|
|
||||||
builder.Services.AddAuthorization();
|
builder.Services.AddAuthorization();
|
||||||
|
|
||||||
WebApplication app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
app.UseSwagger();
|
app.UseSwagger();
|
||||||
app.UseSwaggerUI();
|
app.UseSwaggerUI();
|
||||||
@@ -99,7 +106,7 @@ app.MapControllers();
|
|||||||
app.MapFallbackToController("Handle404", "NotFound");
|
app.MapFallbackToController("Handle404", "NotFound");
|
||||||
|
|
||||||
// Graceful shutdown handling
|
// Graceful shutdown handling
|
||||||
IHostApplicationLifetime lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
|
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
|
||||||
lifetime.ApplicationStopping.Register(() =>
|
lifetime.ApplicationStopping.Register(() =>
|
||||||
{
|
{
|
||||||
app.Logger.LogInformation("Application is shutting down gracefully...");
|
app.Logger.LogInformation("Application is shutting down gracefully...");
|
||||||
|
|||||||
@@ -24,7 +24,10 @@
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<!-- ASP.NET Core integration testing -->
|
<!-- ASP.NET Core integration testing -->
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.1" />
|
<PackageReference
|
||||||
|
Include="Microsoft.AspNetCore.Mvc.Testing"
|
||||||
|
Version="9.0.1"
|
||||||
|
/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,51 +1,51 @@
|
|||||||
Feature: Protected Endpoint Access Token Validation
|
Feature: Protected Endpoint Access Token Validation
|
||||||
As a backend developer
|
As a backend developer
|
||||||
I want protected endpoints to validate access tokens
|
I want protected endpoints to validate access tokens
|
||||||
So that unauthorized requests are rejected
|
So that unauthorized requests are rejected
|
||||||
|
|
||||||
Scenario: Protected endpoint accepts valid access token
|
Scenario: Protected endpoint accepts valid access token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have an existing account
|
And I have an existing account
|
||||||
And I am logged in
|
And I am logged in
|
||||||
When I submit a request to a protected endpoint with a valid access token
|
When I submit a request to a protected endpoint with a valid access token
|
||||||
Then the response has HTTP status 200
|
Then the response has HTTP status 200
|
||||||
|
|
||||||
Scenario: Protected endpoint rejects missing access token
|
Scenario: Protected endpoint rejects missing access token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
When I submit a request to a protected endpoint without an access token
|
When I submit a request to a protected endpoint without an access token
|
||||||
Then the response has HTTP status 401
|
Then the response has HTTP status 401
|
||||||
|
|
||||||
Scenario: Protected endpoint rejects invalid access token
|
Scenario: Protected endpoint rejects invalid access token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
When I submit a request to a protected endpoint with an invalid access token
|
When I submit a request to a protected endpoint with an invalid access token
|
||||||
Then the response has HTTP status 401
|
Then the response has HTTP status 401
|
||||||
And the response JSON should have "message" containing "Unauthorized"
|
And the response JSON should have "message" containing "Unauthorized"
|
||||||
|
|
||||||
Scenario: Protected endpoint rejects expired access token
|
Scenario: Protected endpoint rejects expired access token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have an existing account
|
And I have an existing account
|
||||||
And I am logged in with an immediately-expiring access token
|
And I am logged in with an immediately-expiring access token
|
||||||
When I submit a request to a protected endpoint with the expired token
|
When I submit a request to a protected endpoint with the expired token
|
||||||
Then the response has HTTP status 401
|
Then the response has HTTP status 401
|
||||||
And the response JSON should have "message" containing "Unauthorized"
|
And the response JSON should have "message" containing "Unauthorized"
|
||||||
|
|
||||||
Scenario: Protected endpoint rejects token signed with wrong secret
|
Scenario: Protected endpoint rejects token signed with wrong secret
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have an access token signed with the wrong secret
|
And I have an access token signed with the wrong secret
|
||||||
When I submit a request to a protected endpoint with the tampered token
|
When I submit a request to a protected endpoint with the tampered token
|
||||||
Then the response has HTTP status 401
|
Then the response has HTTP status 401
|
||||||
And the response JSON should have "message" containing "Unauthorized"
|
And the response JSON should have "message" containing "Unauthorized"
|
||||||
|
|
||||||
Scenario: Protected endpoint rejects refresh token as access token
|
Scenario: Protected endpoint rejects refresh token as access token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have an existing account
|
And I have an existing account
|
||||||
And I am logged in
|
And I am logged in
|
||||||
When I submit a request to a protected endpoint with my refresh token instead of access token
|
When I submit a request to a protected endpoint with my refresh token instead of access token
|
||||||
Then the response has HTTP status 401
|
Then the response has HTTP status 401
|
||||||
|
|
||||||
Scenario: Protected endpoint rejects confirmation token as access token
|
Scenario: Protected endpoint rejects confirmation token as access token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have registered a new account
|
And I have registered a new account
|
||||||
And I have a valid confirmation token
|
And I have a valid confirmation token
|
||||||
When I submit a request to a protected endpoint with my confirmation token instead of access token
|
When I submit a request to a protected endpoint with my confirmation token instead of access token
|
||||||
Then the response has HTTP status 401
|
Then the response has HTTP status 401
|
||||||
|
|||||||
@@ -1,77 +1,76 @@
|
|||||||
Feature: User Account Confirmation
|
Feature: User Account Confirmation
|
||||||
As a newly registered user
|
As a newly registered user
|
||||||
I want to confirm my email address via a validation token
|
I want to confirm my email address via a validation token
|
||||||
So that my account is fully activated
|
So that my account is fully activated
|
||||||
|
Scenario: Successful confirmation with valid token
|
||||||
|
Given the API is running
|
||||||
|
And I have registered a new account
|
||||||
|
And I have a valid confirmation token for my account
|
||||||
|
And I have a valid access token for my account
|
||||||
|
When I submit a confirmation request with the valid token
|
||||||
|
Then the response has HTTP status 200
|
||||||
|
And the response JSON should have "message" containing "is confirmed"
|
||||||
|
|
||||||
Scenario: Successful confirmation with valid token
|
Scenario: Re-confirming an already verified account remains successful
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have registered a new account
|
And I have registered a new account
|
||||||
And I have a valid confirmation token for my account
|
And I have a valid confirmation token for my account
|
||||||
And I have a valid access token for my account
|
And I have a valid access token for my account
|
||||||
When I submit a confirmation request with the valid token
|
When I submit a confirmation request with the valid token
|
||||||
Then the response has HTTP status 200
|
And I submit the same confirmation request again
|
||||||
And the response JSON should have "message" containing "is confirmed"
|
Then the response has HTTP status 200
|
||||||
|
And the response JSON should have "message" containing "is confirmed"
|
||||||
|
|
||||||
Scenario: Re-confirming an already verified account remains successful
|
Scenario: Confirmation fails with invalid token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have registered a new account
|
And I have registered a new account
|
||||||
And I have a valid confirmation token for my account
|
And I have a valid access token for my account
|
||||||
And I have a valid access token for my account
|
When I submit a confirmation request with an invalid token
|
||||||
When I submit a confirmation request with the valid token
|
Then the response has HTTP status 401
|
||||||
And I submit the same confirmation request again
|
And the response JSON should have "message" containing "Invalid token"
|
||||||
Then the response has HTTP status 200
|
|
||||||
And the response JSON should have "message" containing "is confirmed"
|
|
||||||
|
|
||||||
Scenario: Confirmation fails with invalid token
|
Scenario: Confirmation fails with expired token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have registered a new account
|
And I have registered a new account
|
||||||
And I have a valid access token for my account
|
And I have an expired confirmation token for my account
|
||||||
When I submit a confirmation request with an invalid token
|
And I have a valid access token for my account
|
||||||
Then the response has HTTP status 401
|
When I submit a confirmation request with the expired token
|
||||||
And the response JSON should have "message" containing "Invalid token"
|
Then the response has HTTP status 401
|
||||||
|
And the response JSON should have "message" containing "Invalid token"
|
||||||
|
|
||||||
Scenario: Confirmation fails with expired token
|
Scenario: Confirmation fails with tampered token (wrong secret)
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have registered a new account
|
And I have registered a new account
|
||||||
And I have an expired confirmation token for my account
|
And I have a confirmation token signed with the wrong secret
|
||||||
And I have a valid access token for my account
|
And I have a valid access token for my account
|
||||||
When I submit a confirmation request with the expired token
|
When I submit a confirmation request with the tampered token
|
||||||
Then the response has HTTP status 401
|
Then the response has HTTP status 401
|
||||||
And the response JSON should have "message" containing "Invalid token"
|
And the response JSON should have "message" containing "Invalid token"
|
||||||
|
|
||||||
Scenario: Confirmation fails with tampered token (wrong secret)
|
Scenario: Confirmation fails when token is missing
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have registered a new account
|
And I have registered a new account
|
||||||
And I have a confirmation token signed with the wrong secret
|
And I have a valid access token for my account
|
||||||
And I have a valid access token for my account
|
When I submit a confirmation request with a missing token
|
||||||
When I submit a confirmation request with the tampered token
|
Then the response has HTTP status 400
|
||||||
Then the response has HTTP status 401
|
|
||||||
And the response JSON should have "message" containing "Invalid token"
|
|
||||||
|
|
||||||
Scenario: Confirmation fails when token is missing
|
Scenario: Confirmation endpoint only accepts POST requests
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have registered a new account
|
And I have a valid confirmation token
|
||||||
And I have a valid access token for my account
|
When I submit a confirmation request using an invalid HTTP method
|
||||||
When I submit a confirmation request with a missing token
|
Then the response has HTTP status 404
|
||||||
Then the response has HTTP status 400
|
|
||||||
|
|
||||||
Scenario: Confirmation endpoint only accepts POST requests
|
Scenario: Confirmation fails with malformed token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have a valid confirmation token
|
And I have registered a new account
|
||||||
When I submit a confirmation request using an invalid HTTP method
|
And I have a valid access token for my account
|
||||||
Then the response has HTTP status 404
|
When I submit a confirmation request with a malformed token
|
||||||
|
Then the response has HTTP status 401
|
||||||
|
And the response JSON should have "message" containing "Invalid token"
|
||||||
|
|
||||||
Scenario: Confirmation fails with malformed token
|
Scenario: Confirmation fails without an access token
|
||||||
Given the API is running
|
Given the API is running
|
||||||
And I have registered a new account
|
And I have registered a new account
|
||||||
And I have a valid access token for my account
|
And I have a valid confirmation token for my account
|
||||||
When I submit a confirmation request with a malformed token
|
When I submit a confirmation request with the valid token without an access token
|
||||||
Then the response has HTTP status 401
|
Then the response has HTTP status 401
|
||||||
And the response JSON should have "message" containing "Invalid token"
|
|
||||||
|
|
||||||
Scenario: Confirmation fails without an access token
|
|
||||||
Given the API is running
|
|
||||||
And I have registered a new account
|
|
||||||
And I have a valid confirmation token for my account
|
|
||||||
When I submit a confirmation request with the valid token without an access token
|
|
||||||
Then the response has HTTP status 401
|
|
||||||
|
|||||||