From b849bd493fc1c0f73288472afa70ddbec8de218d Mon Sep 17 00:00:00 2001 From: Owen Rees Date: Sun, 25 Oct 2026 09:12:07 +0100 Subject: [PATCH] fix: repair clock rendering and harden PDF endpoint (#5) --- Makefile | 4 +- bin/cors.ml | 4 +- bin/main.ml | 2 +- bin/pdf_handler.ml | 25 ++++----- chess-scribe-api.opam | 7 +-- dune-project | 4 +- lib/dune | 3 +- lib/request.ml | 18 +++++++ static/swagger.json | 95 ++++++++++++++++++++++++----------- test/dune | 2 +- test/test_chess_scribe_api.ml | 50 ++++++++++++++++++ 11 files changed, 157 insertions(+), 57 deletions(-) create mode 100644 lib/request.ml diff --git a/Makefile b/Makefile index 2e3e0e0..ca09ab3 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ run: - dune build && dune exec ./_build/default/bin/main.exe DREAM_ENV=production + dune build && DREAM_ENV=production dune exec ./_build/default/bin/main.exe run-dev: - find . -name "*.ml" -o -path "./static/*" | entr -r dune exec ./_build/default/bin/main.exe DREAM_ENV=development \ No newline at end of file + find . -name "*.ml" -o -path "./static/*" | entr -r env DREAM_ENV=development dune exec ./_build/default/bin/main.exe \ No newline at end of file diff --git a/bin/cors.ml b/bin/cors.ml index 1e50226..37496e0 100644 --- a/bin/cors.ml +++ b/bin/cors.ml @@ -5,9 +5,7 @@ let allowed_origins = "http://localhost:3000"; ] -let is_dev_mode () = - Array.to_list Sys.argv - |> List.exists (fun arg -> arg = "DREAM_ENV=development") +let is_dev_mode () = Sys.getenv_opt "DREAM_ENV" = Some "development" let middleware next_handler request = let allowed_origin = diff --git a/bin/main.ml b/bin/main.ml index 790ce72..cf97399 100644 --- a/bin/main.ml +++ b/bin/main.ml @@ -1,6 +1,6 @@ open Lwt.Syntax open Yojson.Safe.Util -open Pgn_logic +open Pgn_to_tex let () = Dream.run ~interface:"0.0.0.0" ~port:8080 diff --git a/bin/pdf_handler.ml b/bin/pdf_handler.ml index a5f3cec..6c8fbb0 100644 --- a/bin/pdf_handler.ml +++ b/bin/pdf_handler.ml @@ -1,6 +1,6 @@ open Lwt.Syntax open Yojson.Safe.Util -open Pgn_logic +open Pgn_to_tex let tex_start = "\\begin{document}\\begin{multicols}{2}" let tex_end = "\\end{multicols}\\end{document}" @@ -36,19 +36,12 @@ let handle_convert request = let* body = Dream.body request in try - let json = Yojson.Safe.from_string body in - - let pgn = json |> member "pgn" |> to_string in - let diagram_clock = json |> member "diagramClock" |> to_bool in - let diagrams_json = json |> member "diagrams" in - - let diagrams_data = - Yojson.Safe.to_string diagrams_json |> Pgn2tex.parse_diagrams_json - in + let parsed = Chess_scribe_api.Request.parse body in let game_tex = tex_start - ^ Pgn2tex.to_tex pgn ~diagram_data:diagrams_data ~clock:diagram_clock + ^ Pgn_to_tex.to_tex ~diagram_data:parsed.diagrams ~clock:parsed.clock + parsed.pgn ^ tex_end in @@ -66,11 +59,12 @@ let handle_convert request = |] in + let dev_null = Unix.openfile Filename.null [ Unix.O_WRONLY ] 0o600 in let pid = - Unix.create_process "pdflatex" argv Unix.stdin Unix.stdout Unix.stderr + Unix.create_process "pdflatex" argv Unix.stdin dev_null dev_null in - let _, _ = Unix.waitpid [] pid in + Unix.close dev_null; if Sys.file_exists pdf_file_path then ( let pdf_content = @@ -100,7 +94,6 @@ let handle_convert request = {|{"type": "error", "message": "Invalid JSON syntax: %s"}|} msg) | exn -> cleanup (); - let err_msg = Printexc.to_string exn in - + Dream.log "PDF conversion failed: %s" (Printexc.to_string exn); Dream.json ~status:`Internal_Server_Error - (Printf.sprintf {|{"type": "error", "message": "%s"}|} err_msg) + {|{"type": "error", "message": "Internal server error"}|} diff --git a/chess-scribe-api.opam b/chess-scribe-api.opam index edc3762..c40e226 100644 --- a/chess-scribe-api.opam +++ b/chess-scribe-api.opam @@ -8,13 +8,14 @@ authors: ["Owen Rees"] license: "AGPL-3.0-or-later" tags: ["chess" "pgn" "pdf"] homepage: "https://github.com/therealowenrees/chess-scribe-api" -doc: "https://github.com/therealowenrees/chess-scribe-api/blob/main/README.md" +doc: "https://github.com/therealowenrees/chess-scribe-api/README.md" bug-reports: "https://github.com/therealowenrees/chess-scribe-api/issues" depends: [ "dune" {>= "3.21"} "ocaml" - "dream" {>= "1.0.0~alpha8"} - "pgn_to_tex" + "dream" {>= "1.0.0"} + "pgn_to_tex" {>= "0.1.0"} + "yojson" "odoc" {with-doc} ] build: [ diff --git a/dune-project b/dune-project index b6bf633..3c68cff 100644 --- a/dune-project +++ b/dune-project @@ -24,7 +24,9 @@ ocaml (dream (>= "1.0.0")) - pgn_to_tex) + (pgn_to_tex + (>= "0.1.0")) + yojson) (tags ("chess" "pgn" "pdf"))) diff --git a/lib/dune b/lib/dune index 4e1955f..4199c35 100644 --- a/lib/dune +++ b/lib/dune @@ -1,2 +1,3 @@ (library - (name chess_scribe_api)) + (name chess_scribe_api) + (libraries yojson pgn_to_tex)) diff --git a/lib/request.ml b/lib/request.ml new file mode 100644 index 0000000..daddf1e --- /dev/null +++ b/lib/request.ml @@ -0,0 +1,18 @@ +open Yojson.Safe.Util + +type parsed = { pgn : string; clock : bool; diagrams : Pgn_to_tex.diagram_data } + +let parse body = + let json = Yojson.Safe.from_string body in + let pgn = json |> member "pgn" |> to_string in + let clock = + json |> member "diagramClock" |> to_bool_option + |> Option.value ~default:false + in + let diagrams = + match json |> member "diagrams" with + | `Null -> Pgn_to_tex.empty_diagrams + | diagrams_json -> + Yojson.Safe.to_string diagrams_json |> Pgn_to_tex.parse_diagrams_json + in + { pgn; clock; diagrams } diff --git a/static/swagger.json b/static/swagger.json index 743dd65..d18a7ce 100644 --- a/static/swagger.json +++ b/static/swagger.json @@ -12,34 +12,7 @@ "description": "Health check. Assume that the API is non-functional if any error code other than 200 is returned.", "responses": { "200": { - "$ref": "#/paths/~1api~1v1~1pdf/post/responses/200" - } - } - } - }, - "/api/v1/pdf": { - "post": { - "summary": "Create PDF", - "description": "Create PDF", - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["texString"], - "properties": { - "texString": { - "type": "string", - "example": "\n\\documentclass{article}\\usepackage{xskak}\\usepackage{multicol}\\usepackage[a4paper]{geometry}\\usepackage{parskip}\\geometry{left=1.25cm,right=1.25cm,top=1.5cm,bottom=1.5cm,columnsep=1.2cm}\\setlength{\\parindent}{0pt}\\title{Alejandro Fernandez Cardenete (1873) - Joan Amat Iglesis (1700)}\\\\[2ex]\\date{2024.04.12, Terrassa}\\author{Obert Barad 2024}\\begin{document}\\begin{multicols}{2}\\maketitle\\newchessgame\\textbf{1.}\\textbf{d4} \\textbf{c5} \\textbf{2.}\\textbf{d5} \\textbf{Nf6} \\textbf{3.}\\textbf{c4} \\textbf{e6} \\textbf{4.}\\textbf{Nc3} \\textbf{exd5} \\textbf{5.}\\textbf{cxd5} \\textbf{d6} \\textbf{6.}\\textbf{e4} \\textbf{g6} \\textbf{7.}\\textbf{Nf3} \\textbf{Bg7} \\textbf{8.}\\textbf{Be2} \\textbf{O-O} \\textbf{9.}\\textbf{O-O} \\textbf{Bg4} \\newline ULTIMA JUGADA DE MESTRE, BG4 392 VEGADES 35/31/34\\% \\par \\textbf{10.}\\textbf{Be3} \\newline Aquí acaba la meva preparació. Be3 no és habitual però no és dolent. Segueixo\namb mainline Re8. STOCKFISH (d50) DONA 0.24 ELS MESTRES JUGUEN BF4 ND2 H3 BG5\nRE1. ELS MESTRES HAN JUGAT BE3 8 VEGADES \\par \\textbf{10...}\\textbf{Re8} \\newline ULTIMA JUGADA LICHESS >100\nVEGADES 43/3/54\\% \\par \\textbf{11.}\\textbf{Qc2} \\newline No és bona però no veig com explotar-ho. Dubto entre\nNa6 i a6. Trio a6 perquè em sembla que Nb5o n té objectius (però Ne5 tampoc !).\nSTOCKFISH (d40) DONA 0.0 I DEMANA NBD7 (0.08), A6 (0.08), QE7 (0.04) O NA6\n(0.28), TOTES TEMÀTIQUES \\par \\textbf{11...}\\textbf{a6} \\textbf{12.}\\textbf{a4} \\textbf{Nbd7} \\textbf{13.}\\textbf{h3} \\newline La meva preparació diu\nque l'alfil ha vingut a morir per ralentitzar l'atac de costat de Rei \\par \\textbf{13...}\\textbf{Bxf3} \\textbf{14.}\\textbf{Bxf3} \\newline No tinc idea de què fer perquè Ne5 no té objectius ! Sabia per\npreparació que que Qc7 és habitual, permet c4 (però no té objectius !) i unir\ntorres. Descarto Ne5 perquè després de Be2 ve f4 i guanya molta iniciativa.\nConsidero Qe7 però em sembla que després de Re1 quedarà mal colocada. Considero\nRb8 però em sembla que obrir queenside em perjudica perquè hi té més peces.\nSTOCKFISH (D=40) VOL QE7 (0.08) C4 (0.11) O RC8 (0.13). \\par \\textbf{14...}\\textbf{Qc7} \\newline STOCKFISH\n(D=35) DONA A5 (0.46) NO ESTAMOS TAN MAL. TRANSPOSEM A LICHESS 40 VEGADES\n35/12/53\\% \\par \\textbf{0-1}\n\\end{multicols}\\end{document}" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Response for successful operation", + "description": "API is functional", "content": { "application/json": { "schema": { @@ -51,12 +24,76 @@ }, "message": { "type": "string", - "example": "success message" + "example": "API is functional" } } } } } + } + } + } + }, + "/api/v1/pdf": { + "post": { + "summary": "Create PDF", + "description": "Convert a PGN game to a PDF. Clock times from [%clk ...] PGN comments are rendered alongside diagrams when diagramClock is true.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["pgn"], + "properties": { + "pgn": { + "type": "string", + "description": "PGN game text, optionally containing [%clk ...] clock comments.", + "example": "1. e4 e5 2. Nf3 Nc6 *" + }, + "diagramClock": { + "type": "boolean", + "description": "Render clock times alongside diagrams.", + "default": false + }, + "diagrams": { + "type": "array", + "description": "Diagram selections. Each item requires fen and either ply, path, or both.", + "default": [], + "items": { + "type": "object", + "required": ["fen"], + "properties": { + "fen": { + "type": "string" + }, + "ply": { + "type": "integer" + }, + "path": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "responses": { + "201": { + "description": "PDF generated", + "content": { + "application/pdf": { + "schema": { + "type": "string", + "format": "binary" + } + } + } }, "400": { "description": "Response for bad request", diff --git a/test/dune b/test/dune index f72e7dd..838ced1 100644 --- a/test/dune +++ b/test/dune @@ -1,3 +1,3 @@ (test (name test_chess_scribe_api) - (libraries chess_scribe_api)) + (libraries chess_scribe_api pgn_to_tex yojson)) diff --git a/test/test_chess_scribe_api.ml b/test/test_chess_scribe_api.ml index e69de29..f41600b 100644 --- a/test/test_chess_scribe_api.ml +++ b/test/test_chess_scribe_api.ml @@ -0,0 +1,50 @@ +let parse = Chess_scribe_api.Request.parse + +let contains haystack needle = + let n = String.length needle and h = String.length haystack in + let rec go i = + i + n <= h && (String.sub haystack i n = needle || go (i + 1)) + in + n = 0 || go 0 + +let () = + let parsed = parse {|{"pgn":"1. e4 e5 *"}|} in + assert (parsed.pgn = "1. e4 e5 *"); + assert (parsed.clock = false); + + let parsed = parse {|{"pgn":"1. e4 *","diagramClock":true}|} in + assert (parsed.clock = true); + + let parsed = parse {|{"pgn":"1. e4 *","diagrams":null}|} in + assert (parsed.clock = false); + + let parsed = + parse + {|{"pgn":"1. e4 *","diagrams":[{"fen":"8/8/8/8/8/8/8/8 w - - 0 1","ply":1}]}|} + in + assert (parsed.clock = false); + + (* Omitting the required pgn must raise so the handler returns 400. *) + let missing_pgn_raises = + try + ignore (parse {|{"diagrams":[]}|}); + false + with Yojson.Safe.Util.Type_error _ | Yojson.Json_error _ -> true + in + assert missing_pgn_raises; + + (* End-to-end: clock times render next to a diagram when requested. *) + let parsed = + parse + {|{"pgn":"1. e4 {[%clk 0:05:00]} e5 2. Nf3 *","diagramClock":true,"diagrams":[{"fen":"rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2","ply":2}]}|} + in + let with_clock = + Pgn_to_tex.to_tex ~diagram_data:parsed.diagrams ~clock:true parsed.pgn + in + let without_clock = + Pgn_to_tex.to_tex ~diagram_data:parsed.diagrams ~clock:false parsed.pgn + in + assert (contains with_clock "0:05:00"); + assert (with_clock <> without_clock); + + print_endline "All request parsing tests passed"