package catalog import ( "bytes" "context" "encoding/json" "errors" "fmt" "io/fs" "log/slog" "os" "regexp" "github.com/jackc/pgx/v5" ) // Collections de documents JSON : tables (id text PRIMARY KEY, data jsonb) // pour les données globales de l'application (comptes, jetons, réglages). // Chaque modification charge la collection sous un verrou consultatif propre // à la table, applique la fonction de l'appelant, puis n'écrit que les // documents ajoutés, modifiés ou supprimés. var fieldRe = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]*$`) func ident(table string) string { return pgx.Identifier{table}.Sanitize() } // loadDocs lit toute la collection ; raw reçoit l'encodage Go de chaque // document (pour détecter ensuite ce qui a changé). func loadDocs[T any](ctx context.Context, tx pgx.Tx, table string, raw map[string][]byte) (map[string]*T, error) { rows, err := tx.Query(ctx, "SELECT id, data FROM "+ident(table)) if err != nil { return nil, err } defer rows.Close() out := map[string]*T{} for rows.Next() { var id string var b []byte if err := rows.Scan(&id, &b); err != nil { return nil, err } v := new(T) if err := json.Unmarshal(b, v); err != nil { return nil, fmt.Errorf("%s/%s : %w", table, id, err) } out[id] = v if raw != nil { if raw[id], err = json.Marshal(v); err != nil { return nil, err } } } return out, rows.Err() } // AllDocs renvoie toute la collection. func AllDocs[T any](ctx context.Context, db *DB, table string) (map[string]*T, error) { var out map[string]*T err := db.Tx(ctx, func(tx pgx.Tx) error { var err error out, err = loadDocs[T](ctx, tx, table, nil) return err }) return out, err } // GetDoc renvoie le document id (nil s'il n'existe pas). func GetDoc[T any](ctx context.Context, db *DB, table, id string) (*T, error) { return findDoc[T](ctx, db, "SELECT data FROM "+ident(table)+" WHERE id = $1", id) } // FindDoc renvoie le premier document dont le champ texte field vaut value // (nil si aucun). field est un nom de champ constant (index sur l'expression). func FindDoc[T any](ctx context.Context, db *DB, table, field, value string) (*T, error) { if !fieldRe.MatchString(field) { return nil, fmt.Errorf("champ %q invalide", field) } return findDoc[T](ctx, db, "SELECT data FROM "+ident(table)+" WHERE data->>'"+field+"' = $1 LIMIT 1", value) } func findDoc[T any](ctx context.Context, db *DB, sql, arg string) (*T, error) { var b []byte err := db.Tx(ctx, func(tx pgx.Tx) error { b = nil err := tx.QueryRow(ctx, sql, arg).Scan(&b) if errors.Is(err, pgx.ErrNoRows) { return nil } return err }) if err != nil || b == nil { return nil, err } v := new(T) if err := json.Unmarshal(b, v); err != nil { return nil, err } return v, nil } // UpdateDocs modifie la collection : fn reçoit tous les documents (qu'elle // peut modifier, ajouter ou supprimer) sous le verrou de la table. Une // erreur de fn annule tout. fn peut être rejouée (voir DB.Tx). func UpdateDocs[T any](ctx context.Context, db *DB, table string, fn func(map[string]*T) error) error { return db.Tx(ctx, func(tx pgx.Tx) error { if err := Lock(ctx, tx, "docs:"+table); err != nil { return err } before := map[string][]byte{} docs, err := loadDocs[T](ctx, tx, table, before) if err != nil { return err } if err := fn(docs); err != nil { return err } return writeDocs(ctx, tx, table, before, docs) }) } func writeDocs[T any](ctx context.Context, tx pgx.Tx, table string, before map[string][]byte, after map[string]*T) error { for id := range before { if _, ok := after[id]; !ok { if _, err := tx.Exec(ctx, "DELETE FROM "+ident(table)+" WHERE id = $1", id); err != nil { return err } } } for id, v := range after { b, err := json.Marshal(v) if err != nil { return err } if old, ok := before[id]; ok && bytes.Equal(old, b) { continue } if _, err := tx.Exec(ctx, "INSERT INTO "+ident(table)+" (id, data) VALUES ($1, $2) "+ "ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data", id, b); err != nil { return err } } return nil } // ReplaceDoc remplace un document existant sans prendre le verrou de la // table (mise à jour légère, par exemple une date de dernière utilisation) ; // un document supprimé entre-temps n'est pas recréé. func ReplaceDoc(ctx context.Context, db *DB, table, id string, v any) error { b, err := json.Marshal(v) if err != nil { return err } return db.Tx(ctx, func(tx pgx.Tx) error { _, err := tx.Exec(ctx, "UPDATE "+ident(table)+" SET data = $2 WHERE id = $1", id, b) return err }) } // ImportFileOnce reprend une seule fois (table imports, clé root + kind) // l'ancien fichier file : fn reçoit son contenu dans la transaction, puis le // fichier est renommé en *.imported. Un fichier absent marque simplement la // reprise comme faite. func (db *DB) ImportFileOnce(ctx context.Context, root, kind, file string, fn func(context.Context, pgx.Tx, []byte) error) error { var found bool err := db.Tx(ctx, func(tx pgx.Tx) error { found = false if err := Lock(ctx, tx, "import:"+root+":"+kind); err != nil { return err } var done bool if err := tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM imports WHERE root = $1 AND kind = $2)", root, kind).Scan(&done); err != nil || done { return err } b, err := os.ReadFile(file) switch { case errors.Is(err, fs.ErrNotExist): case err != nil: return err default: if err := fn(ctx, tx, b); err != nil { return fmt.Errorf("%s : %w", file, err) } found = true } _, err = tx.Exec(ctx, "INSERT INTO imports (root, kind) VALUES ($1, $2)", root, kind) return err }) if err != nil || !found { return err } if err := os.Rename(file, file+".imported"); err != nil && !errors.Is(err, fs.ErrNotExist) { slog.Warn("catalogue : fichier repris non renommé", "fichier", file, "err", err) } slog.Info("catalogue : fichier repris en base", "fichier", file) return nil } // InsertDocs ajoute des documents sans écraser ceux qui existent (reprise). func InsertDocs[T any](ctx context.Context, tx pgx.Tx, table string, docs map[string]*T) error { for id, v := range docs { b, err := json.Marshal(v) if err != nil { return err } if _, err := tx.Exec(ctx, "INSERT INTO "+ident(table)+" (id, data) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING", id, b); err != nil { return err } } return nil } // Blobs : petits fichiers binaires partagés (logo). // GetBlob renvoie le contenu et la version (horodatage) de key, ou nil. func (db *DB) GetBlob(ctx context.Context, key string) ([]byte, int64, error) { var b []byte var v int64 err := db.Tx(ctx, func(tx pgx.Tx) error { b, v = nil, 0 err := tx.QueryRow(ctx, "SELECT data, (extract(epoch FROM updated) * 1e6)::bigint FROM app_blobs WHERE key = $1", key).Scan(&b, &v) if errors.Is(err, pgx.ErrNoRows) { return nil } return err }) return b, v, err } // BlobVersion renvoie la version de key (0 si absent), sans lire le contenu. func (db *DB) BlobVersion(ctx context.Context, key string) (int64, error) { var v int64 err := db.Tx(ctx, func(tx pgx.Tx) error { v = 0 err := tx.QueryRow(ctx, "SELECT (extract(epoch FROM updated) * 1e6)::bigint FROM app_blobs WHERE key = $1", key).Scan(&v) if errors.Is(err, pgx.ErrNoRows) { return nil } return err }) return v, err } // PutBlob enregistre key (data nil : suppression). func (db *DB) PutBlob(ctx context.Context, key string, data []byte) error { return db.Tx(ctx, func(tx pgx.Tx) error { if data == nil { _, err := tx.Exec(ctx, "DELETE FROM app_blobs WHERE key = $1", key) return err } _, err := tx.Exec(ctx, `INSERT INTO app_blobs (key, data, updated) VALUES ($1, $2, clock_timestamp()) ON CONFLICT (key) DO UPDATE SET data = EXCLUDED.data, updated = EXCLUDED.updated`, key, data) return err }) } // PutBlobTx : PutBlob dans une transaction existante (reprise). func PutBlobTx(ctx context.Context, tx pgx.Tx, key string, data []byte) error { _, err := tx.Exec(ctx, `INSERT INTO app_blobs (key, data) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`, key, data) return err }