Compare commits

..
Author SHA1 Message Date
sagifer f037522052 Merge pull request 'Sharing a chart with its short summary, with link previews' (#18) from main into prod
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 41s
Reviewed-on: #18
2026-11-19 09:11:59 +01:00
fecoandClaude Opus 5.5 c7600608d3 Sharing a chart with its short summary, with link previews
CI / test (push) Successful in 1m10s
CI / build (push) Successful in 4m33s
CI / deploy (push) Skipped
The summary card gets a share button: a public link (/s/<slug>) with the
wheel and the newest short summary, no name or birth data. The page carries
og:/twitter: tags, and /s/<slug>/kep/<version>.png renders a 1200x630 preview
(wheel, title, text, big three) with next/og and bundled fonts. The version
changes with the summary, so Facebook fetches a rewritten one again.

Backend: a shared chart comes with its newest finished summary, and sharing
the same thing again returns the open link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-19 07:37:06 +00:00
sagifer e476117c77 Merge pull request 'Main' (#17) from main into prod
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 56s
CI / deploy (push) Successful in 34s
Reviewed-on: #17
2026-11-19 08:13:18 +01:00
fecoandClaude Opus 5.5 da533e8fa9 Worker: separate containers for e-mail and AI generation
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 4m9s
CI / deploy (push) Skipped
WORKER_TASKS (email, cleanup, analyses; all by default) picks the jobs of a
worker process. In production the worker sends e-mails and cleans up (and
will take the other background jobs), worker-ai writes the analyses and
answers with its quick and slow lanes, sized from the server's .env.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-19 06:51:45 +00:00
fecoandClaude Opus 5.5 bc0227042b Worker: separate quick lane for summaries and answers
CI / test (push) Successful in 1m8s
CI / build (push) Successful in 4m9s
CI / deploy (push) Skipped
Summaries and questions get their own slots (QUICK_CONCURRENCY, default 2),
so they never wait behind detailed analyses (ANALYSIS_CONCURRENCY, default
4). A free slow slot also takes quick work; a lane of size 0 is off, so the
lanes can run as separate deployments. Documented that several workers can
share the queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-19 06:40:09 +00:00
sagifer d758f5bf12 Merge pull request 'Frontend: justified generated text, mobile layout without sideways scrolling' (#16) from main into prod
CI / test (push) Successful in 1m7s
CI / build (push) Successful in 21s
CI / deploy (push) Successful in 51s
Reviewed-on: #16
2026-11-19 07:15:09 +01:00
fecoandClaude Opus 5.5 d46cd7a445 Frontend: justified generated text, mobile layout without sideways scrolling
CI / test (push) Successful in 1m12s
CI / build (push) Successful in 5m12s
CI / deploy (push) Skipped
Summaries, analyses and answers are justified with hyphenation in the
text's own language. Grid tracks can no longer grow past the screen
(minmax(0, 1fr), min(…, 100%)), form fields may shrink, the privacy table
scrolls on its own, and the body clips horizontal overflow as a safety net.
Phones get tighter spacing and smaller headings; the facts lists stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-19 06:10:38 +00:00
fecoandClaude Opus 5.5 8b2c4310ba Merge main into prod: restart running generations, error log, retry notice, questions on relationship analyses
CI / test (push) Successful in 1m7s
CI / build (push) Successful in 19s
CI / deploy (push) Successful in 52s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:51:39 +00:00
fecoandClaude Opus 5.5 029a001ca6 Questions about relationship analyses too
CI / test (push) Successful in 1m6s
CI / build (push) Successful in 5m1s
CI / deploy (push) Skipped
- The answer sees both charts and the comparison; both people see the questions
- Heading, hint and example question per analysis kind

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:51:38 +00:00
fecoandClaude Opus 5.5 02e4e225f0 Error log, retry notice, a waiting counter that keeps counting
CI / test (push) Successful in 1m8s
CI / build (push) Successful in 5m13s
CI / deploy (push) Skipped
- generation_errors: every failed attempt (model, attempt, outcome, duration); admin
  Hibanapló page and GET /v1/admin/errors; kept 90 days
- The waiting page counts from when the text was asked for (requested_at), not from
  the page load, so a reload no longer restarts it
- It says when an attempt failed and is retried, and when a failed text's unit was
  given back; admins see the error

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:47:37 +00:00
fecoandClaude Opus 5.5 cf2fb9d454 jobs: plain query string
CI / test (push) Successful in 1m2s
CI / build (push) Successful in 7m53s
CI / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:32:02 +00:00
fecoandClaude Opus 5.5 b5743ec7d1 Admin: list and restart running generations with the models set now
CI / test (push) Successful in 1m17s
CI / build (push) Successful in 5m43s
CI / deploy (push) Skipped
- Modellek page: analyses and answers being written or waiting, with their model
  and the one a restart would use; restart one or all
- Each attempt's started_at is its token: a restarted attempt still running in the
  worker cannot write its result and is dropped within 10 seconds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-18 21:31:09 +00:00
54 changed files with 2530 additions and 239 deletions
+11 -6
View File
@@ -462,8 +462,8 @@ fn question_system(language: &str) -> String {
if language == "hu" { if language == "hu" {
let mut text = format!( let mut text = format!(
"Tapasztalt, empatikus, lélektani szemléletű asztrológus vagy a Sorsfonalak alkalmazásban. Az olvasó már \ "Tapasztalt, empatikus, lélektani szemléletű asztrológus vagy a Sorsfonalak alkalmazásban. Az olvasó már \
megkapta a részletes elemzését (születési képletelemzést vagy éves előrejelzést), és most kérdez róla. Válaszolj a \ megkapta a részletes elemzését (születési képletelemzést, kapcsolati elemzést vagy éves előrejelzést), és most kérdez \
kérdésére. róla. Válaszolj a kérdésére.
Szabályok: Szabályok:
- A válasz a megadott képletadatokon és az elemzésen alapuljon. Ne találj ki pozíciót, fényszöget, házat vagy dátumot, \ - A válasz a megadott képletadatokon és az elemzésen alapuljon. Ne találj ki pozíciót, fényszöget, házat vagy dátumot, \
@@ -471,8 +471,10 @@ amely nincs az adatok között. Ha a kérdésre az adatok alapján nem lehet fel
amit a képlet erről mutat. amit a képlet erről mutat.
- Maradj összhangban az elemzéssel. Ha a kérdés olyan részletre vonatkozik, amelyet az elemzés nem tárgyalt, a \ - Maradj összhangban az elemzéssel. Ha a kérdés olyan részletre vonatkozik, amelyet az elemzés nem tárgyalt, a \
képletadatokból egészítsd ki. képletadatokból egészítsd ki.
- Közvetlenül a kérdezőhöz szólj, tegező formában. Ha a kérdés két ember kapcsolatáról szól, csak abból beszélj, amit \ - Közvetlenül a kérdezőhöz szólj, tegező formában. Kapcsolati elemzésnél (két képlet összevetése) a kérdező az egyik \
az adatok mutatnak. fél: ha a kérdésből nem derül ki, melyik, beszélj kettejükhöz („ti”, „kettőtök”). A feleket az adatokban Person 1 és \
Person 2 jelöli, a szövegben „az első fél” és „a második fél”. Ne feltételezd a nemüket és a kapcsolat jellegét, és \
csak abból beszélj, amit az adatok mutatnak.
- Hangnem: meleg, őszinte, megerősítő és konkrét. Ne légy fatalista: ne jósolj betegséget, halált, balesetet, \ - Hangnem: meleg, őszinte, megerősítő és konkrét. Ne légy fatalista: ne jósolj betegséget, halált, balesetet, \
terhességet vagy biztos eseményeket, és ne adj orvosi, jogi vagy pénzügyi tanácsot. Ha ilyet kérdeznek, kedvesen \ terhességet vagy biztos eseményeket, és ne adj orvosi, jogi vagy pénzügyi tanácsot. Ha ilyet kérdeznek, kedvesen \
tereld a választ arra, amit az asztrológia valóban mutat: hajlamokra, időszakokra, lehetőségekre. tereld a választ arra, amit az asztrológia valóban mutat: hajlamokra, időszakokra, lehetőségekre.
@@ -490,7 +492,8 @@ használhatsz.
} }
format!( format!(
"You are an experienced, warm and psychologically minded astrologer in the Sorsfonalak app. The reader has \ "You are an experienced, warm and psychologically minded astrologer in the Sorsfonalak app. The reader has \
received their detailed analysis (a natal chart interpretation or a yearly forecast) and now asks a question about it. \ received their detailed analysis (a natal chart interpretation, a relationship analysis or a yearly forecast) and now \
asks a question about it. \
Answer it. Answer it.
Write in {lang}. Write in {lang}.
@@ -499,7 +502,9 @@ Rules:
- Base the answer on the chart data and the analysis given. Never invent positions, aspects, houses or dates that are \ - Base the answer on the chart data and the analysis given. Never invent positions, aspects, houses or dates that are \
not listed. If the data cannot answer the question, say so honestly and describe what the chart does show about it. not listed. If the data cannot answer the question, say so honestly and describe what the chart does show about it.
- Stay consistent with the analysis; fill in details it did not cover from the chart data. - Stay consistent with the analysis; fill in details it did not cover from the chart data.
- Speak to the reader directly, in the informal second person. - Speak to the reader directly, in the informal second person. On a relationship analysis the reader is one of the \
two people (Person 1 and Person 2 in the data); when it is unclear which, speak to both. Do not assume their genders \
or the type of relationship.
- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents, pregnancy \ - Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents, pregnancy \
or certain events, and no medical, legal or financial advice; if asked, turn gently to what astrology does show \ or certain events, and no medical, legal or financial advice; if asked, turn gently to what astrology does show \
(tendencies, periods, opportunities). (tendencies, periods, opportunities).
@@ -0,0 +1,26 @@
-- Every failed attempt of an analysis, an answer or a prompt test run, for the
-- admin error log. No foreign keys: the log outlives deleted items. Kept for
-- 90 days (worker cleanup).
CREATE TABLE generation_errors (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now(),
source text NOT NULL CHECK (source IN ('analysis', 'question', 'preview')),
item_id uuid NOT NULL,
kind text NOT NULL,
model text NOT NULL,
attempt integer NOT NULL,
-- What happened next: tried again, the default model took over, or gave up.
outcome text NOT NULL CHECK (outcome IN ('retry', 'fallback', 'failed')),
error text NOT NULL,
seconds integer
);
CREATE INDEX generation_errors_created_idx ON generation_errors (created_at DESC);
CREATE INDEX generation_errors_item_idx ON generation_errors (item_id);
-- When the current text was asked for (a regeneration or an admin restart
-- sets it again): the waiting page counts from here.
ALTER TABLE analyses ADD COLUMN requested_at timestamptz NOT NULL DEFAULT now();
UPDATE analyses SET requested_at = created_at;
ALTER TABLE questions ADD COLUMN requested_at timestamptz NOT NULL DEFAULT now();
UPDATE questions SET requested_at = created_at;
+4
View File
@@ -20,3 +20,7 @@ SIGNUP_MODE=invite
# Image version; every deployment rewrites it # Image version; every deployment rewrites it
TAG=latest TAG=latest
# worker-ai: analyses and answers written at the same time.
# QUICK_CONCURRENCY=2 # summaries and answers
# ANALYSIS_CONCURRENCY=4 # detailed analyses and forecasts
+2 -1
View File
@@ -82,7 +82,8 @@ A Google OAuth kliensnél a `https://sorsfonalak.hu` címet fel kell venni az en
## Üzemeltetés ## Üzemeltetés
- Naplók: `docker compose logs -f backend worker` - Naplók: `docker compose logs -f backend worker worker-ai`
- A worker két konténerben fut, ugyanabból az image-ből: a `worker` küldi az e-maileket és takarít (`WORKER_TASKS=email,cleanup`, ide kerülnek a további háttérfeladatok is), a `worker-ai` írja az elemzéseket és a válaszokat (`WORKER_TASKS=analyses`, gyors és lassú sáv). A sávok mérete a szerver `.env` fájljában állítható (`QUICK_CONCURRENCY`, `ANALYSIS_CONCURRENCY`).
- Visszaállás korábbi verzióra: `.env`-ben `TAG=<régebbi hash>`, utána `docker compose up -d` - Visszaállás korábbi verzióra: `.env`-ben `TAG=<régebbi hash>`, utána `docker compose up -d`
- Mentés: naponta egy `pg_dump` a `/opt/sorsfonalak/backups` mappába, 14 napig megmarad. A mentéseket érdemes a szerverről is elvinni (DigitalOcean backup, vagy `rsync` otthonra). - Mentés: naponta egy `pg_dump` a `/opt/sorsfonalak/backups` mappába, 14 napig megmarad. A mentéseket érdemes a szerverről is elvinni (DigitalOcean backup, vagy `rsync` otthonra).
- Visszatöltés: `gunzip -c backups/sorsfonalak-<dátum>.sql.gz | docker compose exec -T postgres psql -U sorsfonalak sorsfonalak` - Visszatöltés: `gunzip -c backups/sorsfonalak-<dátum>.sql.gz | docker compose exec -T postgres psql -U sorsfonalak sorsfonalak`
+24
View File
@@ -99,10 +99,12 @@ services:
logging: *logging logging: *logging
restart: unless-stopped restart: unless-stopped
# E-mail delivery, cleanup and the other background jobs.
worker: worker:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest} image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
environment: environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
WORKER_TASKS: email,cleanup
# SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md); # SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md);
# listing them here with an empty default would override that file. # listing them here with an empty default would override that file.
SES_REGION: ${SES_REGION:-eu-central-1} SES_REGION: ${SES_REGION:-eu-central-1}
@@ -118,11 +120,33 @@ services:
logging: *logging logging: *logging
restart: unless-stopped restart: unless-stopped
# The same image writing the analyses and answers (quick and slow lane);
# OPENROUTER_API_KEY comes from .env.secrets.
worker-ai:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
WORKER_TASKS: analyses
QUICK_CONCURRENCY: ${QUICK_CONCURRENCY:-2}
ANALYSIS_CONCURRENCY: ${ANALYSIS_CONCURRENCY:-4}
PUBLIC_BASE_URL: https://${DOMAIN}
env_file:
- path: .env.secrets
required: false
depends_on:
postgres:
condition: service_healthy
read_only: true
logging: *logging
restart: unless-stopped
frontend: frontend:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest} image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest}
environment: environment:
BACKEND_URL: http://backend:8081 BACKEND_URL: http://backend:8081
HOROSCOPE_API_URL: http://horoscope-api:8080 HOROSCOPE_API_URL: http://horoscope-api:8080
# Absolute links of the share previews (og:image).
PUBLIC_BASE_URL: https://${DOMAIN}
depends_on: depends_on:
backend: backend:
condition: service_healthy condition: service_healthy
+3 -2
View File
@@ -1,13 +1,14 @@
# Kérdések az elemzésekről # Kérdések az elemzésekről
A kész részletes képletelemzés és éves előrejelzés alatt a felhasználó kérdezhet róla („Kérdezz az elemzésedről”). Minden kérdés egy `question` egységet használ; minden csomagban 3 jár, és külön is vehető (+5 kérdés, 1 000 Ft). Admin ingyen kérdez. A kész részletes képletelemzés, kapcsolati elemzés és éves előrejelzés alatt a felhasználó kérdezhet róla („Kérdezz az elemzésedről”). Minden kérdés egy `question` egységet használ; minden csomagban 3 jár, és külön is vehető (+5 kérdés, 1 000 Ft). Admin ingyen kérdez.
## Hogyan készül a válasz ## Hogyan készül a válasz
- **Modell:** a Modellek oldalon külön beállítható kérdés-válasz modell (alapból Opus 5.5). Ha a választott modell hibára fut, az alapmodell válaszol (tartalék). - **Modell:** a Modellek oldalon külön beállítható kérdés-válasz modell (alapból Opus 5.5). Ha a választott modell hibára fut, az alapmodell válaszol (tartalék).
- **Amit a modell kap:** a képlet tömör adatsorát (előrejelzésnél az év adatait is), magát az elemzést, az ugyanerre az elemzésre feltett korábbi legfeljebb 6 kérdést a válasszal, és az új kérdést. Születési dátum, hely, idő és név nem megy ki. - **Amit a modell kap:** a képlet tömör adatsorát (kapcsolati elemzésnél mindkét képletet és az összevetést, előrejelzésnél az év adatait is), magát az elemzést, az ugyanerre az elemzésre feltett korábbi legfeljebb 6 kérdést a válasszal, és az új kérdést. Születési dátum, hely, idő és név nem megy ki.
- **Prompt:** az admin felületen szerkeszthető (Promptok → Kérdés-válasz). A szóhatár (`QUESTION_MAX_WORDS` = 250) a felhasználói üzenetben is benne van, így a prompt átírásától sem vész el. A kérdés legfeljebb 600 karakter. - **Prompt:** az admin felületen szerkeszthető (Promptok → Kérdés-válasz). A szóhatár (`QUESTION_MAX_WORDS` = 250) a felhasználói üzenetben is benne van, így a prompt átírásától sem vész el. A kérdés legfeljebb 600 karakter.
- **Szabályok:** csak a képletből és az elemzésből válaszol, nem jósol betegséget, halált, balesetet, terhességet vagy biztos eseményt, nem ad orvosi, jogi, pénzügyi tanácsot; a nem asztrológiai kérdést udvariasan elhárítja; a kérdésben lévő utasításokat nem követi. - **Szabályok:** csak a képletből és az elemzésből válaszol, nem jósol betegséget, halált, balesetet, terhességet vagy biztos eseményt, nem ad orvosi, jogi, pénzügyi tanácsot; a nem asztrológiai kérdést udvariasan elhárítja; a kérdésben lévő utasításokat nem követi.
- **Kapcsolati elemzés:** az összevetés mindkét tagja kérdezhet (a saját kérdéseiből), és mindketten látják a kérdéseket és a válaszokat.
- **Egyszerre egy:** amíg egy kérdésre készül a válasz, újabb nem tehető fel ugyanarra az elemzésre (így a válaszok egymásra épülnek). - **Egyszerre egy:** amíg egy kérdésre készül a válasz, újabb nem tehető fel ugyanarra az elemzésre (így a válaszok egymásra épülnek).
- **Hiba:** a worker újrapróbálja, mint az elemzéseket; végleges hibánál a kérdést visszaadja (egyszer). - **Hiba:** a worker újrapróbálja, mint az elemzéseket; végleges hibánál a kérdést visszaadja (egyszer).
- **Újragenerálás:** admin a válasz melletti ↻ gombbal újraírathatja (díjmentesen). - **Újragenerálás:** admin a válasz melletti ↻ gombbal újraírathatja (díjmentesen).
+32
View File
@@ -0,0 +1,32 @@
# Megosztás
A képletoldalon, a rövid összefoglaló alatt van a **Megosztás** gomb. Ez egy nyilvános linket ad (`/s/<kód>`), amelyen a képlet rajza és a legfrissebb rövid összefoglaló látszik. Név és születési adatok nem kerülnek rá.
- **Ugyanaz a link:** ha ugyanazt a képletet újra megosztod, a már nyitott link jön vissza (`POST /v1/shares`: új linknél 201, meglévőnél 200).
- **Visszavonás:** a „Link visszavonása” gomb után az oldal és a kép is 404-et ad.
- **Keresők:** az oldal `noindex`, a keresők nem listázzák.
## Előnézet (Facebook, Messenger, WhatsApp, LinkedIn, X)
Az oldal `og:` és `twitter:` meta tagjei:
| Tag | Tartalom |
|---|---|
| cím | az összefoglaló címe |
| leírás | az összefoglaló első ~200 karaktere |
| kép | `/s/<kód>/kep/<verzió>.png` |
A kép egy 1200×630-as PNG. A Next.js beépített képgenerálója (`next/og`) készíti kérésre, a következőkkel:
- a radix (`src/lib/wheelSvg.ts`; ugyanaz a `<ChartWheel>`, mint az oldalon, beégetett színekkel);
- a cím és a szöveg eleje;
- a Nap, a Hold és az Aszcendens jegye.
Működése:
- **Betűtípusok:** a `src/assets/og` mappából olvassa őket. Hiányzó karakter miatt soha nem tölt le fontot az internetről, mert a nem betű, szám vagy írásjel karaktereket kiszűri.
- **Verzió:** a fájlnévben lévő verzió az összefoglaló azonosítójából és elkészültének idejéből készül. Ha az összefoglaló újragenerálódik, új címet kap a kép, és a Facebook újra letölti.
- **Gyorsítótár:** `Cache-Control: public, max-age=3600, s-maxage=86400`. A Cloudflare egy napig tartja, így egy visszavont link képe legfeljebb egy napig marad ott. A Facebook a saját példányát a saját szabályai szerint tartja meg, nagyjából 30 napig.
- **Frissítés kézzel:** a Facebook megosztás-ellenőrzőjében (Sharing Debugger) a „Scrape Again” gombbal.
A frontend a `PUBLIC_BASE_URL` alapján írja az abszolút címeket; élesben ez `https://${DOMAIN}`.
+2
View File
@@ -127,6 +127,8 @@ Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái
- **Fizetős rész:** a részletes elemzés darabra megy. A képletelemzés egy `natal`, a szinasztria-elemzés egy `synastry` egységet von le (`credit_ledger.unit`). Az egységek csomagvásárlásból (Stripe, később) vagy admin jóváírásból jönnek. Havi ingyenes keret nincs. - **Fizetős rész:** a részletes elemzés darabra megy. A képletelemzés egy `natal`, a szinasztria-elemzés egy `synastry` egységet von le (`credit_ledger.unit`). Az egységek csomagvásárlásból (Stripe, később) vagy admin jóváírásból jönnek. Havi ingyenes keret nincs.
- **Modell:** három beállítás az admin felületen, az OpenRouter listájából (`model_settings` tábla): az elemzések és az éves előrejelzés (képlet-, kapcsolati elemzés, előrejelzés) közös modellje, a kérdés-válasz modellje és a rövid összefoglalóé. Ha nincs beállítva, az `ANALYSIS_MODEL` / `SUMMARY_MODEL` (alapból mindkettő Opus 5.5, a 2026-11-es összevetés legjobbja, lásd `services/worker/README.md`). Csak kötött JSON-választ adó modell választható. A kliens nem választ modellt, és a modell neve felhasználónak sehol nem jelenik meg. - **Modell:** három beállítás az admin felületen, az OpenRouter listájából (`model_settings` tábla): az elemzések és az éves előrejelzés (képlet-, kapcsolati elemzés, előrejelzés) közös modellje, a kérdés-válasz modellje és a rövid összefoglalóé. Ha nincs beállítva, az `ANALYSIS_MODEL` / `SUMMARY_MODEL` (alapból mindkettő Opus 5.5, a 2026-11-es összevetés legjobbja, lásd `services/worker/README.md`). Csak kötött JSON-választ adó modell választható. A kliens nem választ modellt, és a modell neve felhasználónak sehol nem jelenik meg.
- **Tartalék:** ha a választott modell kétszer hibára fut (végleges hibánál egyszer), a worker az alapmodellel próbálja tovább (`fallback_model`, `on_fallback`); csak ha az is elbukik, jár vissza az egység. A Modellek oldal mutatja, hány szövegnél kellett az elmúlt 30 napban. - **Tartalék:** ha a választott modell kétszer hibára fut (végleges hibánál egyszer), a worker az alapmodellel próbálja tovább (`fallback_model`, `on_fallback`); csak ha az is elbukik, jár vissza az egység. A Modellek oldal mutatja, hány szövegnél kellett az elmúlt 30 napban.
- **Hibanapló:** a worker minden sikertelen próbálkozást a `generation_errors` táblába ír (mi, melyik modell, hányadik kísérlet, mi lett: újrapróbálás, tartalék vagy végleges hiba, mennyi ideig tartott); az admin Hibanapló oldala mutatja (`GET /v1/admin/errors?source=&outcome=`), 90 napig őrizzük. A felhasználó a várakozó oldalon látja, ha az előző próbálkozás nem sikerült és újrapróbáljuk; a számláló a kérés idejétől (`requested_at`) mér.
- **Futó generálások:** a Modellek oldalon látszik minden készülő és sorban álló elemzés és válasz, a modelljével és azzal, amivel most indulna; újraindításkor a jelenlegi beállítással indul újra (`GET /v1/admin/jobs`, `POST /v1/admin/jobs/restart`). Minden kísérlet `started_at` értéke a „jegye”: az újraindítás törli, így a workerben még futó régi kísérlet nem írhatja felül az újat, és a worker 10 másodpercen belül eldobja.
- **Újragenerálás:** admin minden elemzést egyenként újraírathat (`POST /v1/admin/analyses/{id}/regenerate`): ugyanaz a sor (az azonosító és a megosztások maradnak), a jelenlegi prompttal és modellel, egységlevonás nélkül. - **Újragenerálás:** admin minden elemzést egyenként újraírathat (`POST /v1/admin/analyses/{id}/regenerate`): ugyanaz a sor (az azonosító és a megosztások maradnak), a jelenlegi prompttal és modellel, egységlevonás nélkül.
- **Újraszámolás:** számítási változás után a `backend recalculate` parancs minden mentett képletet, összevetést és előrejelzést újraszámol, majd minden elemzést újra sorba állít (egységlevonás nélkül). - **Újraszámolás:** számítási változás után a `backend recalculate` parancs minden mentett képletet, összevetést és előrejelzést újraszámol, majd minden elemzést újra sorba állít (egységlevonás nélkül).
- **Kérés:** a `POST .../analyses` (`{language?}`) létrehoz egy `pending` elemzést, és levon egy egységet; a szöveget a worker írja meg, általában 1–2 perc alatt. A kliens a `GET /v1/analyses/{id}` végponton kérdezi le az állapotát. Ha nincs egység, 402 `insufficient_credits` a válasz (`unit`, `balance` részletekkel). Hiba esetén a worker visszaadja az egységet. - **Kérés:** a `POST .../analyses` (`{language?}`) létrehoz egy `pending` elemzést, és levon egy egységet; a szöveget a worker írja meg, általában 1–2 perc alatt. A kliens a `GET /v1/analyses/{id}` végponton kérdezi le az állapotát. Ha nincs egység, 402 `insufficient_credits` a válasz (`unit`, `balance` részletekkel). Hiba esetén a worker visszaadja az egységet.
+23 -24
View File
@@ -49,11 +49,16 @@ pub struct AnalysisRow {
pub credits_charged: i32, pub credits_charged: i32,
pub created_at: OffsetDateTime, pub created_at: OffsetDateTime,
pub completed_at: Option<OffsetDateTime>, pub completed_at: Option<OffsetDateTime>,
/// Attempts so far; above 1 the page says it is being tried again.
pub attempts: i32,
pub next_attempt_at: OffsetDateTime,
/// When the current text was asked for (set again by a regeneration).
pub requested_at: OffsetDateTime,
} }
const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \ const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
content, error, \ content, error, \
credits_charged, created_at, completed_at"; credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at";
impl AnalysisRow { impl AnalysisRow {
pub fn view(&self) -> Value { pub fn view(&self) -> Value {
@@ -71,6 +76,9 @@ impl AnalysisRow {
"credits_charged": self.credits_charged, "credits_charged": self.credits_charged,
"created_at": rfc3339(self.created_at), "created_at": rfc3339(self.created_at),
"completed_at": rfc3339_opt(self.completed_at), "completed_at": rfc3339_opt(self.completed_at),
"attempts": self.attempts,
"next_attempt_at": rfc3339(self.next_attempt_at),
"requested_at": rfc3339(self.requested_at),
}) })
} }
} }
@@ -146,7 +154,7 @@ async fn request(
/// The cache key and the prompt version of a new analysis. The cache key leaves /// The cache key and the prompt version of a new analysis. The cache key leaves
/// out the admin-edited prompt revision, so a chart keeps its analysis when the /// out the admin-edited prompt revision, so a chart keeps its analysis when the
/// prompt changes; copying from another chart needs the same revision. /// prompt changes; copying from another chart needs the same revision.
async fn versions( pub(super) async fn versions(
state: &AppState, state: &AppState,
kind: &str, kind: &str,
hash: &str, hash: &str,
@@ -359,6 +367,17 @@ pub async fn request_for_forecast(
request(&state, &auth, Target::Forecast { forecast_id: forecast.id, hash: forecast.forecast_hash }, req).await request(&state, &auth, Target::Forecast { forecast_id: forecast.id, hash: forecast.forecast_hash }, req).await
} }
/// The hash of what the analysis is about (chart, comparison or forecast),
/// part of its cache key; `None` when that was deleted.
pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result<Option<String>, sqlx::Error> {
let (query, id) = match row.kind.as_str() {
"synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id),
"forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id),
_ => ("SELECT chart_hash FROM charts WHERE id = $1", row.chart_id),
};
sqlx::query_scalar(query).bind(id).fetch_optional(db).await
}
/// Admin: writes an analysis again in place (same id, so links stay), with the /// Admin: writes an analysis again in place (same id, so links stay), with the
/// current prompt and model. Nobody is charged. /// current prompt and model. Nobody is charged.
pub async fn regenerate( pub async fn regenerate(
@@ -371,27 +390,7 @@ pub async fn regenerate(
return Err(ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül.")); return Err(ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül."));
} }
let kind = Kind::parse(&row.kind).ok_or_else(|| ApiError::Internal(format!("unknown kind {}", row.kind)))?; let kind = Kind::parse(&row.kind).ok_or_else(|| ApiError::Internal(format!("unknown kind {}", row.kind)))?;
let hash: Option<String> = match kind { let hash = target_hash(&state.db, &row).await?;
Kind::Question => None,
Kind::Natal | Kind::Summary => {
sqlx::query_scalar("SELECT chart_hash FROM charts WHERE id = $1")
.bind(row.chart_id)
.fetch_optional(&state.db)
.await?
}
Kind::Synastry => {
sqlx::query_scalar("SELECT synastry_hash FROM synastries WHERE id = $1")
.bind(row.synastry_id)
.fetch_optional(&state.db)
.await?
}
Kind::Forecast => {
sqlx::query_scalar("SELECT forecast_hash FROM forecasts WHERE id = $1")
.bind(row.forecast_id)
.fetch_optional(&state.db)
.await?
}
};
let hash = hash.ok_or(ApiError::NotFound("analysis"))?; let hash = hash.ok_or(ApiError::NotFound("analysis"))?;
let (model, fallback) = crate::models::models_for(&state, kind).await?; let (model, fallback) = crate::models::models_for(&state, kind).await?;
let (cache_key, prompt_version) = versions(&state, kind.as_str(), &hash, &model, &row.language).await?; let (cache_key, prompt_version) = versions(&state, kind.as_str(), &hash, &model, &row.language).await?;
@@ -400,7 +399,7 @@ pub async fn regenerate(
"UPDATE analyses SET status = 'pending', content = NULL, error = NULL, model_used = NULL, \ "UPDATE analyses SET status = 'pending', content = NULL, error = NULL, model_used = NULL, \
input_tokens = NULL, output_tokens = NULL, cost_usd = NULL, attempts = 0, next_attempt_at = now(), \ input_tokens = NULL, output_tokens = NULL, cost_usd = NULL, attempts = 0, next_attempt_at = now(), \
started_at = NULL, completed_at = NULL, model = $2, prompt_version = $3, cache_key = $4, \ started_at = NULL, completed_at = NULL, model = $2, prompt_version = $3, cache_key = $4, \
fallback_model = $5, on_fallback = false \ fallback_model = $5, on_fallback = false, requested_at = now() \
WHERE id = $1 AND status IN ('done', 'failed') RETURNING {ANALYSIS_COLUMNS}" WHERE id = $1 AND status IN ('done', 'failed') RETURNING {ANALYSIS_COLUMNS}"
)) ))
.bind(id) .bind(id)
+73
View File
@@ -0,0 +1,73 @@
//! Admin: the error log of the analyses, answers and prompt test runs (every
//! failed attempt, written by the worker), newest first.
use axum::Json;
use axum::extract::{Query, State};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::St;
use crate::auth::AdminUser;
use crate::error::{ApiError, ApiResult};
use crate::views::rfc3339;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ErrorQuery {
limit: Option<i64>,
offset: Option<i64>,
/// `analysis`, `question` or `preview`.
source: Option<String>,
/// `retry`, `fallback` or `failed`.
outcome: Option<String>,
}
type Row = (i64, OffsetDateTime, String, Uuid, String, String, i32, String, String, Option<i32>, Option<String>);
pub async fn list(
State(state): St,
_admin: AdminUser,
WithRejection(Query(query), _): WithRejection<Query<ErrorQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let limit = query.limit.unwrap_or(100).clamp(1, 500);
let offset = query.offset.unwrap_or(0).max(0);
// Whose text it was: the requester of the analysis or the asker.
let rows: Vec<Row> = sqlx::query_as(
"SELECT e.id, e.created_at, e.source, e.item_id, e.kind, e.model, e.attempt, e.outcome, e.error, e.seconds, \
u.email \
FROM generation_errors e \
LEFT JOIN analyses a ON e.source = 'analysis' AND a.id = e.item_id \
LEFT JOIN questions q ON e.source = 'question' AND q.id = e.item_id \
LEFT JOIN prompt_previews p ON e.source = 'preview' AND p.id = e.item_id \
LEFT JOIN users u ON u.id = coalesce(a.requested_by, q.asked_by, p.created_by) \
WHERE ($1::text IS NULL OR e.source = $1) AND ($2::text IS NULL OR e.outcome = $2) \
ORDER BY e.id DESC LIMIT $3 OFFSET $4",
)
.bind(&query.source)
.bind(&query.outcome)
.bind(limit)
.bind(offset)
.fetch_all(&state.db)
.await?;
let (total, last_day): (i64, i64) = sqlx::query_as(
"SELECT count(*), count(*) FILTER (WHERE created_at > now() - interval '1 day') FROM generation_errors \
WHERE ($1::text IS NULL OR source = $1) AND ($2::text IS NULL OR outcome = $2)",
)
.bind(&query.source)
.bind(&query.outcome)
.fetch_one(&state.db)
.await?;
let errors: Vec<Value> = rows
.into_iter()
.map(|(id, at, source, item, kind, model, attempt, outcome, error, seconds, email)| {
json!({
"id": id, "created_at": rfc3339(at), "source": source, "item_id": item, "kind": kind, "model": model,
"attempt": attempt, "outcome": outcome, "error": error, "seconds": seconds, "user": email,
})
})
.collect();
Ok(Json(json!({ "errors": errors, "total": total, "last_day": last_day, "limit": limit, "offset": offset })))
}
+150
View File
@@ -0,0 +1,150 @@
//! Admin: the analyses and answers being written or waiting in the queue,
//! and restarting them with the models set now (e.g. after switching away
//! from a slow model). A restarted attempt that is still running in the
//! worker is dropped there and cannot overwrite the new one.
use std::collections::HashMap;
use analysis_prompt::Kind;
use axum::Json;
use axum::extract::State;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
use uuid::Uuid;
use super::analyses::{find_analysis, target_hash, versions};
use super::{Body, St};
use crate::AppState;
use crate::auth::AdminUser;
use crate::error::ApiResult;
use crate::models::{Function, models_for};
use crate::views::{rfc3339, rfc3339_opt};
type JobRow = (
Uuid,
String,
String,
String,
Option<String>,
bool,
i32,
Option<OffsetDateTime>,
OffsetDateTime,
OffsetDateTime,
Option<String>,
);
const COLUMNS: &str =
"id, kind, status, model, fallback_model, on_fallback, attempts, started_at, created_at, next_attempt_at, error";
async fn open_jobs(state: &AppState) -> Result<Vec<(&'static str, JobRow)>, sqlx::Error> {
let analyses: Vec<JobRow> = sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM analyses WHERE status IN ('pending', 'running') ORDER BY created_at"
))
.fetch_all(&state.db)
.await?;
let questions: Vec<JobRow> = sqlx::query_as(
"SELECT id, 'question', status, model, fallback_model, on_fallback, attempts, started_at, created_at, \
next_attempt_at, error \
FROM questions WHERE status IN ('pending', 'running') ORDER BY created_at",
)
.fetch_all(&state.db)
.await?;
Ok(analyses.into_iter().map(|r| ("analysis", r)).chain(questions.into_iter().map(|r| ("question", r))).collect())
}
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
Ok(Json(json!({ "jobs": views(&state).await? })))
}
async fn views(state: &AppState) -> Result<Vec<Value>, sqlx::Error> {
// The models a restart would use, per function.
let mut next: HashMap<&'static str, (String, Option<String>)> = HashMap::new();
for (function, kind) in
[(Function::Summary, Kind::Summary), (Function::Analysis, Kind::Natal), (Function::Question, Kind::Question)]
{
next.insert(function.key(), models_for(state, kind).await?);
}
Ok(open_jobs(state)
.await?
.into_iter()
.map(|(table, (id, kind, status, model, fallback, on_fallback, attempts, started, created, due, error))| {
let function = Function::of(Kind::parse(&kind).unwrap_or(Kind::Natal)).key();
let (next_model, next_fallback) = &next[function];
let active = if on_fallback { fallback.clone().unwrap_or_else(|| model.clone()) } else { model.clone() };
json!({
"id": id, "type": table, "kind": kind, "status": status, "model": active, "on_fallback": on_fallback,
"next_model": next_model, "next_fallback": next_fallback, "attempts": attempts,
"started_at": rfc3339_opt(started), "created_at": rfc3339(created), "next_attempt_at": rfc3339(due),
"error": error,
})
})
.collect())
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Restart {
/// The jobs to restart; all open ones when missing.
ids: Option<Vec<Uuid>>,
}
pub async fn restart(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Json(req), _): Body<Restart>,
) -> ApiResult<Json<Value>> {
let mut restarted = 0;
for (table, (id, kind, ..)) in open_jobs(&state).await? {
if req.ids.as_ref().is_some_and(|ids| !ids.contains(&id)) {
continue;
}
let done = if table == "question" {
let language: String = sqlx::query_scalar("SELECT language FROM questions WHERE id = $1")
.bind(id)
.fetch_one(&state.db)
.await?;
let (model, fallback, prompt_version) = super::questions::model_and_version(&state, &language).await?;
sqlx::query(
"UPDATE questions SET status = 'pending', model = $2, fallback_model = $3, on_fallback = false, \
prompt_version = $4, attempts = 0, next_attempt_at = now(), started_at = NULL, error = NULL, \
requested_at = now() \
WHERE id = $1 AND status IN ('pending', 'running')",
)
.bind(id)
.bind(&model)
.bind(&fallback)
.bind(&prompt_version)
.execute(&state.db)
.await?
.rows_affected()
} else {
let Some(row) = find_analysis(&state.db, id).await? else { continue };
let Some(hash) = target_hash(&state.db, &row).await? else { continue };
let (model, fallback) = models_for(&state, Kind::parse(&kind).unwrap_or(Kind::Natal)).await?;
let (cache_key, prompt_version) = versions(&state, &kind, &hash, &model, &row.language).await?;
sqlx::query(
"UPDATE analyses SET status = 'pending', model = $2, fallback_model = $3, on_fallback = false, \
cache_key = $4, prompt_version = $5, attempts = 0, next_attempt_at = now(), started_at = NULL, \
error = NULL, requested_at = now() \
WHERE id = $1 AND status IN ('pending', 'running')",
)
.bind(id)
.bind(&model)
.bind(&fallback)
.bind(&cache_key)
.bind(&prompt_version)
.execute(&state.db)
.await?
.rows_affected()
};
restarted += done;
}
if restarted > 0 {
sqlx::query("SELECT pg_notify('analyses', '')").execute(&state.db).await?;
}
tracing::info!(admin = %admin.id(), restarted, "generations restarted");
Ok(Json(json!({ "restarted": restarted, "jobs": views(&state).await? })))
}
+5
View File
@@ -10,8 +10,10 @@ mod admin;
mod analyses; mod analyses;
mod auth; mod auth;
mod charts; mod charts;
mod errors;
mod forecasts; mod forecasts;
mod invitations; mod invitations;
mod jobs;
mod models; mod models;
mod payments; mod payments;
mod prompts; mod prompts;
@@ -116,6 +118,9 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save)) .route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview)) .route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
.route("/v1/admin/previews/{id}", get(prompts::get_preview)) .route("/v1/admin/previews/{id}", get(prompts::get_preview))
.route("/v1/admin/errors", get(errors::list))
.route("/v1/admin/jobs", get(jobs::list))
.route("/v1/admin/jobs/restart", post(jobs::restart))
.route("/v1/admin/models", get(models::list)) .route("/v1/admin/models", get(models::list))
.route("/v1/admin/models/catalog", get(models::catalog)) .route("/v1/admin/models/catalog", get(models::catalog))
.route("/v1/admin/models/{kind}", axum::routing::put(models::save)) .route("/v1/admin/models/{kind}", axum::routing::put(models::save))
+16 -8
View File
@@ -1,5 +1,6 @@
//! Questions about a finished detailed analysis: a natal chart analysis or a //! Questions about a finished detailed analysis: a natal chart analysis, a
//! yearly forecast. Each question uses a `question` unit (admins ask for //! relationship (synastry) analysis or a yearly forecast. On a comparison both
//! people see the questions and answers. Each question uses a `question` unit (admins ask for
//! free). The worker answers with the question model of the admin page, //! free). The worker answers with the question model of the admin page,
//! seeing the chart data, the analysis and the earlier questions about it. //! seeing the chart data, the analysis and the earlier questions about it.
@@ -23,7 +24,7 @@ use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, rfc3339_opt}; use crate::views::{rfc3339, rfc3339_opt};
/// The analyses that can be asked about. /// The analyses that can be asked about.
const ASKABLE: [&str; 2] = ["natal", "forecast"]; const ASKABLE: [&str; 3] = ["natal", "synastry", "forecast"];
/// A safety cap per analysis. /// A safety cap per analysis.
const MAX_PER_ANALYSIS: i64 = 100; const MAX_PER_ANALYSIS: i64 = 100;
@@ -39,10 +40,13 @@ pub struct QuestionRow {
pub credits_charged: i32, pub credits_charged: i32,
pub created_at: OffsetDateTime, pub created_at: OffsetDateTime,
pub completed_at: Option<OffsetDateTime>, pub completed_at: Option<OffsetDateTime>,
pub attempts: i32,
pub next_attempt_at: OffsetDateTime,
pub requested_at: OffsetDateTime,
} }
const QUESTION_COLUMNS: &str = const QUESTION_COLUMNS: &str = "id, analysis_id, question, status, answer, error, credits_charged, created_at, \
"id, analysis_id, question, status, answer, error, credits_charged, created_at, completed_at"; completed_at, attempts, next_attempt_at, requested_at";
impl QuestionRow { impl QuestionRow {
pub fn view(&self) -> Value { pub fn view(&self) -> Value {
@@ -56,6 +60,9 @@ impl QuestionRow {
"credits_charged": self.credits_charged, "credits_charged": self.credits_charged,
"created_at": rfc3339(self.created_at), "created_at": rfc3339(self.created_at),
"completed_at": rfc3339_opt(self.completed_at), "completed_at": rfc3339_opt(self.completed_at),
"attempts": self.attempts,
"next_attempt_at": rfc3339(self.next_attempt_at),
"requested_at": rfc3339(self.requested_at),
}) })
} }
} }
@@ -66,7 +73,7 @@ async fn find_question(db: &PgPool, id: Uuid) -> Result<Option<QuestionRow>, sql
/// The question model (and its fallback) and the version of the question /// The question model (and its fallback) and the version of the question
/// prompt in force. /// prompt in force.
async fn model_and_version( pub(super) async fn model_and_version(
state: &crate::AppState, state: &crate::AppState,
language: &str, language: &str,
) -> Result<(String, Option<String>, String), sqlx::Error> { ) -> Result<(String, Option<String>, String), sqlx::Error> {
@@ -109,7 +116,7 @@ pub async fn ask(
return Err(ApiError::NotFound("analysis")); return Err(ApiError::NotFound("analysis"));
} }
if !ASKABLE.contains(&analysis.kind.as_str()) { if !ASKABLE.contains(&analysis.kind.as_str()) {
return Err(ApiError::BadRequest("questions can be asked about a natal analysis or a forecast".into())); return Err(ApiError::BadRequest("questions can be asked about a detailed analysis or a forecast".into()));
} }
if analysis.status != "done" { if analysis.status != "done" {
return Err(ApiError::conflict("analysis_not_ready", "Az elemzés még nem készült el.")); return Err(ApiError::conflict("analysis_not_ready", "Az elemzés még nem készült el."));
@@ -191,7 +198,8 @@ pub async fn regenerate(
let row: QuestionRow = sqlx::query_as(&format!( let row: QuestionRow = sqlx::query_as(&format!(
"UPDATE questions SET status = 'pending', answer = NULL, error = NULL, model_used = NULL, input_tokens = NULL, \ "UPDATE questions SET status = 'pending', answer = NULL, error = NULL, model_used = NULL, input_tokens = NULL, \
output_tokens = NULL, cost_usd = NULL, attempts = 0, next_attempt_at = now(), started_at = NULL, \ output_tokens = NULL, cost_usd = NULL, attempts = 0, next_attempt_at = now(), started_at = NULL, \
completed_at = NULL, model = $2, prompt_version = $3, fallback_model = $4, on_fallback = false \ completed_at = NULL, model = $2, prompt_version = $3, fallback_model = $4, on_fallback = false, \
requested_at = now() \
WHERE id = $1 AND status IN ('done', 'failed') RETURNING {QUESTION_COLUMNS}" WHERE id = $1 AND status IN ('done', 'failed') RETURNING {QUESTION_COLUMNS}"
)) ))
.bind(id) .bind(id)
+44
View File
@@ -1,6 +1,9 @@
//! Public sharing links. Creating and revoking a link needs login; opening //! Public sharing links. Creating and revoking a link needs login; opening
//! one (`GET /v1/public/shares/{slug}`) does not. The public view never //! one (`GET /v1/public/shares/{slug}`) does not. The public view never
//! contains birth data unless the owner allowed it for their own chart. //! contains birth data unless the owner allowed it for their own chart.
//! A shared chart comes with its newest short summary (the share page and
//! its preview image show both). Sharing the same thing again returns the
//! link that is already open.
use axum::Json; use axum::Json;
use axum::extract::{Path, State}; use axum::extract::{Path, State};
@@ -109,6 +112,24 @@ pub async fn create(
} }
}; };
let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty()); let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty());
let open: Option<ShareRow> = sqlx::query_as(&format!(
"SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \
AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \
AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \
ORDER BY created_at DESC LIMIT 1"
))
.bind(auth.id())
.bind(kind)
.bind(chart_id)
.bind(synastry_id)
.bind(analysis_id)
.bind(&title)
.bind(req.show_birth_data)
.fetch_optional(&state.db)
.await?;
if let Some(row) = open {
return Ok((StatusCode::OK, Json(row.view(&state.config.public_base_url))));
}
let row: ShareRow = sqlx::query_as(&format!( let row: ShareRow = sqlx::query_as(&format!(
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data) \ "INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {SHARE_COLUMNS}" VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {SHARE_COLUMNS}"
@@ -175,6 +196,7 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
if let Some(chart_id) = share.chart_id { if let Some(chart_id) = share.chart_id {
let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?; let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?;
body["chart"] = public_chart_block(&chart, share); body["chart"] = public_chart_block(&chart, share);
body["summary"] = latest_summary(db, chart_id).await?;
} else if let Some(synastry_id) = share.synastry_id { } else if let Some(synastry_id) = share.synastry_id {
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?; let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
body["synastry"] = public_synastry_block(&s, share); body["synastry"] = public_synastry_block(&s, share);
@@ -198,6 +220,28 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
Ok(body) Ok(body)
} }
/// The newest finished short summary of a chart (`null` if none).
async fn latest_summary(db: &PgPool, chart_id: Uuid) -> Result<Value, sqlx::Error> {
type Row = (Uuid, String, Option<Value>, Option<OffsetDateTime>);
let row: Option<Row> = sqlx::query_as(
"SELECT id, language, content, completed_at FROM analyses \
WHERE chart_id = $1 AND kind = 'summary' AND status = 'done' ORDER BY completed_at DESC LIMIT 1",
)
.bind(chart_id)
.fetch_optional(db)
.await?;
Ok(match row {
Some((id, language, content, completed_at)) => json!({
"id": id,
"language": language,
"title": content.as_ref().and_then(|c| c["title"].as_str()),
"summary": content.as_ref().and_then(|c| c["summary"].as_str()),
"completed_at": rfc3339_opt(completed_at),
}),
None => Value::Null,
})
}
/// Public: the shared content for the share page and its OG image. /// Public: the shared content for the share page and its OG image.
pub async fn public_view(State(state): St, Path(slug): Path<String>) -> ApiResult<Json<Value>> { pub async fn public_view(State(state): St, Path(slug): Path<String>) -> ApiResult<Json<Value>> {
let share: ShareRow = sqlx::query_as(&format!( let share: ShareRow = sqlx::query_as(&format!(
+133
View File
@@ -628,6 +628,30 @@ async fn public_shares(pool: PgPool) {
for hidden in ["input", "location", "time", "astronomy", "birth"] { for hidden in ["input", "location", "time", "astronomy", "birth"] {
assert!(shown.get(hidden).is_none(), "{hidden} must not be public"); assert!(shown.get(hidden).is_none(), "{hidden} must not be public");
} }
assert!(r.body["summary"].is_null(), "no finished summary yet");
// the newest finished summary comes with the chart
sqlx::query(
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, \
credits_charged, status, content, completed_at) \
VALUES ($1, 'summary', $2::uuid, (SELECT id FROM users WHERE email = 'anna@example.com'), 'hu', 'm', 'v', \
'k', 0, 'done', $3, now())",
)
.bind(uuid::Uuid::now_v7())
.bind(chart_id)
.bind(json!({"title": "Csendes erő", "summary": "Rövid **összefoglaló**."}))
.execute(&app.pool)
.await
.unwrap();
let r = app.get(&format!("/v1/public/shares/{slug}"), None).await;
assert_eq!(r.body["summary"]["title"], "Csendes erő");
assert_eq!(r.body["summary"]["summary"], "Rövid **összefoglaló**.");
// sharing the same again gives the open link
let r = app
.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart_id, "title": "A radixom"}))
.await;
assert_eq!((r.status, r.body["slug"].as_str()), (StatusCode::OK, Some(slug.as_str())));
let r = app let r = app
.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart_id, "show_birth_data": true})) .post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart_id, "show_birth_data": true}))
@@ -761,6 +785,18 @@ async fn synastry_analyses_use_synastry_units(pool: PgPool) {
app.get("/v1/credits", Some(&anna)).await.body["balance"], app.get("/v1/credits", Some(&anna)).await.body["balance"],
json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 0}) json!({"natal": 1, "synastry": 0, "forecast": 0, "question": 0})
); );
// questions can be asked about the relationship analysis too
let analysis = r.body["id"].as_str().unwrap().to_string();
sqlx::query("UPDATE analyses SET status = 'done', content = '{\"title\": \"Kettőtök\"}' WHERE kind = 'synastry'")
.execute(&app.pool)
.await
.unwrap();
grant_units(&app, &anna, "question", 1).await;
let r = app
.post(&format!("/v1/analyses/{analysis}/questions"), Some(&anna), json!({"question": "Mire figyeljünk?"}))
.await;
assert_eq!((r.status, r.body["status"].as_str()), (StatusCode::ACCEPTED, Some("pending")), "{}", r.body);
} }
#[sqlx::test(migrator = "db::MIGRATOR")] #[sqlx::test(migrator = "db::MIGRATOR")]
@@ -1639,3 +1675,100 @@ async fn questions_about_an_analysis_use_question_units(pool: PgPool) {
); );
assert_eq!(left().await, json!(5), "regenerating charges nobody"); assert_eq!(left().await, json!(5), "regenerating charges nobody");
} }
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn admins_restart_open_generations_with_the_current_models(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let admin = app.register("admin@example.com", "Admin").await;
let anna = app.register("anna@example.com", "Anna").await;
assert_eq!(app.get("/v1/admin/jobs", Some(&anna)).await.status, StatusCode::FORBIDDEN);
let put = |model: &str| {
let (app, admin, body) = (&app, &admin, json!({ "model": model }));
async move { app.call("PUT", "/v1/admin/models/analysis", Some(admin), Some(body)).await }
};
assert_eq!(put("openai/gpt-x").await.status, StatusCode::OK);
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
let chart_id = chart["id"].as_str().unwrap();
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
let id = r.body["id"].as_str().unwrap().to_string();
// the worker is writing it with the chosen model
sqlx::query("UPDATE analyses SET status = 'running', started_at = now(), attempts = 1 WHERE id = $1::uuid")
.bind(&id)
.execute(&pool)
.await
.unwrap();
// after switching back to the default, the list shows what a restart would use
assert_eq!(
app.call("PUT", "/v1/admin/models/analysis", Some(&admin), Some(json!({"model": null}))).await.status,
StatusCode::OK
);
let jobs = app.get("/v1/admin/jobs", Some(&admin)).await.body["jobs"].clone();
let job = jobs.as_array().unwrap().iter().find(|j| j["id"] == json!(id)).expect("the analysis is listed");
assert_eq!(
(&job["status"], &job["model"], &job["next_model"]),
(&json!("running"), &json!("openai/gpt-x"), &json!("anthropic/claude-test"))
);
let r = app.post("/v1/admin/jobs/restart", Some(&admin), json!({ "ids": [id] })).await;
assert_eq!((r.status, &r.body["restarted"]), (StatusCode::OK, &json!(1)), "{}", r.body);
let (status, model, fallback, started, attempts): (
String,
String,
Option<String>,
Option<time::OffsetDateTime>,
i32,
) = sqlx::query_as("SELECT status, model, fallback_model, started_at, attempts FROM analyses WHERE id = $1::uuid")
.bind(&id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(
(status.as_str(), model.as_str(), fallback, started, attempts),
("pending", "anthropic/claude-test", None, None, 0)
);
// finished ones are left alone
sqlx::query("UPDATE analyses SET status = 'done', content = '{}'").execute(&pool).await.unwrap();
assert_eq!(app.post("/v1/admin/jobs/restart", Some(&admin), json!({})).await.body["restarted"], 0);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn admins_read_the_error_log(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let admin = app.register("admin@example.com", "Admin").await;
let anna = app.register("anna@example.com", "Anna").await;
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
let chart_id = chart["id"].as_str().unwrap();
let analysis: uuid::Uuid = sqlx::query_scalar("SELECT id FROM analyses WHERE chart_id = $1::uuid")
.bind(chart_id)
.fetch_one(&pool)
.await
.unwrap();
for (attempt, outcome) in [(1, "retry"), (2, "failed")] {
sqlx::query(
"INSERT INTO generation_errors (source, item_id, kind, model, attempt, outcome, error, seconds) \
VALUES ('analysis', $1, 'summary', 'cheap/model', $2, $3, 'answer cut off at the token limit', 301)",
)
.bind(analysis)
.bind(attempt)
.bind(outcome)
.execute(&pool)
.await
.unwrap();
}
assert_eq!(app.get("/v1/admin/errors", Some(&anna)).await.status, StatusCode::FORBIDDEN);
let r = app.get("/v1/admin/errors", Some(&admin)).await;
assert_eq!((r.status, &r.body["total"], &r.body["last_day"]), (StatusCode::OK, &json!(2), &json!(2)), "{}", r.body);
let first = &r.body["errors"][0];
assert_eq!(
(&first["outcome"], &first["attempt"], &first["user"], &first["seconds"]),
(&json!("failed"), &json!(2), &json!("anna@example.com"), &json!(301))
);
let r = app.get("/v1/admin/errors?outcome=retry", Some(&admin)).await;
assert_eq!(r.body["errors"].as_array().unwrap().len(), 1);
assert_eq!(app.get("/v1/admin/errors?source=question", Some(&admin)).await.body["total"], 0);
// users see the attempts of their analysis (the page says it is tried again)
let r = app.get(&format!("/v1/analyses/{analysis}"), Some(&anna)).await;
assert_eq!(r.body["attempts"], 0);
assert!(r.body["next_attempt_at"].is_string());
}
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+2
View File
@@ -4,6 +4,8 @@ const config: NextConfig = {
// Small self-contained server for the container image. // Small self-contained server for the container image.
output: "standalone", output: "standalone",
poweredByHeader: false, poweredByHeader: false,
// The fonts of the share preview images are read from disk at run time.
outputFileTracingIncludes: { "/s/[slug]/kep/[file]": ["./src/assets/og/*.ttf"] },
}; };
export default config; export default config;
@@ -37,6 +37,7 @@ export default async function PrivacyPage() {
<section> <section>
<h2>2. Milyen adatokat kezelünk, és miért?</h2> <h2>2. Milyen adatokat kezelünk, és miért?</h2>
<div className="table-wrap">
<table className="legal-table"> <table className="legal-table">
<thead> <thead>
<tr> <tr>
@@ -98,6 +99,7 @@ export default async function PrivacyPage() {
</tr> </tr>
</tbody> </tbody>
</table> </table>
</div>
<p> <p>
Bankkártyaadatot nem kezelünk és nem tárolunk; a fizetést, amikor elindul, külső fizetési szolgáltató Bankkártyaadatot nem kezelünk és nem tárolunk; a fizetést, amikor elindul, külső fizetési szolgáltató
végzi, akinek a neve itt lesz feltüntetve. végzi, akinek a neve itt lesz feltüntetve.
@@ -0,0 +1,155 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro";
import type { GenerationError } from "@/lib/types";
const PAGE = 100;
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
const KINDS: Record<string, string> = {
summary: "összefoglaló",
natal: "képletelemzés",
synastry: "kapcsolati",
forecast: "előrejelzés",
question: "válasz",
};
const OUTCOMES: Record<GenerationError["outcome"], { label: string; tone: string }> = {
retry: { label: "újrapróbálva", tone: "neutral" },
fallback: { label: "tartalék modell vette át", tone: "neutral" },
failed: { label: "végleg sikertelen", tone: "tense" },
};
interface Page {
errors: GenerationError[];
total: number;
last_day: number;
}
/** The admin error log with filters and paging. */
export function ErrorLog() {
const [source, setSource] = useState("");
const [outcome, setOutcome] = useState("");
const [errors, setErrors] = useState<GenerationError[] | null>(null);
const [total, setTotal] = useState(0);
const [lastDay, setLastDay] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(
async (offset: number) => {
setBusy(true);
setError(null);
const params = new URLSearchParams({ limit: String(PAGE), offset: String(offset) });
if (source) params.set("source", source);
if (outcome) params.set("outcome", outcome);
try {
const page = await api<Page>(`/admin/errors?${params}`);
setErrors((all) => (offset === 0 ? page.errors : [...(all ?? []), ...page.errors]));
setTotal(page.total);
setLastDay(page.last_day);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
},
[source, outcome],
);
useEffect(() => {
load(0);
}, [load]);
return (
<section className="card" style={{ gap: 12 }}>
<div className="row" style={{ gap: 12, flexWrap: "wrap", alignItems: "flex-end" }}>
<div className="field">
<label htmlFor="error-source">Mi</label>
<select id="error-source" className="inp" value={source} onChange={(e) => setSource(e.target.value)}>
<option value="">mind</option>
{Object.entries(SOURCES).map(([v, l]) => (
<option key={v} value={v}>
{l}
</option>
))}
</select>
</div>
<div className="field">
<label htmlFor="error-outcome">Következmény</label>
<select id="error-outcome" className="inp" value={outcome} onChange={(e) => setOutcome(e.target.value)}>
<option value="">mind</option>
{Object.entries(OUTCOMES).map(([v, o]) => (
<option key={v} value={v}>
{o.label}
</option>
))}
</select>
</div>
<p className="hint" style={{ margin: 0 }}>
{total} bejegyzés, ebből {lastDay} az elmúlt 24 órában
</p>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => load(0)} disabled={busy}>
Frissítés
</button>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{errors === null ? (
<p className="muted">Betöltés…</p>
) : errors.length === 0 ? (
<p className="muted">Nincs hiba. 🎉</p>
) : (
<div className="table-wrap">
<table className="error-log">
<thead>
<tr>
<th>Időpont</th>
<th>Mi</th>
<th>Modell</th>
<th>Kísérlet</th>
<th>Következmény</th>
<th>Hiba</th>
</tr>
</thead>
<tbody>
{errors.map((e) => (
<tr key={e.id}>
<td className="num">{formatDate(e.created_at, true)}</td>
<td>
{SOURCES[e.source] ?? e.source}
{e.source !== "question" && ` (${KINDS[e.kind] ?? e.kind})`}
{e.user && <span className="hint">{e.user}</span>}
<code className="hint" title={e.item_id}>
{e.item_id.slice(0, 8)}
</code>
</td>
<td>
<code>{e.model}</code>
</td>
<td className="num">
{e.attempt}.{e.seconds !== null && <span className="hint">{e.seconds} mp</span>}
</td>
<td>
<span className={`outcome tone-${OUTCOMES[e.outcome].tone}`}>{OUTCOMES[e.outcome].label}</span>
</td>
<td className="error-text">{e.error}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{errors && errors.length < total && (
<button type="button" className="btn btn-sm" onClick={() => load(errors.length)} disabled={busy}>
{busy ? "Betöltés…" : "Régebbiek"}
</button>
)}
</section>
);
}
@@ -0,0 +1,27 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { AdminNav } from "@/components/AdminNav";
import { requireMe } from "@/lib/server";
import { ErrorLog } from "./ErrorLog";
export const metadata: Metadata = { title: "Hibanapló" };
export default async function AdminErrorsPage() {
const me = await requireMe("/admin/hibak");
if (!me.user.roles.includes("admin")) notFound();
return (
<main className="page" style={{ maxWidth: 1180 }}>
<AdminNav current="/admin/hibak" />
<div className="page-head">
<h1>Hibanapló</h1>
<p className="muted">
Az elemzések, válaszok és prompt-próbák minden sikertelen próbálkozása, a legújabb elöl. A worker írja; 90 napig
őrizzük.
</p>
</div>
<ErrorLog />
</main>
);
}
@@ -6,6 +6,8 @@ import { api, errorText } from "@/lib/api";
import { formatDate } from "@/lib/astro"; import { formatDate } from "@/lib/astro";
import type { CatalogModel, ModelFunction } from "@/lib/types"; import type { CatalogModel, ModelFunction } from "@/lib/types";
import { RunningJobs } from "./RunningJobs";
const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = { const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = {
summary: { title: "Tömör összefoglaló", about: "Ingyenes, minden új képlethez magától elkészül. Olcsó, gyors modell elég." }, summary: { title: "Tömör összefoglaló", about: "Ingyenes, minden új képlethez magától elkészül. Olcsó, gyors modell elég." },
analysis: { analysis: {
@@ -66,6 +68,7 @@ export function AdminModels() {
{functions.map((f) => ( {functions.map((f) => (
<FunctionModel key={f.kind} fn={f} catalog={catalog} onSaved={replace} /> <FunctionModel key={f.kind} fn={f} catalog={catalog} onSaved={replace} />
))} ))}
<RunningJobs />
</div> </div>
); );
} }
@@ -0,0 +1,138 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import type { AdminJob } from "@/lib/types";
const KINDS: Record<AdminJob["kind"], string> = {
summary: "Összefoglaló",
natal: "Képletelemzés",
synastry: "Kapcsolati elemzés",
forecast: "Éves előrejelzés",
question: "Kérdés-válasz",
};
const REFRESH_MS = 10_000;
function since(iso: string): string {
const minutes = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 60_000));
return minutes < 1 ? "most" : `${minutes} perce`;
}
/**
* Analyses and answers being written or waiting. A restart starts them again
* with the models set now; an attempt still running is dropped by the worker.
*/
export function RunningJobs() {
const [jobs, setJobs] = useState<AdminJob[] | null>(null);
const [busy, setBusy] = useState(false);
const [asking, setAsking] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(() => {
api<{ jobs: AdminJob[] }>("/admin/jobs")
.then((d) => setJobs(d.jobs))
.catch((e) => setError(errorText(e)));
}, []);
useEffect(() => {
load();
const timer = setInterval(load, REFRESH_MS);
return () => clearInterval(timer);
}, [load]);
async function restart(ids?: string[]) {
setBusy(true);
setError(null);
setMessage(null);
try {
const r = await api<{ restarted: number; jobs: AdminJob[] }>("/admin/jobs/restart", { body: ids ? { ids } : {} });
setJobs(r.jobs);
setMessage(r.restarted > 0 ? `${r.restarted} generálás újraindítva.` : "Nem volt mit újraindítani.");
setAsking(false);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
const changed = (jobs ?? []).filter((j) => j.model !== j.next_model).length;
return (
<section className="card model-card" aria-labelledby="jobs-title">
<div className="model-head">
<div>
<h2 id="jobs-title">Futó generálások</h2>
<p className="hint">
Az éppen készülő és a sorban álló elemzések és válaszok. Újraindításkor mindegyik azzal a modellel indul újra,
ami most be van állítva; a még futó régi kérést a worker eldobja. Senkitől nem von le újabb egységet.
</p>
</div>
{jobs && jobs.length > 0 && (
<div className="regenerate">
{asking ? (
<>
<span className="hint">
{jobs.length} generálás indul újra{changed > 0 ? `, ebből ${changed} másik modellel` : ""}.
</span>
<button type="button" className="btn btn-sm" onClick={() => restart()} disabled={busy}>
{busy ? "Újraindítás…" : "Igen, mind"}
</button>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setAsking(false)} disabled={busy}>
Mégse
</button>
</>
) : (
<button type="button" className="btn btn-sm" onClick={() => setAsking(true)}>
↻ Mind újraindítása ({jobs.length})
</button>
)}
</div>
)}
</div>
{message && (
<p className="msg" role="status">
{message}
</p>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{jobs === null ? (
<p className="muted">Betöltés…</p>
) : jobs.length === 0 ? (
<p className="muted">Most semmi nem készül és semmi nem vár a sorban.</p>
) : (
<ul className="model-options">
{jobs.map((j) => (
<li key={j.id} className="job-row">
<span>
<strong>{KINDS[j.kind]}</strong>
<span className="hint">
{j.status === "running" && j.started_at
? `fut, ${since(j.started_at)} indult`
: `vár (kérve ${since(j.created_at)})`}
{j.attempts > 0 ? ` · ${j.attempts}. kísérlet` : ""}
{j.on_fallback ? " · tartalék modellel" : ""}
</span>
{j.error && <span className="hint">utolsó hiba: {j.error}</span>}
</span>
<span className="model-price">
<code>{j.model}</code>
{j.model !== j.next_model ? <strong>→ {j.next_model}</strong> : <span>újraindítva is ez</span>}
</span>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => restart([j.id])} disabled={busy}>
↻
<span className="sr-only"> Újraindítás</span>
</button>
</li>
))}
</ul>
)}
</section>
);
}
@@ -40,7 +40,7 @@ const KINDS: { kind: PromptKind; id: string; label: string; about: string }[] =
id: "kerdesek", id: "kerdesek",
label: "Kérdés-válasz", label: "Kérdés-válasz",
about: about:
"A kész képletelemzésre vagy előrejelzésre feltett kérdések válasza (legfeljebb 250 szó). A modell kapja a képlet adatait, az elemzést és a korábbi kérdéseket; a Modellek oldalon beállított kérdés-válasz modell válaszol.", "A kész képletelemzésre, kapcsolati elemzésre vagy előrejelzésre feltett kérdések válasza (legfeljebb 250 szó). A modell kapja a képlet adatait, az elemzést és a korábbi kérdéseket; a Modellek oldalon beállított kérdés-válasz modell válaszol.",
}, },
]; ];
+1 -1
View File
@@ -22,7 +22,7 @@ const FAQ: [string, string][] = [
], ],
[ [
"Mit jelent a kérdés?", "Mit jelent a kérdés?",
"A kész részletes képletelemzésed vagy éves előrejelzésed alatt kérdezhetsz róla, például hogy mit jelent egy fényszög a munkádra nézve, vagy mire figyelj egy időszakban. A válasz a képleted és az elemzés alapján készül, legfeljebb 250 szóban. Minden csomagban 3 kérdés van, és külön is vehetsz még.", "A kész képletelemzésed, kapcsolati elemzésed vagy éves előrejelzésed alatt kérdezhetsz róla, például hogy mit jelent egy fényszög a munkádra nézve, mire figyeljetek egy kapcsolatban, vagy mire figyelj egy időszakban. A válasz a képleted és az elemzés alapján készül, legfeljebb 250 szóban. Minden csomagban 3 kérdés van, és külön is vehetsz még.",
], ],
[ [
"Mire kell a személyhely?", "Mire kell a személyhely?",
+80 -18
View File
@@ -28,6 +28,8 @@
html, body { margin: 0; } html, body { margin: 0; }
body { body {
min-height: 100vh; min-height: 100vh;
overflow-x: clip; /* nothing may push the page sideways on a phone */
overflow-wrap: break-word;
background: var(--bg); background: var(--bg);
color: var(--ink); color: var(--ink);
font: 400 15px/1.55 var(--font-body); font: 400 15px/1.55 var(--font-body);
@@ -71,8 +73,8 @@ p { margin: 0; }
.page-head { display: flex; flex-direction: column; gap: 6px; } .page-head { display: flex; flex-direction: column; gap: 6px; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 24px; display: flex; flex-direction: column; gap: 18px; } .card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 24px; display: flex; flex-direction: column; gap: 18px; }
.card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; } .card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; } .grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(240px, 100%), 1fr)); gap: 16px; }
.facts { display: grid; grid-template-columns: max-content 1fr; gap: 8px 20px; margin: 0; } .facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 20px; margin: 0; }
.facts dt { color: var(--muted); } .facts dt { color: var(--muted); }
.facts dd { margin: 0; } .facts dd { margin: 0; }
@@ -81,11 +83,11 @@ p { margin: 0; }
.field label, .label { font-size: 14px; font-weight: 500; } .field label, .label { font-size: 14px; font-weight: 500; }
.hint { font-size: 13px; color: var(--muted); } .hint { font-size: 13px; color: var(--muted); }
.inp { .inp {
width: 100%; min-height: 48px; padding: 0 14px; border-radius: var(--radius); width: 100%; min-width: 0; max-width: 100%; min-height: 48px; padding: 0 14px; border-radius: var(--radius);
border: 1px solid var(--line-2); background: var(--panel-2); color: var(--ink); border: 1px solid var(--line-2); background: var(--panel-2); color: var(--ink);
font: 400 15px var(--font-body); font: 400 15px var(--font-body);
} }
select.inp { padding-right: 32px; } select.inp { padding-right: 32px; text-overflow: ellipsis; }
.inp::placeholder { color: #8a93ab; } .inp::placeholder { color: #8a93ab; }
.inp:focus { outline: none; border-color: var(--gold); box-shadow: 0 0 0 3px rgba(217, 180, 106, 0.25); } .inp:focus { outline: none; border-color: var(--gold); box-shadow: 0 0 0 3px rgba(217, 180, 106, 0.25); }
.inp:disabled { opacity: 0.55; } .inp:disabled { opacity: 0.55; }
@@ -190,7 +192,7 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.analysis-section h3 { font-size: 24px; color: var(--gold); } .analysis-section h3 { font-size: 24px; color: var(--gold); }
.analysis-section p, .analysis-lists li { font-size: 16px; line-height: 1.75; color: var(--ink-2); } .analysis-section p, .analysis-lists li { font-size: 16px; line-height: 1.75; color: var(--ink-2); }
.analysis strong { color: var(--ink); font-weight: 600; } .analysis strong { color: var(--ink); font-weight: 600; }
.analysis-lists { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 24px; } .analysis-lists { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr)); gap: 24px; }
.analysis-lists h3 { font-size: 22px; margin-bottom: 8px; } .analysis-lists h3 { font-size: 22px; margin-bottom: 8px; }
.analysis-lists ul { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 8px; } .analysis-lists ul { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 8px; }
.analysis-advice { border-top: 1px solid var(--line); padding-top: 24px; } .analysis-advice { border-top: 1px solid var(--line); padding-top: 24px; }
@@ -308,7 +310,7 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.w-point:hover .w-point-glyph { fill: var(--gold); } .w-point:hover .w-point-glyph { fill: var(--gold); }
@media (max-width: 900px) { @media (max-width: 900px) {
.chart-layout { grid-template-columns: 1fr; } .chart-layout { grid-template-columns: minmax(0, 1fr); }
} }
@media (max-width: 640px) { @media (max-width: 640px) {
@@ -342,7 +344,7 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
@media (max-width: 640px) { .tab { padding: 12px 10px; font-size: 14px; } .tabs { scroll-margin-top: 120px; } } @media (max-width: 640px) { .tab { padding: 12px 10px; font-size: 14px; } .tabs { scroll-margin-top: 120px; } }
/* Charts list, persons */ /* Charts list, persons */
.chart-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 16px; } .chart-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(240px, 100%), 1fr)); gap: 16px; }
.chart-card { .chart-card {
background: var(--panel); border: 1px solid var(--line); border-radius: 14px; display: flex; flex-direction: column; background: var(--panel); border: 1px solid var(--line); border-radius: 14px; display: flex; flex-direction: column;
transition: border-color 0.15s; transition: border-color 0.15s;
@@ -485,14 +487,14 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.nature-challenging { background: var(--tense); } .nature-challenging { background: var(--tense); }
.nature-neutral { background: var(--gold); } .nature-neutral { background: var(--gold); }
.nature-list { margin: 0; display: flex; flex-direction: column; gap: 8px; } .nature-list { margin: 0; display: flex; flex-direction: column; gap: 8px; }
.nature-list > div { display: grid; grid-template-columns: 128px 1fr; gap: 8px; align-items: baseline; } .nature-list > div { display: grid; grid-template-columns: 128px minmax(0, 1fr); gap: 8px; align-items: baseline; }
.nature-list dt { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink-2); } .nature-list dt { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink-2); }
.nature-list dd { margin: 0; } .nature-list dd { margin: 0; }
.nature-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; } .nature-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
.pair-card { gap: 4px; } .pair-card { gap: 4px; }
.pair-row { .pair-row {
display: grid; grid-template-columns: auto 1fr auto; gap: 12px; align-items: center; padding: 10px 0; display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 10px 0;
color: inherit; text-decoration: none; border-bottom: 1px solid var(--line); color: inherit; text-decoration: none; border-bottom: 1px solid var(--line);
} }
.pair-row:last-child { border-bottom: 0; padding-bottom: 0; } .pair-row:last-child { border-bottom: 0; padding-bottom: 0; }
@@ -501,7 +503,7 @@ a.pair-row:hover strong { color: var(--gold); }
.pair-text strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; } .pair-text strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
.compare-new { gap: 16px; } .compare-new { gap: 16px; }
.compare-form { display: grid; grid-template-columns: 1fr auto 1fr auto; gap: 12px; align-items: end; } .compare-form { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto; gap: 12px; align-items: end; }
.compare-swap { font-size: 20px; padding: 0 10px; } .compare-swap { font-size: 20px; padding: 0 10px; }
.compare-tile { gap: 6px; padding: 16px 20px; } .compare-tile { gap: 6px; padding: 16px 20px; }
.compare-tile strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; } .compare-tile strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
@@ -509,12 +511,12 @@ a.pair-row:hover strong { color: var(--gold); }
.compare-tile .form-actions { margin-top: 6px; } .compare-tile .form-actions { margin-top: 6px; }
.back-link { font-size: 14px; text-decoration: none; align-self: flex-start; } .back-link { font-size: 14px; text-decoration: none; align-self: flex-start; }
@media (max-width: 640px) { @media (max-width: 640px) {
.compare-form { grid-template-columns: 1fr auto; } .compare-form { grid-template-columns: minmax(0, 1fr) auto; }
.compare-form .field:first-child { grid-column: 1; } .compare-form .field:first-child { grid-column: 1; }
.compare-swap { grid-column: 2; grid-row: 1 / span 2; align-self: center; } .compare-swap { grid-column: 2; grid-row: 1 / span 2; align-self: center; }
.compare-form .field:nth-child(3) { grid-column: 1; } .compare-form .field:nth-child(3) { grid-column: 1; }
.compare-form > .btn-primary { grid-column: 1 / -1; width: 100%; } .compare-form > .btn-primary { grid-column: 1 / -1; width: 100%; }
.nature-list > div { grid-template-columns: 1fr; gap: 2px; } .nature-list > div { grid-template-columns: minmax(0, 1fr); gap: 2px; }
.nav { overflow-x: auto; scrollbar-width: none; } .nav { overflow-x: auto; scrollbar-width: none; }
.nav a { white-space: nowrap; padding: 10px 9px; } .nav a { white-space: nowrap; padding: 10px 9px; }
.cross-grid td.cross-corner { min-width: 56px; font-size: 9px; } .cross-grid td.cross-corner { min-width: 56px; font-size: 9px; }
@@ -522,7 +524,7 @@ a.pair-row:hover strong { color: var(--gold); }
/* Packages */ /* Packages */
.pkg-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; align-items: stretch; } .pkg-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; align-items: stretch; }
.pkg-grid-compact { grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 12px; } .pkg-grid-compact { grid-template-columns: repeat(auto-fit, minmax(min(210px, 100%), 1fr)); gap: 12px; }
.pkg { .pkg {
position: relative; display: flex; flex-direction: column; gap: 10px; padding: 22px 20px 20px; position: relative; display: flex; flex-direction: column; gap: 10px; padding: 22px 20px 20px;
background: var(--panel); border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel); border: 1px solid var(--line-2); border-radius: var(--radius);
@@ -589,7 +591,7 @@ a.pair-row:hover strong { color: var(--gold); }
.timeline-month h3 { font-size: 20px; margin: 0 0 8px; text-transform: capitalize; } .timeline-month h3 { font-size: 20px; margin: 0 0 8px; text-transform: capitalize; }
.timeline-month ol, .transit-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; } .timeline-month ol, .transit-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; }
.timeline-item { .timeline-item {
display: grid; grid-template-columns: 64px 56px 1fr; gap: 10px; align-items: baseline; display: grid; grid-template-columns: 64px 56px minmax(0, 1fr); gap: 10px; align-items: baseline;
padding: 8px 12px; border-left: 3px solid var(--line); border-radius: 4px; background: rgba(255, 255, 255, 0.02); padding: 8px 12px; border-left: 3px solid var(--line); border-radius: 4px; background: rgba(255, 255, 255, 0.02);
} }
.timeline-date { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; } .timeline-date { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
@@ -599,15 +601,15 @@ a.pair-row:hover strong { color: var(--gold); }
.timeline-item.tone-harmonic, .transit-list .tone-harmonic { border-left-color: var(--harmonic); } .timeline-item.tone-harmonic, .transit-list .tone-harmonic { border-left-color: var(--harmonic); }
.timeline-item.tone-neutral, .transit-list .tone-neutral { border-left-color: var(--gold); } .timeline-item.tone-neutral, .transit-list .tone-neutral { border-left-color: var(--gold); }
.transit-list li { .transit-list li {
display: grid; grid-template-columns: 72px 1fr; gap: 10px; align-items: baseline; display: grid; grid-template-columns: 72px minmax(0, 1fr); gap: 10px; align-items: baseline;
padding: 8px 12px; border-left: 3px solid var(--line); border-radius: 4px; padding: 8px 12px; border-left: 3px solid var(--line); border-radius: 4px;
} }
.transit-list li > span:last-child { display: flex; flex-direction: column; gap: 2px; } .transit-list li > span:last-child { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.transit-list .sym { font-size: 17px; color: var(--gold); white-space: nowrap; } .transit-list .sym { font-size: 17px; color: var(--gold); white-space: nowrap; }
.transit-list .pill { align-self: flex-start; font-size: 12px; padding: 1px 8px; border: 1px solid var(--gold); border-radius: 999px; color: var(--gold); } .transit-list .pill { align-self: flex-start; font-size: 12px; padding: 1px 8px; border: 1px solid var(--gold); border-radius: 999px; color: var(--gold); }
.plain-list { margin: 8px 0 12px; padding-left: 18px; display: flex; flex-direction: column; gap: 4px; } .plain-list { margin: 8px 0 12px; padding-left: 18px; display: flex; flex-direction: column; gap: 4px; }
@media (max-width: 560px) { @media (max-width: 560px) {
.timeline-item { grid-template-columns: 52px 1fr; } .timeline-item { grid-template-columns: 52px minmax(0, 1fr); }
.timeline-glyph { display: none; } .timeline-glyph { display: none; }
} }
@@ -638,9 +640,69 @@ a.pair-row:hover strong { color: var(--gold); }
.questions { display: flex; flex-direction: column; gap: 14px; margin-top: 28px; padding-top: 22px; border-top: 1px solid var(--line); } .questions { display: flex; flex-direction: column; gap: 14px; margin-top: 28px; padding-top: 22px; border-top: 1px solid var(--line); }
.questions h3 { margin: 0; } .questions h3 { margin: 0; }
.qa { display: flex; flex-direction: column; gap: 8px; padding: 14px 16px; border: 1px solid var(--line); border-radius: 12px; } .qa { display: flex; flex-direction: column; gap: 8px; padding: 14px 16px; border: 1px solid var(--line); border-radius: 12px; }
.qa-question { margin: 0; display: flex; flex-direction: column; gap: 2px; font-weight: 600; white-space: pre-wrap; } .qa-question { margin: 0; display: flex; flex-direction: column; gap: 2px; font-weight: 600; white-space: pre-wrap; overflow-wrap: anywhere; }
.qa-answer { display: flex; flex-direction: column; gap: 6px; } .qa-answer { display: flex; flex-direction: column; gap: 6px; }
.qa-answer p { margin: 0 0 8px; } .qa-answer p { margin: 0 0 8px; }
.qa-form { display: flex; flex-direction: column; gap: 8px; } .qa-form { display: flex; flex-direction: column; gap: 8px; }
.qa-form textarea { resize: vertical; min-height: 84px; } .qa-form textarea { resize: vertical; min-height: 84px; }
.hint.warn { color: var(--gold); } .hint.warn { color: var(--gold); }
.job-row { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 12px; align-items: center; padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; }
.job-row > span:first-child { display: flex; flex-direction: column; min-width: 0; }
@media (max-width: 640px) { .job-row { grid-template-columns: minmax(0, 1fr) auto; } .job-row .model-price { grid-column: 1 / -1; align-items: flex-start; } }
.retry-notice { display: flex; flex-direction: column; gap: 4px; }
.retry-notice p { margin: 0; }
/* admin: error log */
.error-log { width: 100%; border-collapse: collapse; font-size: 14px; }
.error-log th, .error-log td { text-align: left; vertical-align: top; padding: 8px 10px; border-bottom: 1px solid var(--line); }
.error-log td > .hint, .error-log td > code { display: block; }
.error-log .error-text { overflow-wrap: anywhere; max-width: 460px; }
.error-log .outcome { white-space: nowrap; }
.error-log .outcome.tone-tense { color: var(--tense); font-weight: 600; }
/* Generated text (summaries, analyses, answers): justified, with hyphenation so
narrow screens get no wide gaps. The last line of a paragraph stays ragged. */
.analysis-lead, .analysis-section p, .analysis-lists li, .summary-text, .qa-answer p {
text-align: justify;
hyphens: auto;
-webkit-hyphens: auto;
hyphenate-limit-chars: 7 3 3;
}
/* Phones: tighter spacing, smaller headings, no sideways scrolling */
@media (max-width: 640px) {
.page { padding: 20px 14px 48px; gap: 18px; }
.card { padding: 16px; gap: 14px; }
h2 { font-size: 24px; }
.analysis { gap: 22px; }
.analysis-head h2 { font-size: 28px; }
.analysis-section h3 { font-size: 21px; }
.analysis-lists h3 { font-size: 20px; }
.analysis-lead { font-size: 16px; line-height: 1.65; }
.analysis-section p, .analysis-lists li, .summary-text { font-size: 15.5px; line-height: 1.7; }
.analysis-lists ul { padding-left: 18px; }
.summary-title { font-size: 23px; }
.questions { margin-top: 22px; padding-top: 18px; }
.qa { padding: 12px; }
.pay-box { padding: 16px; }
.loading-wheel { width: 96px; height: 96px; }
.tagline { font-size: 32px; }
}
@media (max-width: 480px) {
/* label above value: the label column would squeeze the values */
.facts { grid-template-columns: minmax(0, 1fr); gap: 2px; }
.facts dd + dt { margin-top: 8px; }
.site-header { gap: 8px 12px; }
.logo { font-size: 25px; }
}
/* Sharing a chart (summary card) and the public share page */
.share { display: flex; flex-direction: column; gap: 10px; align-items: flex-start; }
.share-open { align-items: stretch; padding: 14px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2); }
.share-link { display: flex; gap: 8px; }
.share-link .inp { min-height: 36px; font-size: 14px; }
.share-trio { display: flex; flex-wrap: wrap; gap: 6px 18px; color: var(--ink-2); font-size: 14px; }
.share-trio .sym { color: var(--gold); }
.share-cta { gap: 12px; }
.share-cta h2 { font-size: 24px; }
.share-cta .btn { align-self: flex-start; }
@@ -129,6 +129,7 @@ export default async function ComparisonPage({ params }: { params: Promise<{ id:
isAdmin={me.user.roles.includes("admin")} isAdmin={me.user.roles.includes("admin")}
canPay={config?.mock_payments ?? false} canPay={config?.mock_payments ?? false}
note={`Az elemzésben az első fél: ${name1}, a második fél: ${name2}.`} note={`Az elemzésben az első fél: ${name1}, a második fél: ${name2}.`}
questionsLeft={me.analyses_left.question ?? 0}
/> />
), ),
}, },
@@ -0,0 +1,108 @@
// The link preview image of a shared chart (og:image): 1200×630 PNG with the
// wheel, the title and the text of the short summary. The file name carries
// a version (see `imageVersion`), so a rewritten summary gets a new address
// and Facebook and co. fetch it again.
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { ImageResponse } from "next/og";
import { SIGNS, signName } from "@/lib/astro";
import { bigThree, loadShare, plain, shorten } from "@/lib/share";
import { wheelSvg } from "@/lib/wheelSvg";
const W = 1200;
const H = 630;
const WHEEL = 590;
const FONTS = join(process.cwd(), "src/assets/og");
let fonts: Promise<{ name: string; data: Buffer; weight: 400 | 600; style: "normal" }[]> | null = null;
function loadFonts() {
fonts ??= Promise.all(
(
[
["Cormorant Garamond", "CormorantGaramond-SemiBold.ttf", 600],
["Inter", "Inter-Regular.ttf", 400],
["Inter", "Inter-SemiBold.ttf", 600],
["DejaVu Sans", "DejaVuSans.ttf", 400],
] as const
).map(async ([name, file, weight]) => ({
name,
data: await readFile(join(FONTS, file)),
weight,
style: "normal" as const,
})),
);
return fonts;
}
// Letters, digits, punctuation and spaces only: a character missing from the
// fonts would make the renderer download a font from the internet.
const printable = (s: string) => s.replace(/[^\p{L}\p{N}\p{P}\p{Zs}+=<>°]/gu, "");
export async function GET(_req: Request, { params }: { params: Promise<{ slug: string; file: string }> }) {
const { slug } = await params;
const share = await loadShare(slug);
const chart = share?.chart?.chart;
if (!share || !chart) return new Response("Not found", { status: 404 });
const title = printable(share.summary?.title ?? "Születési képlet");
const text = printable(shorten(plain(share.summary?.summary ?? ""), 280));
const svg = wheelSvg(chart, chart.time_known, WHEEL);
const trio = bigThree(chart);
const image = new ImageResponse(
(
<div style={{ display: "flex", width: W, height: H, background: "#0d1220", color: "#ece6d8", fontFamily: "Inter" }}>
<div style={{ display: "flex", width: WHEEL + 40, height: H, alignItems: "center", justifyContent: "center" }}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`}
width={WHEEL}
height={WHEEL}
alt=""
/>
</div>
<div
style={{
display: "flex",
flexDirection: "column",
flex: 1,
padding: "56px 56px 44px 8px",
gap: 18,
}}
>
<div style={{ display: "flex", fontSize: 17, fontWeight: 600, letterSpacing: 2.5, color: "#d9b46a" }}>
SZÜLETÉSI KÉPLET · RÖVIDEN
</div>
<div style={{ display: "flex", fontFamily: "Cormorant Garamond", fontSize: 56, lineHeight: 1.05 }}>{title}</div>
{text && <div style={{ display: "flex", fontSize: 23, lineHeight: 1.45, color: "#c9cfdc" }}>{text}</div>}
<div style={{ display: "flex", marginTop: "auto", gap: 22, fontSize: 21, color: "#c9cfdc" }}>
{trio.map((t) => (
<div key={t.label} style={{ display: "flex", alignItems: "center", gap: 8 }}>
<span style={{ fontFamily: "DejaVu Sans", color: "#d9b46a" }}>
{(SIGNS[t.sign]?.glyph ?? "").replace(/︎/g, "")}
</span>
<span>
{t.label === "Aszcendens" ? "Asc" : t.label} {signName(t.sign)}
</span>
</div>
))}
</div>
<div style={{ display: "flex", fontFamily: "Cormorant Garamond", fontSize: 30, color: "#ece6d8" }}>
sors<span style={{ color: "#d9b46a" }}>fonalak</span>
</div>
</div>
</div>
),
{
width: W,
height: H,
fonts: await loadFonts(),
// A day at the edge: a revoked link's image goes away from there too.
headers: { "Cache-Control": "public, max-age=3600, s-maxage=86400" },
},
);
return image;
}
+112
View File
@@ -0,0 +1,112 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
import { Rich } from "@/components/Rich";
import { Logo } from "@/components/SiteHeader";
import { SIGNS, signName } from "@/lib/astro";
import { getMe } from "@/lib/server";
import { bigThree, imageVersion, loadShare, plain, shorten, siteUrl } from "@/lib/share";
type Props = { params: Promise<{ slug: string }> };
/** Title, description and preview image for Facebook, Messenger, WhatsApp and co. */
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const share = await loadShare(slug);
if (!share?.chart) return { title: "A link nem érhető el", robots: { index: false } };
const base = await siteUrl();
const title = share.summary?.title ?? "Születési képlet";
const description = share.summary?.summary
? shorten(plain(share.summary.summary), 200)
: "Egy születési képlet a Sorsfonalakon.";
const url = `${base}/s/${slug}`;
const image = { url: `${base}/s/${slug}/kep/${imageVersion(share)}.png`, width: 1200, height: 630, alt: title };
return {
title,
description,
// Personal content: shown when shared, not listed in search engines.
robots: { index: false, follow: false },
alternates: { canonical: url },
openGraph: { type: "website", siteName: "Sorsfonalak", locale: "hu_HU", url, title, description, images: [image] },
twitter: { card: "summary_large_image", title, description, images: [image.url] },
};
}
/** A shared chart: the wheel and its short summary, open to anyone with the link. */
export default async function SharedChartPage({ params }: Props) {
const { slug } = await params;
const [share, me] = await Promise.all([loadShare(slug), getMe()]);
const chart = share?.chart?.chart;
if (!share || !chart) notFound();
const summary = share.summary;
const trio = bigThree(chart);
return (
<>
{!me && (
<header className="site-header">
<Logo />
<span style={{ flex: 1 }} />
<Link href="/belepes" className="btn btn-sm">
Belépés
</Link>
</header>
)}
<main className="page" style={{ maxWidth: 1180 }}>
<div className="page-head">
<span className="eyebrow">Megosztott születési képlet</span>
<h1>{summary?.title ?? "Születési képlet"}</h1>
</div>
<section className="chart-layout" aria-label="A megosztott képlet">
<div className="card chart-wheel-card">
<ChartWheel chart={chart} timeKnown={chart.time_known} />
<WheelLegend />
</div>
<div className="field chart-side">
<section className="card summary-card" aria-label="Röviden">
<span className="eyebrow">Röviden</span>
{summary?.summary ? (
<p className="summary-text" lang={summary.language}>
<Rich text={summary.summary} />
</p>
) : (
<p className="muted">Ehhez a képlethez még nincs rövid összefoglaló.</p>
)}
{trio.length > 0 && (
<p className="share-trio">
{trio.map((t) => (
<span key={t.label}>
<span className="sym" aria-hidden="true">
{SIGNS[t.sign]?.glyph}
</span>{" "}
{t.label} {signName(t.sign)}
</span>
))}
</p>
)}
{!chart.time_known && (
<p className="hint">A születési idő nem ismert, ezért a képleten nincsenek házak és Aszcendens.</p>
)}
</section>
<section className="card share-cta">
<h2>És a te képleted mit mutat?</h2>
<p className="muted">
Add meg a születési adataidat, és megkapod a saját képletedet a rövid összefoglalóval együtt, ingyen.
</p>
<Link href={me ? "/keplet" : "/belepes"} className="btn btn-primary">
{me ? "A saját képletem" : "Elkészítem a sajátomat"}
</Link>
</section>
</div>
</section>
<p className="hint">
Ezt a képletet a tulajdonosa osztotta meg, név és születési adatok nélkül. A szöveget mesterséges intelligencia
írta a képlet alapján.
</p>
</main>
</>
);
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,187 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
TeX Gyre DJV Math
-----------------
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
(on behalf of TeX users groups) are in public domain.
Letters imported from Euler Fraktur from AMSfonts are (c) American
Mathematical Society (see below).
Bitstream Vera Fonts Copyright
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license (“Fonts”) and associated
documentation
files (the “Font Software”), to reproduce and distribute the Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute,
and/or sell copies of the Font Software, and to permit persons to whom
the Font Software is furnished to do so, subject to the following
conditions:
The above copyright and trademark notices and this permission notice
shall be
included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional
glyphs or characters may be added to the Fonts, only if the fonts are
renamed
to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or
Font Software
that has been modified and is distributed under the “Bitstream Vera”
names.
The Font Software may be sold as part of a larger software package but
no copy
of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of GNOME, the GNOME
Foundation,
and Bitstream Inc., shall not be used in advertising or otherwise to promote
the sale, use or other dealings in this Font Software without prior written
authorization from the GNOME Foundation or Bitstream Inc., respectively.
For further information, contact: fonts at gnome dot org.
AMSFonts (v. 2.2) copyright
The PostScript Type 1 implementation of the AMSFonts produced by and
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
available for general use. This has been accomplished through the
cooperation
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
Members of this consortium include:
Elsevier Science IBM Corporation Society for Industrial and Applied
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be
held by
the American Mathematical Society. This is not meant to restrict in any way
the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
$Id$
@@ -0,0 +1,93 @@
Copyright 2015 the Cormorant Project Authors (github.com/CatharsisFonts/Cormorant)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,93 @@
Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,5 @@
Fonts of the share preview images (`src/app/s/[slug]/kep`), read at run time.
- Cormorant Garamond SemiBold, Inter Regular and SemiBold: static instances from
Google Fonts, SIL Open Font License (LICENSE-OFL-*.txt).
- DejaVu Sans 2.37: the zodiac and planet glyphs (LICENSE-DejaVu.txt).
@@ -5,6 +5,7 @@ const PAGES = [
{ href: "/admin/meghivok", label: "Meghívók" }, { href: "/admin/meghivok", label: "Meghívók" },
{ href: "/admin/promptok", label: "Promptok" }, { href: "/admin/promptok", label: "Promptok" },
{ href: "/admin/modellek", label: "Modellek" }, { href: "/admin/modellek", label: "Modellek" },
{ href: "/admin/hibak", label: "Hibanapló" },
]; ];
/** Switches between the admin pages. */ /** Switches between the admin pages. */
@@ -4,13 +4,31 @@ import { useEffect, useState } from "react";
import { ZodiacWheel } from "./ZodiacWheel"; import { ZodiacWheel } from "./ZodiacWheel";
/** Slowly turning wheel with the elapsed time, while the LLM writes. */ /**
export function AnalysisLoading({ title, text, compact = false }: { title?: string; text: string; compact?: boolean }) { * Slowly turning wheel with the elapsed time, while the LLM writes. The time
const [seconds, setSeconds] = useState(0); * counts from `since` (when the text was asked for), so it does not start
* again from zero after a reload; without it, from when the wheel appeared.
*/
export function AnalysisLoading({
title,
text,
compact = false,
since,
}: {
title?: string;
text: string;
compact?: boolean;
since?: string;
}) {
const [start] = useState(() => {
const t = since ? Date.parse(since) : NaN;
return Number.isNaN(t) ? Date.now() : Math.min(t, Date.now());
});
const [seconds, setSeconds] = useState(() => Math.floor((Date.now() - start) / 1000));
useEffect(() => { useEffect(() => {
const t = setInterval(() => setSeconds((s) => s + 1), 1000); const t = setInterval(() => setSeconds(Math.floor((Date.now() - start) / 1000)), 1000);
return () => clearInterval(t); return () => clearInterval(t);
}, []); }, [start]);
const elapsed = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; const elapsed = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
return ( return (
@@ -21,7 +39,7 @@ export function AnalysisLoading({ title, text, compact = false }: { title?: stri
<p className="muted" role="status"> <p className="muted" role="status">
{text} {text}
</p> </p>
<p className="hint" aria-hidden="true"> <p className="hint" aria-hidden="true" suppressHydrationWarning>
{elapsed} {elapsed}
</p> </p>
</div> </div>
@@ -8,9 +8,28 @@ import type { Question, UnitBalance } from "@/lib/types";
import { AnalysisLoading } from "./AnalysisLoading"; import { AnalysisLoading } from "./AnalysisLoading";
import { PackageChooser } from "./PackageCards"; import { PackageChooser } from "./PackageCards";
import { RegenerateButton } from "./RegenerateButton"; import { RegenerateButton } from "./RegenerateButton";
import { RetryNotice } from "./RetryNotice";
import { Paragraphs } from "./Rich"; import { Paragraphs } from "./Rich";
const MAX_CHARS = 600; const MAX_CHARS = 600;
const TEXTS = {
natal: {
title: "Kérdezz az elemzésedről",
hint: "Mit jelent ez a te életedben, hogyan kapcsolódik két rész egymáshoz? A válasz a képleted és az elemzés alapján készül, legfeljebb 250 szóban.",
example: "Pl. Hogyan hat a Hold helyzete a kapcsolataimra?",
},
synastry: {
title: "Kérdezz a kapcsolatotokról",
hint: "Hol erősítitek egymást, mire figyeljetek egy vitában, mit ad nektek a kapcsolat? A válasz a két képlet és az elemzés alapján készül, legfeljebb 250 szóban. A kérdéseket és a válaszokat mindketten látjátok.",
example: "Pl. Hogyan kezeljük jobban a nézeteltéréseinket?",
},
forecast: {
title: "Kérdezz az előrejelzésedről",
hint: "Mire figyelj egy időszakban, mit hozhat egy tranzit a munkádban vagy a kapcsolataidban? A válasz az év adatai és az előrejelzés alapján készül, legfeljebb 250 szóban.",
example: "Pl. Mire figyeljek a nyári időszakban a munkámban?",
},
};
const POLL_MS = 3000; const POLL_MS = 3000;
const MAX_POLLS = 80; // 4 minutes const MAX_POLLS = 80; // 4 minutes
@@ -24,13 +43,14 @@ export function AnalysisQuestions({
left: initialLeft, left: initialLeft,
isAdmin, isAdmin,
canPay, canPay,
forecast = false, about,
}: { }: {
analysisId: string; analysisId: string;
left: number; left: number;
isAdmin: boolean; isAdmin: boolean;
canPay: boolean; canPay: boolean;
forecast?: boolean; /** What the analysis is about: the heading and the example question follow it. */
about: "natal" | "synastry" | "forecast";
}) { }) {
const [questions, setQuestions] = useState<Question[] | null>(null); const [questions, setQuestions] = useState<Question[] | null>(null);
const [left, setLeft] = useState(initialLeft); const [left, setLeft] = useState(initialLeft);
@@ -114,11 +134,8 @@ export function AnalysisQuestions({
const canAsk = isAdmin || left > 0; const canAsk = isAdmin || left > 0;
return ( return (
<section className="questions" aria-labelledby={`${fieldId}-title`}> <section className="questions" aria-labelledby={`${fieldId}-title`}>
<h3 id={`${fieldId}-title`}>Kérdezz {forecast ? "az előrejelzésedről" : "az elemzésedről"}</h3> <h3 id={`${fieldId}-title`}>{TEXTS[about].title}</h3>
<p className="hint"> <p className="hint">{TEXTS[about].hint}</p>
Mit jelent ez a te életedben, mire figyelj egy időszakban, hogyan kapcsolódik két rész egymáshoz? A válasz a képleted
és az elemzés alapján készül, legfeljebb 250 szóban.
</p>
{questions?.map((q) => ( {questions?.map((q) => (
<article key={q.id} className="qa" aria-busy={q.status === "pending" || q.status === "running"}> <article key={q.id} className="qa" aria-busy={q.status === "pending" || q.status === "running"}>
@@ -139,12 +156,21 @@ export function AnalysisQuestions({
<RegenerateButton<Question> url={`/admin/questions/${q.id}/regenerate`} onStarted={replace} /> <RegenerateButton<Question> url={`/admin/questions/${q.id}/regenerate`} onStarted={replace} />
)} )}
<p className="msg msg-error" role="alert"> <p className="msg msg-error" role="alert">
Erre most nem sikerült válaszolni{q.credits_charged > 0 ? ", a kérdést visszaadtuk" : ""}. Kérdezz újra Erre többszöri próbálkozás után sem sikerült válaszolni
egy kicsit később. {q.credits_charged > 0 ? ". A kérdést visszaadtuk, így ingyen újra felteheted" : ""}. Kérdezz újra egy
kicsit később.
</p> </p>
{isAdmin && q.error && <p className="hint">Hiba: {q.error}</p>}
</div> </div>
) : ( ) : (
<AnalysisLoading compact text="Készül a válasz, ez általában fél perc…" /> <>
<AnalysisLoading
compact
text="Készül a válasz, ez általában fél perc…"
since={q.requested_at ?? q.created_at}
/>
<RetryNotice status={q.status} error={q.error} nextAttemptAt={q.next_attempt_at} isAdmin={isAdmin} />
</>
)} )}
</article> </article>
))} ))}
@@ -160,9 +186,7 @@ export function AnalysisQuestions({
rows={3} rows={3}
maxLength={MAX_CHARS} maxLength={MAX_CHARS}
value={text} value={text}
placeholder={ placeholder={TEXTS[about].example}
forecast ? "Pl. Mire figyeljek a nyári időszakban a munkámban?" : "Pl. Hogyan hat a Hold helyzete a kapcsolataimra?"
}
onChange={(e) => setText(e.target.value)} onChange={(e) => setText(e.target.value)}
disabled={busy || waiting} disabled={busy || waiting}
/> />
@@ -11,14 +11,17 @@ const ORDER = { natal: NATAL_ORDER, synastry: SYNASTRY_ORDER, forecast: FORECAST
export function AnalysisView({ export function AnalysisView({
content, content,
kind = "natal", kind = "natal",
language,
}: { }: {
content: AnalysisContent; content: AnalysisContent;
kind?: "natal" | "synastry" | "forecast"; kind?: "natal" | "synastry" | "forecast";
/** The language of the text, for hyphenation. */
language?: string;
}) { }) {
const order = ORDER[kind]; const order = ORDER[kind];
const sections = order.map((key) => content.sections?.[key]).filter((s) => s !== undefined); const sections = order.map((key) => content.sections?.[key]).filter((s) => s !== undefined);
return ( return (
<article className="analysis"> <article className="analysis" lang={language}>
<header className="analysis-head"> <header className="analysis-head">
<h2>{content.title}</h2> <h2>{content.title}</h2>
{content.summary && ( {content.summary && (
@@ -7,7 +7,9 @@ import type { Analysis } from "@/lib/types";
import { AnalysisLoading } from "./AnalysisLoading"; import { AnalysisLoading } from "./AnalysisLoading";
import { RegenerateButton } from "./RegenerateButton"; import { RegenerateButton } from "./RegenerateButton";
import { RetryNotice } from "./RetryNotice";
import { Rich } from "./Rich"; import { Rich } from "./Rich";
import { ShareChart } from "./ShareChart";
import { openTab } from "./Tabs"; import { openTab } from "./Tabs";
const POLL_MS = 3000; const POLL_MS = 3000;
@@ -77,9 +79,10 @@ export function ChartSummary({
<h2 id="summary-title" className="summary-title"> <h2 id="summary-title" className="summary-title">
{content.title} {content.title}
</h2> </h2>
<p className="summary-text"> <p className="summary-text" lang={summary?.language}>
<Rich text={content.summary ?? ""} /> <Rich text={content.summary ?? ""} />
</p> </p>
<ShareChart chartId={chartId} />
<a <a
href="#elemzes" href="#elemzes"
className="summary-more" className="summary-more"
@@ -102,7 +105,21 @@ export function ChartSummary({
Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később. Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később.
</p> </p>
) : ( ) : (
<AnalysisLoading compact text="Az összefoglalód készül, ez néhány másodperc…" /> <>
<AnalysisLoading
compact
text="Az összefoglalód készül, ez néhány másodperc…"
since={summary?.requested_at ?? summary?.created_at}
/>
{summary && (
<RetryNotice
status={summary.status}
error={summary.error}
nextAttemptAt={summary.next_attempt_at}
isAdmin={isAdmin}
/>
)}
</>
)} )}
</> </>
)} )}
@@ -11,6 +11,7 @@ import { AnalysisLoading } from "./AnalysisLoading";
import { AnalysisQuestions } from "./AnalysisQuestions"; import { AnalysisQuestions } from "./AnalysisQuestions";
import { PackageChooser } from "./PackageCards"; import { PackageChooser } from "./PackageCards";
import { RegenerateButton } from "./RegenerateButton"; import { RegenerateButton } from "./RegenerateButton";
import { RetryNotice } from "./RetryNotice";
import { AnalysisView } from "./AnalysisView"; import { AnalysisView } from "./AnalysisView";
const POLL_MS = 5000; const POLL_MS = 5000;
@@ -99,7 +100,7 @@ export function DetailedAnalysis({
canPay: boolean; canPay: boolean;
/** Shown above a finished analysis (e.g. who is the first and the second person). */ /** Shown above a finished analysis (e.g. who is the first and the second person). */
note?: string; note?: string;
/** Questions left; given where questions can be asked (natal analysis, forecast). */ /** Questions left; given where questions can be asked. */
questionsLeft?: number; questionsLeft?: number;
}) { }) {
const [analysis, setAnalysis] = useState<Analysis | null>(initial); const [analysis, setAnalysis] = useState<Analysis | null>(initial);
@@ -154,14 +155,14 @@ export function DetailedAnalysis({
<RegenerateButton<Analysis> url={`/admin/analyses/${analysis.id}/regenerate`} onStarted={setAnalysis} /> <RegenerateButton<Analysis> url={`/admin/analyses/${analysis.id}/regenerate`} onStarted={setAnalysis} />
)} )}
{note && <p className="hint">{note}</p>} {note && <p className="hint">{note}</p>}
<AnalysisView content={analysis.content} kind={target.kind} /> <AnalysisView content={analysis.content} kind={target.kind} language={analysis.language} />
{questionsLeft !== undefined && target.kind !== "synastry" && ( {questionsLeft !== undefined && (
<AnalysisQuestions <AnalysisQuestions
analysisId={analysis.id} analysisId={analysis.id}
left={questionsLeft} left={questionsLeft}
isAdmin={isAdmin} isAdmin={isAdmin}
canPay={canPay} canPay={canPay}
forecast={target.kind === "forecast"} about={target.kind}
/> />
)} )}
</section> </section>
@@ -172,7 +173,15 @@ export function DetailedAnalysis({
return ( return (
<section className="analysis-card" aria-label={t.eyebrow} aria-busy="true"> <section className="analysis-card" aria-label={t.eyebrow} aria-busy="true">
<span className="eyebrow">{t.eyebrow}</span> <span className="eyebrow">{t.eyebrow}</span>
<AnalysisLoading title={t.loadingTitle} text={t.loading} /> <AnalysisLoading title={t.loadingTitle} text={t.loading} since={analysis?.requested_at ?? analysis?.created_at} />
{analysis && (
<RetryNotice
status={analysis.status}
error={analysis.error}
nextAttemptAt={analysis.next_attempt_at}
isAdmin={isAdmin}
/>
)}
</section> </section>
); );
} }
@@ -186,9 +195,15 @@ export function DetailedAnalysis({
<p className="muted">{t.about}</p> <p className="muted">{t.about}</p>
<p className="ai-line">{AI_SHORT}</p> <p className="ai-line">{AI_SHORT}</p>
{analysis?.status === "failed" && ( {analysis?.status === "failed" && (
<p className="msg msg-error" role="alert"> <div className="msg msg-error" role="alert">
Az előző kérés nem sikerült{isAdmin ? "" : ", az elemzést visszaadtuk a keretedbe"}. Próbáld újra. <p style={{ margin: 0 }}>
Az elemzés többszöri próbálkozás után sem készült el.
{isAdmin || analysis.credits_charged === 0
? " Próbáld újra."
: " A felhasznált egységet visszaadtuk, így ingyen újra kérheted."}
</p> </p>
{isAdmin && analysis.error && <p className="hint">Hiba: {analysis.error}</p>}
</div>
)} )}
{error && ( {error && (
<p className="msg msg-error" role="alert"> <p className="msg msg-error" role="alert">
@@ -0,0 +1,28 @@
/**
* Shown while a text is being written again after a failed attempt: it is
* retried on its own, nothing to do. Admins also see the error.
*/
export function RetryNotice({
status,
error,
nextAttemptAt,
isAdmin = false,
}: {
status: string;
error?: string | null;
nextAttemptAt?: string;
isAdmin?: boolean;
}) {
if (!error || (status !== "pending" && status !== "running")) return null;
const wait = nextAttemptAt ? Math.round((Date.parse(nextAttemptAt) - Date.now()) / 60_000) : 0;
return (
<div className="msg retry-notice" role="status">
<p>
Az előző próbálkozás nem sikerült, ezért automatikusan újrapróbáljuk. Nem kell újra kérned, és nem kerül
többe.
{status === "pending" && wait >= 1 ? ` A következő próbálkozás kb. ${wait} perc múlva indul.` : ""}
</p>
{isAdmin && <p className="hint">Hiba: {error}</p>}
</div>
);
}
@@ -0,0 +1,122 @@
"use client";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
interface Share {
id: string;
url: string;
}
/** Share link of a chart with its short summary: copy, Facebook, the phone's share menu, revoke. */
export function ShareChart({ chartId }: { chartId: string }) {
const [share, setShare] = useState<Share | null>(null);
const [busy, setBusy] = useState(false);
const [copied, setCopied] = useState(false);
const [error, setError] = useState<string | null>(null);
const [revoked, setRevoked] = useState(false);
async function open() {
setBusy(true);
setError(null);
try {
setShare(await api<Share>("/shares", { body: { kind: "chart", target_id: chartId } }));
setRevoked(false);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
async function copy() {
if (!share) return;
try {
await navigator.clipboard.writeText(share.url);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
setError("Nem sikerült másolni; jelöld ki a linket, és másold kézzel.");
}
}
async function nativeShare() {
if (!share) return;
try {
await navigator.share({ url: share.url });
} catch {
// closed by the user
}
}
async function revoke() {
if (!share || !window.confirm("Visszavonod a linket? Aki megkapta, többé nem tudja megnyitni.")) return;
setBusy(true);
try {
await api(`/shares/${share.id}`, { method: "DELETE" });
setShare(null);
setRevoked(true);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
if (!share) {
return (
<div className="share">
<button type="button" className="btn btn-sm" onClick={open} disabled={busy}>
{busy ? "Link készül…" : "Megosztás"}
</button>
{revoked && <p className="hint">A linket visszavontad.</p>}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</div>
);
}
const facebook = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(share.url)}`;
return (
<div className="share share-open">
<p className="hint">
A linken a képleted rajza és ez az összefoglaló látszik, név és születési adatok nélkül. Bárki megnyithatja,
akinek elküldöd.
</p>
<div className="share-link">
<input
className="inp"
readOnly
value={share.url}
aria-label="Megosztási link"
onFocus={(e) => e.currentTarget.select()}
/>
<button type="button" className="btn btn-sm" onClick={copy}>
{copied ? "Kimásolva" : "Másolás"}
</button>
</div>
<div className="form-actions">
<a className="btn btn-sm btn-primary" href={facebook} target="_blank" rel="noopener noreferrer">
Megosztás Facebookon
</a>
{typeof navigator !== "undefined" && "share" in navigator && (
<button type="button" className="btn btn-sm" onClick={nativeShare}>
Küldés…
</button>
)}
<button type="button" className="btn btn-sm btn-ghost" onClick={revoke} disabled={busy}>
Link visszavonása
</button>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</div>
);
}
+81
View File
@@ -0,0 +1,81 @@
// Public share links (`/s/<slug>`): loading the shared content and the
// texts of the page, its link preview and its preview image.
import "server-only";
import { headers } from "next/headers";
import { cache } from "react";
import { BACKEND_URL } from "./server";
import type { ChartResult } from "./types";
export interface PublicSummary {
id: string;
language: string;
title: string | null;
summary: string | null;
completed_at: string | null;
}
/** `GET /v1/public/shares/{slug}` of a shared chart. */
export interface PublicShare {
kind: "chart" | "synastry" | "analysis";
title: string | null;
created_at: string;
chart?: { label: string; chart: ChartResult & { time_known: boolean } };
summary?: PublicSummary | null;
}
const SLUG = /^[A-Za-z0-9_-]{8,64}$/;
/** The shared content, or `null` if the link is unknown or revoked (one backend call per request). */
export const loadShare = cache(async (slug: string): Promise<PublicShare | null> => {
if (!SLUG.test(slug)) return null;
const res = await fetch(`${BACKEND_URL}/v1/public/shares/${slug}`, { cache: "no-store" });
if (res.status === 404) return null;
if (!res.ok) throw new Error(`share ${slug}: HTTP ${res.status}`);
return (await res.json()) as PublicShare;
});
/** The site's own address, for absolute links in the preview tags. */
export async function siteUrl(): Promise<string> {
const fixed = process.env.PUBLIC_BASE_URL;
if (fixed) return fixed.replace(/\/$/, "");
const h = await headers();
const host = h.get("x-forwarded-host") ?? h.get("host") ?? "localhost:3001";
const proto = h.get("x-forwarded-proto") ?? (host.startsWith("localhost") ? "http" : "https");
return `${proto}://${host}`;
}
/** Model text without the `**bold**` marks. */
export function plain(text: string): string {
return text.replace(/\*\*/g, "").replace(/\s+/g, " ").trim();
}
/** At most `max` characters, cut at a word, with an ellipsis. */
export function shorten(text: string, max: number): string {
if (text.length <= max) return text;
const cut = text.slice(0, max - 1);
const space = cut.lastIndexOf(" ");
return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,;:–-]+$/, "")}…`;
}
/** Changes whenever the summary is rewritten, so link previews fetch the new image. */
export function imageVersion(share: PublicShare): string {
const s = share.summary;
if (!s) return "kep";
const time = s.completed_at ? Date.parse(s.completed_at).toString(36) : "0";
return `${s.id.replace(/-/g, "").slice(-8)}${time}`;
}
/** "Nap Nyilas · Hold Bika · Aszcendens Mérleg" (the ascendant only with a known time). */
export function bigThree(chart: ChartResult & { time_known: boolean }): { label: string; sign: string }[] {
const sign = (id: string) => chart.points.find((p) => p.id === id)?.sign;
const asc = chart.angles?.ascendant;
const out: { label: string; sign: string }[] = [];
const sun = sign("sun");
const moon = sign("moon");
if (sun) out.push({ label: "Nap", sign: sun });
if (moon) out.push({ label: "Hold", sign: moon });
if (chart.time_known && typeof asc === "object" && asc) out.push({ label: "Aszcendens", sign: asc.sign });
return out;
}
+42
View File
@@ -77,6 +77,9 @@ export interface Question {
credits_charged: number; credits_charged: number;
created_at: string; created_at: string;
completed_at: string | null; completed_at: string | null;
attempts?: number;
next_attempt_at?: string;
requested_at?: string;
} }
export interface PublicConfig { export interface PublicConfig {
@@ -232,6 +235,26 @@ export interface Analysis {
credits_charged: number; credits_charged: number;
created_at: string; created_at: string;
completed_at: string | null; completed_at: string | null;
/** Attempts so far, and when the next one starts (while it is retried). */
attempts?: number;
next_attempt_at?: string;
/** When the current text was asked for: the waiting page counts from here. */
requested_at?: string;
}
/** Admin: one failed attempt in the error log. */
export interface GenerationError {
id: number;
created_at: string;
source: "analysis" | "question" | "preview";
item_id: string;
kind: string;
model: string;
attempt: number;
outcome: "retry" | "fallback" | "failed";
error: string;
seconds: number | null;
user: string | null;
} }
export interface AdminUser { export interface AdminUser {
@@ -266,6 +289,25 @@ export interface ModelFunction {
finished_30d: number; finished_30d: number;
} }
/** Admin: an analysis or answer being written or waiting in the queue. */
export interface AdminJob {
id: string;
type: "analysis" | "question";
kind: "summary" | "natal" | "synastry" | "forecast" | "question";
status: "pending" | "running";
/** The model of the current attempt. */
model: string;
on_fallback: boolean;
/** What a restart would use now. */
next_model: string;
next_fallback: string | null;
attempts: number;
started_at: string | null;
created_at: string;
next_attempt_at: string;
error: string | null;
}
/** A model OpenRouter offers; prices in USD per million tokens. */ /** A model OpenRouter offers; prices in USD per million tokens. */
export interface CatalogModel { export interface CatalogModel {
id: string; id: string;
+74
View File
@@ -0,0 +1,74 @@
// The chart wheel as a standalone SVG document, for the share preview image.
// It reuses the page's <ChartWheel> and turns its element tree into markup
// with the colours inlined (no page CSS there).
import { Fragment, isValidElement, type ReactElement, type ReactNode } from "react";
import { ChartWheel, SIZE } from "@/components/ChartWheel";
import type { ChartResult } from "@/lib/types";
// The page's wheel rules (globals.css) with the colour tokens resolved.
const STYLE = `
.w-ring{fill:none;stroke:#2c3654;stroke-width:1.2}
.w-faint{stroke:#1f2740}
.w-inner{fill:#0f1426}
.w-sign{stroke:#2c3654;stroke-width:1}
.w-fire{fill:rgba(227,139,106,.09)}
.w-earth{fill:rgba(159,216,176,.07)}
.w-air{fill:rgba(217,180,106,.08)}
.w-water{fill:rgba(127,176,224,.09)}
.w-sign-glyph{fill:#d9b46a;font-family:'DejaVu Sans';font-size:22px}
.w-tick,.w-cusp{stroke:#2c3654;stroke-width:1}
.w-axis{stroke:#d9b46a;stroke-width:1.8}
.w-axis-label{fill:#d9b46a;font-family:Inter;font-weight:600;font-size:14px}
.w-house-num{fill:#a3abc0;font-family:Inter;font-size:12px}
.w-aspect{stroke-linecap:round}
.w-asp-trine{stroke:#7fb0e0}
.w-asp-sextile{stroke:#7fb0e0;stroke-dasharray:5 4}
.w-asp-square{stroke:#f0a35e}
.w-asp-opposition{stroke:#e38b8b}
.w-point-tick{stroke:#ece6d8;stroke-width:1.6}
.w-leader{stroke:#a3abc0;stroke-width:.7;stroke-opacity:.6}
.w-point-glyph{fill:#ece6d8;font-family:'DejaVu Sans';font-size:22px}
.w-point-deg{fill:#a3abc0;font-family:Inter;font-size:10.5px}
.w-end{fill:#c9cfdc}
.w-point-glyph,.w-point-deg,.w-house-num,.w-axis-label{paint-order:stroke;stroke:#111729;stroke-width:4px;stroke-linejoin:round}
`;
// React prop names that are not SVG attributes (or not wanted in the image).
const SKIP = new Set(["children", "key", "role", "id"]);
const escape = (s: string) =>
s.replace(/︎/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
function attribute(name: string): string {
if (name === "className") return "class";
if (name === "viewBox") return name;
return name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
}
function markup(node: ReactNode): string {
if (node === null || node === undefined || typeof node === "boolean") return "";
if (typeof node === "string" || typeof node === "number") return escape(String(node));
if (Array.isArray(node)) return node.map(markup).join("");
if (!isValidElement(node)) return "";
const { type, props } = node as ReactElement<Record<string, unknown>>;
if (type === Fragment) return markup(props.children as ReactNode);
if (typeof type === "function") return markup((type as (p: unknown) => ReactNode)(props));
if (typeof type !== "string" || type === "title" || type === "desc") return "";
const attrs = Object.entries(props)
.filter(([k, v]) => !SKIP.has(k) && !k.startsWith("aria-") && v !== undefined && v !== null && v !== false)
.map(([k, v]) => ` ${attribute(k)}="${escape(String(v))}"`)
.join("");
return `<${type}${attrs}>${markup(props.children as ReactNode)}</${type}>`;
}
/** The wheel as an SVG document of `size` pixels. */
export function wheelSvg(chart: ChartResult, timeKnown: boolean, size = SIZE): string {
const body = markup(ChartWheel({ chart, timeKnown }))
.replace(/^<svg[^>]*>/, "")
.replace(/<\/svg>$/, "");
return (
`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${SIZE} ${SIZE}">` +
`<style>${STYLE}</style>${body}</svg>`
);
}
+8 -1
View File
@@ -21,6 +21,11 @@ Háttérmunkák a közös PostgreSQL-adatbázis fölött: e-mail-küldés, szöv
**Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`) **Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`)
- A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül. - A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül.
- **Két sáv**, saját helyekkel, hogy egy rövid szöveg ne várjon a hosszúak mögött:
- *gyors sáv* (`QUICK_CONCURRENCY`, alapból 2): előbb a kérdések, aztán a rövid összefoglalók;
- *lassú sáv* (`ANALYSIS_CONCURRENCY`, alapból 4): a részletes elemzések és az előrejelzések. Ha nincs ilyen, a szabad hely gyors munkát vesz fel, végül az admin próbafuttatásait.
- A 0 kikapcsolja a sávot, így a két sáv külön telepítésként is futhat (például Kubernetesen: egy gyors és egy lassú deployment).
- **Több worker** is dolgozhat ugyanabból a sorból: a sorokat `FOR UPDATE SKIP LOCKED` foglalja, egy munkát csak egy worker kap meg. Leálláskor mindegyik csak a saját félbehagyott munkáit adja vissza a sorba, az elakadt (15 percnél régebben futó) munkákat bármelyik visszateszi. Az e-mail-küldés és a takarítás is biztonságos több példányban.
- A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC. - A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC.
- **5 fokos szabály:** ha egy pont legfeljebb 5°-kal (`CUSP_ORB`) a következő ház csúcsa előtt áll, a szöveg már abban a házban adja meg, és odaírja, hogy formálisan az előzőben van („house 11 (on the cusp: 2°00' before it, formally house 10)”). Így olvassák az asztrológusok. A számított ház, a képlet rajza és a táblázatok nem változnak. Ugyanez érvényes az összevetés házátfedéseire, a szolár Aszcendensre, az év urára és a fogyatkozásokra. - **5 fokos szabály:** ha egy pont legfeljebb 5°-kal (`CUSP_ORB`) a következő ház csúcsa előtt áll, a szöveg már abban a házban adja meg, és odaírja, hogy formálisan az előzőben van („house 11 (on the cusp: 2°00' before it, formally house 10)”). Így olvassák az asztrológusok. A számított ház, a képlet rajza és a táblázatok nem változnak. Ugyanez érvényes az összevetés házátfedéseire, a szolár Aszcendensre, az év urára és a fogyatkozásokra.
- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v3`; ha a sor `prompt_version`-je `v3-r<id>`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön): - A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v3`; ha a sor `prompt_version`-je `v3-r<id>`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön):
@@ -72,7 +77,9 @@ Ugyanazt a radix-elemzést több modellel is megírja, véletlenszerű betűkkel
| `OPENROUTER_API_KEY` | – | OpenRouter-kulcs (compose-ban a `.env.secrets` fájlból); nélküle az elemzések várnak | | `OPENROUTER_API_KEY` | – | OpenRouter-kulcs (compose-ban a `.env.secrets` fájlból); nélküle az elemzések várnak |
| `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | | | `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | |
| `PUBLIC_BASE_URL` | – | `HTTP-Referer` fejléc az OpenRouter felé | | `PUBLIC_BASE_URL` | – | `HTTP-Referer` fejléc az OpenRouter felé |
| `ANALYSIS_CONCURRENCY` | `4` | egyszerre írt elemzések | | `WORKER_TASKS` | `email,cleanup,analyses` | a folyamat feladatai; élesben `worker`: `email,cleanup`, `worker-ai`: `analyses` |
| `ANALYSIS_CONCURRENCY` | `4` | lassú sáv: egyszerre írt részletes elemzések és előrejelzések (0: kikapcsolva) |
| `QUICK_CONCURRENCY` | `2` | gyors sáv: egyszerre írt rövid összefoglalók és válaszok (0: kikapcsolva) |
| `MAX_ANALYSIS_ATTEMPTS` | `3` | ennyi próbálkozás után sikertelen az elemzés (az egység visszajár) | | `MAX_ANALYSIS_ATTEMPTS` | `3` | ennyi próbálkozás után sikertelen az elemzés (az egység visszajár) |
| `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8082`, `text`, `info` | | | `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8082`, `text`, `info` | |
+182 -49
View File
@@ -9,6 +9,13 @@
//! Admin test runs of an edited prompt (`prompt_previews`) go through the //! Admin test runs of an edited prompt (`prompt_previews`) go through the
//! same loop when no analysis is due: one attempt, no credits, no retries. //! same loop when no analysis is due: one attempt, no credits, no retries.
//! //!
//! Two lanes, each with its own slots, so a short text never waits behind
//! the long ones: the quick lane writes summaries and answers questions, the
//! slow lane writes the detailed analyses and forecasts (and the test runs).
//! A free slow slot also takes quick work. A lane of size 0 is off, so the
//! lanes can run as separate deployments; several workers may share the
//! queue, rows are claimed with `FOR UPDATE SKIP LOCKED`.
//!
//! Fallback: when the model chosen on the admin page fails twice (or once with //! Fallback: when the model chosen on the admin page fails twice (or once with
//! a permanent error), the default model (`fallback_model`) takes over with a //! a permanent error), the default model (`fallback_model`) takes over with a
//! fresh set of attempts; only when that fails too is the unit refunded. //! fresh set of attempts; only when that fails too is the unit refunded.
@@ -29,6 +36,7 @@ use uuid::Uuid;
use self::openrouter::{Completion, LlmError, OpenRouter}; use self::openrouter::{Completion, LlmError, OpenRouter};
use self::prompt::{Kind, PROMPT_VERSION, Prompt}; use self::prompt::{Kind, PROMPT_VERSION, Prompt};
use self::questions::QuestionJob;
/// A `running` analysis older than this was left behind by a stopped worker. /// A `running` analysis older than this was left behind by a stopped worker.
const STUCK_AFTER_MINUTES: i32 = 15; const STUCK_AFTER_MINUTES: i32 = 15;
@@ -47,6 +55,9 @@ pub struct Job {
/// The default model, when the chosen one is another (see the module docs). /// The default model, when the chosen one is another (see the module docs).
pub fallback_model: Option<String>, pub fallback_model: Option<String>,
pub on_fallback: bool, pub on_fallback: bool,
/// When this attempt started; also its token: an admin restart clears it,
/// so a superseded attempt neither writes its result nor keeps running.
pub started_at: time::OffsetDateTime,
} }
impl Job { impl Job {
@@ -98,11 +109,36 @@ pub struct PreviewJob {
pub system: String, pub system: String,
} }
/// Which analyses a claim may take.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lane {
/// The short summary of a chart (questions are claimed separately).
Quick,
/// The detailed analyses and the yearly forecast.
Slow,
}
impl Lane {
fn kinds(self) -> &'static [&'static str] {
match self {
Lane::Quick => &["summary"],
Lane::Slow => &["natal", "synastry", "forecast"],
}
}
}
/// Slots per lane; 0 turns a lane off.
#[derive(Debug, Clone, Copy)]
pub struct Lanes {
pub quick: usize,
pub slow: usize,
}
pub struct Analyzer { pub struct Analyzer {
pub db: PgPool, pub db: PgPool,
pub llm: OpenRouter, pub llm: OpenRouter,
pub max_attempts: i32, pub max_attempts: i32,
pub concurrency: usize, pub lanes: Lanes,
/// Analyses and previews being written right now (released on shutdown). /// Analyses and previews being written right now (released on shutdown).
running: Mutex<HashSet<Uuid>>, running: Mutex<HashSet<Uuid>>,
} }
@@ -114,19 +150,21 @@ pub fn backoff(attempts: i32) -> Duration {
} }
impl Analyzer { impl Analyzer {
pub fn new(db: PgPool, llm: OpenRouter, max_attempts: i32, concurrency: usize) -> Self { pub fn new(db: PgPool, llm: OpenRouter, max_attempts: i32, lanes: Lanes) -> Self {
Self { db, llm, max_attempts, concurrency: concurrency.max(1), running: Mutex::default() } Self { db, llm, max_attempts, lanes, running: Mutex::default() }
} }
/// Takes the next due analysis, if any. /// Takes the next due analysis of the lane, if any.
pub async fn claim(&self) -> Result<Option<Job>, sqlx::Error> { pub async fn claim(&self, lane: Lane) -> Result<Option<Job>, sqlx::Error> {
let job: Option<Job> = sqlx::query_as( let job: Option<Job> = sqlx::query_as(
"UPDATE analyses SET status = 'running', started_at = now(), attempts = attempts + 1 \ "UPDATE analyses SET status = 'running', started_at = now(), attempts = attempts + 1 \
WHERE id = (SELECT id FROM analyses WHERE status = 'pending' AND next_attempt_at <= now() \ WHERE id = (SELECT id FROM analyses WHERE status = 'pending' AND next_attempt_at <= now() \
AND kind = ANY($1) \
ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \ ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, prompt_version, attempts, \ RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, prompt_version, attempts, \
fallback_model, on_fallback", fallback_model, on_fallback, started_at",
) )
.bind(lane.kinds())
.fetch_optional(&self.db) .fetch_optional(&self.db)
.await?; .await?;
if let Some(job) = &job { if let Some(job) = &job {
@@ -250,6 +288,8 @@ impl Analyzer {
.await .await
} }
Err(e) => { Err(e) => {
self.log_error("preview", job.id, &job.kind, &job.model, 1, "failed", e.message(), started.elapsed())
.await;
sqlx::query( sqlx::query(
"UPDATE prompt_previews SET status = 'failed', error = $2, completed_at = now() \ "UPDATE prompt_previews SET status = 'failed', error = $2, completed_at = now() \
WHERE id = $1 AND status = 'running'", WHERE id = $1 AND status = 'running'",
@@ -273,12 +313,21 @@ impl Analyzer {
/// Writes one claimed analysis and records the outcome. /// Writes one claimed analysis and records the outcome.
pub async fn handle(&self, job: Job) { pub async fn handle(&self, job: Job) {
let started = Instant::now(); let started = Instant::now();
let result = match self.prompt_for(&job).await { let work = async {
match self.prompt_for(&job).await {
Ok(prompt) => self.llm.complete(job.active_model(), &prompt).await.map(|mut c| { Ok(prompt) => self.llm.complete(job.active_model(), &prompt).await.map(|mut c| {
prompt::polish(&job.language, &mut c.content); prompt::polish(&job.language, &mut c.content);
c c
}), }),
Err(e) => Err(e), Err(e) => Err(e),
}
};
let result = tokio::select! {
result = work => result,
() = self.superseded("analyses", job.id, job.started_at) => {
tracing::info!(id = %job.id, "analysis restarted by an admin; this attempt is dropped");
return;
}
}; };
if let Err(e) = self.finish(&job, result, started.elapsed()).await { if let Err(e) = self.finish(&job, result, started.elapsed()).await {
tracing::error!(id = %job.id, error = %e, "saving the analysis result failed"); tracing::error!(id = %job.id, error = %e, "saving the analysis result failed");
@@ -292,7 +341,7 @@ impl Analyzer {
sqlx::query( sqlx::query(
"UPDATE analyses SET status = 'done', content = $2, model_used = $3, input_tokens = $4, \ "UPDATE analyses SET status = 'done', content = $2, model_used = $3, input_tokens = $4, \
output_tokens = $5, cost_usd = $6, error = NULL, completed_at = now() \ output_tokens = $5, cost_usd = $6, error = NULL, completed_at = now() \
WHERE id = $1 AND status = 'running'", WHERE id = $1 AND status = 'running' AND started_at = $7",
) )
.bind(job.id) .bind(job.id)
.bind(&c.content) .bind(&c.content)
@@ -300,6 +349,7 @@ impl Analyzer {
.bind(c.input_tokens) .bind(c.input_tokens)
.bind(c.output_tokens) .bind(c.output_tokens)
.bind(c.cost_usd) .bind(c.cost_usd)
.bind(job.started_at)
.execute(&self.db) .execute(&self.db)
.await?; .await?;
tracing::info!( tracing::info!(
@@ -309,15 +359,34 @@ impl Analyzer {
} }
Err(e) => { Err(e) => {
let can_fall_back = !job.on_fallback && job.fallback_model.is_some(); let can_fall_back = !job.on_fallback && job.fallback_model.is_some();
match next_step(&e, job.attempts, self.max_attempts, can_fall_back) { let next = next_step(&e, job.attempts, self.max_attempts, can_fall_back);
let outcome = match next {
Next::Retry(_) => "retry",
Next::Fallback => "fallback",
Next::Fail => "failed",
};
self.log_error(
"analysis",
job.id,
&job.kind,
job.active_model(),
job.attempts,
outcome,
e.message(),
took,
)
.await;
match next {
Next::Retry(wait) => { Next::Retry(wait) => {
sqlx::query( sqlx::query(
"UPDATE analyses SET status = 'pending', error = $2, \ "UPDATE analyses SET status = 'pending', error = $2, \
next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1 AND status = 'running'", next_attempt_at = now() + make_interval(secs => $3) \
WHERE id = $1 AND status = 'running' AND started_at = $4",
) )
.bind(job.id) .bind(job.id)
.bind(e.message()) .bind(e.message())
.bind(wait.as_secs_f64()) .bind(wait.as_secs_f64())
.bind(job.started_at)
.execute(&self.db) .execute(&self.db)
.await?; .await?;
tracing::warn!(id = %job.id, attempts = job.attempts, retry_in_secs = wait.as_secs(), error = %e.message(), "analysis will be retried"); tracing::warn!(id = %job.id, attempts = job.attempts, retry_in_secs = wait.as_secs(), error = %e.message(), "analysis will be retried");
@@ -325,10 +394,11 @@ impl Analyzer {
Next::Fallback => { Next::Fallback => {
sqlx::query( sqlx::query(
"UPDATE analyses SET status = 'pending', error = $2, on_fallback = true, attempts = 0, \ "UPDATE analyses SET status = 'pending', error = $2, on_fallback = true, attempts = 0, \
next_attempt_at = now() WHERE id = $1 AND status = 'running'", next_attempt_at = now() WHERE id = $1 AND status = 'running' AND started_at = $3",
) )
.bind(job.id) .bind(job.id)
.bind(e.message()) .bind(e.message())
.bind(job.started_at)
.execute(&self.db) .execute(&self.db)
.await?; .await?;
tracing::warn!( tracing::warn!(
@@ -337,7 +407,7 @@ impl Analyzer {
); );
} }
Next::Fail => { Next::Fail => {
self.fail(job.id, e.message()).await?; self.fail(job.id, job.started_at, e.message()).await?;
tracing::error!(id = %job.id, attempts = job.attempts, error = %e.message(), "analysis failed"); tracing::error!(id = %job.id, attempts = job.attempts, error = %e.message(), "analysis failed");
} }
} }
@@ -347,14 +417,15 @@ impl Analyzer {
} }
/// Marks the analysis failed and gives its unit back (once). /// Marks the analysis failed and gives its unit back (once).
async fn fail(&self, id: Uuid, message: &str) -> Result<(), sqlx::Error> { async fn fail(&self, id: Uuid, started_at: time::OffsetDateTime, message: &str) -> Result<(), sqlx::Error> {
let mut tx = self.db.begin().await?; let mut tx = self.db.begin().await?;
let row: Option<(Option<Uuid>, i32, String)> = sqlx::query_as( let row: Option<(Option<Uuid>, i32, String)> = sqlx::query_as(
"UPDATE analyses SET status = 'failed', error = $2, completed_at = now() \ "UPDATE analyses SET status = 'failed', error = $2, completed_at = now() \
WHERE id = $1 AND status = 'running' RETURNING requested_by, credits_charged, kind", WHERE id = $1 AND status = 'running' AND started_at = $3 RETURNING requested_by, credits_charged, kind",
) )
.bind(id) .bind(id)
.bind(message) .bind(message)
.bind(started_at)
.fetch_optional(&mut *tx) .fetch_optional(&mut *tx)
.await?; .await?;
if let Some((Some(user), units, kind)) = row if let Some((Some(user), units, kind)) = row
@@ -407,6 +478,53 @@ impl Analyzer {
Ok(result.rows_affected()) Ok(result.rows_affected())
} }
/// Records a failed attempt in the admin error log (a failure here is only logged).
#[allow(clippy::too_many_arguments)]
pub(crate) async fn log_error(
&self,
source: &str,
item_id: Uuid,
kind: &str,
model: &str,
attempt: i32,
outcome: &str,
error: &str,
took: Duration,
) {
let result = sqlx::query(
"INSERT INTO generation_errors (source, item_id, kind, model, attempt, outcome, error, seconds) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
)
.bind(source)
.bind(item_id)
.bind(kind)
.bind(model)
.bind(attempt)
.bind(outcome)
.bind(error.chars().take(2000).collect::<String>())
.bind(i32::try_from(took.as_secs()).unwrap_or(i32::MAX))
.execute(&self.db)
.await;
if let Err(e) = result {
tracing::error!(error = %e, "writing the error log");
}
}
/// Resolves when this attempt is no longer the current one (an admin
/// restarted it); checked every 10 seconds, never on a database error.
async fn superseded(&self, table: &str, id: Uuid, started_at: time::OffsetDateTime) {
let query = format!("SELECT status = 'running' AND started_at = $2 FROM {table} WHERE id = $1");
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
match sqlx::query_scalar::<_, Option<bool>>(&query).bind(id).bind(started_at).fetch_optional(&self.db).await
{
Ok(Some(Some(true))) => {}
Ok(_) => return,
Err(_) => {}
}
}
}
/// On shutdown: analyses still being written go back to `pending` at once. /// On shutdown: analyses still being written go back to `pending` at once.
async fn release_running(&self) { async fn release_running(&self) {
let ids: Vec<Uuid> = self.running.lock().unwrap().drain().collect(); let ids: Vec<Uuid> = self.running.lock().unwrap().drain().collect();
@@ -447,8 +565,46 @@ impl Analyzer {
} }
} }
/// Work a free slot can take, in order of preference.
pub(crate) enum Work {
Analysis(Job),
Question(QuestionJob),
Preview(PreviewJob),
}
impl Analyzer {
/// Quick work: a question first (someone is waiting for a short answer),
/// then a summary.
pub(crate) async fn claim_quick(&self) -> Result<Option<Work>, sqlx::Error> {
if let Some(job) = self.claim_question().await? {
return Ok(Some(Work::Question(job)));
}
Ok(self.claim(Lane::Quick).await?.map(Work::Analysis))
}
/// Slow work: a detailed analysis, else quick work, else a test run.
pub(crate) async fn claim_slow(&self) -> Result<Option<Work>, sqlx::Error> {
if let Some(job) = self.claim(Lane::Slow).await? {
return Ok(Some(Work::Analysis(job)));
}
if let Some(work) = self.claim_quick().await? {
return Ok(Some(work));
}
Ok(self.claim_preview().await?.map(Work::Preview))
}
async fn work(&self, work: Work) {
match work {
Work::Analysis(job) => self.handle(job).await,
Work::Question(job) => self.handle_question(job).await,
Work::Preview(job) => self.handle_preview(job).await,
}
}
}
pub async fn run(analyzer: Arc<Analyzer>, poll: Duration, stop: watch::Receiver<bool>) { pub async fn run(analyzer: Arc<Analyzer>, poll: Duration, stop: watch::Receiver<bool>) {
let slots = Arc::new(Semaphore::new(analyzer.concurrency)); let quick = Arc::new(Semaphore::new(analyzer.lanes.quick));
let slow = Arc::new(Semaphore::new(analyzer.lanes.slow));
let mut tasks = tokio::task::JoinSet::new(); let mut tasks = tokio::task::JoinSet::new();
let mut listener = crate::listen(&analyzer.db, "analyses").await; let mut listener = crate::listen(&analyzer.db, "analyses").await;
let mut last_requeue: Option<Instant> = None; let mut last_requeue: Option<Instant> = None;
@@ -464,50 +620,27 @@ pub async fn run(analyzer: Arc<Analyzer>, poll: Duration, stop: watch::Receiver<
Err(e) => tracing::error!(error = %e, "requeueing analyses"), Err(e) => tracing::error!(error = %e, "requeueing analyses"),
} }
} }
// Fill the free slots. // Fill the free slots: the quick lane first, then the slow one.
for lane in [Lane::Quick, Lane::Slow] {
let slots = if lane == Lane::Quick { &quick } else { &slow };
while let Ok(permit) = slots.clone().try_acquire_owned() { while let Ok(permit) = slots.clone().try_acquire_owned() {
// Questions first: someone is waiting for a short answer. let claimed = match lane {
match analyzer.claim_question().await { Lane::Quick => analyzer.claim_quick().await,
Ok(Some(job)) => { Lane::Slow => analyzer.claim_slow().await,
};
match claimed {
Ok(Some(work)) => {
let analyzer = analyzer.clone(); let analyzer = analyzer.clone();
tasks.spawn(async move { tasks.spawn(async move {
analyzer.handle_question(job).await; analyzer.work(work).await;
drop(permit);
});
continue;
}
Ok(None) => {}
Err(e) => {
tracing::error!(error = %e, "claiming a question");
break;
}
}
match analyzer.claim().await {
Ok(Some(job)) => {
let analyzer = analyzer.clone();
tasks.spawn(async move {
analyzer.handle(job).await;
drop(permit);
});
}
// No analysis is due: a prompt test run, if one waits.
Ok(None) => match analyzer.claim_preview().await {
Ok(Some(job)) => {
let analyzer = analyzer.clone();
tasks.spawn(async move {
analyzer.handle_preview(job).await;
drop(permit); drop(permit);
}); });
} }
Ok(None) => break, Ok(None) => break,
Err(e) => { Err(e) => {
tracing::error!(error = %e, "claiming a prompt preview"); tracing::error!(error = %e, ?lane, "claiming work");
break; break;
} }
},
Err(e) => {
tracing::error!(error = %e, "claiming an analysis");
break;
} }
} }
} }
+42 -11
View File
@@ -27,6 +27,8 @@ pub struct QuestionJob {
pub created_at: time::OffsetDateTime, pub created_at: time::OffsetDateTime,
pub fallback_model: Option<String>, pub fallback_model: Option<String>,
pub on_fallback: bool, pub on_fallback: bool,
/// The token of this attempt (see `Job::started_at`).
pub started_at: time::OffsetDateTime,
} }
impl Analyzer { impl Analyzer {
@@ -37,7 +39,7 @@ impl Analyzer {
WHERE id = (SELECT id FROM questions WHERE status = 'pending' AND next_attempt_at <= now() \ WHERE id = (SELECT id FROM questions WHERE status = 'pending' AND next_attempt_at <= now() \
ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \ ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
RETURNING id, analysis_id, question, language, model, prompt_version, attempts, created_at, \ RETURNING id, analysis_id, question, language, model, prompt_version, attempts, created_at, \
fallback_model, on_fallback", fallback_model, on_fallback, started_at",
) )
.fetch_optional(&self.db) .fetch_optional(&self.db)
.await?; .await?;
@@ -49,8 +51,9 @@ impl Analyzer {
async fn question_prompt(&self, job: &QuestionJob) -> Result<prompt::Prompt, LlmError> { async fn question_prompt(&self, job: &QuestionJob) -> Result<prompt::Prompt, LlmError> {
let db_err = |e: sqlx::Error| LlmError::Transient(format!("database: {e}")); let db_err = |e: sqlx::Error| LlmError::Transient(format!("database: {e}"));
let (kind, chart_id, forecast_id, content): (String, Option<Uuid>, Option<Uuid>, Option<Value>) = type Row = (String, Option<Uuid>, Option<Uuid>, Option<Uuid>, Option<Value>);
sqlx::query_as("SELECT kind, chart_id, forecast_id, content FROM analyses WHERE id = $1") let (kind, chart_id, synastry_id, forecast_id, content): Row =
sqlx::query_as("SELECT kind, chart_id, synastry_id, forecast_id, content FROM analyses WHERE id = $1")
.bind(job.analysis_id) .bind(job.analysis_id)
.fetch_optional(&self.db) .fetch_optional(&self.db)
.await .await
@@ -60,6 +63,7 @@ impl Analyzer {
let content = content.ok_or_else(|| LlmError::Permanent("the analysis has no text".into()))?; let content = content.ok_or_else(|| LlmError::Permanent("the analysis has no text".into()))?;
let chart_text = match kind { let chart_text = match kind {
Kind::Forecast => self.forecast_text(forecast_id).await?, Kind::Forecast => self.forecast_text(forecast_id).await?,
Kind::Synastry => self.synastry_text(synastry_id).await?,
_ => self.natal_text(chart_id).await?, _ => self.natal_text(chart_id).await?,
}; };
let analysis = prompt::to_markdown(kind, &job.language, &content); let analysis = prompt::to_markdown(kind, &job.language, &content);
@@ -91,7 +95,8 @@ impl Analyzer {
/// Answers one claimed question and records the outcome. /// Answers one claimed question and records the outcome.
pub async fn handle_question(&self, job: QuestionJob) { pub async fn handle_question(&self, job: QuestionJob) {
let started = Instant::now(); let started = Instant::now();
let result = match self.question_prompt(&job).await { let work = async {
match self.question_prompt(&job).await {
Ok(p) => { Ok(p) => {
let model = active_model(&job.model, job.fallback_model.as_deref(), job.on_fallback); let model = active_model(&job.model, job.fallback_model.as_deref(), job.on_fallback);
self.llm.complete(model, &p).await.map(|mut c| { self.llm.complete(model, &p).await.map(|mut c| {
@@ -100,6 +105,14 @@ impl Analyzer {
}) })
} }
Err(e) => Err(e), Err(e) => Err(e),
}
};
let result = tokio::select! {
result = work => result,
() = self.superseded("questions", job.id, job.started_at) => {
tracing::info!(id = %job.id, "answer restarted by an admin; this attempt is dropped");
return;
}
}; };
if let Err(e) = self.finish_question(&job, result, started.elapsed()).await { if let Err(e) = self.finish_question(&job, result, started.elapsed()).await {
tracing::error!(id = %job.id, error = %e, "saving the answer failed"); tracing::error!(id = %job.id, error = %e, "saving the answer failed");
@@ -119,7 +132,7 @@ impl Analyzer {
sqlx::query( sqlx::query(
"UPDATE questions SET status = 'done', answer = $2, model_used = $3, input_tokens = $4, \ "UPDATE questions SET status = 'done', answer = $2, model_used = $3, input_tokens = $4, \
output_tokens = $5, cost_usd = $6, error = NULL, completed_at = now() \ output_tokens = $5, cost_usd = $6, error = NULL, completed_at = now() \
WHERE id = $1 AND status = 'running'", WHERE id = $1 AND status = 'running' AND started_at = $7",
) )
.bind(job.id) .bind(job.id)
.bind(&answer) .bind(&answer)
@@ -127,6 +140,7 @@ impl Analyzer {
.bind(c.input_tokens) .bind(c.input_tokens)
.bind(c.output_tokens) .bind(c.output_tokens)
.bind(c.cost_usd) .bind(c.cost_usd)
.bind(job.started_at)
.execute(&self.db) .execute(&self.db)
.await?; .await?;
tracing::info!( tracing::info!(
@@ -136,15 +150,25 @@ impl Analyzer {
} }
Err(e) => { Err(e) => {
let can_fall_back = !job.on_fallback && job.fallback_model.is_some(); let can_fall_back = !job.on_fallback && job.fallback_model.is_some();
match next_step(&e, job.attempts, self.max_attempts, can_fall_back) { let next = next_step(&e, job.attempts, self.max_attempts, can_fall_back);
let outcome = match next {
Next::Retry(_) => "retry",
Next::Fallback => "fallback",
Next::Fail => "failed",
};
let model = active_model(&job.model, job.fallback_model.as_deref(), job.on_fallback);
self.log_error("question", job.id, "question", model, job.attempts, outcome, e.message(), took).await;
match next {
Next::Retry(wait) => { Next::Retry(wait) => {
sqlx::query( sqlx::query(
"UPDATE questions SET status = 'pending', error = $2, \ "UPDATE questions SET status = 'pending', error = $2, \
next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1 AND status = 'running'", next_attempt_at = now() + make_interval(secs => $3) \
WHERE id = $1 AND status = 'running' AND started_at = $4",
) )
.bind(job.id) .bind(job.id)
.bind(e.message()) .bind(e.message())
.bind(wait.as_secs_f64()) .bind(wait.as_secs_f64())
.bind(job.started_at)
.execute(&self.db) .execute(&self.db)
.await?; .await?;
tracing::warn!(id = %job.id, attempts = job.attempts, error = %e.message(), "answer will be retried"); tracing::warn!(id = %job.id, attempts = job.attempts, error = %e.message(), "answer will be retried");
@@ -152,10 +176,11 @@ impl Analyzer {
Next::Fallback => { Next::Fallback => {
sqlx::query( sqlx::query(
"UPDATE questions SET status = 'pending', error = $2, on_fallback = true, attempts = 0, \ "UPDATE questions SET status = 'pending', error = $2, on_fallback = true, attempts = 0, \
next_attempt_at = now() WHERE id = $1 AND status = 'running'", next_attempt_at = now() WHERE id = $1 AND status = 'running' AND started_at = $3",
) )
.bind(job.id) .bind(job.id)
.bind(e.message()) .bind(e.message())
.bind(job.started_at)
.execute(&self.db) .execute(&self.db)
.await?; .await?;
tracing::warn!( tracing::warn!(
@@ -164,7 +189,7 @@ impl Analyzer {
); );
} }
Next::Fail => { Next::Fail => {
self.fail_question(job.id, e.message()).await?; self.fail_question(job.id, job.started_at, e.message()).await?;
tracing::error!(id = %job.id, attempts = job.attempts, error = %e.message(), "answer failed"); tracing::error!(id = %job.id, attempts = job.attempts, error = %e.message(), "answer failed");
} }
} }
@@ -174,14 +199,20 @@ impl Analyzer {
} }
/// Marks the question failed and gives its unit back (once). /// Marks the question failed and gives its unit back (once).
async fn fail_question(&self, id: Uuid, message: &str) -> Result<(), sqlx::Error> { async fn fail_question(
&self,
id: Uuid,
started_at: time::OffsetDateTime,
message: &str,
) -> Result<(), sqlx::Error> {
let mut tx = self.db.begin().await?; let mut tx = self.db.begin().await?;
let row: Option<(Option<Uuid>, i32)> = sqlx::query_as( let row: Option<(Option<Uuid>, i32)> = sqlx::query_as(
"UPDATE questions SET status = 'failed', error = $2, completed_at = now() \ "UPDATE questions SET status = 'failed', error = $2, completed_at = now() \
WHERE id = $1 AND status = 'running' RETURNING asked_by, credits_charged", WHERE id = $1 AND status = 'running' AND started_at = $3 RETURNING asked_by, credits_charged",
) )
.bind(id) .bind(id)
.bind(message) .bind(message)
.bind(started_at)
.fetch_optional(&mut *tx) .fetch_optional(&mut *tx)
.await?; .await?;
if let Some((Some(user), units)) = row if let Some((Some(user), units)) = row
+2 -1
View File
@@ -8,7 +8,7 @@ use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600); const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows. /// (what, statement) pairs; each returns the number of deleted rows.
const STATEMENTS: [(&str, &str); 6] = [ const STATEMENTS: [(&str, &str); 7] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"), ("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"), ("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support. // Sent e-mails contain links with tokens; keep them a week for support.
@@ -26,6 +26,7 @@ const STATEMENTS: [(&str, &str); 6] = [
OR (accepted_at IS NOT NULL AND accepted_by IS NULL)", OR (accepted_at IS NOT NULL AND accepted_by IS NULL)",
), ),
("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"), ("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
("generation_errors", "DELETE FROM generation_errors WHERE created_at < now() - interval '90 days'"),
]; ];
pub async fn run_once(db: &PgPool) -> Result<Vec<(&'static str, u64)>, sqlx::Error> { pub async fn run_once(db: &PgPool) -> Result<Vec<(&'static str, u64)>, sqlx::Error> {
+36 -1
View File
@@ -5,7 +5,38 @@ use std::time::Duration;
use anyhow::Context; use anyhow::Context;
use lettre::message::Mailbox; use lettre::message::Mailbox;
/// The jobs a worker process runs (`WORKER_TASKS`, comma-separated).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tasks {
/// Sending the e-mails of `email_outbox`.
pub email: bool,
/// The hourly removal of expired data.
pub cleanup: bool,
/// Writing the analyses and answers with the LLM (both lanes).
pub analyses: bool,
}
impl Tasks {
pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true };
pub fn parse(raw: &str) -> anyhow::Result<Self> {
let mut tasks = Tasks { email: false, cleanup: false, analyses: false };
for name in raw.split(',').map(str::trim).filter(|n| !n.is_empty()) {
match name {
"email" => tasks.email = true,
"cleanup" => tasks.cleanup = true,
"analyses" => tasks.analyses = true,
other => anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses)"),
}
}
anyhow::ensure!(tasks != Tasks { email: false, cleanup: false, analyses: false }, "WORKER_TASKS names no task");
Ok(tasks)
}
}
pub struct Config { pub struct Config {
/// What this process does; all of it by default.
pub tasks: Tasks,
pub database_url: String, pub database_url: String,
/// `smtp://host:port` (plain, e.g. Mailpit), `smtp://user:pass@host:587?tls=required` /// `smtp://host:port` (plain, e.g. Mailpit), `smtp://user:pass@host:587?tls=required`
/// (STARTTLS) or `smtps://...` (TLS). Without it, Amazon SES from the AWS /// (STARTTLS) or `smtps://...` (TLS). Without it, Amazon SES from the AWS
@@ -24,8 +55,10 @@ pub struct Config {
pub openrouter_base_url: String, pub openrouter_base_url: String,
/// Frontend address, sent to OpenRouter as `HTTP-Referer`. /// Frontend address, sent to OpenRouter as `HTTP-Referer`.
pub public_base_url: Option<String>, pub public_base_url: Option<String>,
/// Analyses written at the same time. /// Detailed analyses and forecasts written at the same time (0: none).
pub analysis_concurrency: usize, pub analysis_concurrency: usize,
/// Summaries and answers written at the same time (0: none).
pub quick_concurrency: usize,
/// After this many failed attempts an analysis fails and is refunded. /// After this many failed attempts an analysis fails and is refunded.
pub max_analysis_attempts: i32, pub max_analysis_attempts: i32,
} }
@@ -55,6 +88,7 @@ impl Config {
}, },
}; };
Ok(Self { Ok(Self {
tasks: var("WORKER_TASKS").map(|raw| Tasks::parse(&raw)).transpose()?.unwrap_or(Tasks::ALL),
database_url: var("DATABASE_URL").context("DATABASE_URL is required")?, database_url: var("DATABASE_URL").context("DATABASE_URL is required")?,
smtp_url, smtp_url,
smtp_about, smtp_about,
@@ -67,6 +101,7 @@ impl Config {
.unwrap_or_else(|| crate::analysis::openrouter::DEFAULT_BASE_URL.into()), .unwrap_or_else(|| crate::analysis::openrouter::DEFAULT_BASE_URL.into()),
public_base_url: var("PUBLIC_BASE_URL"), public_base_url: var("PUBLIC_BASE_URL"),
analysis_concurrency: parsed("ANALYSIS_CONCURRENCY", 4)?, analysis_concurrency: parsed("ANALYSIS_CONCURRENCY", 4)?,
quick_concurrency: parsed("QUICK_CONCURRENCY", 2)?,
max_analysis_attempts: parsed("MAX_ANALYSIS_ATTEMPTS", 3)?, max_analysis_attempts: parsed("MAX_ANALYSIS_ATTEMPTS", 3)?,
}) })
} }
+16 -3
View File
@@ -5,6 +5,9 @@
//! * hourly cleanup of expired sessions, tokens, invites and old e-mails //! * hourly cleanup of expired sessions, tokens, invites and old e-mails
//! * writing the requested text analyses with an LLM (OpenRouter) //! * writing the requested text analyses with an LLM (OpenRouter)
//! //!
//! `WORKER_TASKS` (e.g. `email,cleanup` or `analyses`) picks the jobs of one
//! process, so they can run in separate containers; all of them by default.
//!
//! Configuration: see [`config::Config`]; plus `BIND_ADDR` (default //! Configuration: see [`config::Config`]; plus `BIND_ADDR` (default
//! `0.0.0.0:8082`, only `/healthz`), `LOG_FORMAT` and `RUST_LOG`. //! `0.0.0.0:8082`, only `/healthz`), `LOG_FORMAT` and `RUST_LOG`.
//! `worker healthcheck` performs a local health check (for Docker); //! `worker healthcheck` performs a local health check (for Docker);
@@ -91,7 +94,10 @@ async fn main() -> anyhow::Result<()> {
let (stop_tx, stop) = watch::channel(false); let (stop_tx, stop) = watch::channel(false);
let mut jobs = tokio::task::JoinSet::new(); let mut jobs = tokio::task::JoinSet::new();
let tasks = config.tasks;
tracing::info!(email = tasks.email, cleanup = tasks.cleanup, analyses = tasks.analyses, "worker tasks");
match &config.smtp_url { match &config.smtp_url {
_ if !tasks.email => {}
Some(url) => { Some(url) => {
let delivery = email::Delivery::new(pool.clone(), email::Mailer::smtp(url)?, &config); let delivery = email::Delivery::new(pool.clone(), email::Mailer::smtp(url)?, &config);
let via = config.smtp_about.clone().unwrap_or_else(|| "SMTP_URL".into()); let via = config.smtp_about.clone().unwrap_or_else(|| "SMTP_URL".into());
@@ -101,17 +107,24 @@ async fn main() -> anyhow::Result<()> {
None => tracing::warn!("neither SMTP_URL nor SES credentials are set: e-mails stay in the outbox"), None => tracing::warn!("neither SMTP_URL nor SES credentials are set: e-mails stay in the outbox"),
} }
match &config.openrouter_api_key { match &config.openrouter_api_key {
_ if !tasks.analyses => {}
Some(key) => { Some(key) => {
let llm = let llm =
analysis::openrouter::OpenRouter::new(&config.openrouter_base_url, key, config.public_base_url.clone()); analysis::openrouter::OpenRouter::new(&config.openrouter_base_url, key, config.public_base_url.clone());
let analyzer = let lanes = analysis::Lanes { quick: config.quick_concurrency, slow: config.analysis_concurrency };
analysis::Analyzer::new(pool.clone(), llm, config.max_analysis_attempts, config.analysis_concurrency); if lanes.quick + lanes.slow == 0 {
tracing::info!(concurrency = analyzer.concurrency, "analyses enabled"); tracing::warn!("QUICK_CONCURRENCY and ANALYSIS_CONCURRENCY are both 0: this worker writes no analyses");
} else {
let analyzer = analysis::Analyzer::new(pool.clone(), llm, config.max_analysis_attempts, lanes);
tracing::info!(quick = lanes.quick, slow = lanes.slow, "analyses enabled");
jobs.spawn(analysis::run(Arc::new(analyzer), config.poll_interval, stop.clone())); jobs.spawn(analysis::run(Arc::new(analyzer), config.poll_interval, stop.clone()));
} }
}
None => tracing::warn!("OPENROUTER_API_KEY is not set: analyses stay pending"), None => tracing::warn!("OPENROUTER_API_KEY is not set: analyses stay pending"),
} }
if tasks.cleanup {
jobs.spawn(cleanup::run(pool.clone(), stop.clone())); jobs.spawn(cleanup::run(pool.clone(), stop.clone()));
}
let app = Router::new().route("/healthz", get(healthz)).with_state(pool); let app = Router::new().route("/healthz", get(healthz)).with_state(pool);
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?; let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
+148 -6
View File
@@ -212,7 +212,8 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
("emails", 1), ("emails", 1),
("invites", 0), ("invites", 0),
("invitations", 0), ("invitations", 0),
("prompt_previews", 0) ("prompt_previews", 0),
("generation_errors", 0)
] ]
); );
let (left,): (Vec<Uuid>,) = let (left,): (Vec<Uuid>,) =
@@ -222,6 +223,16 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
// --- analyses ---------------------------------------------------------------------------- // --- analyses ----------------------------------------------------------------------------
#[test]
fn worker_tasks_are_chosen_by_name() {
use crate::config::Tasks;
let mail = Tasks::parse("email, cleanup").unwrap();
assert_eq!(mail, Tasks { email: true, cleanup: true, analyses: false });
assert_eq!(Tasks::parse("analyses").unwrap(), Tasks { email: false, cleanup: false, analyses: true });
assert!(Tasks::parse("emails").is_err());
assert!(Tasks::parse(" , ").is_err());
}
mod analyses { mod analyses {
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -234,7 +245,7 @@ mod analyses {
use crate::analysis::openrouter::OpenRouter; use crate::analysis::openrouter::OpenRouter;
use crate::analysis::prompt::{Kind, schema, validate}; use crate::analysis::prompt::{Kind, schema, validate};
use crate::analysis::{Analyzer, backoff}; use crate::analysis::{Analyzer, Lane, Lanes, backoff};
/// Scripted replies (then the last one forever) and the requests received. /// Scripted replies (then the last one forever) and the requests received.
#[derive(Clone, Default)] #[derive(Clone, Default)]
@@ -336,11 +347,11 @@ mod analyses {
} }
fn analyzer(db: &PgPool, base_url: &str) -> Analyzer { fn analyzer(db: &PgPool, base_url: &str) -> Analyzer {
Analyzer::new(db.clone(), OpenRouter::new(base_url, "test-key", None), 3, 2) Analyzer::new(db.clone(), OpenRouter::new(base_url, "test-key", None), 3, Lanes { quick: 1, slow: 2 })
} }
async fn run_once(a: &Analyzer) -> bool { async fn run_once(a: &Analyzer) -> bool {
match a.claim().await.unwrap() { match a.claim(Lane::Slow).await.unwrap() {
Some(job) => { Some(job) => {
a.handle(job).await; a.handle(job).await;
true true
@@ -463,10 +474,10 @@ mod analyses {
let a = analyzer(&db, &url); let a = analyzer(&db, &url);
// the analysis goes first; the preview only when nothing else is due // the analysis goes first; the preview only when nothing else is due
let job = a.claim().await.unwrap().expect("the analysis"); let job = a.claim(Lane::Slow).await.unwrap().expect("the analysis");
assert_eq!(job.id, analysis); assert_eq!(job.id, analysis);
a.handle(job).await; a.handle(job).await;
assert!(a.claim().await.unwrap().is_none()); assert!(a.claim(Lane::Slow).await.unwrap().is_none());
let job = a.claim_preview().await.unwrap().expect("the preview"); let job = a.claim_preview().await.unwrap().expect("the preview");
a.handle_preview(job).await; a.handle_preview(job).await;
let (status, title, model, credits): (String, Option<String>, Option<String>, i64) = sqlx::query_as( let (status, title, model, credits): (String, Option<String>, Option<String>, i64) = sqlx::query_as(
@@ -533,6 +544,18 @@ mod analyses {
let (status, attempts, ..) = row(&db, id).await; let (status, attempts, ..) = row(&db, id).await;
assert_eq!((status.as_str(), attempts), ("failed", 3)); assert_eq!((status.as_str(), attempts), ("failed", 3));
assert_eq!(refunds(&db, s.user).await, vec![1]); assert_eq!(refunds(&db, s.user).await, vec![1]);
// every failed attempt is in the admin error log
let log: Vec<(String, i32, String, String)> = sqlx::query_as(
"SELECT source, attempt, outcome, model FROM generation_errors WHERE item_id = $1 ORDER BY id",
)
.bind(id)
.fetch_all(&db)
.await
.unwrap();
let expected = |attempt: i32, outcome: &str| {
("analysis".to_string(), attempt, outcome.to_string(), "test/model".to_string())
};
assert_eq!(log, vec![expected(1, "retry"), expected(2, "retry"), expected(3, "failed")]);
} }
#[sqlx::test(migrator = "db::MIGRATOR")] #[sqlx::test(migrator = "db::MIGRATOR")]
@@ -780,5 +803,124 @@ mod analyses {
let models: Vec<String> = let models: Vec<String> =
fake.requests.lock().unwrap().iter().map(|b| b["model"].as_str().unwrap().to_string()).collect(); fake.requests.lock().unwrap().iter().map(|b| b["model"].as_str().unwrap().to_string()).collect();
assert_eq!(models, ["cheap/model", "cheap/model", "test/model"]); assert_eq!(models, ["cheap/model", "cheap/model", "test/model"]);
let outcomes: Vec<(String, String)> =
sqlx::query_as("SELECT outcome, model FROM generation_errors WHERE item_id = $1 ORDER BY id")
.bind(id)
.fetch_all(&db)
.await
.unwrap();
assert_eq!(
outcomes,
[("retry".to_string(), "cheap/model".to_string()), ("fallback".to_string(), "cheap/model".to_string())]
);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_restarted_attempt_does_not_write_its_result(db: PgPool) {
let s = setup(&db).await;
let id = request_analysis(&db, &s).await;
let (_, url) = fake_openrouter(vec![reply(&content(Kind::Natal))]).await;
let a = analyzer(&db, &url);
let job = a.claim(Lane::Slow).await.unwrap().expect("a job");
// an admin restarts it while the worker is still writing it
sqlx::query("UPDATE analyses SET status = 'pending', started_at = NULL, attempts = 0 WHERE id = $1")
.bind(id)
.execute(&db)
.await
.unwrap();
a.handle(job).await;
let (status, content): (String, Option<Value>) =
sqlx::query_as("SELECT status, content FROM analyses WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
assert_eq!((status.as_str(), content), ("pending", None));
// the new attempt writes it
assert!(run_once(&a).await);
let status: String =
sqlx::query_scalar("SELECT status FROM analyses WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
assert_eq!(status, "done");
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn summaries_have_their_own_lane(db: PgPool) {
let s = setup(&db).await;
let natal = request_analysis(&db, &s).await;
let summary = |id: Uuid| {
sqlx::query(
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, \
credits_charged) \
VALUES ($1, 'summary', $2, $3, 'hu', 'test/model', 'v1', 'key', 0)",
)
.bind(id)
.bind(s.chart)
.bind(s.user)
};
let first = Uuid::now_v7();
summary(first).execute(&db).await.unwrap();
let a = analyzer(&db, "http://127.0.0.1:9");
// the quick lane takes the summary, never the detailed analysis
let id_of = |work: Option<crate::analysis::Work>| match work {
Some(crate::analysis::Work::Analysis(job)) => Some(job.id),
Some(_) => panic!("not an analysis"),
None => None,
};
assert_eq!(id_of(a.claim_quick().await.unwrap()), Some(first));
assert_eq!(id_of(a.claim_quick().await.unwrap()), None);
// the slow lane prefers the detailed analysis, then helps with quick work
let second = Uuid::now_v7();
summary(second).execute(&db).await.unwrap();
assert_eq!(id_of(a.claim_slow().await.unwrap()), Some(natal));
assert_eq!(id_of(a.claim_slow().await.unwrap()), Some(second));
assert_eq!(id_of(a.claim_slow().await.unwrap()), None);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn answers_a_question_about_a_relationship_with_both_charts(db: PgPool) {
let s = setup(&db).await;
let response = fixture("synastry-response.json");
let (chart2, synastry, analysis) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
sqlx::query(
"INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
VALUES ($1, $2, 'Partner', false, 'person', '{}', $3, 'hash2')",
)
.bind(chart2)
.bind(s.user)
.bind(&response["person2"])
.execute(&db)
.await
.unwrap();
sqlx::query(
"INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
VALUES ($1, $2, $3, $4, $5, 'sh')",
)
.bind(synastry)
.bind(s.user)
.bind(s.chart)
.bind(chart2)
.bind(&response)
.execute(&db)
.await
.unwrap();
sqlx::query(
"INSERT INTO analyses (id, kind, synastry_id, requested_by, language, model, prompt_version, cache_key, \
status, content) VALUES ($1, 'synastry', $2, $3, 'hu', 'test/model', 'v1', 'k', 'done', $4)",
)
.bind(analysis)
.bind(synastry)
.bind(s.user)
.bind(content(Kind::Synastry))
.execute(&db)
.await
.unwrap();
let id = ask(&db, analysis, s.user, "Mire figyeljünk egy vitában?", "pending", None).await;
let (fake, url) = fake_openrouter(vec![reply(&json!({"answer": "Arra, hogy..."}))]).await;
let a = analyzer(&db, &url);
assert!(answer_once(&a).await);
let status: String =
sqlx::query_scalar("SELECT status FROM questions WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
assert_eq!(status, "done");
let requests = fake.requests.lock().unwrap();
let user = requests[0]["messages"][1]["content"].as_str().unwrap();
assert!(user.starts_with("Képletadatok:\n\nSYNASTRY") && user.contains("Person 2"), "both charts");
assert!(!user.contains("Szeged") && !user.contains("Pécs"));
} }
} }