Files
Kazier/backend/service/ocr.go
T
m a6b7f2002b
CI / lint-backend (push) Failing after 1m39s
CI / lint-mobile (push) Canceled after 11m8s
CI / test-backend (push) Canceled after 0s
CI / test-mobile (push) Canceled after 0s
CI / build-backend (push) Canceled after 0s
CI / docker (push) Canceled after 0s
fix backend audit findings (auth, upload, sync, data, ocr, contract)
2026-09-21 19:59:52 +02:00

233 lines
7.2 KiB
Go

package service
import (
"context"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/kazier/backend/ocr"
"github.com/kazier/backend/repository"
)
const (
// StaleClaimTimeout : un job `processing` plus vieux que ça est ré-enfilé
// au boot (worker mort / process redémarré).
StaleClaimTimeout = 15 * time.Minute
// QueuePollInterval : cadence de scrutation quand la file est vide.
QueuePollInterval = time.Second
)
// OcrJobDTO serializes exactly as mobile/api/types.ts OcrJob.
type OcrJobDTO struct {
ID string `json:"id"`
Status string `json:"status"`
Text string `json:"text,omitempty"`
Error string `json:"error,omitempty"`
}
// Ocr queues OCR jobs in `ocr_jobs` (status `queued`) and processes them
// asynchronously through a bounded worker ([Run]) — Tesseract ne tourne jamais
// dans un request handler. Le client poll GET /ocr/jobs/:id toutes les 3s.
type Ocr struct {
Repository *repository.Repository
UploadDir string
Lang string
Engine ocr.Engine
StaleAfter time.Duration
}
func NewOcr(repo *repository.Repository, uploadDir, lang string, engine ocr.Engine) *Ocr {
return &Ocr{Repository: repo, UploadDir: uploadDir, Lang: normalizeOcrLang(lang), Engine: engine, StaleAfter: StaleClaimTimeout}
}
var (
// ocrLangPattern : whitelist OCR_LANG (A12) — lettres Tesseract + `+`
// uniquement (ex. `fra`, `eng`, `fra+eng`). Tout le reste (espaces,
// `;`, `-`, options `--...`) est une tentative d'injection `-l`.
ocrLangPattern = regexp.MustCompile(`^[a-z+]{2,20}$`)
// hexIDPattern : identifiants 32-hex (anti `..` dans physicalPath).
hexIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
)
// DefaultOcrLang est la langue Tesseract de repli (OCR_LANG, défaut fra+eng).
const DefaultOcrLang = "fra+eng"
// normalizeOcrLang applique la whitelist OCR_LANG : valeur invalide → repli
// sur le défaut avec log (jamais d'injection vers `tesseract -l`).
func normalizeOcrLang(lang string) string {
if ocrLangPattern.MatchString(lang) {
return lang
}
log.Printf("ocr: OCR_LANG %q invalide (whitelist ^[a-z+]{2,20}$), repli sur %q", lang, DefaultOcrLang)
return DefaultOcrLang
}
// Create valide la ressource (ownership par user) et l'enfile uniquement
// (status `queued`) — le traitement est délégué au worker [Run] pour ne pas
// stresser le serveur. Le job reste scopé par device.
func (o *Ocr) Create(userID, deviceID, fileID string) (OcrJobDTO, error) {
if _, err := o.Repository.Resources.GetFile(userID, fileID); err != nil {
return OcrJobDTO{}, err
}
jobID := repository.NewID()
if err := o.Repository.OcrJobs.Create(jobID, deviceID, fileID); err != nil {
return OcrJobDTO{}, err
}
return OcrJobDTO{ID: jobID, Status: "queued"}, nil
}
func (o *Ocr) Get(deviceID, jobID string) (OcrJobDTO, error) {
row, err := o.Repository.OcrJobs.Get(deviceID, jobID)
if err != nil {
return OcrJobDTO{}, err
}
return toOcrJobDTO(row), nil
}
// Run fait tourner le worker OCR : au démarrage il requeue les jobs laissés
// en `processing` (crash), puis `workers` boucles consomment la file FIFO via
// ClaimNext (atomique, `FOR UPDATE SKIP LOCKED`). `workers` borne la
// concurrence Tesseract. Retourne quand ctx est annulé.
func (o *Ocr) Run(ctx context.Context, workers int) {
if workers < 1 {
workers = 1
}
if _, err := o.Repository.OcrJobs.ResetStaleProcessing(o.StaleAfter); err != nil {
log.Printf("ocr: requeue jobs stale: %v", err)
}
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
o.workerLoop(ctx)
}()
}
wg.Wait()
}
// workerLoop consomme la file : un job `queued` → processing → done/failed.
// File vide → scrutation à QueuePollInterval jusqu'à annulation du ctx.
func (o *Ocr) workerLoop(ctx context.Context) {
for {
row, err := o.Repository.OcrJobs.ClaimNext()
if err != nil {
if !errors.Is(err, repository.ErrNoQueuedJobs) {
log.Printf("ocr: claim: %v", err)
}
select {
case <-ctx.Done():
return
case <-time.After(QueuePollInterval):
}
continue
}
o.process(ctx, row)
}
}
// process exécute l'extraction pour un job déjà réclamé (`processing`).
// Ordre A13 : l'écriture `UpdateOcrText` est vérifiée AVANT le `Complete` —
// hôte supprimé entre-temps (0 ligne, ErrNotFound) → le job `Fail` au lieu
// de rester `done` avec un texte fantôme. Les erreurs `Fail`/`Complete`
// (conflit d'état : job requeue et repris par un autre worker) sont loggées,
// jamais silencieuses.
func (o *Ocr) process(ctx context.Context, row repository.OcrJobRow) {
fail := func(message string) {
if err := o.Repository.OcrJobs.Fail(row.DeviceID, row.ID, message); err != nil {
log.Printf("ocr: fail job %s: %v", row.ID, err)
}
}
complete := func(text string) {
if err := o.Repository.OcrJobs.Complete(row.DeviceID, row.ID, text); err != nil {
log.Printf("ocr: complete job %s: %v", row.ID, err)
}
}
userID, err := o.Repository.Resources.GetResourceOwner(row.FileID)
if err != nil {
fail("file not readable")
return
}
path, err := o.physicalPath(userID, row.FileID)
if err != nil {
fail("file not readable")
return
}
text, err := o.Engine.ExtractText(ctx, path, o.Lang)
if err != nil {
fail(err.Error())
return
}
// Le texte atterrit sur la ressource (updated_at bumpé) : consultable par
// tous les devices du user et les grantees via GET /files/:id/ocr.
if trimmed := strings.TrimSpace(text); trimmed != "" {
if err := o.Repository.Resources.UpdateOcrText(userID, row.FileID, trimmed); err != nil {
if errors.Is(err, repository.ErrNotFound) {
fail("file not readable")
} else {
fail(err.Error())
}
return
}
}
complete(text)
}
// physicalPath résout UPLOAD_DIR/<user_id>/<resource_id>.<ext> — l'ext est
// choisi à l'upload, le fichier réel est retrouvé par préfixe. Durci (A12) :
// identifiants 32-hex uniquement (anti `..`), `Lstat` + fichier régulier
// (ni dossier, ni symlink brut), `EvalSymlinks` contenu dans UPLOAD_DIR
// (anti évasion par lien symbolique). Candidat rejeté → candidat suivant ;
// aucun candidat → ErrNotFound.
func (o *Ocr) physicalPath(userID, fileID string) (string, error) {
if !hexIDPattern.MatchString(userID) || !hexIDPattern.MatchString(fileID) {
return "", fmt.Errorf("physicalPath: identifiant non 32-hex")
}
base, err := filepath.EvalSymlinks(o.UploadDir)
if err != nil {
return "", fmt.Errorf("physicalPath: upload dir illisible: %w", err)
}
matches, err := filepath.Glob(filepath.Join(o.UploadDir, userID, fileID+".*"))
if err != nil {
return "", err
}
for _, m := range matches {
if !strings.HasPrefix(filepath.Base(m), fileID+".") {
continue
}
fi, err := os.Lstat(m)
if err != nil || !fi.Mode().IsRegular() {
continue
}
resolved, err := filepath.EvalSymlinks(m)
if err != nil {
continue
}
rel, err := filepath.Rel(base, resolved)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
continue
}
return resolved, nil
}
return "", repository.ErrNotFound
}
func toOcrJobDTO(row repository.OcrJobRow) OcrJobDTO {
dto := OcrJobDTO{ID: row.ID, Status: row.Status}
if row.Text != nil {
dto.Text = *row.Text
}
if row.Error != nil {
dto.Error = *row.Error
}
return dto
}