V2-4 : placements multi-device (report_bytes, tables 000015, copies UI)

This commit is contained in:
venture
2026-09-25 19:45:33 +02:00
parent 0f90aad938
commit a91ddf7aa8
42 changed files with 714 additions and 25 deletions
+56
View File
@@ -0,0 +1,56 @@
package service
import (
"time"
"github.com/kazier/backend/repository"
)
// PlacementDTO serializes one byte-presence entry for
// GET /files/:id/placements. The `server` entry is implicit (derived from
// `resources.has_content`, no row) ; device entries come from client reports
// (`report_bytes` ops). `updatedAt` is RFC3339 (server entry: resource
// timestamp ; device entries: report timestamp).
type PlacementDTO struct {
LocationType string `json:"locationType"`
DeviceID string `json:"deviceId,omitempty"`
HasBytes bool `json:"hasBytes"`
UpdatedAt string `json:"updatedAt,omitempty"`
}
// ListPlacements returns byte presence of a resource the user OWNS (server
// entry + device reports, newest first). Non-owner → ErrNotFound (same
// owner-only scoping as shares/links reads).
func (s *Resources) ListPlacements(userID, resourceID string) ([]PlacementDTO, error) {
ownerID, err := s.Repo.GetResourceOwner(resourceID)
if err != nil {
return nil, err
}
if ownerID != userID {
return nil, repository.ErrNotFound
}
row, err := s.Repo.GetFileVisible(userID, resourceID)
if err != nil {
return nil, err
}
out := []PlacementDTO{
{
LocationType: "server",
HasBytes: row.HasContent,
UpdatedAt: row.UpdatedAt.UTC().Format(time.RFC3339),
},
}
placements, err := s.Repository.Placements.ListForResource(resourceID)
if err != nil {
return nil, err
}
for _, p := range placements {
out = append(out, PlacementDTO{
LocationType: p.LocationType,
DeviceID: p.DeviceID,
HasBytes: p.HasBytes,
UpdatedAt: p.UpdatedAt.UTC().Format(time.RFC3339),
})
}
return out, nil
}
+39 -7
View File
@@ -23,6 +23,8 @@ const (
OpUpdateShare = "update_share"
OpCreateLink = "create_link"
OpRevokeLink = "revoke_link"
// V2 placements : un device signale la présence de ses octets.
OpReportBytes = "report_bytes"
)
// SyncOperation is one outbox entry (shadow of mobile PendingOperationRow).
@@ -85,6 +87,10 @@ type revokeLinkPayload struct {
Token string `json:"token"`
}
type reportBytesPayload struct {
HasBytes *bool `json:"hasBytes"`
}
func classifySyncError(err error) (string, string) {
switch {
case errors.Is(err, repository.ErrNameConflict):
@@ -166,7 +172,7 @@ func (s *Resources) ApplyBatch(userID, deviceID string, ops []SyncOperation) (Sy
// Trace 'failed' à payload identique : la première tentative est
// morte avant MarkApplied (crash) → on ré-applique (recovery).
}
if err := s.applySyncOp(userID, op); err != nil {
if err := s.applySyncOp(userID, deviceID, op); err != nil {
code, message := classifySyncError(err)
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}}, nil
}
@@ -190,7 +196,8 @@ func validateSyncOp(op *SyncOperation) error {
}
switch op.Operation {
case OpCreateResource, OpUpdateMetadata, OpMoveResource, OpDeleteResource,
OpShare, OpRevokeShare, OpUpdateShare, OpCreateLink, OpRevokeLink:
OpShare, OpRevokeShare, OpUpdateShare, OpCreateLink, OpRevokeLink,
OpReportBytes:
default:
return errors.New("unknown operation " + op.Operation)
}
@@ -200,7 +207,7 @@ func validateSyncOp(op *SyncOperation) error {
return nil
}
func (s *Resources) applySyncOp(ownerID string, op *SyncOperation) error {
func (s *Resources) applySyncOp(ownerID, deviceID string, op *SyncOperation) error {
resourceID := derefString(op.ResourceID)
switch op.Operation {
case OpCreateResource:
@@ -272,10 +279,10 @@ func (s *Resources) applySyncOp(ownerID string, op *SyncOperation) error {
return errors.New("payload.name required")
}
// NOTE : UpdateNameByID (non-scopé) est volontaire ici — un editor
// non-owner peut renommer (EffectiveAccess vérifié plus haut), donc
// UpdateNameOwned(ownerID, ...) rejetterait à tort. La garde
// d'autorisation précède immédiatement l'écriture.
return s.Repo.UpdateNameByID(resourceID, p.Name)
// non-owner peut renommer (EffectiveAccess vérifié plus haut), donc
// UpdateNameOwned(ownerID, ...) rejetterait à tort. La garde
// d'autorisation précède immédiatement l'écriture.
return s.Repo.UpdateNameByID(resourceID, p.Name)
case OpMoveResource:
// A8 : move owner-only. Source non-owned (absente OU d'autrui) →
@@ -333,11 +340,36 @@ func (s *Resources) applySyncOp(ownerID string, op *SyncOperation) error {
case OpRevokeLink:
return s.applyRevokeLinkOp(ownerID, resourceID, op)
case OpReportBytes:
return s.applyReportBytesOp(ownerID, deviceID, resourceID, op)
default:
return errors.New("unknown operation " + op.Operation)
}
}
// applyReportBytesOp handles OpReportBytes: a device reports its byte
// presence (V2 placements). Scope is viewer+ (owned or shared,
// GetFileVisible) — a grantee downloading a shared file reports too.
// Invisible → ErrNotFound (no enumeration). Naturally idempotent ; the A9
// replay guard requires a FRESH operation_id per state change.
func (s *Resources) applyReportBytesOp(userID, deviceID, resourceID string, op *SyncOperation) error {
if derefString(op.ResourceType) != "file" {
return errors.New("resource_type must be 'file' for report_bytes")
}
if _, err := s.Repo.GetFileVisible(userID, resourceID); err != nil {
return err
}
var p reportBytesPayload
if err := json.Unmarshal(op.Payload, &p); err != nil {
return errors.New("invalid payload: " + err.Error())
}
if p.HasBytes == nil {
return errors.New("payload.hasBytes required")
}
return s.Repository.Placements.Report(userID, deviceID, resourceID, *p.HasBytes)
}
// applyShareOp handles OpShare and OpUpdateShare: upsert a user-to-user grant.
func (s *Resources) applyShareOp(ownerID, resourceID string, op *SyncOperation) error {
exists, err := s.Repo.ExistsOwner(ownerID, resourceID)
+73
View File
@@ -1485,3 +1485,76 @@ func TestDeleteAbsentIsIdempotentNoop(t *testing.T) {
t.Errorf("delete absent: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err)
}
}
func TestApplyBatchReportBytes(t *testing.T) {
s := newServiceStore(t)
ownerID := mustCreateUser(t, s.Repository, "report-owner")
granteeID := mustCreateUser(t, s.Repository, "report-grantee")
outsiderID := mustCreateUser(t, s.Repository, "report-outsider")
deviceID := mustRegisterDevice(t, s.Repository, shareTestDeviceID)
otherDevice := mustRegisterDevice(t, s.Repository, "b0000000000000000000000000000001")
fileID := repository.NewID()
if _, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(repository.NewID(), fileID, OpCreateResource, "file", map[string]any{"name": "r.txt"}),
syncOp(repository.NewID(), fileID, OpShare, "file", map[string]any{"granteeUserId": granteeID, "access": "viewer"}),
}); err != nil {
t.Fatalf("setup: %v", err)
}
report := func(user, device, res string, hasBytes bool) (SyncResult, error) {
return s.ApplyBatch(user, device, []SyncOperation{
syncOp(repository.NewID(), res, OpReportBytes, "file", map[string]any{"hasBytes": hasBytes}),
})
}
// Owner + grantee (viewer) peuvent reporter ; l'owner lit serveur + device.
if result, err := report(ownerID, deviceID, fileID, true); err != nil || result.Applied != 1 || result.Failed != nil {
t.Fatalf("report owner: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err)
}
if result, err := report(granteeID, otherDevice, fileID, true); err != nil || result.Applied != 1 || result.Failed != nil {
t.Fatalf("report grantee: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err)
}
placements, err := s.ListPlacements(ownerID, fileID)
if err != nil {
t.Fatalf("ListPlacements: %v", err)
}
if len(placements) != 3 {
t.Fatalf("attendu serveur + 2 devices, got %+v", placements)
}
if placements[0].LocationType != "server" || placements[0].HasBytes {
t.Errorf("entrée serveur = %+v, attendu hasBytes=false", placements[0])
}
// Changement d'état (drop) avec un NOUVEL operation_id ; hasBytes manquant → halt.
if result, err := report(ownerID, deviceID, fileID, false); err != nil || result.Applied != 1 || result.Failed != nil {
t.Fatalf("report drop: applied=%d failed=%+v err=%v", result.Applied, result.Failed, err)
}
bad, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(repository.NewID(), fileID, OpReportBytes, "file", map[string]any{}),
})
if err != nil || bad.Applied != 0 || bad.Failed == nil || bad.Failed.Code != "INVALID_REQUEST" {
t.Errorf("hasBytes manquant: attendu halt INVALID_REQUEST, got %+v err=%v", bad, err)
}
// Outsider (invisible) → halt NOT_FOUND, sans énumération.
denied, err := report(outsiderID, otherDevice, fileID, true)
if err != nil || denied.Applied != 0 || denied.Failed == nil || denied.Failed.Code != "NOT_FOUND" {
t.Errorf("report outsider: attendu halt NOT_FOUND, got %+v err=%v", denied, err)
}
// Rejeu à l'identique → idempotent (skip, pas d'erreur).
replayID := repository.NewID()
first, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(replayID, fileID, OpReportBytes, "file", map[string]any{"hasBytes": true}),
})
if err != nil || first.Applied != 1 || first.Failed != nil {
t.Fatalf("report initial: %+v err=%v", first, err)
}
second, err := s.ApplyBatch(ownerID, deviceID, []SyncOperation{
syncOp(replayID, fileID, OpReportBytes, "file", map[string]any{"hasBytes": true}),
})
if err != nil || second.Applied != 1 || second.Failed != nil {
t.Errorf("rejeu identique: attendu skip idempotent, got %+v err=%v", second, err)
}
}