Files
Kazier/backend/repository/operations.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

227 lines
7.5 KiB
Go

package repository
import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"regexp"
)
// operationIDPattern — operation_id outbox = TEXT 32-hex (cf. docs/api-v1.md §6.1).
var operationIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
// Operations persists the per-device outbox trace enforcing idempotence
// UNIQUE(device_id, operation_id) — cf. docs/api-v1.md §6.1.
type Operations struct {
DB *sql.DB
}
// Statuts de la trace outbox (CHECK status IN ('applied','failed'), 000004).
// 'failed' = brouillon claimé pas encore confirmé (ou apply en échec) ;
// 'applied' = effet durable confirmé.
const (
OpStatusApplied = "applied"
OpStatusFailed = "failed"
)
// ErrInvalidOperationID is returned when operation_id is not 32 lowercase hex.
var ErrInvalidOperationID = errors.New("operation_id must be 32 lowercase hex chars")
// ErrInvalidPayload is returned when the trace payload is not valid JSON.
// Le service le mappe en INVALID_REQUEST (faute client, message statique sûr).
var ErrInvalidPayload = errors.New("invalid payload JSON")
// ErrPayloadMismatch is returned when an operation is replayed under the same
// (device_id, operation_id) with a different payload (cf. A9). The replay
// must halt in INVALID_REQUEST, never skip silently.
var ErrPayloadMismatch = errors.New("operation replayed with different payload")
// Applied reports whether the operation was already processed for this device.
func (o *Operations) Applied(deviceID, operationID string) (bool, error) {
var exists int
err := o.DB.QueryRow(
`SELECT 1 FROM operations WHERE device_id = $1 AND operation_id = $2`,
deviceID, operationID,
).Scan(&exists)
if err == sql.ErrNoRows {
return false, nil
}
return err == nil, err
}
// StoredOp is the persisted trace of an applied operation (replay compare).
type StoredOp struct {
OpType string
ResourceID string
Payload []byte
Status string
PayloadHash string // "" = trace héritée pré-000013 (hash recalculé depuis Payload)
}
// Get returns the stored trace for (device, operation), or sql.ErrNoRows.
func (o *Operations) Get(deviceID, operationID string) (StoredOp, error) {
var op StoredOp
var resourceID sql.NullString
var payloadHash sql.NullString
var payload []byte
err := o.DB.QueryRow(
`SELECT op_type, resource_id, COALESCE(payload::text, '{}'), status, payload_hash
FROM operations WHERE device_id = $1 AND operation_id = $2`,
deviceID, operationID,
).Scan(&op.OpType, &resourceID, &payload, &op.Status, &payloadHash)
if err != nil {
return StoredOp{}, err
}
if resourceID.Valid {
op.ResourceID = resourceID.String
}
if payloadHash.Valid {
op.PayloadHash = payloadHash.String
}
op.Payload = payload
return op, nil
}
// Claim atomically takes ownership of an operation slot for this device
// (#7 : sérialisation des batches concurrents sur la contrainte
// UNIQUE(device_id, operation_id)). Premier appelant → claimed=true, la ligne
// est insérée en status='failed' (brouillon) avec le hash du payload ; le
// perdant du conflit (claimed=false) suit le chemin rejeu (comparer via Get).
// Après apply réussi, l'appelant promeut la ligne via MarkApplied ; en cas
// d'échec d'apply, la ligne reste 'failed' (rejouable à payload identique).
func (o *Operations) Claim(deviceID, operationID string, opType, refType string, refID *int64, resourceID string, payload []byte) (bool, error) {
if !operationIDPattern.MatchString(operationID) {
return false, ErrInvalidOperationID
}
if len(payload) != 0 && string(payload) != "null" && !json.Valid(payload) {
return false, ErrInvalidPayload
}
var refTypeValue any
if refType != "" {
refTypeValue = refType
}
res, err := o.DB.Exec(
`INSERT INTO operations (device_id, operation_id, op_type, ref_type, ref_id, resource_id, payload, payload_hash, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'failed')
ON CONFLICT (device_id, operation_id) DO NOTHING`,
deviceID, operationID, opType, refTypeValue, refID, nullable(resourceID), jsonBytes(payload), CanonicalPayloadHash(payload),
)
if err != nil {
return false, err
}
affected, err := res.RowsAffected()
if err != nil {
return false, err
}
return affected == 1, nil
}
// MarkApplied promotes a claimed ('failed') trace row to 'applied' once the
// operation effect is durable. Best-effort : l'échec est remonté pour que le
// batch retourne applied:i explicite (rejouable, pas 500 nu).
func (o *Operations) MarkApplied(deviceID, operationID string) error {
res, err := o.DB.Exec(
`UPDATE operations SET status = 'applied'
WHERE device_id = $1 AND operation_id = $2 AND status = 'failed'`,
deviceID, operationID,
)
if err != nil {
return err
}
affected, err := res.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
// Déjà promue (rejeu concurrent) ou ligne absente : pas d'erreur,
// l'idempotence est portée par la contrainte d'unicité.
return nil
}
return nil
}
// MatchesReplay reports whether an incoming operation matches the stored
// trace: same op type, same resource, same canonical payload hash. Legacy
// rows (payload_hash NULL, pré-000013) comparent le hash recalculé depuis le
// payload stocké. Mismatch → ErrPayloadMismatch (wrappable via errors.Is).
func (op StoredOp) MatchesReplay(opType, resourceID string, payload []byte) error {
if op.OpType != opType || op.ResourceID != resourceID {
return ErrPayloadMismatch
}
want := CanonicalPayloadHash(payload)
got := op.PayloadHash
if got == "" {
got = CanonicalPayloadHash(op.Payload)
}
if got != want {
return ErrPayloadMismatch
}
return nil
}
// CanonicalPayloadHash is sha256-hex of the canonical payload form: empty /
// "null" → {}, sinon round-trip JSON (clés triées, espaces neutralisés) pour
// que deux sérialisations du même objet donnent le même hash.
func CanonicalPayloadHash(payload []byte) string {
sum := sha256.Sum256(canonicalPayloadBytes(payload))
return hex.EncodeToString(sum[:])
}
func canonicalPayloadBytes(payload []byte) []byte {
if len(payload) == 0 || string(payload) == "null" {
return []byte(`{}`)
}
var v any
if err := json.Unmarshal(payload, &v); err != nil {
return []byte(`{}`)
}
out, err := json.Marshal(v)
if err != nil {
return []byte(`{}`)
}
return out
}
// Record stores an applied operation trace (idempotent on replay).
// Le hash canonique du payload est persisté (000013, cf. A9) ; status='applied'.
func (o *Operations) Record(deviceID, operationID string, opType, refType string, refID *int64, resourceID string, payload []byte) error {
if !operationIDPattern.MatchString(operationID) {
return ErrInvalidOperationID
}
if len(payload) != 0 && string(payload) != "null" && !json.Valid(payload) {
return ErrInvalidPayload
}
var refTypeValue any
if refType != "" {
refTypeValue = refType
}
_, err := o.DB.Exec(
`INSERT INTO operations (device_id, operation_id, op_type, ref_type, ref_id, resource_id, payload, payload_hash, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'applied')
ON CONFLICT (device_id, operation_id) DO NOTHING`,
deviceID, operationID, opType, refTypeValue, refID, nullable(resourceID), jsonBytes(payload), CanonicalPayloadHash(payload),
)
return err
}
func nullable(value string) any {
if value == "" {
return nil
}
return value
}
func jsonBytes(payload []byte) any {
if len(payload) == 0 || string(payload) == "null" {
return []byte(`{}`)
}
if !json.Valid(payload) {
// Trace infidèle refusée (cf. A15) : l'appelant doit rejeter en amont ;
// ici on ne normalise plus silencieusement vers {}.
return nil
}
return payload
}