feat(sync): paginate Android sync with change tokens
Lint / Lint (push) Successful in 1m8s
Tests / Go backend (push) Failing after 1m23s
Tests / Dashboard checks (push) Failing after 38s
Docker / Docker Build & Push (push) Failing after 6m29s

This commit is contained in:
Gabriel20xx committed 2026-10-20 15:27:53 +00:00
1 parent 0ff94f9b10
commit 97c237be80
76 files changed
+3401 -851

No files matched your search

@@ -22,12 +22,25 @@ import (
"os"
"strconv"
"strings"
"sync"
"time"
)
// httpClient has no blanket timeout since it streams large media files;
// callers bound individual calls with a context deadline instead.
var httpClient = &http.Client{}
// httpClient has no total timeout since it streams large media files. The
// transport still bounds how long a request may wait for response headers;
// callers that need a shorter bound add a context deadline as well.
var httpClient = newHTTPClient()
func newHTTPClient() *http.Client {
var transport *http.Transport
if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok {
transport = defaultTransport.Clone()
} else {
transport = &http.Transport{Proxy: http.ProxyFromEnvironment}
}
transport.ResponseHeaderTimeout = 10 * time.Second
return &http.Client{Transport: transport}
}
var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
@@ -69,6 +82,17 @@ type Client struct {
// multiple candidates are actually used (union for discovery, first-match
// for reads, primary-only for writes).
BaseURLs func(ctx context.Context) []string
thumbnailMu sync.Mutex
thumbnailPaths map[string]thumbnailPathEntry
}
const thumbnailPathCacheTTL = 5 * time.Minute
const thumbnailPathCacheLimit = 2048
type thumbnailPathEntry struct {
path string
expires time.Time
}
// New returns a Client backed by a single CarrierNode instance. baseURL is
@@ -536,15 +560,103 @@ func (c *Client) ProxyThumbnail(w http.ResponseWriter, r *http.Request, project,
if err != nil {
return false
}
cacheKey := project + "\x00" + id
cachedPath := c.cachedThumbnailPath(cacheKey)
if cachedPath != "" {
ordered := make([]string, 0, len(paths))
ordered = append(ordered, cachedPath)
for _, path := range paths {
if path != cachedPath {
ordered = append(ordered, path)
}
}
paths = ordered
}
for _, path := range paths {
if exists, _, _, probeErr := c.Probe(r.Context(), path); probeErr == nil && exists {
c.Proxy(w, r, path)
for _, baseURL := range c.candidateBaseURLs(r.Context()) {
request, err := c.newRequest(r.Context(), baseURL, r.Method, path, nil)
if err != nil {
continue
}
for _, header := range forwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := httpClient.Do(request)
if err != nil {
continue
}
if response.StatusCode >= http.StatusBadRequest {
response.Body.Close()
if path == cachedPath {
c.forgetThumbnailPath(cacheKey)
}
continue
}
for _, header := range forwardResponseHeaders {
if value := response.Header.Get(header); value != "" {
w.Header().Set(header, value)
}
}
w.WriteHeader(response.StatusCode)
if r.Method != http.MethodHead {
_, _ = io.Copy(w, response.Body)
}
response.Body.Close()
c.rememberThumbnailPath(cacheKey, path)
return true
}
}
return false
}
func (c *Client) cachedThumbnailPath(key string) string {
c.thumbnailMu.Lock()
defer c.thumbnailMu.Unlock()
entry, ok := c.thumbnailPaths[key]
if !ok {
return ""
}
if !time.Now().Before(entry.expires) {
delete(c.thumbnailPaths, key)
return ""
}
return entry.path
}
func (c *Client) rememberThumbnailPath(key, path string) {
c.thumbnailMu.Lock()
defer c.thumbnailMu.Unlock()
if c.thumbnailPaths == nil {
c.thumbnailPaths = make(map[string]thumbnailPathEntry)
}
now := time.Now()
for cacheKey, entry := range c.thumbnailPaths {
if !now.Before(entry.expires) {
delete(c.thumbnailPaths, cacheKey)
}
}
if len(c.thumbnailPaths) >= thumbnailPathCacheLimit {
var oldestKey string
var oldest time.Time
first := true
for cacheKey, entry := range c.thumbnailPaths {
if first || entry.expires.Before(oldest) {
oldestKey, oldest, first = cacheKey, entry.expires, false
}
}
delete(c.thumbnailPaths, oldestKey)
}
c.thumbnailPaths[key] = thumbnailPathEntry{path: path, expires: now.Add(thumbnailPathCacheTTL)}
}
func (c *Client) forgetThumbnailPath(key string) {
c.thumbnailMu.Lock()
delete(c.thumbnailPaths, key)
c.thumbnailMu.Unlock()
}
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
// cleanup once done.
@@ -1,265 +1,21 @@
package carriernodeclient
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestListFilesMergesAcrossInstances(t *testing.T) {
first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
}))
defer first.Close()
second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"b.mp4"}]}`))
}))
defer second.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
files, err := client.ListFiles(context.Background(), "", false, 0)
if err != nil {
t.Fatalf("ListFiles error: %v", err)
func TestHTTPClientBoundsResponseHeaderWaitWithoutLimitingStreams(t *testing.T) {
client := newHTTPClient()
if client.Timeout != 0 {
t.Fatalf("client total timeout = %s, want no total timeout for media streams", client.Timeout)
}
if len(files) != 2 {
t.Fatalf("ListFiles returned %d files, want 2: %+v", len(files), files)
transport, ok := client.Transport.(*http.Transport)
if !ok {
t.Fatalf("transport type = %T, want *http.Transport", client.Transport)
}
}
func TestRequestsCarryProjectAttribution(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Internal-Auth"); got != "secret" {
t.Fatalf("X-Internal-Auth = %q, want secret", got)
}
if got := r.Header.Get("X-Project-Key"); got != "ContentScanner" {
t.Fatalf("X-Project-Key = %q, want ContentScanner", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[]}`))
}))
defer server.Close()
client := New("secret", func(ctx context.Context) string { return server.URL })
client.ProjectKey = "ContentScanner"
if _, err := client.ListFiles(context.Background(), "", false, 0); err != nil {
t.Fatalf("ListFiles error: %v", err)
}
}
func TestListFilesSkipsUnreachableInstance(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
down.Close() // closed immediately so requests to it fail outright
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL, up.URL} })
files, err := client.ListFiles(context.Background(), "", false, 0)
if err != nil {
t.Fatalf("ListFiles error: %v", err)
}
if len(files) != 1 || files[0].Rel != "a.mp4" {
t.Fatalf("ListFiles = %+v, want just the reachable instance's file", files)
}
}
func TestListFilesErrorsWhenNoInstanceReachable(t *testing.T) {
down := httptest.NewServer(nil)
down.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL} })
if _, err := client.ListFiles(context.Background(), "", false, 0); err == nil {
t.Fatal("ListFiles error = nil, want an error when every instance is unreachable")
}
}
func TestProbeFallsBackToNextInstance(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
found := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "42")
w.WriteHeader(http.StatusOK)
}))
defer found.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, found.URL} })
exists, size, _, err := client.Probe(context.Background(), "/media/a.mp4")
if err != nil {
t.Fatalf("Probe error: %v", err)
}
if !exists {
t.Fatal("Probe exists = false, want true (second instance has it)")
}
if size != 42 {
t.Fatalf("Probe size = %d, want 42", size)
}
}
func TestProbeExistsFalseWhenNoInstanceHasFile(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
exists, _, _, err := client.Probe(context.Background(), "/media/missing.mp4")
if err != nil {
t.Fatalf("Probe error: %v", err)
}
if exists {
t.Fatal("Probe exists = true, want false")
}
}
func TestProxyPrefersPrimaryInstanceWhenItHasTheFile(t *testing.T) {
var primaryHit, secondaryHit bool
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
primaryHit = true
w.WriteHeader(http.StatusOK)
}))
defer primary.Close()
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secondaryHit = true
w.WriteHeader(http.StatusOK)
}))
defer secondary.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
req := httptest.NewRequest(http.MethodGet, "/thumbnails/x.jpg", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/thumbnails/x.jpg")
if !primaryHit {
t.Fatal("Proxy did not hit the primary instance")
}
if secondaryHit {
t.Fatal("Proxy hit the secondary instance even though the primary had the file")
}
}
func TestProxyFallsBackToSecondaryInstanceWhenPrimaryMisses(t *testing.T) {
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer primary.Close()
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "video/mp4")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("video bytes"))
}))
defer secondary.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
req := httptest.NewRequest(http.MethodGet, "/media/a.mp4", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/media/a.mp4")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 from the secondary instance", rec.Code)
}
if rec.Body.String() != "video bytes" {
t.Fatalf("body = %q, want secondary instance's bytes", rec.Body.String())
}
}
func TestProxyForwardsLastInstanceErrorWhenNoneHaveTheFile(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
req := httptest.NewRequest(http.MethodGet, "/media/missing.mp4", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/media/missing.mp4")
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 forwarded from the last instance", rec.Code)
}
}
func mountListingServer(status int, body string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write([]byte(body))
}))
}
func TestListMountFilesReportsNotFoundWhenEveryInstanceMisses(t *testing.T) {
first := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer first.Close()
second := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer second.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "gone")
if !errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, want ErrMountNotFound", err)
}
}
func TestListMountFilesDoesNotReportNotFoundWhenAnInstanceIsUnreachable(t *testing.T) {
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer missing.Close()
down := httptest.NewServer(nil)
down.Close() // closed immediately so requests to it fail outright
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, down.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "maybe-on-the-down-instance")
if err == nil {
t.Fatal("ListMountFiles succeeded, want an error")
}
if errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, must not claim the directory is missing when an instance could not be checked", err)
}
}
func TestListMountFilesDoesNotReportNotFoundOnServerError(t *testing.T) {
broken := mountListingServer(http.StatusInternalServerError, `{"error":"boom"}`)
defer broken.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{broken.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
if err == nil || errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, want a non-ErrMountNotFound failure", err)
}
}
func TestListMountFilesUsesTheInstanceThatHasTheDirectory(t *testing.T) {
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer missing.Close()
present := mountListingServer(http.StatusOK, `{"files":[{"name":"repo","path":"repo","directory":true}]}`)
defer present.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, present.URL} })
files, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
if err != nil {
t.Fatalf("ListMountFiles error: %v", err)
}
if len(files) != 1 || files[0].Name != "repo" || !files[0].Directory {
t.Fatalf("ListMountFiles = %+v, want the one directory from the instance that has it", files)
if transport.ResponseHeaderTimeout != 10*time.Second {
t.Fatalf("response header timeout = %s, want 10s", transport.ResponseHeaderTimeout)
}
}
@@ -8,7 +8,6 @@ import (
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
)
@@ -94,16 +93,15 @@ func TestProxyThumbnailPrefersProjectMount(t *testing.T) {
if rec.Body.String() != "from mount" {
t.Fatalf("body = %q, want the mount copy", rec.Body.String())
}
for _, request := range node.seen() {
if !strings.Contains(request, "/api/mount/") {
t.Fatalf("legacy root was consulted although the mount had the thumbnail: %v", node.seen())
}
want := []string{"GET " + mount}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one direct GET to the mount", got)
}
}
func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, _ := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
client, node := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
rec := httptest.NewRecorder()
if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
@@ -112,10 +110,28 @@ func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
if rec.Body.String() != "from legacy" {
t.Fatalf("body = %q, want the legacy copy", rec.Body.String())
}
want := []string{"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg", "GET " + legacy}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want mount miss followed by legacy GET", got)
}
}
func TestProxyThumbnailCachesResolvedPath(t *testing.T) {
mount := "/api/mount/MediaViewer/thumbnails/" + testThumbnailID + ".jpg"
client, node := newThumbnailTestClient(t, map[string]string{mount: "from mount"})
for range 2 {
if !client.ProxyThumbnail(httptest.NewRecorder(), thumbnailRequest(), "MediaViewer", testThumbnailID) {
t.Fatal("ProxyThumbnail missed although the mount holds the thumbnail")
}
}
want := []string{"GET " + mount, "GET " + mount}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one direct GET per request to the cached path", got)
}
}
func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
client, _ := newThumbnailTestClient(t, nil)
client, node := newThumbnailTestClient(t, nil)
rec := httptest.NewRecorder()
if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
@@ -124,6 +140,13 @@ func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
if rec.Body.Len() != 0 {
t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String())
}
want := []string{
"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg",
"GET /thumbnails/" + testThumbnailID + ".jpg",
}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one GET for each candidate path", got)
}
}
func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) {