From 1639b0bd87035604f83d08afd4501b046b12aa9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 14:38:12 +0100 Subject: [PATCH 1/4] feat(search): index-backed word search and rating sort, tested at 100k - Search: full-text search on a generated tsvector of title and description with a GIN index (config 'simple', no extension needed). Every word must match as a word prefix, so "chicken rice" finds "Rice with chicken". The query is built from letters and digits only, so user input cannot break the tsquery syntax. Behaviour change: words no longer match mid-word ("cake" does not find "pancakes"). - Highest rated: rating_avg/rating_count cached on recipes and kept in step by a trigger on ratings (covers API, seed and manual SQL); the touch trigger now ignores these columns so rating does not change a recipe's updated time. Summaries read the cached values. - Partial indexes for category, total time and rating whose order matches each ORDER BY; the row query is skipped when the count is 0. - npm run db:seed:large -- | --remove loads or removes a generated catalogue (never run by CI or deploy). Measured locally on 100 000 recipes (EXPLAIN ANALYZE, median of 3): highest rated 439 -> 0.1 ms, quickest 42 -> 0.1 ms, search count 94 -> 10 ms; whole GraphQL list requests 2-29 ms. Numbers and method in docs/performance-and-images.md. Closes #69 Closes #80 --- README.md | 28 +- .../0005_recipe_search_and_ratings.sql | 47 + apps/api/migrations/meta/0005_snapshot.json | 923 ++++++++++++++++++ apps/api/migrations/meta/_journal.json | 7 + apps/api/src/db/schema.ts | 47 + .../src/features/recipes/recipeRepository.ts | 43 +- .../src/features/recipes/recipeSearch.test.ts | 36 + docs/architecture.md | 7 +- docs/database-model.md | 6 +- docs/performance-and-images.md | 44 + docs/recipe-api.md | 4 +- package.json | 1 + scripts/seed-large.ts | 151 +++ scripts/test-recipe-api.ts | 59 ++ scripts/tsconfig.json | 2 +- 15 files changed, 1375 insertions(+), 30 deletions(-) create mode 100644 apps/api/migrations/0005_recipe_search_and_ratings.sql create mode 100644 apps/api/migrations/meta/0005_snapshot.json create mode 100644 apps/api/src/features/recipes/recipeSearch.test.ts create mode 100644 scripts/seed-large.ts diff --git a/README.md b/README.md index 1441d45..985f2ab 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Recipe Platform er en responsiv oppskriftsapplikasjon hvor brukere kan utforske - Registrering, innlogging og utlogging bruker GraphQL, PostgreSQL og HttpOnly-cookies. - Explore, My Cookbook og oppskriftsdetaljer henter data fra API-et. - Oppretting, redigering, sletting, lagring i kokebok og vurderinger lagres i databasen. -- Søk i tittel/beskrivelse, kategori- og tidsfilter samt paginering utføres i backend. Resultatene kan sorteres med nyeste først, kortest tilberedningstid eller høyest vurdering. +- Ordsøk i tittel/beskrivelse (alle ord må finnes), kategori- og tidsfilter samt paginering utføres i backend. Resultatene kan sorteres med nyeste først, kortest tilberedningstid eller høyest vurdering. - Bildeopplasting støtter JPG, PNG og WebP, med tilgangskontroll og opprydding. Applikasjonen bruker ikke lenger prototypeoppskriftene som datakilde. Testene bruker egne fixtures. Valgfri seed oppretter 51 demooppskrifter inkludert bilder; et større eksternt datasett er ikke importert. Se [kjente begrensninger](#kjente-begrensninger). @@ -172,17 +172,18 @@ Oppsett for CI-testdatabase, migrasjoner og utrulling er samlet i [drift og test ## Nyttige kommandoer -| Kommando | Bruk | -| ---------------------- | ------------------------------------------- | -| `npm run dev` | Start utviklingsmiljøet | -| `npm run dev:web` | Start bare React-klienten | -| `npm run dev:api` | Start bare API-et | -| `npm run typecheck` | Kontroller TypeScript i frontend og backend | -| `npm run lint` | Kjør ESLint | -| `npm run format` | Formater kode med Prettier | -| `npm run format:check` | Kontroller formatering uten å endre filer | -| `npm run test` | Kjør Vitest-testene | -| `npm run build` | Bygg workspaces for produksjon | +| Kommando | Bruk | +| --------------------------------- | -------------------------------------------------------- | +| `npm run dev` | Start utviklingsmiljøet | +| `npm run dev:web` | Start bare React-klienten | +| `npm run dev:api` | Start bare API-et | +| `npm run typecheck` | Kontroller TypeScript i frontend og backend | +| `npm run lint` | Kjør ESLint | +| `npm run format` | Formater kode med Prettier | +| `npm run format:check` | Kontroller formatering uten å endre filer | +| `npm run test` | Kjør Vitest-testene | +| `npm run build` | Bygg workspaces for produksjon | +| `npm run db:seed:large -- 100000` | Last 100 000 testoppskrifter (`-- --remove` fjerner dem) | Før en Pull Request bør minst følgende kjøres: @@ -398,7 +399,8 @@ KI-verktøy får ikke ekte passord, tokens, personopplysninger eller andre hemme - Søk dekker tittel og beskrivelse; ingrediens- og tagsøk er videre arbeid. - Trending er ikke implementert. Høyest vurdering bruker gjennomsnittet uten vekting etter antall stemmer. - Utkast beholdes bare i skjemaet og overlever ikke navigering eller oppdatering. -- Seed inneholder 51 demooppskrifter og demonstrerer ikke ytelse med store datamengder. +- Ytelse er målt lokalt med 100 000 genererte oppskrifter (`npm run db:seed:large`), ikke på VM-en. Se [søk og skalerbarhet](docs/performance-and-images.md#søk-og-skalerbarhet). +- Søk finner hele ord og begynnelsen av ord, ikke deler midt i et ord («cake» finner ikke «pancakes»). - Bildeoperasjoner bruker en global lås for korrekt koordinering. Dette begrenser samtidige skriveoperasjoner. - Bildekvoter har faste grenser. Registrering har IP-begrensning, men flere kontoer kan fortsatt omgå brukerkvotene. Refererte bilder teller mot totalgrensen og slettes ikke av cleanup. - VM-en bruker HTTP. Foreleser har avklart at HTTPS ikke er et krav for denne innleveringen, men det er nødvendig for å beskytte innlogging under transport. Bruk bare testpassord. diff --git a/apps/api/migrations/0005_recipe_search_and_ratings.sql b/apps/api/migrations/0005_recipe_search_and_ratings.sql new file mode 100644 index 0000000..40a2af6 --- /dev/null +++ b/apps/api/migrations/0005_recipe_search_and_ratings.sql @@ -0,0 +1,47 @@ +ALTER TABLE "project2"."recipes" ADD COLUMN "rating_avg" numeric;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "rating_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "search_vector" "tsvector" GENERATED ALWAYS AS (to_tsvector('simple'::regconfig, "title" || ' ' || "description")) STORED NOT NULL;--> statement-breakpoint +CREATE INDEX "recipes_public_category_created_idx" ON "project2"."recipes" USING btree ("category","created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint +CREATE INDEX "recipes_public_total_time_idx" ON "project2"."recipes" USING btree (("prep_minutes" + "cook_minutes"),"created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint +CREATE INDEX "recipes_public_rating_idx" ON "project2"."recipes" USING btree ("rating_avg" DESC NULLS LAST,"created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint +CREATE INDEX "recipes_search_idx" ON "project2"."recipes" USING gin ("search_vector");--> statement-breakpoint +-- Keep recipes.rating_avg/rating_count in step with ratings for every write +-- path (API, seed, manual SQL), so the highest-rated sort can use an index. +CREATE FUNCTION "project2"."refresh_recipe_rating"() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + target uuid := CASE WHEN TG_OP = 'DELETE' THEN OLD.recipe_id ELSE NEW.recipe_id END; +BEGIN + UPDATE "project2"."recipes" r + SET rating_avg = s.average, rating_count = s.total + FROM ( + SELECT avg(score) AS average, count(*)::int AS total + FROM "project2"."ratings" WHERE recipe_id = target + ) s + WHERE r.id = target; + RETURN NULL; +END $$; +--> statement-breakpoint +CREATE TRIGGER ratings_refresh_recipe_rating +AFTER INSERT OR UPDATE OF score OR DELETE ON "project2"."ratings" +FOR EACH ROW EXECUTE FUNCTION "project2"."refresh_recipe_rating"(); +--> statement-breakpoint +-- Backfill existing ratings. +UPDATE "project2"."recipes" r +SET rating_avg = s.average, rating_count = s.total +FROM ( + SELECT recipe_id, avg(score) AS average, count(*)::int AS total + FROM "project2"."ratings" GROUP BY recipe_id +) s +WHERE r.id = s.recipe_id; +--> statement-breakpoint +-- A new rating must not change the recipe's "last updated" time: fire the +-- touch trigger only when recipe content (or updated_at itself) is written. +DROP TRIGGER recipes_touch_updated_at ON "project2"."recipes"; +--> statement-breakpoint +CREATE TRIGGER recipes_touch_updated_at +BEFORE UPDATE OF title, description, image_url, category, cuisine, difficulty, + visibility, prep_minutes, cook_minutes, servings, source_recipe_id, author_id, + updated_at +ON "project2"."recipes" +FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"(); diff --git a/apps/api/migrations/meta/0005_snapshot.json b/apps/api/migrations/meta/0005_snapshot.json new file mode 100644 index 0000000..0351e55 --- /dev/null +++ b/apps/api/migrations/meta/0005_snapshot.json @@ -0,0 +1,923 @@ +{ + "id": "fcab55b4-ec14-42f6-b29e-f10d136309ac", + "prevId": "ecd5b606-3009-44eb-a2a2-bfc879930465", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.ratings": { + "name": "ratings", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ratings_recipe_idx": { + "name": "ratings_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ratings_user_id_recipe_id_pk": { + "name": "ratings_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ratings_score_valid": { + "name": "ratings_score_valid", + "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_ingredients": { + "name": "recipe_ingredients", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_ingredients_recipe_position_unique": { + "name": "recipe_ingredients_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_ingredients_name_not_blank": { + "name": "recipe_ingredients_name_not_blank", + "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0" + }, + "recipe_ingredients_amount_positive": { + "name": "recipe_ingredients_amount_positive", + "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric" + }, + "recipe_ingredients_position_positive": { + "name": "recipe_ingredients_position_positive", + "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_instructions": { + "name": "recipe_instructions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_instructions_recipe_position_unique": { + "name": "recipe_instructions_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_instructions_text_not_blank": { + "name": "recipe_instructions_text_not_blank", + "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0" + }, + "recipe_instructions_position_positive": { + "name": "recipe_instructions_position_positive", + "value": "\"project2\".\"recipe_instructions\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_tags": { + "name": "recipe_tags", + "schema": "project2", + "columns": { + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_tags_recipe_id_recipes_id_fk": { + "name": "recipe_tags_recipe_id_recipes_id_fk", + "tableFrom": "recipe_tags", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "recipe_tags_recipe_id_tag_pk": { + "name": "recipe_tags_recipe_id_tag_pk", + "columns": ["recipe_id", "tag"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_tags_normalized": { + "name": "recipe_tags_normalized", + "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))" + } + }, + "isRLSEnabled": false + }, + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_recipe_id": { + "name": "source_recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cuisine": { + "name": "cuisine", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "prep_minutes": { + "name": "prep_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cook_minutes": { + "name": "cook_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "servings": { + "name": "servings", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "rating_avg": { + "name": "rating_avg", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "rating_count": { + "name": "rating_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "search_vector": { + "name": "search_vector", + "type": "tsvector", + "primaryKey": false, + "notNull": true, + "generated": { + "as": "to_tsvector('simple'::regconfig, \"title\" || ' ' || \"description\")", + "type": "stored" + } + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_source_idx": { + "name": "recipes_source_idx", + "columns": [ + { + "expression": "source_recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_created_idx": { + "name": "recipes_public_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_category_created_idx": { + "name": "recipes_public_category_created_idx", + "columns": [ + { + "expression": "category", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "first" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "first" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_total_time_idx": { + "name": "recipes_public_total_time_idx", + "columns": [ + { + "expression": "(\"prep_minutes\" + \"cook_minutes\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "first" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "first" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_rating_idx": { + "name": "recipes_public_rating_idx", + "columns": [ + { + "expression": "rating_avg", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "first" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "first" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_search_idx": { + "name": "recipes_search_idx", + "columns": [ + { + "expression": "search_vector", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "recipes_source_recipe_id_recipes_id_fk": { + "name": "recipes_source_recipe_id_recipes_id_fk", + "tableFrom": "recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["source_recipe_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipes_title_not_blank": { + "name": "recipes_title_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0" + }, + "recipes_category_valid": { + "name": "recipes_category_valid", + "value": "\"project2\".\"recipes\".\"category\" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')" + }, + "recipes_cuisine_not_blank": { + "name": "recipes_cuisine_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0" + }, + "recipes_difficulty_valid": { + "name": "recipes_difficulty_valid", + "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')" + }, + "recipes_visibility_valid": { + "name": "recipes_visibility_valid", + "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')" + }, + "recipes_prep_minutes_nonnegative": { + "name": "recipes_prep_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0" + }, + "recipes_cook_minutes_nonnegative": { + "name": "recipes_cook_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0" + }, + "recipes_servings_positive": { + "name": "recipes_servings_positive", + "value": "\"project2\".\"recipes\".\"servings\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.saved_recipes": { + "name": "saved_recipes", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "saved_recipes_recipe_idx": { + "name": "saved_recipes_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "saved_recipes_user_id_recipe_id_pk": { + "name": "saved_recipes_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.uploaded_images": { + "name": "uploaded_images", + "schema": "project2", + "columns": { + "filename": { + "name": "filename", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "byte_size": { + "name": "byte_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "uploaded_images_owner_idx": { + "name": "uploaded_images_owner_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "uploaded_images_owner_id_users_id_fk": { + "name": "uploaded_images_owner_id_users_id_fk", + "tableFrom": "uploaded_images", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "uploaded_images_size_valid": { + "name": "uploaded_images_size_valid", + "value": "\"project2\".\"uploaded_images\".\"byte_size\" >= 0" + } + }, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index 13c88f1..1b944be 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1793008961317, "tag": "0004_uploaded_images", "breakpoints": true + }, + { + "idx": 5, + "version": "7", + "when": 1794835877793, + "tag": "0005_recipe_search_and_ratings", + "breakpoints": true } ] } diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index 2ac1a59..30ac6a9 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -2,6 +2,7 @@ import { sql } from 'drizzle-orm'; import { type AnyPgColumn, check, + customType, index, integer, numeric, @@ -15,6 +16,11 @@ import { const project2 = pgSchema('project2'); +// PostgreSQL full-text search document; Drizzle has no built-in type for it. +const tsvector = customType<{ data: string }>({ + dataType: () => 'tsvector', +}); + export const users = project2.table( 'users', { @@ -70,13 +76,54 @@ export const recipes = project2.table( updatedAt: timestamp('updated_at', { withTimezone: true }) .defaultNow() .notNull(), + /* + * Cached rating summary, maintained by a trigger on ratings (migration + * 0005) so every write path, including the seed, keeps it correct. Lets + * "highest rated" sort on an index instead of averaging all ratings of + * every matching recipe per request. NULL means no ratings yet. + */ + ratingAvg: numeric('rating_avg'), + ratingCount: integer('rating_count').notNull().default(0), + /* + * Words of title and description for full-text search, kept up to date + * by PostgreSQL. The 'simple' configuration lowercases words without + * language-specific stemming, which suits mixed English and Norwegian. + */ + searchVector: tsvector('search_vector') + .notNull() + .generatedAlwaysAs( + sql`to_tsvector('simple'::regconfig, "title" || ' ' || "description")`, + ), }, (table) => [ index('recipes_author_idx').on(table.authorId), index('recipes_source_idx').on(table.sourceRecipeId), + // One index per public listing order (see recipeRepository list()). index('recipes_public_created_idx') .on(table.createdAt, table.id) .where(sql`${table.visibility} = 'public'`), + index('recipes_public_category_created_idx') + .on( + table.category, + table.createdAt.desc().nullsFirst(), + table.id.desc().nullsFirst(), + ) + .where(sql`${table.visibility} = 'public'`), + index('recipes_public_total_time_idx') + .on( + sql`(${table.prepMinutes} + ${table.cookMinutes})`, + table.createdAt.desc().nullsFirst(), + table.id.desc().nullsFirst(), + ) + .where(sql`${table.visibility} = 'public'`), + index('recipes_public_rating_idx') + .on( + table.ratingAvg.desc().nullsLast(), + table.createdAt.desc().nullsFirst(), + table.id.desc().nullsFirst(), + ) + .where(sql`${table.visibility} = 'public'`), + index('recipes_search_idx').using('gin', table.searchVector), check('recipes_title_not_blank', sql`length(trim(${table.title})) > 0`), check( 'recipes_category_valid', diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index ffd4316..db6dc2b 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -5,6 +5,23 @@ import type { CookbookScope, Recipe } from '../../generated.js'; import type { RecipeInput, ListInput } from './recipeValidation.js'; import { validateImageReference, lockImages } from './imageRepository.js'; +const MAX_SEARCH_TERMS = 8; + +/** + * Turns the user's search text into a PostgreSQL tsquery that matches + * recipes containing every word, each as a prefix: "chick rice" becomes + * "chick:* & rice:*" and finds "Rice with chicken". Only letters and digits + * are kept, so input such as "soup &" or "(" can never break the query + * syntax. Returns '' when there is nothing to search for. + */ +export function toSearchQuery(search: string) { + const words = search.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []; + return words + .slice(0, MAX_SEARCH_TERMS) + .map((word) => `${word}:*`) + .join(' & '); +} + export function createRecipeRepository(pool: Pool = db, schema = 'project2') { if (!/^[a-z_][a-z0-9_]*$/.test(schema)) throw new Error('Invalid database schema.'); @@ -26,8 +43,9 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { function listFilterConditions() { // Keep filter parameters separate from access rules; shared by count and rows. + // $2 is a tsquery from toSearchQuery(); search_vector has a GIN index. return [ - "($2='' OR strpos(lower(r.title || ' ' || r.description),lower($2))>0)", + "($2='' OR r.search_vector @@ to_tsquery('simple',$2))", '($3::text IS NULL OR r.category=$3)', '($4::int IS NULL OR r.prep_minutes+r.cook_minutes <= $4)', ]; @@ -42,7 +60,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { coalesce(r.author_id = $1::uuid,false) AS "isCreatedByCurrentUser", EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved", (SELECT count(*)::int FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id) AS "saveCount", - (SELECT json_build_object('average',coalesce(round(avg(score),1),0)::float,'count',count(*)::int) FROM ${t('ratings')} WHERE recipe_id=r.id) AS rating, + json_build_object('average',coalesce(round(r.rating_avg,1),0)::float,'count',r.rating_count) AS rating, (SELECT score FROM ${t('ratings')} WHERE recipe_id=r.id AND user_id=$1::uuid) AS "userRating", coalesce((SELECT json_agg(json_build_object('id',i.id,'name',i.name,'amount',i.amount::float,'unit',i.unit,'note',i.note) ORDER BY i.position) FROM ${t('recipe_ingredients')} i WHERE i.recipe_id=r.id),'[]') AS ingredients, coalesce((SELECT json_agg(json_build_object('step',i.position,'text',i.text) ORDER BY i.position) FROM ${t('recipe_instructions')} i WHERE i.recipe_id=r.id),'[]') AS instructions, @@ -56,7 +74,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { coalesce(r.author_id=$1::uuid,false) AS "isCreatedByCurrentUser", EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved", coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${t('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags, - (SELECT json_build_object('average',coalesce(round(avg(score),1),0)::float,'count',count(*)::int) FROM ${t('ratings')} WHERE recipe_id=r.id) AS rating + json_build_object('average',coalesce(round(r.rating_avg,1),0)::float,'count',r.rating_count) AS rating FROM ${t('recipes')} r`; async function transaction(work: (client: PoolClient) => Promise) { @@ -147,12 +165,13 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { newest: 'r.created_at DESC,r.id DESC', quickest: 'r.prep_minutes+r.cook_minutes ASC,r.created_at DESC,r.id DESC', - highest_rated: `(SELECT avg(score) FROM ${t('ratings')} WHERE recipe_id=r.id) DESC NULLS LAST,r.created_at DESC,r.id DESC`, + highest_rated: + 'r.rating_avg DESC NULLS LAST,r.created_at DESC,r.id DESC', }[input.sort]; const where = ` WHERE ${[listAccessCondition(scope), ...listFilterConditions()].join(' AND ')}`; const args = [ userId, - input.search, + toSearchQuery(input.search), input.category ?? null, input.maxCookingMinutes ?? null, ]; @@ -167,10 +186,16 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { const totalCount = count.rows[0]!.total; const totalPages = Math.ceil(totalCount / input.pageSize); const page = Math.min(input.page, Math.max(totalPages, 1)); - const rows = await client.query( - summarySelect + where + ` ORDER BY ${order} LIMIT $5 OFFSET $6`, - [...args, input.pageSize, (page - 1) * input.pageSize], - ); + // With no matches there is nothing to fetch. Skipping the query also + // avoids a worst case: for a word that matches nothing, the planner + // may scan the whole date index looking for a first page. + const rows = + totalCount === 0 + ? { rows: [] } + : await client.query( + summarySelect + where + ` ORDER BY ${order} LIMIT $5 OFFSET $6`, + [...args, input.pageSize, (page - 1) * input.pageSize], + ); return { items: rows.rows, totalCount, diff --git a/apps/api/src/features/recipes/recipeSearch.test.ts b/apps/api/src/features/recipes/recipeSearch.test.ts new file mode 100644 index 0000000..d165f29 --- /dev/null +++ b/apps/api/src/features/recipes/recipeSearch.test.ts @@ -0,0 +1,36 @@ +// @vitest-environment node +import { describe, expect, it } from 'vitest'; +import { toSearchQuery } from './recipeRepository.js'; + +describe('toSearchQuery', () => { + it('requires every word and matches word prefixes', () => { + expect(toSearchQuery('chicken rice')).toBe('chicken:* & rice:*'); + expect(toSearchQuery(' Chick ')).toBe('chick:*'); + }); + + it('keeps non-English letters and digits', () => { + expect(toSearchQuery('Palačinke')).toBe('palačinke:*'); + expect(toSearchQuery('bringebær muffins')).toBe('bringebær:* & muffins:*'); + expect(toSearchQuery('15 min')).toBe('15:* & min:*'); + }); + + it('splits hyphenated words like the database does', () => { + expect(toSearchQuery('sunny-side-up')).toBe('sunny:* & side:* & up:*'); + }); + + it('drops tsquery syntax so user input can never break the query', () => { + expect(toSearchQuery('soup &')).toBe('soup:*'); + expect(toSearchQuery("it's (soup) | !cake:*")).toBe( + 'it:* & s:* & soup:* & cake:*', + ); + }); + + it('returns an empty query when there is nothing to search for', () => { + expect(toSearchQuery('')).toBe(''); + expect(toSearchQuery('&|!():*')).toBe(''); + }); + + it('caps very long searches at eight words', () => { + expect(toSearchQuery('a b c d e f g h i j').split(' & ')).toHaveLength(8); + }); +}); diff --git a/docs/architecture.md b/docs/architecture.md index 38c61f4..e89baf9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -42,9 +42,10 @@ dermed ikke Drizzle som spørringsbygger i repositories. SQL-valget gir direkte kontroll over tilgangsvilkår, aggregater og transaksjoner, men krever at SQL og resultattyper vedlikeholdes og testes. -Søk og filtre utføres før `LIMIT`/`OFFSET`. Det finnes indekser for blant annet -forfatter, offentlige oppskrifters opprettingstid og relasjoner. Et stort datasett -og målinger av spørringsplaner trengs før vi kan hevde at løsningen skalerer godt. +Søk og filtre utføres før `LIMIT`/`OFFSET`. Ordsøk bruker PostgreSQL-fulltekstsøk +med GIN-indeks, og hver sortering har en indeks som matcher `ORDER BY`. Løsningen +er målt med 100 000 genererte oppskrifter; se +[søk og skalerbarhet](performance-and-images.md#søk-og-skalerbarhet). ## Klientens dataflyt diff --git a/docs/database-model.md b/docs/database-model.md index f90830d..53d3295 100644 --- a/docs/database-model.md +++ b/docs/database-model.md @@ -69,8 +69,10 @@ senere API. Indekser støtter oppslag etter forfatter, offentlige oppskrifter sortert etter opprettelsesdato og ID, og lagringer/vurderinger per oppskrift. De sammensatte primærnøklene støtter brukerens egne lagringer og vurderinger. Unike indekser -støtter ordnede ingredienser og steg. Flere søke- og filterindekser bør velges -etter at API-spørringene finnes og kan måles. +støtter ordnede ingredienser og steg. Migrasjon 0005 legger til fulltekstsøk +(`search_vector` med GIN-indeks), lagret vurderingssnitt (`rating_avg`, +`rating_count`, vedlikeholdt av en trigger) og delindekser for kategori, tid og +vurdering. Se [søk og skalerbarhet](performance-and-images.md#søk-og-skalerbarhet). ## Klar for CRUD diff --git a/docs/performance-and-images.md b/docs/performance-and-images.md index c2eda90..b0a2c3a 100644 --- a/docs/performance-and-images.md +++ b/docs/performance-and-images.md @@ -13,6 +13,50 @@ bruker gjennomsnittet av avgitte vurderinger; oppskrifter uten vurderinger komme sist. Like resultater sorteres stabilt etter opprettingstid og ID. Sortering utføres i SQL før `LIMIT`/`OFFSET`, slik at den gjelder hele resultatsettet. +## Søk og skalerbarhet + +Alle listevisninger er indeksstøttet, slik at kostnaden ikke vokser med hele +katalogen (migrasjon `0005_recipe_search_and_ratings.sql`): + +- **Ordsøk:** `recipes.search_vector` er en generert `tsvector` av tittel og + beskrivelse med GIN-indeks (PostgreSQL-fulltekstsøk, konfigurasjon `simple` + uten språkspesifikk bøying). Søketeksten deles i ord i API-et, og alle ord må + finnes som begynnelsen av et ord: «chick rice» finner «Rice with chicken». + Spesialtegn fjernes, så brukerinput kan ikke gi syntaksfeil. Delord midt i et + ord gir ikke treff («cake» finner ikke «pancakes»). Fulltekstsøk krever ingen + utvidelse som `pg_trgm`, og dermed ingen ekstra databaserettigheter. +- **Høyest vurdert:** `rating_avg` og `rating_count` lagres på oppskriften og + holdes oppdatert av en trigger på `ratings`. Sorteringen bruker en indeks i + stedet for å regne gjennomsnitt for alle treff ved hver forespørsel. +- **Kategori og kortest tid:** egne delindekser for offentlige oppskrifter, + med samme rekkefølge som `ORDER BY` i spørringen. +- Når totalantallet er 0, hoppes radspørringen over. + +### Målinger med 100 000 oppskrifter + +`npm run db:seed:large -- 100000` legger til 100 000 genererte oppskrifter +(635 000 ingredienser, 230 000 vurderinger) basert på demooppskriftene, og +`npm run db:seed:large -- --remove` fjerner dem igjen. Skriptet kjøres aldri av +CI eller deploy. Målingene under er gjort lokalt (PostgreSQL 16 i Docker på en +utviklermaskin), median av tre kjøringer med `EXPLAIN ANALYZE`. «Før» er de +gamle spørringene med de nye indeksene fjernet, på de samme dataene. + +| Spørring (offentlige oppskrifter) | Før | Etter | Plan etter | +| ------------------------------------ | ------ | ------ | ------------------------------------- | +| Høyest vurdert, første side | 439 ms | 0,1 ms | `recipes_public_rating_idx` | +| Kortest tid, første side | 42 ms | 0,1 ms | `recipes_public_total_time_idx` | +| Søk «chicken», antall treff | 94 ms | 10 ms | `recipes_search_idx` (GIN) | +| Søk «gingerbread», antall treff | 52 ms | 3,5 ms | `recipes_search_idx` (GIN) | +| Søk uten treff, antall + første side | 228 ms | 0,1 ms | GIN-indeks; radspørring hoppes over | +| Kategori «soup», første side | 0,3 ms | 0,2 ms | `recipes_public_category_created_idx` | +| Nyeste, side 1000 (`OFFSET` 5994) | 61 ms | 26 ms | `recipes_public_created_idx` | + +Hele GraphQL-forespørsler (API + database) tok 2–29 ms for alle kombinasjoner +som ble testet, også side 1000. Dyp paginering med `OFFSET` vokser fortsatt +lineært med sidetallet; markørbasert paginering (keyset) er mulig videre arbeid. +Kombinasjoner av filter og sortering uten egen indeks (for eksempel kategori og +høyest vurdert) bruker en av indeksene og sorterer resten. + ## Kortlivet minnecache Oppskriftslesinger caches i nettleserens minne i 30 sekunder, med maksimalt 40 diff --git a/docs/recipe-api.md b/docs/recipe-api.md index cb939bb..e496939 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -131,7 +131,7 @@ dokumenter i `contracts/generated.ts`. Regenerer med `npm run types:api`. | `unsaveRecipe(id)` | Fjerner bare egen lagring; idempotent, også etter at oppskriften blir privat. | | `cookbook(input, scope)` | Krever innlogging. Scope er `all`, `saved` eller `created`. | -Listeinput støtter `search` (tittel/beskrivelse), `category`, `maxCookingMinutes`, +Listeinput støtter `search` (ordsøk i tittel/beskrivelse; alle ord må finnes, som begynnelse av ord), `category`, `maxCookingMinutes`, `sort`, `page` og `pageSize` (1–50, standard 6). Filtrering, sortering og paginering skjer i SQL. Standard er nyeste først. Kortest tilberedningstid og høyest vurdering støttes også, med opprettingstid og ID som stabile tie-breakere. En side utenfor området begrenses til siste side. Tom liste har `totalPages: 0` og `page: 1`. @@ -180,7 +180,7 @@ ukjente oppskrifter gir samme feil og avslører ikke private data. som strenger, men inline enumverdier skrives uten anførselstegn. Cookbook- operasjoner må deklarere `$scope: CookbookScope`, ikke `$scope: String`. Bruk de regenererte kontraktene; ingen databasemigrasjon er nødvendig. -- Søk gjelder foreløpig bare tittel/beskrivelse. Mock-søket inkluderer også +- Søk gjelder tittel/beskrivelse som ordsøk (fulltekst). Mock-søket inkluderer også ingredienser/tagger og normaliserer bindestrek, understrek og mellomrom mer omfattende. UI-et beskriver det faktiske søkeomfanget. Behold søkeinput ved datagrensen; ingrediens-/taggsøk og felles diff --git a/package.json b/package.json index 09c0afc..80fc263 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts", "test:api": "tsx --env-file-if-exists=.env scripts/test-recipe-api.ts", "db:seed": "tsx --env-file-if-exists=.env apps/api/src/db/seed.ts", + "db:seed:large": "tsx --env-file-if-exists=.env scripts/seed-large.ts", "images:cleanup": "tsx --env-file-if-exists=.env scripts/cleanup-images.ts" }, "devDependencies": { diff --git a/scripts/seed-large.ts b/scripts/seed-large.ts new file mode 100644 index 0000000..e300e6d --- /dev/null +++ b/scripts/seed-large.ts @@ -0,0 +1,151 @@ +/* + * Loads a large generated recipe catalogue for scalability testing. + * + * npm run db:seed:large -- 100000 add 100 000 recipes + * npm run db:seed:large -- --remove delete everything this script added + * + * Explicit opt-in, like db:seed; never run by CI or deploy. Run db:seed first: + * the 51 demo recipes are used as templates (title, text, image, ingredients, + * steps, tags), with varied names, times, dates and visibility. All rows + * belong to one "Load Test Cook" account that cannot log in, so --remove + * deletes them (and their ratings) through ON DELETE CASCADE. + */ +import { Pool } from 'pg'; + +const SCHEMA = 'project2'; +const LOAD_AUTHOR_ID = '22222222-2222-4222-8222-222222222222'; +const RATER_COUNT = 200; +const t = (name: string) => `"${SCHEMA}"."${name}"`; + +const argument = process.argv[2]; +if (!argument || (argument !== '--remove' && !/^\d+$/.test(argument))) { + console.error('Usage: npm run db:seed:large -- | --remove'); + process.exit(1); +} + +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); +const client = await pool.connect(); +try { + await client.query('BEGIN'); + if (argument === '--remove') { + // Raters are identified by their reserved e-mail domain. + const removed = await client.query( + `DELETE FROM ${t('recipes')} WHERE author_id = $1`, + [LOAD_AUTHOR_ID], + ); + await client.query( + `DELETE FROM ${t('users')} WHERE id = $1 OR email LIKE '%@load-test.invalid'`, + [LOAD_AUTHOR_ID], + ); + await client.query('COMMIT'); + console.log(`Removed ${removed.rowCount} generated recipes.`); + } else { + const count = Number(argument); + const templates = await client.query( + `SELECT count(*)::int AS n FROM ${t('recipes')} + WHERE author_id = '11111111-1111-4111-8111-111111111111'`, + ); + if (!templates.rows[0].n) + throw new Error('Run npm run db:seed first; its recipes are templates.'); + + // Password hash '!' matches no password, so these accounts cannot log in. + await client.query( + `INSERT INTO ${t('users')} (id, name, email, password_hash) + VALUES ($1, 'Load Test Cook', 'cook@load-test.invalid', '!') + ON CONFLICT DO NOTHING`, + [LOAD_AUTHOR_ID], + ); + await client.query( + `INSERT INTO ${t('users')} (name, email, password_hash) + SELECT 'Load Test Rater ' || g, 'rater-' || g || '@load-test.invalid', '!' + FROM generate_series(1, $1::int) g + ON CONFLICT DO NOTHING`, + [RATER_COUNT], + ); + + // Each generated recipe copies template n = g mod 51 with a new name, + // cooking time, creation date (spread over two years) and visibility. + await client.query( + `CREATE TEMP TABLE generated ON COMMIT DROP AS + WITH template AS ( + SELECT r.*, row_number() OVER (ORDER BY r.id) - 1 AS n, + count(*) OVER () AS total + FROM ${t('recipes')} r + WHERE r.author_id = '11111111-1111-4111-8111-111111111111' + ) + SELECT gen_random_uuid() AS id, tp.id AS template_id, g + FROM generate_series(1, $1::int) g + JOIN template tp ON tp.n = g % tp.total`, + [count], + ); + await client.query( + `INSERT INTO ${t('recipes')} (id, author_id, title, description, + image_url, category, cuisine, difficulty, visibility, + prep_minutes, cook_minutes, servings, created_at, updated_at) + SELECT x.id, $1, (ARRAY['Quick','Easy','Spicy','Family','Weekend', + 'Classic','Rustic','Light','Hearty','Simple','Festive','Budget']) + [1 + x.g % 12] || ' ' || r.title || ' ' || x.g, + r.description, r.image_url, r.category, r.cuisine, r.difficulty, + CASE WHEN x.g % 10 = 0 THEN 'private' ELSE 'public' END, + greatest(0, r.prep_minutes + (x.g % 21) - 10), + greatest(0, r.cook_minutes + (x.g % 31) - 15), + r.servings, + now() - (x.g * interval '10 minutes'), + now() - (x.g * interval '10 minutes') + FROM generated x JOIN ${t('recipes')} r ON r.id = x.template_id`, + [LOAD_AUTHOR_ID], + ); + for (const [table, columns] of [ + ['recipe_ingredients', 'name, amount, unit, note, position'], + ['recipe_instructions', 'text, position'], + ['recipe_tags', 'tag'], + ] as const) + await client.query( + `INSERT INTO ${t(table)} (recipe_id, ${columns}) + SELECT x.id, ${columns + .split(', ') + .map((column) => 'c.' + column) + .join(', ')} + FROM generated x JOIN ${t(table)} c ON c.recipe_id = x.template_id`, + ); + + // About three ratings per public recipe. The per-row rating trigger is + // paused for the bulk insert and the cached columns refreshed once. + await client.query( + `ALTER TABLE ${t('ratings')} DISABLE TRIGGER ratings_refresh_recipe_rating`, + ); + await client.query( + `INSERT INTO ${t('ratings')} (recipe_id, user_id, score) + SELECT x.id, u.id, 1 + (abs(hashtext(x.id::text || u.id::text)) % 5) + FROM generated x + JOIN ${t('recipes')} r ON r.id = x.id AND r.visibility = 'public' + CROSS JOIN LATERAL ( + SELECT id FROM ${t('users')} + WHERE email LIKE 'rater-%@load-test.invalid' + ORDER BY md5(x.id::text || id::text) LIMIT (x.g % 6) + ) u + ON CONFLICT DO NOTHING`, + ); + await client.query( + `ALTER TABLE ${t('ratings')} ENABLE TRIGGER ratings_refresh_recipe_rating`, + ); + await client.query( + `UPDATE ${t('recipes')} r SET rating_avg = s.average, rating_count = s.total + FROM (SELECT recipe_id, avg(score) AS average, count(*)::int AS total + FROM ${t('ratings')} GROUP BY recipe_id) s + WHERE r.id = s.recipe_id AND r.author_id = $1`, + [LOAD_AUTHOR_ID], + ); + await client.query('COMMIT'); + // Fresh statistics so the planner sees the new table sizes. + await client.query(`ANALYZE ${t('recipes')}`); + await client.query(`ANALYZE ${t('ratings')}`); + console.log(`Added ${count} generated recipes.`); + } +} catch (error) { + await client.query('ROLLBACK'); + throw error; +} finally { + client.release(); + await pool.end(); +} diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index 75befa0..3b5774b 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -637,6 +637,65 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { } }, ); + await t.test( + 'word search and cached ratings are index-backed and stay correct', + async () => { + const created: string[] = []; + const search = async (text: string) => + ( + await ok(RecipesDocument, { + input: { search: text, pageSize: 50 }, + }) + ).recipes.items.map((item) => item.title); + try { + for (const title of ['Rice with chicken', 'Slovenian palačinke']) + created.push( + ( + await ok( + CreateRecipeDocument, + { input: { ...input, title } }, + owner.cookie, + ) + ).createRecipe.id, + ); + // Every word must match, in any order; words match as prefixes. + assert.deepEqual(await search('chicken rice'), ['Rice with chicken']); + assert.deepEqual(await search('CHICK'), ['Rice with chicken']); + assert.deepEqual(await search('chicken cake'), []); + assert.deepEqual(await search('Palačinke'), ['Slovenian palačinke']); + // Query syntax in user input is ignored, never a server error. + assert.deepEqual(await search('rice & (chicken'), [ + 'Rice with chicken', + ]); + assert.ok((await search('&|!')).length >= created.length); + + // A trigger keeps the cached rating summary in step with ratings. + const before = (await ok(RecipeDocument, { id: created[0]! })) + .recipe!; + await ok( + RateRecipeDocument, + { id: created[0]!, score: 4 }, + reader.cookie, + ); + const rated = (await ok(RecipeDocument, { id: created[0]! })).recipe!; + assert.deepEqual(rated.rating, { average: 4, count: 1 }); + // Rating a recipe does not count as editing it. + assert.equal(rated.updatedAt, before.updatedAt); + await ok( + RemoveRecipeRatingDocument, + { id: created[0]! }, + reader.cookie, + ); + assert.deepEqual( + (await ok(RecipeDocument, { id: created[0]! })).recipe!.rating, + { average: 0, count: 0 }, + ); + } finally { + for (const id of created) + await ok(DeleteRecipeDocument, { id }, owner.cookie); + } + }, + ); await t.test('only the owner can update or delete', async () => { await fails( UpdateRecipeDocument, diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json index c532c65..9874c65 100644 --- a/scripts/tsconfig.json +++ b/scripts/tsconfig.json @@ -6,5 +6,5 @@ "types": ["node"], "noEmit": true }, - "include": ["test-recipe-api.ts", "cleanup-images.ts"] + "include": ["test-recipe-api.ts", "cleanup-images.ts", "seed-large.ts"] } From ecfef653066b0a8cc8b464dab0d80953c7b5760b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 15:04:45 +0100 Subject: [PATCH 2/4] feat(search): search ingredient names and tags as well Following team review: the search document now covers title, description, ingredient names and tags. search_vector is a plain column kept current by a row trigger on recipes and statement-level triggers on recipe_ingredients/recipe_tags, so one search still hits one row per recipe (no duplicates, exact counts, same visibility rules). seed-large now runs VACUUM ANALYZE after loading (the triggers leave dead rows that made counts several times slower). Docs updated with new measurements and a warning to use a separate test database, never production. Refs #69, #80 --- README.md | 5 +- .../0005_recipe_search_and_ratings.sql | 57 ++++++++++++++++- apps/api/migrations/meta/0005_snapshot.json | 7 +-- apps/api/migrations/meta/_journal.json | 2 +- apps/api/src/db/schema.ts | 12 ++-- .../src/features/cookbook/CookbookPage.tsx | 2 +- apps/web/src/features/explore/ExplorePage.tsx | 2 +- docs/architecture.md | 2 +- docs/performance-and-images.md | 36 +++++++---- docs/recipe-api.md | 10 ++- scripts/seed-large.ts | 19 ++++-- scripts/test-recipe-api.ts | 63 +++++++++++++++++++ 12 files changed, 173 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 985f2ab..822de9f 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Recipe Platform er en responsiv oppskriftsapplikasjon hvor brukere kan utforske - Registrering, innlogging og utlogging bruker GraphQL, PostgreSQL og HttpOnly-cookies. - Explore, My Cookbook og oppskriftsdetaljer henter data fra API-et. - Oppretting, redigering, sletting, lagring i kokebok og vurderinger lagres i databasen. -- Ordsøk i tittel/beskrivelse (alle ord må finnes), kategori- og tidsfilter samt paginering utføres i backend. Resultatene kan sorteres med nyeste først, kortest tilberedningstid eller høyest vurdering. +- Ordsøk i tittel, beskrivelse, ingredienser og tagger (alle ord må finnes), kategori- og tidsfilter samt paginering utføres i backend. Resultatene kan sorteres med nyeste først, kortest tilberedningstid eller høyest vurdering. - Bildeopplasting støtter JPG, PNG og WebP, med tilgangskontroll og opprydding. Applikasjonen bruker ikke lenger prototypeoppskriftene som datakilde. Testene bruker egne fixtures. Valgfri seed oppretter 51 demooppskrifter inkludert bilder; et større eksternt datasett er ikke importert. Se [kjente begrensninger](#kjente-begrensninger). @@ -396,10 +396,9 @@ KI-verktøy får ikke ekte passord, tokens, personopplysninger eller andre hemme ## Kjente begrensninger -- Søk dekker tittel og beskrivelse; ingrediens- og tagsøk er videre arbeid. - Trending er ikke implementert. Høyest vurdering bruker gjennomsnittet uten vekting etter antall stemmer. - Utkast beholdes bare i skjemaet og overlever ikke navigering eller oppdatering. -- Ytelse er målt lokalt med 100 000 genererte oppskrifter (`npm run db:seed:large`), ikke på VM-en. Se [søk og skalerbarhet](docs/performance-and-images.md#søk-og-skalerbarhet). +- Ytelse er målt lokalt med 100 000 genererte oppskrifter (`npm run db:seed:large`) i en egen testdatabase, ikke på VM-en. Se [søk og skalerbarhet](docs/performance-and-images.md#søk-og-skalerbarhet). - Søk finner hele ord og begynnelsen av ord, ikke deler midt i et ord («cake» finner ikke «pancakes»). - Bildeoperasjoner bruker en global lås for korrekt koordinering. Dette begrenser samtidige skriveoperasjoner. - Bildekvoter har faste grenser. Registrering har IP-begrensning, men flere kontoer kan fortsatt omgå brukerkvotene. Refererte bilder teller mot totalgrensen og slettes ikke av cleanup. diff --git a/apps/api/migrations/0005_recipe_search_and_ratings.sql b/apps/api/migrations/0005_recipe_search_and_ratings.sql index 40a2af6..8ff9f36 100644 --- a/apps/api/migrations/0005_recipe_search_and_ratings.sql +++ b/apps/api/migrations/0005_recipe_search_and_ratings.sql @@ -1,10 +1,11 @@ ALTER TABLE "project2"."recipes" ADD COLUMN "rating_avg" numeric;--> statement-breakpoint ALTER TABLE "project2"."recipes" ADD COLUMN "rating_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint -ALTER TABLE "project2"."recipes" ADD COLUMN "search_vector" "tsvector" GENERATED ALWAYS AS (to_tsvector('simple'::regconfig, "title" || ' ' || "description")) STORED NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "search_vector" "tsvector" DEFAULT ''::tsvector NOT NULL;--> statement-breakpoint CREATE INDEX "recipes_public_category_created_idx" ON "project2"."recipes" USING btree ("category","created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint CREATE INDEX "recipes_public_total_time_idx" ON "project2"."recipes" USING btree (("prep_minutes" + "cook_minutes"),"created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint CREATE INDEX "recipes_public_rating_idx" ON "project2"."recipes" USING btree ("rating_avg" DESC NULLS LAST,"created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint -CREATE INDEX "recipes_search_idx" ON "project2"."recipes" USING gin ("search_vector");--> statement-breakpoint +CREATE INDEX "recipes_search_idx" ON "project2"."recipes" USING gin ("search_vector"); +--> statement-breakpoint -- Keep recipes.rating_avg/rating_count in step with ratings for every write -- path (API, seed, manual SQL), so the highest-rated sort can use an index. CREATE FUNCTION "project2"."refresh_recipe_rating"() RETURNS trigger @@ -45,3 +46,55 @@ BEFORE UPDATE OF title, description, image_url, category, cuisine, difficulty, updated_at ON "project2"."recipes" FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"(); +--> statement-breakpoint +-- Full-text search document: title, description, ingredient names and tags. +CREATE FUNCTION "project2"."recipe_search_document"(recipe uuid, title text, description text) +RETURNS tsvector LANGUAGE sql STABLE AS $$ + SELECT to_tsvector('simple', concat_ws(' ', title, description, + (SELECT string_agg(i.name, ' ') FROM "project2"."recipe_ingredients" i WHERE i.recipe_id = recipe), + (SELECT string_agg(t.tag, ' ') FROM "project2"."recipe_tags" t WHERE t.recipe_id = recipe))) +$$; +--> statement-breakpoint +CREATE FUNCTION "project2"."set_recipe_search_vector"() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + NEW.search_vector := "project2"."recipe_search_document"(NEW.id, NEW.title, NEW.description); + RETURN NEW; +END $$; +--> statement-breakpoint +CREATE TRIGGER recipes_set_search_vector +BEFORE INSERT OR UPDATE OF title, description ON "project2"."recipes" +FOR EACH ROW EXECUTE FUNCTION "project2"."set_recipe_search_vector"(); +--> statement-breakpoint +-- Statement-level: one refresh per INSERT/UPDATE/DELETE statement on +-- ingredients or tags, for every recipe the statement touched ("changed"). +CREATE FUNCTION "project2"."refresh_recipe_search_vector"() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + UPDATE "project2"."recipes" r + SET search_vector = "project2"."recipe_search_document"(r.id, r.title, r.description) + WHERE r.id IN (SELECT DISTINCT recipe_id FROM changed); + RETURN NULL; +END $$; +--> statement-breakpoint +CREATE TRIGGER recipe_ingredients_search_insert AFTER INSERT ON "project2"."recipe_ingredients" +REFERENCING NEW TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +--> statement-breakpoint +CREATE TRIGGER recipe_ingredients_search_update AFTER UPDATE ON "project2"."recipe_ingredients" +REFERENCING NEW TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +--> statement-breakpoint +CREATE TRIGGER recipe_ingredients_search_delete AFTER DELETE ON "project2"."recipe_ingredients" +REFERENCING OLD TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +--> statement-breakpoint +CREATE TRIGGER recipe_tags_search_insert AFTER INSERT ON "project2"."recipe_tags" +REFERENCING NEW TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +--> statement-breakpoint +CREATE TRIGGER recipe_tags_search_update AFTER UPDATE ON "project2"."recipe_tags" +REFERENCING NEW TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +--> statement-breakpoint +CREATE TRIGGER recipe_tags_search_delete AFTER DELETE ON "project2"."recipe_tags" +REFERENCING OLD TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +--> statement-breakpoint +-- Backfill existing recipes. +UPDATE "project2"."recipes" +SET search_vector = "project2"."recipe_search_document"(id, title, description); diff --git a/apps/api/migrations/meta/0005_snapshot.json b/apps/api/migrations/meta/0005_snapshot.json index 0351e55..1b72c2f 100644 --- a/apps/api/migrations/meta/0005_snapshot.json +++ b/apps/api/migrations/meta/0005_snapshot.json @@ -1,5 +1,5 @@ { - "id": "fcab55b4-ec14-42f6-b29e-f10d136309ac", + "id": "1c6400ab-7455-4e6f-8c2e-a9e6b7053209", "prevId": "ecd5b606-3009-44eb-a2a2-bfc879930465", "version": "7", "dialect": "postgresql", @@ -440,10 +440,7 @@ "type": "tsvector", "primaryKey": false, "notNull": true, - "generated": { - "as": "to_tsvector('simple'::regconfig, \"title\" || ' ' || \"description\")", - "type": "stored" - } + "default": "''::tsvector" } }, "indexes": { diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index 1b944be..8266efe 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -40,7 +40,7 @@ { "idx": 5, "version": "7", - "when": 1794835877793, + "when": 1794837583052, "tag": "0005_recipe_search_and_ratings", "breakpoints": true } diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index 30ac6a9..166d9b6 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -85,15 +85,15 @@ export const recipes = project2.table( ratingAvg: numeric('rating_avg'), ratingCount: integer('rating_count').notNull().default(0), /* - * Words of title and description for full-text search, kept up to date - * by PostgreSQL. The 'simple' configuration lowercases words without - * language-specific stemming, which suits mixed English and Norwegian. + * Words of the title, description, ingredient names and tags for + * full-text search. Triggers keep it current when the recipe or its + * ingredients or tags change (migration 0005). The 'simple' + * configuration lowercases words without language-specific stemming, + * which suits mixed English and Norwegian. */ searchVector: tsvector('search_vector') .notNull() - .generatedAlwaysAs( - sql`to_tsvector('simple'::regconfig, "title" || ' ' || "description")`, - ), + .default(sql`''::tsvector`), }, (table) => [ index('recipes_author_idx').on(table.authorId), diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx index bf753b4..a5c4783 100644 --- a/apps/web/src/features/cookbook/CookbookPage.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.tsx @@ -327,7 +327,7 @@ function CookbookPage() { type="search" name="search" value={searchInput} - placeholder="Search recipe titles or descriptions..." + placeholder="Search recipes, ingredients or tags..." autoComplete="off" onChange={(event) => { const value = event.currentTarget.value; diff --git a/apps/web/src/features/explore/ExplorePage.tsx b/apps/web/src/features/explore/ExplorePage.tsx index f5e486c..8be9479 100644 --- a/apps/web/src/features/explore/ExplorePage.tsx +++ b/apps/web/src/features/explore/ExplorePage.tsx @@ -294,7 +294,7 @@ function ExplorePage() { type="search" name="search" value={searchInput} - placeholder="Search recipe titles or descriptions..." + placeholder="Search recipes, ingredients or tags..." autoComplete="off" onChange={(event) => { const value = event.currentTarget.value; diff --git a/docs/architecture.md b/docs/architecture.md index e89baf9..5934d63 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -42,7 +42,7 @@ dermed ikke Drizzle som spørringsbygger i repositories. SQL-valget gir direkte kontroll over tilgangsvilkår, aggregater og transaksjoner, men krever at SQL og resultattyper vedlikeholdes og testes. -Søk og filtre utføres før `LIMIT`/`OFFSET`. Ordsøk bruker PostgreSQL-fulltekstsøk +Søk og filtre utføres før `LIMIT`/`OFFSET`. Ordsøk i tittel, beskrivelse, ingredienser og tagger bruker PostgreSQL-fulltekstsøk med GIN-indeks, og hver sortering har en indeks som matcher `ORDER BY`. Løsningen er målt med 100 000 genererte oppskrifter; se [søk og skalerbarhet](performance-and-images.md#søk-og-skalerbarhet). diff --git a/docs/performance-and-images.md b/docs/performance-and-images.md index b0a2c3a..a5f6122 100644 --- a/docs/performance-and-images.md +++ b/docs/performance-and-images.md @@ -18,10 +18,15 @@ utføres i SQL før `LIMIT`/`OFFSET`, slik at den gjelder hele resultatsettet. Alle listevisninger er indeksstøttet, slik at kostnaden ikke vokser med hele katalogen (migrasjon `0005_recipe_search_and_ratings.sql`): -- **Ordsøk:** `recipes.search_vector` er en generert `tsvector` av tittel og - beskrivelse med GIN-indeks (PostgreSQL-fulltekstsøk, konfigurasjon `simple` - uten språkspesifikk bøying). Søketeksten deles i ord i API-et, og alle ord må - finnes som begynnelsen av et ord: «chick rice» finner «Rice with chicken». +- **Ordsøk:** `recipes.search_vector` er en `tsvector` av tittel, + beskrivelse, ingrediensnavn og tagger med GIN-indeks (PostgreSQL-fulltekstsøk, + konfigurasjon `simple` uten språkspesifikk bøying). Triggere oppdaterer den + når oppskriften, ingrediensene eller taggene endres. Søket går mot én rad per + oppskrift, så treff i flere ingredienser gir ikke duplikater, og antallet er + eksakt. Synlighetsreglene er de samme som før. Søketeksten deles i ord i + API-et, og alle ord må finnes, i hvilket som helst felt, som begynnelsen av et + ord: «chick rice» finner «Rice with chicken», og «golden saffron» finner en + oppskrift med «Golden» i tittelen og safran som ingrediens. Spesialtegn fjernes, så brukerinput kan ikke gi syntaksfeil. Delord midt i et ord gir ikke treff («cake» finner ikke «pancakes»). Fulltekstsøk krever ingen utvidelse som `pg_trgm`, og dermed ingen ekstra databaserettigheter. @@ -36,23 +41,28 @@ katalogen (migrasjon `0005_recipe_search_and_ratings.sql`): `npm run db:seed:large -- 100000` legger til 100 000 genererte oppskrifter (635 000 ingredienser, 230 000 vurderinger) basert på demooppskriftene, og -`npm run db:seed:large -- --remove` fjerner dem igjen. Skriptet kjøres aldri av -CI eller deploy. Målingene under er gjort lokalt (PostgreSQL 16 i Docker på en +`npm run db:seed:large -- --remove` fjerner dem igjen. **Kjør det bare mot en +egen testdatabase, aldri mot produksjonsdatabasen** – applikasjonen faglærer +ser skal bare vise ekte demoinnhold. Skriptet kjøres aldri av CI eller deploy. Målingene under er gjort lokalt (PostgreSQL 16 i Docker på en utviklermaskin), median av tre kjøringer med `EXPLAIN ANALYZE`. «Før» er de gamle spørringene med de nye indeksene fjernet, på de samme dataene. | Spørring (offentlige oppskrifter) | Før | Etter | Plan etter | | ------------------------------------ | ------ | ------ | ------------------------------------- | -| Høyest vurdert, første side | 439 ms | 0,1 ms | `recipes_public_rating_idx` | -| Kortest tid, første side | 42 ms | 0,1 ms | `recipes_public_total_time_idx` | -| Søk «chicken», antall treff | 94 ms | 10 ms | `recipes_search_idx` (GIN) | -| Søk «gingerbread», antall treff | 52 ms | 3,5 ms | `recipes_search_idx` (GIN) | -| Søk uten treff, antall + første side | 228 ms | 0,1 ms | GIN-indeks; radspørring hoppes over | +| Høyest vurdert, første side | 719 ms | 0,2 ms | `recipes_public_rating_idx` | +| Kortest tid, første side | 84 ms | 0,2 ms | `recipes_public_total_time_idx` | +| Søk «chicken», antall treff | 91 ms | 11 ms | `recipes_search_idx` (GIN) | +| Søk «gingerbread», antall treff | 80 ms | 7 ms | `recipes_search_idx` (GIN) | +| Søk uten treff, antall + første side | 352 ms | 0,2 ms | GIN-indeks; radspørring hoppes over | | Kategori «soup», første side | 0,3 ms | 0,2 ms | `recipes_public_category_created_idx` | | Nyeste, side 1000 (`OFFSET` 5994) | 61 ms | 26 ms | `recipes_public_created_idx` | -Hele GraphQL-forespørsler (API + database) tok 2–29 ms for alle kombinasjoner -som ble testet, også side 1000. Dyp paginering med `OFFSET` vokser fortsatt +«Før» søkte bare i tittel og beskrivelse; «etter» søker også i ingredienser og +tagger. Hele GraphQL-forespørsler (API + database) tok 4–25 ms for typiske +søk, filtre og sorteringer. Svært vanlige ord som treffer halve katalogen +(«butter»: 49 000 treff) tok 70–100 ms, fordi et eksakt antall må telle alle +treffene. Etter masseinnlasting kjører skriptet `VACUUM ANALYZE`; uten det +var spørringene flere ganger tregere til autovacuum hadde ryddet. Dyp paginering med `OFFSET` vokser fortsatt lineært med sidetallet; markørbasert paginering (keyset) er mulig videre arbeid. Kombinasjoner av filter og sortering uten egen indeks (for eksempel kategori og høyest vurdert) bruker en av indeksene og sorterer resten. diff --git a/docs/recipe-api.md b/docs/recipe-api.md index e496939..a1a6e5b 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -131,7 +131,7 @@ dokumenter i `contracts/generated.ts`. Regenerer med `npm run types:api`. | `unsaveRecipe(id)` | Fjerner bare egen lagring; idempotent, også etter at oppskriften blir privat. | | `cookbook(input, scope)` | Krever innlogging. Scope er `all`, `saved` eller `created`. | -Listeinput støtter `search` (ordsøk i tittel/beskrivelse; alle ord må finnes, som begynnelse av ord), `category`, `maxCookingMinutes`, +Listeinput støtter `search` (ordsøk i tittel, beskrivelse, ingredienser og tagger; alle ord må finnes, som begynnelse av ord), `category`, `maxCookingMinutes`, `sort`, `page` og `pageSize` (1–50, standard 6). Filtrering, sortering og paginering skjer i SQL. Standard er nyeste først. Kortest tilberedningstid og høyest vurdering støttes også, med opprettingstid og ID som stabile tie-breakere. En side utenfor området begrenses til siste side. Tom liste har `totalPages: 0` og `page: 1`. @@ -180,11 +180,9 @@ ukjente oppskrifter gir samme feil og avslører ikke private data. som strenger, men inline enumverdier skrives uten anførselstegn. Cookbook- operasjoner må deklarere `$scope: CookbookScope`, ikke `$scope: String`. Bruk de regenererte kontraktene; ingen databasemigrasjon er nødvendig. -- Søk gjelder tittel/beskrivelse som ordsøk (fulltekst). Mock-søket inkluderer også - ingredienser/tagger og normaliserer bindestrek, understrek og mellomrom mer - omfattende. UI-et beskriver det faktiske søkeomfanget. - Behold søkeinput ved datagrensen; ingrediens-/taggsøk og felles - normaliseringsregler avklares i D3 og implementeres i backend. +- Søk gjelder tittel, beskrivelse, ingrediensnavn og tagger som ordsøk + (fulltekst, se [søk og skalerbarhet](performance-and-images.md#søk-og-skalerbarhet)). + Søkefeltet i Explore og My Cookbook beskriver dette omfanget. - UI-et tilbyr nyeste først, kortest tilberedningstid og høyest vurdering. Sorteringen utføres i backend før paginering. Ikke sorter eller filtrer én hentet side lokalt. - Innloggede brukere kan velge og beskjære bilder før opplasting. API-et tar imot JPG, PNG og WebP opptil 5 MB på `/uploads` og returnerer en generert sti. diff --git a/scripts/seed-large.ts b/scripts/seed-large.ts index e300e6d..d4dba7e 100644 --- a/scripts/seed-large.ts +++ b/scripts/seed-large.ts @@ -4,7 +4,10 @@ * npm run db:seed:large -- 100000 add 100 000 recipes * npm run db:seed:large -- --remove delete everything this script added * - * Explicit opt-in, like db:seed; never run by CI or deploy. Run db:seed first: + * Never run this against the production database: the lecturer-facing app + * should only show real demo content. Point DATABASE_URL at a separate test + * database. Explicit opt-in, like db:seed; never run by CI or deploy. + * Run db:seed first: * the 51 demo recipes are used as templates (title, text, image, ingredients, * steps, tags), with varied names, times, dates and visibility. All rows * belong to one "Load Test Cook" account that cannot log in, so --remove @@ -19,7 +22,10 @@ const t = (name: string) => `"${SCHEMA}"."${name}"`; const argument = process.argv[2]; if (!argument || (argument !== '--remove' && !/^\d+$/.test(argument))) { - console.error('Usage: npm run db:seed:large -- | --remove'); + console.error( + 'Usage: npm run db:seed:large -- | --remove\n' + + 'Use a separate test database (DATABASE_URL), never production.', + ); process.exit(1); } @@ -137,9 +143,12 @@ try { [LOAD_AUTHOR_ID], ); await client.query('COMMIT'); - // Fresh statistics so the planner sees the new table sizes. - await client.query(`ANALYZE ${t('recipes')}`); - await client.query(`ANALYZE ${t('ratings')}`); + // The search triggers rewrite every new recipe once after its ingredients + // and tags are inserted. Reclaim those dead rows and refresh statistics, + // otherwise counts stay several times slower until autovacuum runs. + // PARALLEL 0 avoids running out of shared memory in small containers. + await client.query(`VACUUM (ANALYZE, PARALLEL 0) ${t('recipes')}`); + await client.query(`VACUUM (ANALYZE, PARALLEL 0) ${t('ratings')}`); console.log(`Added ${count} generated recipes.`); } } catch (error) { diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index 3b5774b..fc24cd2 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -669,6 +669,69 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { ]); assert.ok((await search('&|!')).length >= created.length); + // Ingredient names and tags are searchable too, across fields. + const saffron = { + ...input, + title: 'Golden festival bread', + ingredients: [ + { name: 'Saffron threads', amount: 1, unit: 'g' }, + { name: 'Saffron water', amount: 50, unit: 'ml' }, + ], + tags: ['festive'], + }; + const publicSaffron = ( + await ok(CreateRecipeDocument, { input: saffron }, owner.cookie) + ).createRecipe.id; + const privateSaffron = ( + await ok( + CreateRecipeDocument, + { + input: { + ...saffron, + title: 'Private saffron buns', + visibility: 'private', + }, + }, + owner.cookie, + ) + ).createRecipe.id; + created.push(publicSaffron, privateSaffron); + // Two matching ingredients still give one result and count of 1. + const bySaffron = ( + await ok(RecipesDocument, { input: { search: 'saffron' } }) + ).recipes; + assert.deepEqual( + [bySaffron.totalCount, bySaffron.items.map((item) => item.title)], + [1, ['Golden festival bread']], + ); + assert.deepEqual(await search('festive'), ['Golden festival bread']); + assert.deepEqual(await search('golden saffron festive'), [ + 'Golden festival bread', + ]); + // Visibility rules still apply: the owner's cookbook finds both. + const cookbookSaffron = ( + await ok( + CookbookDocument, + { scope: 'created', input: { search: 'saffron' } }, + owner.cookie, + ) + ).cookbook; + assert.equal(cookbookSaffron.totalCount, 2); + // Editing ingredients updates the search document. + await ok( + UpdateRecipeDocument, + { + id: publicSaffron, + input: { + ...saffron, + ingredients: [{ name: 'Turmeric', amount: 1, unit: 'tsp' }], + }, + }, + owner.cookie, + ); + assert.deepEqual(await search('saffron'), []); + assert.deepEqual(await search('turmeric'), ['Golden festival bread']); + // A trigger keeps the cached rating summary in step with ratings. const before = (await ok(RecipeDocument, { id: created[0]! })) .recipe!; From d3dfed203e2f42da08b775aa3b2c95562d444c49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 00:39:15 +0100 Subject: [PATCH 3/4] fix(search): serialize cached rating and search updates, use every search word - rate() takes FOR NO KEY UPDATE instead of FOR SHARE: the ratings trigger updates the same recipe row, so two shared locks deadlocked. removeRating() takes the same lock first, in a transaction. - The rating and search-vector triggers lock the recipe row(s) (in id order) before recomputing, so a concurrent write is counted instead of being overwritten from a stale snapshot. - Moving a rating, ingredient or tag to another recipe refreshes both recipes (rating trigger also fires on recipe_id; update triggers use both transition tables). - toSearchQuery() no longer drops words after the eighth; repeated words are searched once, and the 200-character input limit bounds the query. - test:api: concurrent rate/remove through the API, interleaved raw-SQL writes on ratings, ingredients and tags, moved rows, and a 9-word search. --- .../0005_recipe_search_and_ratings.sql | 65 ++++-- .../src/features/recipes/recipeRepository.ts | 34 +-- .../src/features/recipes/recipeSearch.test.ts | 7 +- docs/performance-and-images.md | 6 + scripts/test-recipe-api.ts | 193 ++++++++++++++++++ 5 files changed, 273 insertions(+), 32 deletions(-) diff --git a/apps/api/migrations/0005_recipe_search_and_ratings.sql b/apps/api/migrations/0005_recipe_search_and_ratings.sql index 8ff9f36..24651f1 100644 --- a/apps/api/migrations/0005_recipe_search_and_ratings.sql +++ b/apps/api/migrations/0005_recipe_search_and_ratings.sql @@ -8,23 +8,37 @@ CREATE INDEX "recipes_search_idx" ON "project2"."recipes" USING gin ("search_vec --> statement-breakpoint -- Keep recipes.rating_avg/rating_count in step with ratings for every write -- path (API, seed, manual SQL), so the highest-rated sort can use an index. +-- The recipe row is locked before counting. A concurrent rating of the same +-- recipe then waits until this one commits, and its count (a new snapshot, +-- since this is a separate statement) includes this rating instead of +-- overwriting the cache with a stale value. A rating moved to another recipe +-- refreshes both recipes, locked in id order so two moves cannot deadlock. CREATE FUNCTION "project2"."refresh_recipe_rating"() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE - target uuid := CASE WHEN TG_OP = 'DELETE' THEN OLD.recipe_id ELSE NEW.recipe_id END; + target uuid; BEGIN - UPDATE "project2"."recipes" r - SET rating_avg = s.average, rating_count = s.total - FROM ( - SELECT avg(score) AS average, count(*)::int AS total - FROM "project2"."ratings" WHERE recipe_id = target - ) s - WHERE r.id = target; + FOR target IN + SELECT DISTINCT changed.id FROM unnest(ARRAY[ + CASE WHEN TG_OP <> 'INSERT' THEN OLD.recipe_id END, + CASE WHEN TG_OP <> 'DELETE' THEN NEW.recipe_id END + ]) AS changed(id) + WHERE changed.id IS NOT NULL ORDER BY changed.id + LOOP + PERFORM 1 FROM "project2"."recipes" WHERE id = target FOR NO KEY UPDATE; + UPDATE "project2"."recipes" r + SET rating_avg = s.average, rating_count = s.total + FROM ( + SELECT avg(score) AS average, count(*)::int AS total + FROM "project2"."ratings" WHERE recipe_id = target + ) s + WHERE r.id = target; + END LOOP; RETURN NULL; END $$; --> statement-breakpoint CREATE TRIGGER ratings_refresh_recipe_rating -AFTER INSERT OR UPDATE OF score OR DELETE ON "project2"."ratings" +AFTER INSERT OR UPDATE OF score, recipe_id OR DELETE ON "project2"."ratings" FOR EACH ROW EXECUTE FUNCTION "project2"."refresh_recipe_rating"(); --> statement-breakpoint -- Backfill existing ratings. @@ -67,33 +81,50 @@ BEFORE INSERT OR UPDATE OF title, description ON "project2"."recipes" FOR EACH ROW EXECUTE FUNCTION "project2"."set_recipe_search_vector"(); --> statement-breakpoint -- Statement-level: one refresh per INSERT/UPDATE/DELETE statement on --- ingredients or tags, for every recipe the statement touched ("changed"). +-- ingredients or tags, for every recipe the statement touched. An UPDATE that +-- moves rows to another recipe refreshes both the old and the new recipe. +-- As for ratings, the recipes are locked (in id order, so concurrent writers +-- cannot deadlock) before the document is rebuilt in a new snapshot, so a +-- concurrent ingredient or tag write is never overwritten by stale words. CREATE FUNCTION "project2"."refresh_recipe_search_vector"() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE + targets uuid[]; BEGIN + IF TG_OP = 'INSERT' THEN + SELECT array_agg(DISTINCT recipe_id) INTO targets FROM new_rows; + ELSIF TG_OP = 'DELETE' THEN + SELECT array_agg(DISTINCT recipe_id) INTO targets FROM old_rows; + ELSE + SELECT array_agg(recipe_id) INTO targets FROM ( + SELECT recipe_id FROM old_rows UNION SELECT recipe_id FROM new_rows + ) touched; + END IF; + PERFORM 1 FROM "project2"."recipes" + WHERE id = ANY(targets) ORDER BY id FOR NO KEY UPDATE; UPDATE "project2"."recipes" r SET search_vector = "project2"."recipe_search_document"(r.id, r.title, r.description) - WHERE r.id IN (SELECT DISTINCT recipe_id FROM changed); + WHERE r.id = ANY(targets); RETURN NULL; END $$; --> statement-breakpoint CREATE TRIGGER recipe_ingredients_search_insert AFTER INSERT ON "project2"."recipe_ingredients" -REFERENCING NEW TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); --> statement-breakpoint CREATE TRIGGER recipe_ingredients_search_update AFTER UPDATE ON "project2"."recipe_ingredients" -REFERENCING NEW TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); --> statement-breakpoint CREATE TRIGGER recipe_ingredients_search_delete AFTER DELETE ON "project2"."recipe_ingredients" -REFERENCING OLD TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); --> statement-breakpoint CREATE TRIGGER recipe_tags_search_insert AFTER INSERT ON "project2"."recipe_tags" -REFERENCING NEW TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); --> statement-breakpoint CREATE TRIGGER recipe_tags_search_update AFTER UPDATE ON "project2"."recipe_tags" -REFERENCING NEW TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); --> statement-breakpoint CREATE TRIGGER recipe_tags_search_delete AFTER DELETE ON "project2"."recipe_tags" -REFERENCING OLD TABLE AS changed FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); +REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"(); --> statement-breakpoint -- Backfill existing recipes. UPDATE "project2"."recipes" diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index db6dc2b..dea26fc 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -5,21 +5,18 @@ import type { CookbookScope, Recipe } from '../../generated.js'; import type { RecipeInput, ListInput } from './recipeValidation.js'; import { validateImageReference, lockImages } from './imageRepository.js'; -const MAX_SEARCH_TERMS = 8; - /** * Turns the user's search text into a PostgreSQL tsquery that matches * recipes containing every word, each as a prefix: "chick rice" becomes * "chick:* & rice:*" and finds "Rice with chicken". Only letters and digits * are kept, so input such as "soup &" or "(" can never break the query - * syntax. Returns '' when there is nothing to search for. + * syntax. Every word is used; the 200-character input limit bounds the + * query, and repeated words are only searched once. Returns '' when there + * is nothing to search for. */ export function toSearchQuery(search: string) { const words = search.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []; - return words - .slice(0, MAX_SEARCH_TERMS) - .map((word) => `${word}:*`) - .join(' & '); + return [...new Set(words)].map((word) => `${word}:*`).join(' & '); } export function createRecipeRepository(pool: Pool = db, schema = 'project2') { @@ -277,7 +274,10 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { async rate(id: string, score: number, userId: string) { return transaction(async (client) => { const result = await client.query( - `SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`, + // Exclusive, not FOR SHARE: the ratings trigger updates this row's + // cached rating. Two raters holding a shared lock would each wait + // for the other to release it before updating, a deadlock. + `SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR NO KEY UPDATE`, [id, userId], ); if (!result.rowCount) @@ -296,11 +296,19 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { }); }, async removeRating(id: string, userId: string) { - await pool.query( - `DELETE FROM ${t('ratings')} WHERE recipe_id=$1 AND user_id=$2`, - [id, userId], - ); - return true; + return transaction(async (client) => { + // Lock the recipe before the rating, in the same order as rate(), so + // a concurrent rate and remove by the same user cannot deadlock. + await client.query( + `SELECT id FROM ${t('recipes')} WHERE id=$1 FOR NO KEY UPDATE`, + [id], + ); + await client.query( + `DELETE FROM ${t('ratings')} WHERE recipe_id=$1 AND user_id=$2`, + [id, userId], + ); + return true; + }); }, }; } diff --git a/apps/api/src/features/recipes/recipeSearch.test.ts b/apps/api/src/features/recipes/recipeSearch.test.ts index d165f29..94c0ba3 100644 --- a/apps/api/src/features/recipes/recipeSearch.test.ts +++ b/apps/api/src/features/recipes/recipeSearch.test.ts @@ -30,7 +30,10 @@ describe('toSearchQuery', () => { expect(toSearchQuery('&|!():*')).toBe(''); }); - it('caps very long searches at eight words', () => { - expect(toSearchQuery('a b c d e f g h i j').split(' & ')).toHaveLength(8); + it('uses every word of a long search, each only once', () => { + const words = 'one two three four five six seven eight nine ten'; + expect(toSearchQuery(words).split(' & ')).toHaveLength(10); + expect(toSearchQuery(`${words} ten`)).toBe(toSearchQuery(words)); + expect(toSearchQuery(words)).toMatch(/ten:\*$/); }); }); diff --git a/docs/performance-and-images.md b/docs/performance-and-images.md index a5f6122..76aa365 100644 --- a/docs/performance-and-images.md +++ b/docs/performance-and-images.md @@ -33,6 +33,12 @@ katalogen (migrasjon `0005_recipe_search_and_ratings.sql`): - **Høyest vurdert:** `rating_avg` og `rating_count` lagres på oppskriften og holdes oppdatert av en trigger på `ratings`. Sorteringen bruker en indeks i stedet for å regne gjennomsnitt for alle treff ved hver forespørsel. +- **Samtidige skrivinger:** triggerne låser oppskriftsraden før de regner ut + vurderingssnitt eller søkedokument på nytt, slik at to samtidige vurderinger + eller ingrediensendringer ikke overskriver hverandre med utdaterte verdier. + `rateRecipe` og `removeRecipeRating` tar samme eksklusive lås først, så + samtidige vurderinger venter på hverandre i stedet for å gi vranglås. Flyttes + en vurdering, ingrediens eller tagg til en annen oppskrift, oppdateres begge. - **Kategori og kortest tid:** egne delindekser for offentlige oppskrifter, med samme rekkefølge som `ORDER BY` i spørringen. - Når totalantallet er 0, hoppes radspørringen over. diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index fc24cd2..8f4d2a8 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -708,6 +708,11 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { assert.deepEqual(await search('golden saffron festive'), [ 'Golden festival bread', ]); + // No word is ignored, however long the search: a ninth word that + // matches nothing still means no results. + const eight = 'golden festival bread saffron festive gol fest bre'; + assert.deepEqual(await search(eight), ['Golden festival bread']); + assert.deepEqual(await search(`${eight} cake`), []); // Visibility rules still apply: the owner's cookbook finds both. const cookbookSaffron = ( await ok( @@ -759,6 +764,194 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { } }, ); + await t.test( + 'cached ratings and search words stay correct under concurrent writes', + async () => { + const table = (name: string) => `"${schema}".${name}`; + const createRecipe = async (title: string, extra = {}) => + ( + await ok( + CreateRecipeDocument, + { input: { ...input, title, ...extra } }, + owner.cookie, + ) + ).createRecipe.id; + const cached = async (id: string) => + ( + await pool.query<{ count: number; average: number | null }>( + `SELECT rating_count AS count, rating_avg::float AS average FROM ${table('recipes')} WHERE id=$1`, + [id], + ) + ).rows[0]!; + const search = async (text: string) => + ( + await ok(RecipesDocument, { + input: { search: text, pageSize: 50 }, + }) + ).recipes.items.map((item) => item.title); + // Resolves once `pid` is waiting for a lock held by another session. + async function blockedOnLock(pid: number) { + for (let attempt = 0; attempt < 200; attempt++) { + const waiting = await pool.query( + `SELECT 1 FROM pg_stat_activity WHERE pid=$1 AND wait_event_type='Lock'`, + [pid], + ); + if (waiting.rowCount) return; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + assert.fail('The second writer never waited for the first.'); + } + const created: string[] = []; + try { + // Many users rating the same recipe at once: no deadlock, and the + // cached summary counts every rating. + const target = await createRecipe('Popular stew'); + created.push(target); + // Created directly: registration through the API is rate limited. + const cookieName = owner.cookie.split('=')[0]!; + const raters = await Promise.all( + Array.from({ length: 6 }, async (_, index) => { + const { user, sessionToken } = await createAuthRepository( + pool, + pool, + schema, + ).createUserWithSession( + `Rater ${index}`, + `rater-${index}@example.com`, + 'not-a-real-hash', + new Date(Date.now() + 3_600_000), + ); + return { user, cookie: `${cookieName}=${sessionToken}` }; + }), + ); + for (let round = 0; round < 3; round++) { + const results = await Promise.all( + raters.map((rater, index) => + request( + RateRecipeDocument, + { id: target, score: ((index + round) % 5) + 1 }, + rater.cookie, + ), + ), + ); + assert.deepEqual( + results.flatMap((result) => result.errors ?? []), + [], + ); + } + const scores = raters.map((_, index) => ((index + 2) % 5) + 1); + const expected = scores.reduce((sum, s) => sum + s, 0) / 6; + assert.equal((await cached(target)).count, 6); + assert.equal((await cached(target)).average, expected); + // Removing ratings at the same time as others rate. + const mixed = await Promise.all( + raters.map((rater, index) => + index % 2 + ? request( + RemoveRecipeRatingDocument, + { id: target }, + rater.cookie, + ) + : request( + RateRecipeDocument, + { id: target, score: 5 }, + rater.cookie, + ), + ), + ); + assert.deepEqual( + mixed.flatMap((result) => result.errors ?? []), + [], + ); + assert.deepEqual(await cached(target), { count: 3, average: 5 }); + + // A write that commits while another is in progress, outside the + // API (seed, manual SQL): the second must count the first. + const second = await createRecipe('Second stew'); + created.push(second); + const first = await pool.connect(); + const later = await pool.connect(); + try { + await first.query('BEGIN'); + await later.query('BEGIN'); + await first.query( + `INSERT INTO ${table('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,2)`, + [second, raters[0]!.user.id], + ); + const laterPid = ( + await later.query<{ pid: number }>('SELECT pg_backend_pid() pid') + ).rows[0]!.pid; + const pending = later.query( + `INSERT INTO ${table('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,4)`, + [second, raters[1]!.user.id], + ); + await blockedOnLock(laterPid); + await first.query('COMMIT'); + await pending; + await later.query('COMMIT'); + } finally { + first.release(); + later.release(); + } + assert.deepEqual(await cached(second), { count: 2, average: 3 }); + + // The same for ingredients: two concurrent ingredient writes on + // one recipe both end up searchable. + const a = await pool.connect(); + const b = await pool.connect(); + try { + await a.query('BEGIN'); + await b.query('BEGIN'); + await a.query( + `INSERT INTO ${table('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) VALUES ($1,'Cardamom',1,'tsp',NULL,10)`, + [second], + ); + const bPid = ( + await b.query<{ pid: number }>('SELECT pg_backend_pid() pid') + ).rows[0]!.pid; + const pending = b.query( + `INSERT INTO ${table('recipe_tags')} (recipe_id,tag) VALUES ($1,'wintery')`, + [second], + ); + await blockedOnLock(bPid); + await a.query('COMMIT'); + await pending; + await b.query('COMMIT'); + } finally { + a.release(); + b.release(); + } + assert.deepEqual(await search('cardamom wintery'), ['Second stew']); + + // Moving a rating, ingredient or tag to another recipe refreshes + // both the recipe it left and the one it joined. + const moved = await createRecipe('Moved-to stew', { + ingredients: [{ name: 'Water', amount: 1, unit: 'l' }], + tags: [], + }); + created.push(moved); + await pool.query( + `UPDATE ${table('ratings')} SET recipe_id=$1 WHERE recipe_id=$2 AND user_id=$3`, + [moved, second, raters[1]!.user.id], + ); + assert.deepEqual(await cached(second), { count: 1, average: 2 }); + assert.deepEqual(await cached(moved), { count: 1, average: 4 }); + await pool.query( + `UPDATE ${table('recipe_ingredients')} SET recipe_id=$1 WHERE recipe_id=$2 AND name='Cardamom'`, + [moved, second], + ); + await pool.query( + `UPDATE ${table('recipe_tags')} SET recipe_id=$1 WHERE recipe_id=$2 AND tag='wintery'`, + [moved, second], + ); + assert.deepEqual(await search('cardamom'), ['Moved-to stew']); + assert.deepEqual(await search('wintery'), ['Moved-to stew']); + } finally { + for (const id of created) + await ok(DeleteRecipeDocument, { id }, owner.cookie); + } + }, + ); await t.test('only the owner can update or delete', async () => { await fails( UpdateRecipeDocument, From 3a239f05b91bdf2dd1caa7ee08121c4d4024cac1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 16:29:18 +0100 Subject: [PATCH 4/4] fix(search): retry API transactions that lose a deadlock to direct SQL The API locks a recipe before its ratings, ingredients or tags; a write outside the API (seed, manual SQL) locks the child row first and the recipe in its trigger, so the two can deadlock. Lock order cannot be forced on such writers, so transaction() now rolls back and retries a transaction that fails with 40P01 (deadlock) or 40001 (serialization), up to three attempts with a short jittered pause. test:api: a manual session locks a rating, the API rate() then waits for it while holding the recipe, and the manual update's trigger waits for the recipe. Before this change the API returned "deadlock detected"; now it retries, succeeds, and the cached rating counts both writes. Refs #69 --- .../src/features/recipes/recipeRepository.ts | 25 ++++++++++- scripts/test-recipe-api.ts | 45 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index dea26fc..be2e8e8 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -74,7 +74,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { json_build_object('average',coalesce(round(r.rating_avg,1),0)::float,'count',r.rating_count) AS rating FROM ${t('recipes')} r`; - async function transaction(work: (client: PoolClient) => Promise) { + async function attempt(work: (client: PoolClient) => Promise) { const client = await pool.connect(); try { await client.query('BEGIN'); @@ -88,6 +88,29 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { client.release(); } } + /* + * The API locks a recipe before its ratings, ingredients or tags, but a + * write outside the API (seed, manual SQL) locks the child row first and + * the recipe in its trigger. When the two meet, PostgreSQL aborts one of + * them as a deadlock (40P01). Lock order cannot be forced on such writers, + * so an API transaction that loses is rolled back and run again, which + * then simply waits for the other writer. Serialization failures (40001) + * are retried the same way. Work functions only touch the database, so + * running them again is safe. + */ + async function transaction(work: (client: PoolClient) => Promise) { + for (let tries = 1; ; tries++) { + try { + return await attempt(work); + } catch (error) { + const code = (error as { code?: unknown }).code; + if (tries >= 3 || (code !== '40P01' && code !== '40001')) throw error; + await new Promise((resolve) => + setTimeout(resolve, tries * 20 + Math.random() * 30), + ); + } + } + } async function read( executor: Pick, id: string, diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index b88a23a..3ecd906 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -969,6 +969,51 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { ); assert.deepEqual(await cached(target), { count: 3, average: 5 }); + // Opposite lock order: a manual SQL session locks a rating, the API + // then locks the recipe and waits for that rating, and the SQL + // update's trigger waits for the recipe. PostgreSQL aborts the API + // transaction (it waited first) as a deadlock; the API retries it + // and succeeds after the SQL session commits. + const manual = await pool.connect(); + try { + await manual.query('BEGIN'); + await manual.query( + `SELECT 1 FROM ${table('ratings')} WHERE recipe_id=$1 AND user_id=$2 FOR UPDATE`, + [target, raters[0]!.user.id], + ); + const manualPid = ( + await manual.query<{ pid: number }>('SELECT pg_backend_pid() pid') + ).rows[0]!.pid; + const apiRating = request( + RateRecipeDocument, + { id: target, score: 1 }, + raters[0]!.cookie, + ); + // Wait until the API is blocked on the manual session's lock. + for (let waited = 0; ; waited++) { + const blocked = await pool.query( + `SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))`, + [manualPid], + ); + if (blocked.rowCount) break; + assert.ok(waited < 200, 'The API never waited for the rating.'); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + await manual.query( + `UPDATE ${table('ratings')} SET score=3 WHERE recipe_id=$1 AND user_id=$2`, + [target, raters[0]!.user.id], + ); + await manual.query('COMMIT'); + assert.equal((await apiRating).errors, undefined); + } finally { + manual.release(); + } + // The API's rating (1) was written after the manual one (3). + assert.deepEqual(await cached(target), { + count: 3, + average: 11 / 3, + }); + // A write that commits while another is in progress, outside the // API (seed, manual SQL): the second must count the first. const second = await createRecipe('Second stew');