V2-4 : placements multi-device (report_bytes, tables 000015, copies UI)
This commit is contained in:
@@ -38,9 +38,9 @@ Tests mobiles : JVM unit tests dans `app/src/test` (JUnit + Robolectric + Room i
|
||||
- `config/` — env (`godotenv`, optionnel) + defaults: `PORT`, `DATABASE_URL`, `UPLOAD_DIR`, `MAX_FILE_SIZE_MB`, `OCR_LANG`, `AUTH_SECRET` (secret des tokens paseto), `ADMIN_USERNAME`/`ADMIN_PASSWORD` (bootstrap du premier admin)
|
||||
- `models/` — domain entities (users, devices, documents/resources, clients)
|
||||
- `service/` — business logic (permissions, upload, create folder, move, **sync outbox + snapshot**, bootstrap admin)
|
||||
- `handlers/` — HTTP handlers (health, devices register, **auth/login**, **users resolve + change password**, files CRUD/upload/search, folders, **sync/ops + sync/permissions, ocr/jobs, files/:id/content, files/:id/shares, files/:id/links** — réels) ; middleware `RequireAuth`
|
||||
- `repository/` — Postgres persistence (`repository.Resources` : insert/list/get/soft-delete scoping `owner_id`, search, move, rename, root-name unique index, `ListOwned` pour le snapshot, `OpenContent` (bytes streaming + lazy healing `has_content`), `ListShares`/`ListLinks` (owner-only), `SetHasContent` ; `repository.Devices` : Upsert, Exists, MarkUser ; `repository.Operations` : trace outbox idempotente `(device_id, operation_id)` ; `repository.OcrJobs` : jobs queued→processing→done/failed ; `repository.Users` : GetByUsernameNormalized, ResolveExact, UpdatePassword ; `repository.Shares` : Upsert/Revoke, CreateLink/RevokeLink, ListActiveForResource, ListActiveLinksForResource, snapshot `ListEffectivePermissions`) ; IDs sont TEXT 32-hex, `NewID()` = `crypto/rand` 16 octets hex (jamais UUID conversion, cf. `docs/api-v1.md`)
|
||||
- `db/` — package migrations (`golang-migrate/v4`, embarquées via `embed` dans `db/migrations/*.sql`, 000001→000014) : `db.MigrateDatabase(url)` au boot du serveur ; test harness `db/migrations_test.go` (up → assertions schéma → down, `TEST_DATABASE_URL`, skip si PG indisponible) ; `dbtest/` — helper cross-package pour les tests repo/handlers (crée la DB test si absente, reset schema, migrate ; skip si PG down)
|
||||
- `handlers/` — HTTP handlers (health, devices register, **auth/login**, **users resolve + change password**, files CRUD/upload/search, folders, **sync/ops + sync/permissions, ocr/jobs, files/:id/content, files/:id/shares, files/:id/links, files/:id/placements** — réels) ; middleware `RequireAuth`
|
||||
- `repository/` — Postgres persistence (`repository.Resources` : insert/list/get/soft-delete scoping `owner_id`, search, move, rename, root-name unique index, `ListOwned` pour le snapshot, `OpenContent` (bytes streaming + lazy healing `has_content`), `ListShares`/`ListLinks` (owner-only), `SetHasContent` ; `repository.Devices` : Upsert, Exists, MarkUser ; `repository.Operations` : trace outbox idempotente `(device_id, operation_id)` ; `repository.OcrJobs` : jobs queued→processing→done/failed ; `repository.Users` : GetByUsernameNormalized, ResolveExact, UpdatePassword ; `repository.Shares` : Upsert/Revoke, CreateLink/RevokeLink, ListActiveForResource, ListActiveLinksForResource, snapshot `ListEffectivePermissions` ; `repository.Placements` : EnsureLocation/Report/ListForResource (V2 multi-device) ; IDs sont TEXT 32-hex, `NewID()` = `crypto/rand` 16 octets hex (jamais UUID conversion, cf. `docs/api-v1.md`)
|
||||
- `db/` — package migrations (`golang-migrate/v4`, embarquées via `embed` dans `db/migrations/*.sql`, 000001→000015) : `db.MigrateDatabase(url)` au boot du serveur ; test harness `db/migrations_test.go` (up → assertions schéma → down, `TEST_DATABASE_URL`, skip si PG indisponible) ; `dbtest/` — helper cross-package pour les tests repo/handlers (crée la DB test si absente, reset schema, migrate ; skip si PG down)
|
||||
- `ocr/` — OCR engine behind an interface (Tesseract system call, `OCR_LANG` défaut `fra+eng`)
|
||||
- `pkg/api/` — response helpers (`response.go`) ; `pkg/auth/` — tokens **paseto v4-local** (subject = `user_id`, claim = `device_id`, TTL 7j, voir `docs/api-v1.md`) ; `pkg/passwd/` — hashing/vérification argon2id (comparaison `subtle`, délai égalisé)
|
||||
- File uploads stored in `backend/uploads/`
|
||||
@@ -54,14 +54,14 @@ Tests mobiles : JVM unit tests dans `app/src/test` (JUnit + Robolectric + Room i
|
||||
- Data layer — `data/`:
|
||||
- `data/local/` — Room SQLite (DB `dot.db`, **version 18**, `Migrations.kt` : tables `folders`, `files` (+ `category`, `processed`, `content`, `ocr_text`, `ocr_attempts`, `ocr_queued_at`, `bytes_uploaded`, `bytes_upload_attempts`, `has_content_server`, `wanted_offline`), `user_preferences`, `pending_operations` (+ `device_id`, `parent_resource_id`), `scan_sessions`, `scan_pages`, `resource_permissions`) : entités + DAO, tri (`FileOrdering`), schéma exporté (`app/schemas/`, m19) ; flag `processed` sur `files` (mode review « traiter », local au device, **gate de sync** : un fichier pas encore traité n'est jamais poussé) ; outbox transactionnel `pending_operations`
|
||||
- `data/remote/` — Retrofit/Moshi : `ApiService.kt` + `dto/Dtos.kt` = **contrat HTTP** (`{ data, meta }`, erreurs `{ error: { code, message } }`) ; `ApiClient.kt` normalise les réponses ; interceptors OkHttp (`AuthInterceptor`, `ServerUrlInterceptor`) ; `SafMultipart.kt` (multipart SAF paresseux partagé upload OCR + V2)
|
||||
- `data/repository/` — `FolderRepository`, `FileRepository`, `AuthRepository`, `OutboxRepository` (enqueue `create_resource`/`move_resource`/`delete_resource` + ops partage `share`/`update_share`/`revoke_share`/`create_link`/`revoke_link`, écrivains dans la même transaction Room que la mutation parente ; pour un fichier SAF, la mutation parente du `create_resource` est le **garder** de la review (`markProcessed`), et `hasCreateOperation` en garde l'unicité), `ShareRepository` (hydratation + delta + `canAccess` depuis `GET /sync/permissions`), `OcrRepository` (upload ciblé + jobs + `syncFromServer`), `RemoteContentRepository` (streaming `GET /files/:id/content`, jamais persisté ; **upload V2** des octets après metadata synced, `bytes_uploaded` ; **download V2** vers SAF + rattachement, `wanted_offline`)
|
||||
- `data/repository/` — `FolderRepository`, `FileRepository`, `AuthRepository`, `OutboxRepository` (enqueue `create_resource`/`move_resource`/`delete_resource` + ops partage `share`/`update_share`/`revoke_share`/`create_link`/`revoke_link` + `report_bytes` V2 (`{ hasBytes }`, nouvel `operation_id` par état), écrivains dans la même transaction Room que la mutation parente ; pour un fichier SAF, la mutation parente du `create_resource` est le **garder** de la review (`markProcessed`), et `hasCreateOperation` en garde l'unicité), `ShareRepository` (hydratation + delta + `canAccess` depuis `GET /sync/permissions`), `OcrRepository` (upload ciblé + jobs + `syncFromServer`), `RemoteContentRepository` (streaming `GET /files/:id/content`, jamais persisté ; **upload V2** des octets après metadata synced, `bytes_uploaded` ; **download V2** vers SAF + rattachement, `wanted_offline`)
|
||||
- `features/` — logique descendue côté client :
|
||||
- `sync/DeviceSync.kt` + `SafScanner.kt` — sync device↔SAF : **two-pass walk** (listing hors transaction puis upserts Room dans une seule transaction), réconciliation `exists = 0` (jamais de suppression), single-flight via `Mutex` ; les nouveaux **dossiers** sont journalisés dans l'outbox à la découverte, les **fichiers** uniquement au « garder » de la review (gate `processed`)
|
||||
- `saf/` — `SafUris`, `SafFolderCreator`, `FileMover` (relocalisation SAF `DocumentsContract.moveDocument`, repli métadonnée seule ; le déplacement est poussé en `move_resource`), `SafFileDeleter` (suppression SAF + `delete_resource` atomique), `FileDeleter.releaseLocalCopies` (purge sûre V2-3 : gate `isReleasable`, détachement cloud-only, zéro outbox)
|
||||
- `sync/OutboxSyncWorker.kt` — worker WorkManager (`enqueueUniqueWork` KEEP, single-flight, `NetworkType.CONNECTED`, backoff 30s) qui draine `pending_operations` vers `POST /sync/ops` (batch 20, dead-letter immédiat `failed` sur erreur 4xx non-idempotente — `attempts` diagnostic, purge synced > 7 jours) ; **schedulé** au login/restauration de session (`AuthViewModel`) et après chaque `syncAll()` (`SyncViewModel`) ; enchaîne `OcrAutoWorker` + `BytesUploadWorker` quand un fichier est promu (`DownloadWorker` sur demande hors-ligne)
|
||||
- `sync/OutboxSyncWorker.kt` — worker WorkManager (`enqueueUniqueWork` KEEP, single-flight, `NetworkType.CONNECTED`, backoff 30s) qui draine `pending_operations` vers `POST /sync/ops` (batch 20, dead-letter immédiat `failed` sur erreur 4xx non-idempotente — `attempts` diagnostic, purge synced > 7 jours, **sauf `report_bytes` : dead-letter + suite du batch, jamais bloquant**) ; **schedulé** au login/restauration de session (`AuthViewModel`) et après chaque `syncAll()` (`SyncViewModel`) ; enchaîne `OcrAutoWorker` + `BytesUploadWorker` quand un fichier est promu (`DownloadWorker` sur demande hors-ligne)
|
||||
- `sync/SyncViewModel.kt` — état du sync exposé à l'UI (`SyncStatus` : marche en cours, ops en attente, dernières opérations) via le badge header `ui/components/SyncStatusBadge.kt` + `SyncOperationsDialog.kt` (« liste des sync »)
|
||||
- `auth/` — session (login user + token paseto + **re-login silencieux** sur 401 via identifiants chiffrés persistés, single-flight, événements `Reauthenticated`/`SessionExpired`) : `SessionManager`, `SecureTokenStore`, `TokenProvider`, `TokenStore` (+ `Credentials`)
|
||||
- `ui/` — écrans Compose : `folderlist`, `folderdetail`, `document` (contenu PDF/image/texte local + streaming distant image/texte/PDF multi-pages via `RemoteDocumentViewer`, autres types non supportés en streaming), `search` (**recherche locale** via Room, sans endpoint serveur), `settings` (URL serveur + thème), `pdfbuilder` (multi-select → génération PDF), `auth` (login, mode local, avis d'expiration), `share` (`ShareBottomSheet` : grants + liens + ouverture de lien ; `OpenLinkScreen` + deep-link `kazier://share/<token>`), `components`, `theme`
|
||||
- `ui/` — écrans Compose : `folderlist`, `folderdetail`, `document` (contenu PDF/image/texte local + streaming distant image/texte/PDF multi-pages via `RemoteDocumentViewer`, autres types non supportés en streaming), `search` (**recherche locale** via Room, sans endpoint serveur), `settings` (URL serveur + thème), `pdfbuilder` (multi-select → génération PDF), `auth` (login, mode local, avis d'expiration), `share` (`ShareBottomSheet` : grants + liens + ouverture de lien + copies V2 ; `OpenLinkScreen` + deep-link `kazier://share/<token>`), `components`, `theme`
|
||||
- `domain/` — stores de préférences: `DeviceIdentity`, `ActiveUserStore`, `LocalModeStore`, `ServerConfigStore`, `ThemePreferenceStore`, `GenerateId` (identifiants 32-hex)
|
||||
- `di/` — modules Hilt (`AppModule`, `DatabaseModule`, `NetworkModule`)
|
||||
- Base URL serveur **configurée à l'exécution** dans les Réglages (`ServerConfigStore`, persistée en `user_preferences`), défaut `http://10.0.2.2:8080/api/v1` (pas de variable d'env)
|
||||
@@ -83,7 +83,7 @@ Tests mobiles : JVM unit tests dans `app/src/test` (JUnit + Robolectric + Room i
|
||||
- **Identity (user-first, V1 finale)**: le device s'enregistre (`POST /devices`, `{ "deviceId" }` seul, sans token), puis `POST /auth/login` (`username` + `password` + `device_id`) émet le seul token paseto **v4-local** — subject = `user_id` (autorise, scoping de toutes les ressources), claim `device_id` (porté, non autorisant seul), **TTL 7j sans refresh**. À expiration, le client re-logine **silencieusement** via les identifiants chiffrés persistés (`SecureTokenStore`, single-flight, événements `Reauthenticated`/`SessionExpired`), sans rejouer la requête en vol.
|
||||
- **Bootstrap**: au premier démarrage, si `users` est vide, `ADMIN_USERNAME`/`ADMIN_PASSWORD` (env) créent le premier admin ; absents → le serveur refuse de démarrer. L'env n'écrase jamais un compte existant. Usernames résolus sur `username_normalized` (lowercase + trim), `GET /users/resolve` exact uniquement (pas d'énumération).
|
||||
- **Identifiers**: `resource_id` / `device_user_id` / `user_id` / share-link `token` / `operation_id` sont des **lowercase 32-hex** TEXT (`^[0-9a-f]{32}$`, CHECK-enforced), stockés tels quels côté serveur (pas de conversion UUID). Le mobile génère toujours 32-hex.
|
||||
- **Outbox idempotence + ordering**: le serveur applique les batchs de `pending_operations` **séquentiellement**, s'arrête à la première erreur non-idempotente et retourne l'index atteint. Consommé par le client Kotlin (`OutboxSyncWorker` → `POST /sync/ops`, batch 20, dead-letter immédiat sur 4xx non-idempotente, purge > 7 jours). `create_resource` porte le `parentResourceId` optionnel (racine si absent) — le walk SAF garantit parent avant enfant dans l'ordre d'`id`.
|
||||
- **Outbox idempotence + ordering**: le serveur applique les batchs de `pending_operations` **séquentiellement**, s'arrête à la première erreur non-idempotente et retourne l'index atteint. Consommé par le client Kotlin (`OutboxSyncWorker` → `POST /sync/ops`, batch 20, dead-letter immédiat sur 4xx non-idempotente, purge > 7 jours). `create_resource` porte le `parentResourceId` optionnel (racine si absent) ; `report_bytes` (`{ hasBytes }`, V2 placements, nouvel `operation_id` par changement d'état) — le walk SAF garantit parent avant enfant dans l'ordre d'`id`.
|
||||
- **Permissions snapshot**: le serveur pousse des snapshots `resource_permissions` (`effective_access` ranking viewer < commenter < editor < owner, `inherit`, `expires_at`, TTL 24h → read-only downgrade). Consommé par le client Kotlin (`ShareRepository` : hydratation + delta + `canAccess`).
|
||||
|
||||
- **Lecture partagée** : `GET /files/:id/shares` + `GET /files/:id/links` (owner uniquement, 404 sinon) exposent grants et liens au propriétaire ; `GET /files/:id/content` streame les octets (viewer+, `Range` supporté).
|
||||
|
||||
@@ -10,6 +10,7 @@ Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/) et le ve
|
||||
- Flag serveur `has_content` (migration `000014`, lazy healing : TRUE à l'upload / au `OpenContent` réussi, FALSE si octets disparus), exposé en `FileDto.hasContent` (persistance Room prévue en V2-2).
|
||||
- Download V2 hors-ligne : `DownloadWorker` (fichier par fichier, écriture SAF dossier propre sinon racine, rattachement même `resource_id`, walk convergent par URI), marqueurs `has_content_server`/`wanted_offline` (Room v18, migration 17→18), bouton « Rendre disponible hors-ligne » dans le viewer distant.
|
||||
- Purge sûre V2-3 « libérer de l'espace » : gate `isReleasable` (copie serveur connue), détachement cloud-only sans op outbox, bouton viewer + action multi-sélection.
|
||||
- Placements multi-device : tables `storage_locations` + `resource_placements` (migration `000015`), op outbox `report_bytes` (viewer+, nouvel `operation_id` par état, dead-letter sans bloquer la file), `GET /files/:id/placements` (owner-only), reporting auto (upload/download/release/delete locale), section copies dans le sheet de partage.
|
||||
|
||||
## [1.0.0] - 2026-09-25
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ var expectedRoutes = []string{
|
||||
"GET /api/v1/files/:id/content",
|
||||
"GET /api/v1/files/:id/shares",
|
||||
"GET /api/v1/files/:id/links",
|
||||
"GET /api/v1/files/:id/placements",
|
||||
"DELETE /api/v1/files/:id",
|
||||
"POST /api/v1/files/upload",
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS resource_placements;
|
||||
DROP TABLE IF EXISTS storage_locations;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- V2 placements multi-device : où existent les octets d'une ressource.
|
||||
-- `storage_locations` modélise chaque device (le serveur reste implicite via
|
||||
-- `resources.has_content`, pas de ligne). `resource_placements` matérialise
|
||||
-- les reports clients (`report_bytes` via l'outbox) : hint de présence,
|
||||
-- jamais une preuve — le serveur ne vérifie pas les octets du device.
|
||||
CREATE TABLE storage_locations (
|
||||
id TEXT PRIMARY KEY CHECK (id ~ '^[0-9a-f]{32}$'),
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
device_id TEXT NOT NULL UNIQUE CHECK (device_id ~ '^[0-9a-f]{32}$'),
|
||||
type TEXT NOT NULL DEFAULT 'mobile' CHECK (type IN ('mobile', 'desktop', 'server')),
|
||||
last_seen_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_storage_locations_user ON storage_locations(user_id);
|
||||
|
||||
CREATE TABLE resource_placements (
|
||||
resource_id TEXT NOT NULL REFERENCES resources(resource_id) ON DELETE CASCADE,
|
||||
location_id TEXT NOT NULL REFERENCES storage_locations(id) ON DELETE CASCADE,
|
||||
has_bytes BOOLEAN NOT NULL,
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
PRIMARY KEY (resource_id, location_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_placements_location ON resource_placements(location_id);
|
||||
@@ -333,6 +333,23 @@ func TestMigrationsUpDown(t *testing.T) {
|
||||
t.Error("index unique partiel (id) WHERE revoked_at IS NULL manquant sur share_links")
|
||||
}
|
||||
|
||||
// --- 000014 : has_content + 000015 : placements -------------------------
|
||||
var hasContentCol int
|
||||
err = conn.QueryRow(`
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'resources' AND column_name = 'has_content'`).Scan(&hasContentCol)
|
||||
if err != nil {
|
||||
t.Fatalf("has_content column: %v", err)
|
||||
}
|
||||
if hasContentCol == 0 {
|
||||
t.Error("colonne resources.has_content manquante après 000014")
|
||||
}
|
||||
|
||||
assertTables(t, conn, "users", "devices", "resources", "operations", "ocr_jobs", "shares", "share_links", "storage_locations", "resource_placements", "schema_migrations")
|
||||
|
||||
assertHexCheck(t, conn, "storage_locations", "id")
|
||||
assertHexCheck(t, conn, "storage_locations", "device_id")
|
||||
|
||||
if err := MigrateDownDatabase(url); err != nil {
|
||||
t.Fatalf("migrate down: %v", err)
|
||||
}
|
||||
|
||||
@@ -900,3 +900,68 @@ func TestFilesSharesLinksListing(t *testing.T) {
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/shares", ownerToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "shares-invalid-id")
|
||||
}
|
||||
|
||||
func TestFilesPlacementsListing(t *testing.T) {
|
||||
r, _, repo := setup(t)
|
||||
ownerDevice := repository.NewID()
|
||||
ownerToken, owner := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "pl"), "placements-password", ownerDevice)
|
||||
granteeDevice := repository.NewID()
|
||||
granteeToken, grantee := registerAndLogin(t, r, repo, testUserUsername(granteeDevice, "pg"), "placements-password-b", granteeDevice)
|
||||
outsiderDevice := repository.NewID()
|
||||
outsiderToken, _ := registerAndLogin(t, r, repo, testUserUsername(outsiderDevice, "ph"), "placements-password-c", outsiderDevice)
|
||||
|
||||
fileID := repository.NewID()
|
||||
if err := repo.Resources.InsertFile(owner, fileID, "placed.txt", "", 4, nil, nil); err != nil {
|
||||
t.Fatalf("insert file: %v", err)
|
||||
}
|
||||
|
||||
// Sans report : seule l'entrée serveur (hasContent false, metadata-only).
|
||||
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/placements", ownerToken, nil, "")
|
||||
env := expectOK(t, rec, "placements-server-only")
|
||||
var only []map[string]any
|
||||
if err := json.Unmarshal(env.Data, &only); err != nil {
|
||||
t.Fatalf("placements-server-only: unmarshal: %v", err)
|
||||
}
|
||||
if len(only) != 1 || only[0]["locationType"] != "server" || only[0]["hasBytes"] != false {
|
||||
t.Errorf("placements-server-only = %v, attendu 1 entrée serveur false", only)
|
||||
}
|
||||
|
||||
// Report via l'outbox (owner) : l'entrée device apparaît.
|
||||
reportBody := fmt.Sprintf(
|
||||
`{"operations":[{"operation_id":%q,"resource_id":%q,"resource_type":"file","operation":"report_bytes","payload":{"hasBytes":true}}]}`,
|
||||
repository.NewID(), fileID,
|
||||
)
|
||||
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/sync/ops", ownerToken, []byte(reportBody), "application/json")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("sync/ops report: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/placements", ownerToken, nil, "")
|
||||
env = expectOK(t, rec, "placements-owner")
|
||||
var entries []struct {
|
||||
LocationType string `json:"locationType"`
|
||||
DeviceID string `json:"deviceId"`
|
||||
HasBytes bool `json:"hasBytes"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Data, &entries); err != nil {
|
||||
t.Fatalf("placements-owner: unmarshal: %v", err)
|
||||
}
|
||||
if len(entries) != 2 || entries[0].LocationType != "server" {
|
||||
t.Fatalf("placements-owner = %+v, attendu serveur + 1 device", entries)
|
||||
}
|
||||
if entries[1].LocationType != "mobile" || !entries[1].HasBytes || entries[1].DeviceID != ownerDevice {
|
||||
t.Errorf("placements-owner[1] = %+v, attendu device owner true", entries[1])
|
||||
}
|
||||
|
||||
// Granté et outsider : 404 (owner-only, pas d'énumération).
|
||||
if err := repo.Shares.Upsert(fileID, grantee, "viewer", false, nil, owner); err != nil {
|
||||
t.Fatalf("share: %v", err)
|
||||
}
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/placements", granteeToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "placements-grantee")
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/placements", outsiderToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "placements-outsider")
|
||||
|
||||
// ID invalide → 404.
|
||||
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/placements", ownerToken, nil, "")
|
||||
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "placements-invalid-id")
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ func RegisterRoutes(r *gin.Engine) {
|
||||
protected.GET("/files/:id/content", FilesContent)
|
||||
protected.GET("/files/:id/shares", SharesList)
|
||||
protected.GET("/files/:id/links", LinksList)
|
||||
protected.GET("/files/:id/placements", PlacementsList)
|
||||
protected.DELETE("/files/:id", FilesDelete)
|
||||
protected.POST("/files/upload", FilesUpload)
|
||||
|
||||
|
||||
@@ -50,3 +50,25 @@ func LinksList(c *gin.Context) {
|
||||
}
|
||||
api.OK(c, links)
|
||||
}
|
||||
|
||||
// PlacementsList exposes byte presence of a resource the caller OWNS
|
||||
// (server entry + device reports, newest first) : GET /files/:id/placements.
|
||||
// Owner-only (404 otherwise, no enumeration).
|
||||
func PlacementsList(c *gin.Context) {
|
||||
if Store == nil {
|
||||
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
|
||||
return
|
||||
}
|
||||
userID := c.GetString(UserIDKey)
|
||||
id := c.Param("id")
|
||||
if !deviceIDPattern.MatchString(id) {
|
||||
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
|
||||
return
|
||||
}
|
||||
placements, err := Store.ListPlacements(userID, id)
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
api.OK(c, placements)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Placement is one device's reported byte presence on a resource.
|
||||
type Placement struct {
|
||||
LocationType string
|
||||
DeviceID string
|
||||
HasBytes bool
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// Placements implements the V2 multi-device presence hints
|
||||
// (`storage_locations` + `resource_placements`, cf. V2.md §3.4-3.5, réduit :
|
||||
// pas de `status` pending, juste `has_bytes` + fraîcheur).
|
||||
type Placements struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// EnsureLocation returns the location id for (user, device), creating it on
|
||||
// first report. `user_id` tracks the last reporter (a device may change
|
||||
// accounts) ; rows of departed users stay but are filtered at read time by
|
||||
// resource visibility.
|
||||
func (p *Placements) EnsureLocation(userID, deviceID string) (string, error) {
|
||||
var id string
|
||||
err := p.DB.QueryRow(
|
||||
`INSERT INTO storage_locations (id, user_id, device_id, type)
|
||||
VALUES ($1, $2, $3, 'mobile')
|
||||
ON CONFLICT (device_id) DO UPDATE SET user_id = EXCLUDED.user_id, last_seen_at = NOW()
|
||||
RETURNING id`,
|
||||
NewID(), userID, deviceID,
|
||||
).Scan(&id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// Report upserts a device's byte presence for a resource. Naturally
|
||||
// idempotent (same state twice = no-op) ; the outbox replay guard (A9)
|
||||
// requires a FRESH operation_id per state change, documented in api-v1.md.
|
||||
func (p *Placements) Report(userID, deviceID, resourceID string, hasBytes bool) error {
|
||||
locationID, err := p.EnsureLocation(userID, deviceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = p.DB.Exec(
|
||||
`INSERT INTO resource_placements (resource_id, location_id, has_bytes, updated_at)
|
||||
VALUES ($1, $2, $3, NOW())
|
||||
ON CONFLICT (resource_id, location_id)
|
||||
DO UPDATE SET has_bytes = EXCLUDED.has_bytes, updated_at = NOW()`,
|
||||
resourceID, locationID, hasBytes,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
// ListForResource returns all device placements of a resource, newest first.
|
||||
// Server-side bytes (`resources.has_content`) are NOT a row — the caller
|
||||
// prepends the implicit server entry.
|
||||
func (p *Placements) ListForResource(resourceID string) ([]Placement, error) {
|
||||
rows, err := p.DB.Query(
|
||||
`SELECT sl.type, sl.device_id, rp.has_bytes, rp.updated_at
|
||||
FROM resource_placements rp
|
||||
JOIN storage_locations sl ON sl.id = rp.location_id
|
||||
WHERE rp.resource_id = $1
|
||||
ORDER BY rp.updated_at DESC`,
|
||||
resourceID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Placement
|
||||
for rows.Next() {
|
||||
var pl Placement
|
||||
if err := rows.Scan(&pl.LocationType, &pl.DeviceID, &pl.HasBytes, &pl.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, pl)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -12,6 +12,7 @@ type Repository struct {
|
||||
OcrJobs *OcrJobs
|
||||
Users *Users
|
||||
Shares *Shares
|
||||
Placements *Placements
|
||||
}
|
||||
|
||||
func NewRepository(conn *sql.DB) *Repository {
|
||||
@@ -22,5 +23,6 @@ func NewRepository(conn *sql.DB) *Repository {
|
||||
OcrJobs: &OcrJobs{DB: conn},
|
||||
Users: &Users{DB: conn},
|
||||
Shares: &Shares{DB: conn},
|
||||
Placements: &Placements{DB: conn},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,6 +543,7 @@ func (r *Resources) SetHasContent(ownerID, resourceID string, has bool) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateOcrText writes the server-computed OCR extract onto the resource
|
||||
// (owner-scoped, bumping updated_at so the change flows through the sync
|
||||
// snapshot). The text is then readable by every device of the user AND by
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+35
-3
@@ -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:
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+4
-1
@@ -47,6 +47,7 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync)
|
||||
| GET | `/files/:id/ocr` | — | `FileOcr` (`{ text, updatedAt }`) | `NOT_FOUND` |
|
||||
| GET | `/files/:id/shares` | — (owner uniquement) | `ShareGrant[]` (`{ granteeUserId, username, access, inherit, expiresAt (ms\|null), updatedAt (ms) }`) | `NOT_FOUND` (non-owner ou inconnue — pas d'énumération) |
|
||||
| GET | `/files/:id/links` | — (owner uniquement) | `ShareLink[]` (même forme que `GET /shares/links/:token`) | `NOT_FOUND` (non-owner ou inconnue) |
|
||||
| GET | `/files/:id/placements` | — (owner uniquement) | `Placement[]` (`{ locationType: "server"|"mobile", deviceId?, hasBytes, updatedAt }`, entrée serveur en premier) | `NOT_FOUND` (non-owner ou inconnue) |
|
||||
| POST | `/sync/ops` | voir §6 | voir §6 | — |
|
||||
| GET | `/sync/permissions` | query `after?` (cached_at ms) | `ResourcePermission[]` | — |
|
||||
|
||||
@@ -108,7 +109,7 @@ type FileOcr = { text: string; updatedAt?: string | null };
|
||||
}
|
||||
```
|
||||
|
||||
- `operation` ∈ `create_resource | update_metadata | delete_resource | move_resource | share | revoke_share | update_share | create_link | revoke_link` (cf. `PendingOperationType` mobile).
|
||||
- `operation` ∈ `create_resource | update_metadata | delete_resource | move_resource | share | revoke_share | update_share | create_link | revoke_link | report_bytes` (cf. `PendingOperationType` mobile).
|
||||
- **Identifiants** : `operation_id` est un **TEXT 32-hex** généré par le client (`^[0-9a-f]{32}$`, CHECK-enforced depuis la migration `000008`), distinct de `resource_id`. L'idempotence outbox reste **par device** : `UNIQUE(device_id, operation_id)` (la réinscription d'un device avec un login différent ne réutilise pas l'historique outbox d'un autre compte). Pour chaque op : si déjà traitée → **no-op** (comptée comme appliquée, les doublons arrivent à cause du backoff/retry). Sinon appliquée si valide.
|
||||
- **Ordre** : les opérations sont appliquées **séquentiellement**, dans l'ordre du batch. Le serveur **s'arrête à la première erreur non-idempotente** et renvoie l'index atteint — le client reprend à cet index.
|
||||
- Réponse : `2xx` avec `{ "applied": int, "failed": { "operation_id": "…32-hex", "code": string, "message": string } | null }` (`applied` = index de la prochaine op à envoyer).
|
||||
@@ -121,6 +122,7 @@ type FileOcr = { text: string; updatedAt?: string | null };
|
||||
- `revoke_share` : `payload = { "granteeUserId": "…32-hex" }`. **Idempotent** (déjà révoqué/absent → no-op).
|
||||
- `create_link` : `payload = { "token": "…32-hex", "access": "viewer"|"commenter"|"editor", "expiresAt"?: ms }`. Le token est **généré côté client** (`GenerateId`), c'est l'identifiant du lien (colonne `id` de `share_links`).
|
||||
- `revoke_link` : `payload = { "token": "…32-hex" }`. **Idempotent**.
|
||||
- **Présence multi-device** (`report_bytes`) : `payload = { "hasBytes": bool }` (**requis**). Le device signale ses octets locaux pour un fichier visible (`viewer+`, own ou partagé — sinon `NOT_FOUND`). Upsert idempotent par `(device, resource)` ; le rejeu à l'identique est no-op, mais chaque **changement d'état exige un nouvel `operation_id`** (garde anti-rejeu A9). Portée `file` uniquement.
|
||||
- Validation (deuxième champ `operation_id`, hex32 pour `resource_id` **et** `operation_id`, enum `operation`) → échec `INVALID_REQUEST` avec arrêt du batch.
|
||||
- Nom déjà pris (même parent, ou à la racine) → échec `NAME_CONFLICT`.**
|
||||
- **Lien public** : `GET /shares/links/:token` est **sans authentification** (résolution publique d'un lien) et renvoie `{ "token", "resource_id", "resourceType", "name", "access", "expiresAt" }`. `NOT_FOUND` si le lien est inconnu, révoqué ou expiré. Le client partage les liens sous forme de deep-link `kazier://share/<token>` (custom scheme, pas d'App Links https) : indépendant du domaine du serveur, donc compatible self-hosting (chaque instance a son propre host).
|
||||
@@ -157,6 +159,7 @@ type ResourcePermission = {
|
||||
### 6.3 Placements
|
||||
|
||||
- Le statut de placement (`sync_status` mobile : `local` | `cloud` | `local-cloud`) est le reflet du `resource_placements` serveur (statuts V2 : `local_only`, `synced`, `cloud_only`, `pending_upload`, `pending_download`). La matérialisation se fait via l'outbox (`create_resource` → `synced`/`pending_upload` ; suppression physique locale ≠ suppression serveur).
|
||||
- **Présence multi-device (V2)** : les devices reportent leurs octets via l'op `report_bytes` (tables `storage_locations` + `resource_placements`, migration `000015`) ; le propriétaire lit `GET /files/:id/placements` (entrée `server` implicite depuis `has_content` + reports devices, owner-only). Hint de présence, jamais preuve — le serveur ne vérifie pas les octets distants.
|
||||
|
||||
## 7. Codes d'erreur courants
|
||||
|
||||
|
||||
+7
@@ -83,4 +83,11 @@ object PendingOperationType {
|
||||
const val UPDATE_SHARE = "update_share"
|
||||
const val CREATE_LINK = "create_link"
|
||||
const val REVOKE_LINK = "revoke_link"
|
||||
/**
|
||||
* V2 placements : signalement de présence d'octets (`{ hasBytes }`).
|
||||
* Hint, jamais bloquant : un échec est dead-letter + suite du batch
|
||||
* (voir `OutboxSyncWorker`), et chaque changement d'état exige un nouvel
|
||||
* `operation_id` (garde anti-rejeu serveur A9).
|
||||
*/
|
||||
const val REPORT_BYTES = "report_bytes"
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
@@ -176,6 +177,13 @@ class ApiClient @Inject constructor(
|
||||
suspend fun listLinks(fileId: String): List<ShareLinkDto> =
|
||||
unwrap({ apiService.listLinks(fileId) })
|
||||
|
||||
/**
|
||||
* Présence des octets d'une ressource possédée —
|
||||
* `GET /files/:id/placements` (owner uniquement, 404 sinon, V2).
|
||||
*/
|
||||
suspend fun listPlacements(fileId: String): List<PlacementDto> =
|
||||
unwrap({ apiService.listPlacements(fileId) })
|
||||
|
||||
/**
|
||||
* Octets physiques d'un fichier visible — `GET /files/:id/content`
|
||||
* (binaire brut, hors enveloppe). Streaming sans cache : lecture bornée
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
@@ -187,4 +188,14 @@ interface ApiService {
|
||||
suspend fun listLinks(
|
||||
@Path("id") fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>>
|
||||
|
||||
/**
|
||||
* Présence des octets d'une ressource possédée
|
||||
* (`GET /files/:id/placements`, owner uniquement — entrée `server`
|
||||
* implicite + reports devices, V2).
|
||||
*/
|
||||
@GET("files/{id}/placements")
|
||||
suspend fun listPlacements(
|
||||
@Path("id") fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>>
|
||||
}
|
||||
@@ -118,6 +118,18 @@ data class ShareLinkDto(
|
||||
@Json(name = "expiresAt") val expiresAt: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Entrée de présence `GET /files/:id/placements` (owner uniquement, V2) —
|
||||
* miroir de `PlacementDTO` Go. L'entrée `server` est implicite (dérivée de
|
||||
* `has_content`) ; les entrées devices viennent des reports `report_bytes`.
|
||||
*/
|
||||
data class PlacementDto(
|
||||
@Json(name = "locationType") val locationType: String,
|
||||
@Json(name = "deviceId") val deviceId: String? = null,
|
||||
@Json(name = "hasBytes") val hasBytes: Boolean,
|
||||
@Json(name = "updatedAt") val updatedAt: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Grant actif `GET /files/:id/shares` (owner uniquement) — miroir de
|
||||
* `ShareGrantDTO` Go. `expiresAt` en ms epoch (null = jamais), même
|
||||
|
||||
@@ -219,6 +219,23 @@ class OutboxRepository @Inject constructor(
|
||||
payload = mapOf("token" to token),
|
||||
)
|
||||
|
||||
/**
|
||||
* Raccourci `report_bytes` — payload `{ hasBytes }` (V2 placements).
|
||||
* Uniquement sur changement d'état réel (upload/download/release/delete
|
||||
* locale) : le serveur exige un `operation_id` frais par état (A9) et
|
||||
* l'échec est dead-letter sans bloquer la file.
|
||||
*/
|
||||
suspend fun enqueueReportBytes(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
hasBytes: Boolean,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.REPORT_BYTES,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = mapOf("hasBytes" to hasBytes),
|
||||
)
|
||||
|
||||
/** Nombre d'ops en attente de push (stats UI optionnelles). */
|
||||
suspend fun countPending(): Int = pendingOperationDao.countPending()
|
||||
|
||||
|
||||
+5
-1
@@ -39,6 +39,7 @@ class RemoteContentRepository @Inject constructor(
|
||||
private val fileDao: FileDao,
|
||||
private val folderDao: FolderDao,
|
||||
private val defaultRootStore: DefaultRootStore,
|
||||
private val outboxRepository: OutboxRepository,
|
||||
@ApplicationContext private val context: Context,
|
||||
) {
|
||||
/** Octets du fichier, bornés ([ApiClient.MAX_CONTENT_BYTES]). */
|
||||
@@ -47,7 +48,8 @@ class RemoteContentRepository @Inject constructor(
|
||||
|
||||
/**
|
||||
* Pousse les octets locaux vers le serveur (overwrite ciblé idempotent).
|
||||
* Succès → `bytes_uploaded = 1` ; 4xx (trop gros, rejeté) → +1 tentative
|
||||
* Succès → `bytes_uploaded = 1` + report `hasBytes = true` (V2
|
||||
* placements, état frais) ; 4xx (trop gros, rejeté) → +1 tentative
|
||||
* (cap 3, le worker passe au suivant) ; réseau/5xx → `Retryable` sans
|
||||
* toucher au compteur ; 401 → `Unauthorized` (re-login via l'UI).
|
||||
*/
|
||||
@@ -61,6 +63,7 @@ class RemoteContentRepository @Inject constructor(
|
||||
)
|
||||
apiClient.uploadFile(file = part, resourceId = file.resourceId)
|
||||
fileDao.markBytesUploaded(file.resourceId, System.currentTimeMillis())
|
||||
outboxRepository.enqueueReportBytes(file.resourceId, "file", true)
|
||||
BytesUploadOutcome.Done
|
||||
} catch (e: ApiException) {
|
||||
when {
|
||||
@@ -120,6 +123,7 @@ class RemoteContentRepository @Inject constructor(
|
||||
}
|
||||
if (createdUri == null) return DownloadOutcome.Retryable
|
||||
fileDao.attachDownloaded(file.resourceId, createdUri, target.folderId, bytes.size.toLong(), now)
|
||||
outboxRepository.enqueueReportBytes(file.resourceId, "file", true)
|
||||
return DownloadOutcome.Done
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,8 @@ class FileDeleter @Inject constructor(
|
||||
if (deleted) {
|
||||
fileRepository.markMissing(file.resourceId, System.currentTimeMillis())
|
||||
thumbnailStore.delete(file.resourceId)
|
||||
// Octets partis : le serveur doit l'apprendre (V2 placements).
|
||||
outboxRepository.enqueueReportBytes(file.resourceId, "file", false)
|
||||
Timber.d("deleted locally %s", uri)
|
||||
} else {
|
||||
Timber.w("deleteDocument returned false for %s", uri)
|
||||
@@ -174,6 +176,8 @@ class FileDeleter @Inject constructor(
|
||||
}.getOrDefault(false)
|
||||
if (deleted) {
|
||||
thumbnailStore.delete(file.resourceId)
|
||||
// Rattrapage : ces octets n'avaient jamais été signalés partis.
|
||||
outboxRepository.enqueueReportBytes(file.resourceId, "file", false)
|
||||
swept++
|
||||
}
|
||||
}
|
||||
@@ -212,6 +216,8 @@ class FileDeleter @Inject constructor(
|
||||
} else {
|
||||
fileRepository.detachLocalCopy(file.resourceId)
|
||||
thumbnailStore.delete(file.resourceId)
|
||||
// Octets partis : le serveur doit l'apprendre (V2).
|
||||
outboxRepository.enqueueReportBytes(file.resourceId, "file", false)
|
||||
released++
|
||||
Timber.d("released local copy %s", uri)
|
||||
}
|
||||
|
||||
+12
-2
@@ -168,7 +168,10 @@ class OutboxSyncWorker @AssistedInject constructor(
|
||||
}
|
||||
|
||||
// Première erreur non-idempotente → dead-letter + cascade éventuelle.
|
||||
result.failed?.let { fail ->
|
||||
// (if explicite plutôt que `?.let` : le `continue` V2 ci-dessous
|
||||
// est interdit dans un lambda inline.)
|
||||
val fail = result.failed
|
||||
if (fail != null) {
|
||||
val failedIndex = pending.indexOfFirst { it.operationId == fail.operationId }
|
||||
if (failedIndex < 0) {
|
||||
// Garde C7 : `operation_id` inconnu → stop, pas de boucle
|
||||
@@ -179,6 +182,13 @@ class OutboxSyncWorker @AssistedInject constructor(
|
||||
val failedOp = pending[failedIndex]
|
||||
pendingOperationDao.markFailed(failedOp.id, now)
|
||||
Timber.w("outbox failed %s (%s: %s)", fail.operationId, fail.code, fail.message)
|
||||
if (failedOp.operation == PendingOperationType.REPORT_BYTES) {
|
||||
// V2 placements : un hint périmé (partage révoqué,
|
||||
// ressource supprimée côté serveur) ne doit jamais
|
||||
// bloquer la file — dead-letter et suite du batch
|
||||
// (re-sélection du pending restant).
|
||||
continue
|
||||
}
|
||||
if (failedOp.operation == PendingOperationType.CREATE_RESOURCE) {
|
||||
failedOp.resourceId?.let { resourceId ->
|
||||
pendingOperationDao.failDescendants(resourceId, now)
|
||||
@@ -187,7 +197,7 @@ class OutboxSyncWorker @AssistedInject constructor(
|
||||
}
|
||||
// C6 : stop au 1er échec — le serveur s'est arrêté là, tout ce
|
||||
// qui suit reste pending pour le prochain run (jamais de
|
||||
// `continue` vers le batch suivant).
|
||||
// `continue` vers le batch suivant, sauf hint V2 ci-dessus).
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
|
||||
@@ -14,10 +14,12 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Cloud
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.Smartphone
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
@@ -146,6 +148,7 @@ fun ShareBottomSheet(
|
||||
},
|
||||
onRevoke = { grant -> viewModel.revoke(resourceId, resourceType, grant) },
|
||||
)
|
||||
PlacementsSection(placements = state.placements)
|
||||
AddShareSection(
|
||||
sharing = state.sharing,
|
||||
error = state.error,
|
||||
@@ -223,6 +226,58 @@ private fun SectionTitle(text: String) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Copies des octets (V2) : serveur + devices ayant reporté. */
|
||||
@Composable
|
||||
private fun PlacementsSection(placements: List<PlacementUi>) {
|
||||
SectionTitle(stringResource(R.string.share_section_copies))
|
||||
if (placements.isEmpty()) {
|
||||
Text(
|
||||
text = stringResource(R.string.share_empty_copies),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
placements.forEach { placement ->
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = if (placement.locationType == "server") Icons.Filled.Cloud else Icons.Filled.Smartphone,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Text(
|
||||
text = placementLabel(placement),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 1,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (placement.hasBytes) R.string.share_copy_present
|
||||
else R.string.share_copy_absent,
|
||||
),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = if (placement.hasBytes) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun placementLabel(placement: PlacementUi): String =
|
||||
if (placement.locationType == "server") {
|
||||
stringResource(R.string.share_copy_server)
|
||||
} else {
|
||||
val id = placement.deviceId?.take(8).orEmpty()
|
||||
stringResource(R.string.share_copy_device, id)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GrantsSection(
|
||||
grants: List<ShareGrantUi>,
|
||||
|
||||
@@ -53,6 +53,13 @@ data class ResolvedLinkUi(
|
||||
val access: String,
|
||||
)
|
||||
|
||||
/** Entrée de présence des octets (V2) affichée dans le sheet. */
|
||||
data class PlacementUi(
|
||||
val locationType: String,
|
||||
val deviceId: String?,
|
||||
val hasBytes: Boolean,
|
||||
)
|
||||
|
||||
data class ShareUiState(
|
||||
val loading: Boolean = false,
|
||||
/** Cible courante du sheet (resource partagée). */
|
||||
@@ -60,6 +67,8 @@ data class ShareUiState(
|
||||
val resourceType: String? = null,
|
||||
val shares: List<ShareGrantUi> = emptyList(),
|
||||
val links: List<ShareLinkUi> = emptyList(),
|
||||
/** Présence des octets (serveur + reports devices, V2). */
|
||||
val placements: List<PlacementUi> = emptyList(),
|
||||
/** Ops de partage en attente d'envoi (pas encore reflétées serveur). */
|
||||
val pendingCount: Int = 0,
|
||||
/** Erreur de chargement des listes (`LOAD_FAILED`, `FORBIDDEN`). */
|
||||
@@ -122,9 +131,10 @@ class ShareViewModel @Inject constructor(
|
||||
runCatching {
|
||||
val shares = apiClient.listShares(resourceId)
|
||||
val links = apiClient.listLinks(resourceId)
|
||||
val placements = apiClient.listPlacements(resourceId)
|
||||
val pending = outboxRepository.pendingShareOps(resourceId).size
|
||||
Triple(shares, links, pending)
|
||||
}.onSuccess { (shares, links, pending) ->
|
||||
Quad(shares, links, placements, pending)
|
||||
}.onSuccess { (shares, links, placements, pending) ->
|
||||
val now = System.currentTimeMillis()
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
@@ -147,6 +157,13 @@ class ShareViewModel @Inject constructor(
|
||||
url = ShareLinkParser.shareUrl(dto.token),
|
||||
)
|
||||
},
|
||||
placements = placements.map { dto ->
|
||||
PlacementUi(
|
||||
locationType = dto.locationType,
|
||||
deviceId = dto.deviceId,
|
||||
hasBytes = dto.hasBytes,
|
||||
)
|
||||
},
|
||||
pendingCount = pending,
|
||||
)
|
||||
}
|
||||
@@ -364,3 +381,6 @@ class ShareViewModel @Inject constructor(
|
||||
super.onCleared()
|
||||
}
|
||||
}
|
||||
|
||||
/** Quadruplet local (pas de Tuple4 stdlib en Kotlin). */
|
||||
private data class Quad<A, B, C, D>(val first: A, val second: B, val third: C, val fourth: D)
|
||||
|
||||
@@ -326,6 +326,12 @@
|
||||
<string name="share_enqueued">Share saved — syncing.</string>
|
||||
<string name="share_pending">%1$d change(s) pending upload.</string>
|
||||
<string name="share_section_grants">People with access</string>
|
||||
<string name="share_section_copies">File copies</string>
|
||||
<string name="share_empty_copies">No known copies.</string>
|
||||
<string name="share_copy_server">Server</string>
|
||||
<string name="share_copy_device">Device %1$s</string>
|
||||
<string name="share_copy_present">bytes present</string>
|
||||
<string name="share_copy_absent">no bytes</string>
|
||||
<string name="share_section_add">Add access</string>
|
||||
<string name="share_section_links">Public links</string>
|
||||
<string name="share_section_open_link">Open a received link</string>
|
||||
|
||||
@@ -327,6 +327,12 @@
|
||||
<string name="share_enqueued">Partage enregistré — synchronisation en cours.</string>
|
||||
<string name="share_pending">%1$d modification(s) en attente d\'envoi.</string>
|
||||
<string name="share_section_grants">Personnes avec accès</string>
|
||||
<string name="share_section_copies">Copies des fichiers</string>
|
||||
<string name="share_empty_copies">Aucune copie connue.</string>
|
||||
<string name="share_copy_server">Serveur</string>
|
||||
<string name="share_copy_device">Appareil %1$s</string>
|
||||
<string name="share_copy_present">octets présents</string>
|
||||
<string name="share_copy_absent">sans octets</string>
|
||||
<string name="share_section_add">Ajouter un accès</string>
|
||||
<string name="share_section_links">Liens publics</string>
|
||||
<string name="share_section_open_link">Ouvrir un lien reçu</string>
|
||||
|
||||
@@ -22,6 +22,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
@@ -332,5 +333,9 @@ class Auth401Test {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
@@ -206,5 +207,9 @@ class PaginationTest {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
@@ -145,5 +146,9 @@ class RemoteContentTest {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
@@ -336,5 +337,9 @@ class SessionReloginTest {
|
||||
|
||||
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
@@ -87,9 +88,24 @@ class ShareManagementTest {
|
||||
assertEquals("NOT_FOUND", (ex as ApiException).code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `listPlacements_retourne_serveur_puis_devices`() = runTest {
|
||||
val placements = listOf(
|
||||
PlacementDto("server", null, true, "2026-09-25T00:00:00Z"),
|
||||
PlacementDto("mobile", "d".repeat(32), false, "2026-09-25T01:00:00Z"),
|
||||
)
|
||||
val fake = SharesFake(placements = placements)
|
||||
val got = client(fake).listPlacements("f".repeat(32))
|
||||
assertEquals(2, got.size)
|
||||
assertEquals("server", got[0].locationType)
|
||||
assertTrue(got[0].hasBytes)
|
||||
assertEquals("d".repeat(32), got[1].deviceId)
|
||||
}
|
||||
|
||||
private class SharesFake(
|
||||
private val shares: List<ShareGrantDto> = emptyList(),
|
||||
private val links: List<ShareLinkDto> = emptyList(),
|
||||
private val placements: List<PlacementDto> = emptyList(),
|
||||
private val failShares: Boolean = false,
|
||||
private val failLink: Boolean = false,
|
||||
) : ApiService {
|
||||
@@ -158,6 +174,9 @@ class ShareManagementTest {
|
||||
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
|
||||
Response.success(ApiEnvelope(data = links))
|
||||
|
||||
override suspend fun listPlacements(fileId: String): Response<ApiEnvelope<List<PlacementDto>>> =
|
||||
Response.success(ApiEnvelope(data = placements))
|
||||
|
||||
private fun errBody(code: String) =
|
||||
"{\"error\":{\"code\":\"$code\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType())
|
||||
}
|
||||
|
||||
+20
-1
@@ -11,6 +11,9 @@ import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FileStatus
|
||||
import com.kazier.mobile.data.preferences.DefaultRootStore
|
||||
import com.kazier.mobile.data.repository.OutboxRepository
|
||||
import com.kazier.mobile.domain.DeviceIdentity
|
||||
import com.kazier.mobile.domain.GenerateId
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.remote.ApiService
|
||||
@@ -25,6 +28,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
@@ -73,9 +77,14 @@ class BytesUploadTest {
|
||||
.build()
|
||||
fileDao = db.fileDao()
|
||||
apiService = UploadFake()
|
||||
val generateId = GenerateId()
|
||||
val outbox = OutboxRepository(
|
||||
db.pendingOperationDao(), generateId,
|
||||
DeviceIdentity(db.userPreferenceDao(), generateId), moshi(),
|
||||
)
|
||||
repository = RemoteContentRepository(
|
||||
ApiClient(apiService, moshi()), fileDao, db.folderDao(),
|
||||
DefaultRootStore(context), context,
|
||||
DefaultRootStore(context), outbox, context,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -94,6 +103,12 @@ class BytesUploadTest {
|
||||
assertEquals("ok-content", apiService.uploadedBytes)
|
||||
assertEquals(file.resourceId, apiService.uploadedResourceId)
|
||||
assertEquals(1, fileDao.getByResourceId(file.resourceId)?.bytesUploaded)
|
||||
// V2 placements : le succès reporte l'état frais (un nouvel
|
||||
// operation_id, payload {hasBytes:true}).
|
||||
val reported = db.pendingOperationDao().selectPending(10)
|
||||
assertEquals(1, reported.size)
|
||||
assertEquals("report_bytes", reported.single().operation)
|
||||
assertTrue(reported.single().payload.contains("\"hasBytes\":true"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -263,5 +278,9 @@ class BytesUploadTest {
|
||||
|
||||
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -20,6 +20,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
@@ -392,4 +393,8 @@ private class FolderMergeApiService : ApiService {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
+5
@@ -26,6 +26,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
@@ -481,4 +482,8 @@ private class MoveProtectionApiService : ApiService {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
@@ -399,4 +400,8 @@ private class OcrApiServiceFake : ApiService {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
+18
-1
@@ -11,6 +11,9 @@ import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FileStatus
|
||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||
import com.kazier.mobile.data.preferences.DefaultRootStore
|
||||
import com.kazier.mobile.data.repository.OutboxRepository
|
||||
import com.kazier.mobile.domain.DeviceIdentity
|
||||
import com.kazier.mobile.domain.GenerateId
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiService
|
||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||
@@ -24,6 +27,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
@@ -76,8 +80,13 @@ class OfflineDownloadTest {
|
||||
fake = DownloadFake()
|
||||
rootStore = DefaultRootStore(context)
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
val generateId = GenerateId()
|
||||
val outbox = OutboxRepository(
|
||||
db.pendingOperationDao(), generateId,
|
||||
DeviceIdentity(db.userPreferenceDao(), generateId), moshi,
|
||||
)
|
||||
repository = RemoteContentRepository(
|
||||
ApiClient(fake, moshi), fileDao, db.folderDao(), rootStore, context,
|
||||
ApiClient(fake, moshi), fileDao, db.folderDao(), rootStore, outbox, context,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -102,6 +111,10 @@ class OfflineDownloadTest {
|
||||
assertTrue(stored.processed)
|
||||
assertEquals(false, stored.wantedOffline)
|
||||
assertEquals(1, stored.exists)
|
||||
// V2 placements : le rattachement reporte l'état frais.
|
||||
val reported = db.pendingOperationDao().selectPending(10)
|
||||
assertEquals(1, reported.size)
|
||||
assertEquals("report_bytes", reported.single().operation)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -279,5 +292,9 @@ class OfflineDownloadTest {
|
||||
|
||||
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<ShareLinkDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
@@ -248,4 +249,8 @@ private class RefreshVsMoveApiService : ApiService {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
|
||||
+5
@@ -19,6 +19,7 @@ import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareGrantDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
@@ -502,4 +503,8 @@ private class FakeApiService : ApiService {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
+6
-2
@@ -103,8 +103,11 @@ class ReleaseLocalCopyTest {
|
||||
assertEquals("ligne toujours visible", 1, stored.exists)
|
||||
// L'intouchable n'a même pas été tenté en SAF.
|
||||
assertEquals("content://x/3", db.fileDao().getByResourceId(unsafe.resourceId)!!.uri)
|
||||
// Aucune op outbox (purge purement locale).
|
||||
assertEquals(0, db.pendingOperationDao().countPending())
|
||||
// Seul le report V2 (hint, pas une mutation) est journalisé.
|
||||
val ops = db.pendingOperationDao().selectPending(10)
|
||||
assertEquals(1, ops.size)
|
||||
assertEquals("report_bytes", ops.single().operation)
|
||||
assertTrue(ops.single().payload.contains("\"hasBytes\":false"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -158,5 +161,6 @@ class ReleaseLocalCopyTest {
|
||||
override suspend fun downloadContent(fileId: String): retrofit2.Response<okhttp3.ResponseBody> = TODO()
|
||||
override suspend fun listShares(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareGrantDto>>> = TODO()
|
||||
override suspend fun listLinks(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareLinkDto>>> = TODO()
|
||||
override suspend fun listPlacements(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.PlacementDto>>> = TODO()
|
||||
}
|
||||
}
|
||||
|
||||
+38
-1
@@ -37,6 +37,7 @@ import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.PlacementDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
@@ -214,8 +215,40 @@ class OutboxSyncWorkerTest {
|
||||
assertEquals("le voisin est intact", PendingOpStatus.PENDING, byOp[opId(3)]!!.status)
|
||||
}
|
||||
|
||||
// --- C7 : gardes ----------------------------------------------------------
|
||||
// --- V2 placements : hint périmé ne bloque pas la file -------------------
|
||||
|
||||
@Test
|
||||
fun echec_report_bytes_deadletter_sans_bloquer_la_suite() = runTest {
|
||||
insertOp(
|
||||
operationId = opId(1), resourceId = resId(1), resourceType = "file",
|
||||
operation = PendingOperationType.REPORT_BYTES,
|
||||
payload = """{"hasBytes":true}""",
|
||||
)
|
||||
insertOp(operationId = opId(2), resourceId = resId(2))
|
||||
var calls = 0
|
||||
fake.syncOpsHandler = { req ->
|
||||
calls++
|
||||
if (calls == 1) {
|
||||
assertEquals(2, req.operations.size)
|
||||
assertEquals("report_bytes", req.operations[0].operation)
|
||||
opsResult(applied = 0, failed = SyncFailedDto(opId(1), "NOT_FOUND", "invisible"))
|
||||
} else {
|
||||
assertEquals(listOf(opId(2)), req.operations.map { it.operationId })
|
||||
opsResult(applied = 1, failed = null)
|
||||
}
|
||||
}
|
||||
|
||||
val result = worker.doWork()
|
||||
|
||||
assertTrue(result is ListenableWorker.Result.Success)
|
||||
assertEquals("batch reparti sans le hint mort", 2, calls)
|
||||
val byOp = opsDao.observeRecent(100).first().associateBy { it.operationId }
|
||||
assertEquals(PendingOpStatus.FAILED, byOp[opId(1)]!!.status)
|
||||
assertEquals(PendingOpStatus.SYNCED, byOp[opId(2)]!!.status)
|
||||
assertEquals(0, opsDao.countPending())
|
||||
}
|
||||
|
||||
// --- C7 : gardes ----------------------------------------------------------
|
||||
@Test
|
||||
fun failed_inconnu_pas_de_boucle() = runTest {
|
||||
insertOp(opId(1))
|
||||
@@ -462,5 +495,9 @@ class OutboxSyncWorkerTest {
|
||||
override suspend fun listLinks(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<ShareLinkDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listPlacements(
|
||||
fileId: String,
|
||||
): Response<ApiEnvelope<List<PlacementDto>>> = Response.success(ApiEnvelope(data = emptyList()))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user