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() }