Skip to content

Storage caching

A download through the offline bucket goes to the network first and is kept on disk; when the network fails, the kept copy is served instead, and when the server says the kept copy is still current, it is served without the object being sent again. An upload made with a MutationStrategy can wait in the mutation queue with the row writes around it, its bytes on the device (below). Every other write (an upload without one, updates, deletes, moves and copies) is online only and never queued, and one that reaches the server drops the cached copies it made stale.

From the samples: TaskPhotoFiles.kt · TaskRepository+Photos.swift

/**
 * The offline bucket. An app adds a header here when its gateway wants one on every Storage
 * request, such as a proxy's key; this one names the app, which Storage ignores. The bucket
 * `setHeader` returns still keeps downloads on the device.
 */
private val bucket: OfflineBucketApi =
    offline.storage.from(PHOTOS_BUCKET).setHeader("X-Client-Name", "offline-tasks-android")
/// The bucket every photo lives in, through the offline client: its downloads are kept on the
/// device and served from there offline.
var photoBucket: OfflineBucketApi {
    client.storage.from(PhotoPath.bucket)
}

The Swift package's bucket has no setHeader.

supabase.offline.storage.from(bucket) is an OfflineBucketApi: every operation of supabase-kt's BucketApi, under its name, plus the file cache. Bucket management stays on supabase.storage.

Downloads

// The server's bytes, kept on disk; the kept copy when the network fails
val bytes = photos.downloadAuthenticated(path)

downloadAuthenticated and downloadPublic, to bytes or to a channel, go to the network first. A success is written to the cache, whole or not at all (a failure to write the copy is logged and never fails the download); a "not found" drops the cached copy and is rethrown; any other failure is answered from the cached copy, or thrown when there is none. An image transform is cached per transform, apart from the original. A channel download streams through a file on disk rather than memory, and its answer's status is checked first: an error answer throws as the bytes download does, and nothing of it is cached or handed on. A download whose httpOverride asks for part of the object (a Range or If-Range header) or none of it (a HEAD) is the caller's alone: it is never cached, and offline it is not answered from the whole copy. A download still on the wire when a write of the same object lands through the offline bucket is handed to its caller but never becomes the cached copy.

A copy is kept with the ETag the server sent it under, and a download of an object whose copy has one asks the server about it with If-None-Match. A "not modified" (HTTP 304) answers the download from that copy, sends no body and moves its fetchedAt to now; any other answer is handled as above, so a changed object replaces the copy and its ETag. The answer is served only while the copy is still the one the request asked about: when the object was written or its copies evicted through the offline bucket after the download started, or the copy was replaced or is gone from the disk, the download asks once more without If-None-Match, gets the whole object and caches it. A download whose own httpOverride, or a header set on the bucket, sets If-None-Match or If-Modified-Since sends that alone, and one that asks for part of the object, by either, asks about no copy: it goes out as it would without the cache, so a 304 to it is never taken for one about the copy.

Cached files

From the samples: TaskPhotoFiles.kt · LibraryMappings.kt · TaskRepository+Photos.swift

/** The copy on this device, or null; never touches the network. */
suspend fun cachedFile(path: String): PhotoFile? = bucket.cachedFile(path)?.toPhotoFile()

/**
 * The copy on this device, downloaded into the cache first when there is none. A copy is
 * returned however old it is; the photos never change in place but through Replace photo, which
 * drops the copy.
 */
suspend fun ensureCachedFile(path: String): PhotoFile =
    bucket.ensureCachedFile(path).toPhotoFile() // isPublic = false: a private bucket


/** A cached file's facts in the app's terms: where it is, when it was fetched, how large. */
internal fun CachedFile.toPhotoFile(): PhotoFile = PhotoFile(path, fetchedAt, sizeBytes)
/// Where a photo's file stands on this device: kept, or fetched now and kept when it is not
/// and the server can be asked.
///
/// A private file is asked for only once a user is signed in: without the user's token,
/// Storage answers "not found", which would drop a copy kept earlier.
func photoFile(for photo: TaskPhoto) async -> PhotoFileState {
    do {
        if let file = try await photoBucket.cachedFile(path: photo.objectPath) { return .onDevice(file) }
        guard session.userID != nil, canReachNetwork else { return .notOnDevice }
        return .onDevice(try await photoBucket.ensureCachedFile(path: photo.objectPath))
    } catch {
        switch SampleFailure.storage(error) as? SampleFailure {
        case .needsNetwork?: return .notOnDevice
        case .photoMissing?: return .missing
        default: return .unavailable
        }
    }
}

cachedFile(path) returns the cached copy, or null, and never touches the network; ensureCachedFile(path) first streams the object to disk when there is no copy. Only an untransformed download or ensureCachedFile caches the copy these return: a CachedFile, the cache's own file at an absolute path, with fetchedAt and sizeBytes. cachedFile(path) { … } returns the copy of one image transform instead, the one a download with the same transform { … } keeps, so a cached thumbnail can be handed to an image loader as a file; a transform that sets nothing is the untransformed copy, as it is for a download. A moved object's copy keeps the fetchedAt of the download that made it. Read it or hand it to an image loader, but do not move or write it: the cache may delete it when the object is uploaded, updated, deleted, moved or copied over through the offline bucket, when the server reports it gone, when the cache passes its bound and the file has not been used for 30 seconds (unless the object is pinned), when the cache passes to another user, when it is evicted or the file cache cleared (below), and when local data is cleared. A file whose size on disk is not the one recorded for it, which a power loss right after a download can leave, is deleted too, and the object is downloaded again when next asked for. Open it soon, or copy it if it must outlive those. cachedFile and ensureCachedFile never ask the server whether the copy is current: compare fetchedAt with your own rule, and download the object when the copy is too old. That download sends the body only when the object changed (Downloads), and either way leaves fetchedAt at the time of its answer.

On Android, four helpers give the cached copy in the platform's terms: ensureLocalUri and ensureLocalFile are ensureCachedFile as a Uri or a File, throwing what it throws, and localUriIfCached is cachedFile as a Uri, with a transform or without, and localFileIfCached as a File; on iOS, ensureLocalPath(path) and localPathIfCached(path) give the absolute path the same way, and localPathIfCached(path) { … } a transform's. The sample draws thumbnails from localUriIfCached and the viewer from ensureLocalUri, and Share copies the file from ensureLocalFile out of the cache, since another app reads it later and a file: URI cannot leave the app:

From the samples: TaskPhotoFiles.kt · Sharing.kt · TaskRepository+Photos.swift

/** A thumbnail's copy as a `file:` URI when it is on this device; never touches the network. */
suspend fun uriIfCached(path: String): String? = bucket.localUriIfCached(path)?.toString()

/**
 * The copy as a `file:` URI for the image loader, downloaded into the cache first if needed.
 */
suspend fun uri(path: String): String = bucket.ensureLocalUri(path).toString()

/** The copy as a [File], downloaded first if needed: Share copies it out of the cache. */
suspend fun file(path: String): File = bucket.ensureLocalFile(path)


/**
 * Opens the system's share sheet with the JPEG at [path], the library's cached copy. Another app
 * reads it later, and the cache may drop its own copy at any time, so it is copied out first and
 * handed over through the app's file provider: a `file:` URI cannot leave the app.
 */
suspend fun Context.shareJpeg(path: String) {
    val shared =
        withContext(Dispatchers.IO) {
            val folder = File(cacheDir, SHARED_FOLDER).apply { mkdirs() }
            File(path).copyTo(File(folder, "photo.jpg"), overwrite = true)
        }
    val uri = FileProvider.getUriForFile(this, "$packageName.files", shared)
    val send =
        Intent(Intent.ACTION_SEND).apply {
            type = "image/jpeg"
            putExtra(Intent.EXTRA_STREAM, uri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
    startActivity(Intent.createChooser(send, null))
}
/// The device's copy of `photo`'s file, fetched first when there is none, for the share sheet:
/// its ``CachedFile/url`` is a file URL any app can be handed. The file is the cache's own, to
/// read and share, never to move or write.
func shareableFile(for photo: TaskPhoto) async throws -> URL {
    do {
        return try await photoBucket.ensureCachedFile(path: photo.objectPath).url
    } catch {
        throw SampleFailure.storage(error)
    }
}

Download progress

// Runs on this coroutine's dispatcher; totalBytes is null when the server gave no size
val photo =
    photos.ensureCachedFile(path) { progress ->
        val total = progress.totalBytes
        showFraction(total?.let { progress.bytesReceived.toFloat() / it })
    }

ensureCachedFile(path) { progress -> … } hands the download's progress to its lambda: the bytesReceived so far, and totalBytes, the object's size when the server's answer gave it, or null. Every call waiting for one object's download is handed its progress, and a call that joins the download late starts from where it stands; each is handed the last progress before it returns. The lambda runs in the caller's coroutine, on its dispatcher, so it can update a UI from the main thread, one call at a time: a progress that arrives while it runs replaces any it has not been handed yet. What it throws ends that call alone, and the download goes on for the others. A cached copy is returned without a call. A download started again counts from zero: after the object was written meanwhile, or after a download the call joined failed, when the call makes its own request. A call without the lambda adds nothing to the download. The Swift package has ensureCachedFile(path:isPublic:onProgress:), whose closure runs on a background thread; when its task is canceled, one call already under way may finish after the CancellationError is thrown.

Evicting and clearing

// The cached thumbnail a download with this transform kept, or null; never a request
val thumbnail = photos.cachedFile(path) { size(256, 256) }

// One photo's copies, the full image and every thumbnail
photos.evictCachedFile(path)

// Every downloaded file, in every bucket; queued writes and cached lists stay
offline.storage.clearFileCache()

Three calls delete cached files on the device and send nothing; the objects stay in their buckets, and the next download of each fetches it again. A bucket's evictCachedFile(path) deletes one object's copies, the untransformed one and every image transform, and its pin, and no other object's; evictCachedFile(path) { … } deletes one transform's copy alone and leaves the pin. offline.storage.clearFileCache() deletes every downloaded file in every bucket, with its record, and every pin, and leaves the mutation queue, the cached query results and the rejected and conflicted lists: it frees the device's storage without dropping writes waiting to sync, so a "Free up space" button can call it. At sign-out, call clearLocalData() instead (Signing out and switching users): it deletes these files too, with the user's queued writes, and rewrites the database without what it deleted, which clearFileCache() does not.

A download still on the wire when its copies are evicted is handed to its caller but not cached, as when the object is written; an ensureCachedFile running meanwhile downloads it once more and caches that. A download in flight when the file cache is cleared is handed to its caller, or fails, but is not cached, as across clearLocalData(): an ensureCachedFile running meanwhile throws IllegalStateException. The Swift package has the same calls: evictCachedFile(path:), evictCachedFile(path:transform:) and storage.clearFileCache().

Pinned files

if (keep) {
    // Never evicted from now on; downloaded now, so it is there offline
    documents.pinCachedFile(path)
    documents.ensureCachedFile(path)
} else {
    // Evicted again when the cache needs the room
    documents.unpinCachedFile(path)
}

A bucket's pinCachedFile(path) keeps an object on the device: the cache never evicts its copies, the untransformed one and every image transform's, kept now or later, however long ago they were used. It sends nothing and downloads nothing, so pinning an object that is not cached records the pin alone, and its next download is kept; call ensureCachedFile(path) after it to have the object offline now. unpinCachedFile(path) removes the pin and leaves the copies, which the cache then evicts as it does any other file. isCachedFilePinned(path) says whether the object is pinned, cached or not. A path that cannot be cached (below) cannot be pinned: pinCachedFile throws IllegalArgumentException and sends nothing.

The pin is stored in the database and outlives a restart. It stays through every write to the object: an upload or update drops its copies, as for any object, and the next download is kept pinned. A move through the bucket takes the pin to the new path, or drops it when the new path cannot be pinned; a delete through the bucket removes it, as do evictCachedFile(path), clearFileCache(), clearLocalData() and the cache passing to another user. A move or delete that timed out leaves the pin where the object may be: on both ends of the move, and on the object that may not have been deleted. Pinned while the cache still belongs to the user before, until a sign-in settles, the pin is not kept, as a download then is not.

Pinned copies count toward fileCacheSizeBytes. When they alone take more than nine tenths of it, eviction stops at the bound rather than a tenth below; when they fill it, the cache stays over its bound, and every other file is evicted once it has not been used for 30 seconds (Cache size and eviction). The Swift package has the same calls: pinCachedFile(path:), unpinCachedFile(path:) and isCachedFilePinned(path:).

Queued uploads

// Kept on the device and queued when it cannot be sent now
val upload =
    offline.storage.from("photos").upload(path, jpeg, MutationStrategy.QueueIfOffline) {
        contentType = ContentType.Image.JPEG
    }
// The row that names the file is sent after it
offline.from("task_photos").insert(row)

// The bytes on the device while it waits; the cached copy once Storage has it
val shown = offline.storage.from("photos").cachedFile(path)

upload(path, data, mutationStrategy) makes an upload as a row write is made (Writes and the offline queue). Under QueueIfOffline the bytes are first written to the device and the upload queued, then it is sent at once when nothing of the user waits ahead of it: the result is UploadOutcome.Applied with Storage's response. Otherwise it waits and is UploadOutcome.Queued, with a PendingUpload: no connection or no answer, an answer that says the request did not finish (a 408, 429, 502, 503, 504, 520, 522 or 524), a token Storage refused, earlier writes still pending, network access off, or a session still restoring. A later pass sends it in the order it was made among the user's writes, so a row written after it that names the file reaches the server after the file, and one written before it, a task the photo belongs to, say, before it. Sent at once and refused, or failing with another 5xx, it throws Storage's error and is not kept. OnlineOnly is the plain upload, its response wrapped in Applied.

  • Where the bytes wait: a file of their own under storage-uploads/ in the data directory (On-device data), written through to the disk before the upload is queued. The file cache's bound never evicts it and clearFileCache() leaves it.
  • While it waits, cachedFile(path) and ensureCachedFile(path) return that file, with no request, and so do the platform helpers built on them, so a photo shows at once: the newest upload of the path wins over any cached copy, and its fetchedAt is when it was queued. A refused upload's file is never answered there, since Storage may hold other bytes at the path: its entry's localPath names it, for the app to show what was refused. Once Storage has the file its bytes become the object's cached copy, and the file under storage-uploads/ goes. A transform's copy is never answered from it, and a download still asks the server, which does not hold the file yet.
  • Options: upsert, contentType and userMetadata are kept with it. An upload whose options add an httpOverride, one through a bucket with a header set by setHeader, one whose user cannot be told, one whose bytes the device cannot write, and one on its way into the queue while local data is cleared are sent at once instead; offline they throw MutationNotQueueableException with the connectivity failure as its cause.
  • Replay: it is a write of the user's queue, sent with that user's token and never another's, through the same order and the same stops as a row (Replaying the queue). An upload whose earlier send's answer was lost is sent again. When Storage refuses that send, as it refuses a duplicate of an upload that may not overwrite, the upload counts as sent only when the object at its path is verifiably its bytes: the same size, and the same MD5 by Storage's ETag or, when the ETag is not an MD5 one, the same bytes downloaded. Any other object there leaves the refusal standing, on the rejected list, and its cached copy is never the device's bytes.
  • Refusals: an upload Storage refuses for good moves to the rejected list with its bytes, as storage.rejectedUploads() lists it, with the status Storage's error body names, its error code (code, such as NoSuchKey) and message, and the file's path on the device as localPath while it is whole; retryRejectedMutation(id) queues it again at the end of the queue, and dismissRejectedMutation(id) drops it with its file. A refused upload does not hold the writes behind it: a row that names its file is still sent, so show the refusal and let the user retry.
// The current user's uploads still to send, in the order they will go
val waiting = offline.storage.pendingUploads().first()

// Refused ones keep their bytes: retry once the cause is fixed, or dismiss
offline.storage.rejectedUploadList().forEach { refused ->
    if (refused.isRetryable) offline.retryRejectedMutation(refused.id)
    else offline.dismissRejectedMutation(refused.id)
}

// Drop one that has not gone yet, with its bytes
waiting.firstOrNull()?.let { upload -> offline.discardPendingMutation(upload.id) }

storage.pendingUploads() lists the current user's uploads still to send, in queue order, each a PendingUpload with its id, bucketId, path, createdAt, sizeBytes, contentType and upsert; discardPendingMutation(id) drops one, with its file. They count as writes in syncStatus and in pendingMutationCount() with no table; pendingMutations() lists the row writes beside them. They stay with the user who made them across a sign-out, as queued rows do, and go with clearLocalData() (Signing out and switching users). Resumable uploads, and every other write, are never queued.

Writes

Uploads without a strategy, updates, deletes, moves and copies are online only, and nothing is queued. Offline, a write is tried whatever the connectivity monitor says and fails with supabase-kt's own connectivity error; with network access off, every Storage call but a download throws NetworkDisabledException and sends nothing, and a download is answered from the file cache (or throws NetworkDisabledException with nothing cached). A write that reaches the server drops the cached copies it made stale, a resumable upload once it finishes. Such an upload does not put its bytes in the cache, so a file uploaded just before the device goes offline is not available offline until it is downloaded; a queued upload does. The Android sample adds a photo through the queued upload, the iOS sample from its own queue of photos waiting to upload (below); both replace a file in place, and move or copy one to another task's folder, writing the photo's row too, since the schema ties a row to its path:

From the samples: TaskPhotoFiles.kt · OfflineTaskRepository.kt · TaskRepository+Photos.swift

/**
 * The bucket a photo is added through: without the header, since a header set on a bucket is
 * not kept with a queued upload, and an upload through one is sent at once instead of queued.
 */
private val queueingBucket: OfflineBucketApi = offline.storage.from(PHOTOS_BUCKET)

/**
 * Uploads a JPEG to [path], or keeps it on the device and queues it when it cannot be sent now:
 * a later sync sends it before the writes made after it, its photo's row among them.
 */
suspend fun upload(path: String, jpeg: ByteArray): UploadOutcome =
    queueingBucket.upload(path, jpeg, MutationStrategy.QueueIfOffline) {
        upsert = false // a path is never reused, so an existing file is an error
        contentType = ContentType.Image.JPEG // the only type the bucket takes
    }


/** Replaces the file at [path] in place; the cached copy goes, so the next read downloads. */
suspend fun replace(path: String, jpeg: ByteArray) {
    bucket.update(path, jpeg) {
        upsert = false // replace only: there must be a file there already
        contentType = ContentType.Image.JPEG
    }
}


/** The file moves to the other task's folder first, then the row follows it, in one update. */
override suspend fun movePhoto(photo: TaskPhoto, taskId: String): TaskMutationOutcome =
    detached {
        requireNetwork()
        val newPath = photoObjectPath(photo.userId, taskId, photo.id)
        storage(photo.objectPath) { files.move(photo.objectPath, newPath) }
        write(Tables.TASK_PHOTOS, TaskMutationOperation.Update, taskTitle = null) {
                offline.from(Tables.TASK_PHOTOS).update({
                    set(TASK_ID, taskId)
                    set(OBJECT_PATH, newPath) // the schema ties the path to the task
                }) {
                    filter { eq(ID, photo.id) }
                }
            }
            .toTaskMutationOutcome()
    }


/** A copy of the file in the other task's folder, under a new id, then a row for it. */
override suspend fun copyPhoto(photo: TaskPhoto, taskId: String): TaskMutationOutcome =
    detached {
        requireNetwork()
        val copyId = newId()
        val copyPath = photoObjectPath(photo.userId, taskId, copyId)
        storage(photo.objectPath) { files.copy(photo.objectPath, copyPath) }
        insertPhotoRow(copyId, photo.userId, taskId, copyPath, photo.width, photo.height)
        TaskMutationOutcome.Applied
    }
/// Uploads the JPEG of `pending`, a photo picked on this device, to the path its record names.
///
/// - Throws: ``SampleFailure/needsNetwork`` offline, and Storage's refusal as
///   ``SampleFailure/storageRefused(status:message:)``.
func uploadFile(of pending: PendingPhoto, jpeg: Data) async throws {
    do {
        try await photoBucket.upload(
            pending.objectPath,
            data: jpeg,
            options: OfflineBucketApi.UploadOptions(
                // The bucket takes JPEGs only.
                contentType: pending.contentType,
                // A path is never reused, so there is nothing to write over.
                upsert: false,
                // Kept with the file, for Storage's own listing and the Details sheet.
                userMetadata: ["task_id": .string(pending.taskID)]
            )
        )
    } catch let error as OfflineError where error.httpStatus == 409 || error.serverError?.code == "Duplicate" {
        // Already there: the path holds an id this device made, so only an earlier attempt at
        // this photo, whose answer was lost, can have stored it.
    } catch {
        throw SampleFailure.upload(error)
    }
}

/// Writes `replacement` over `photo`'s file, at the same path, and its new size into the row.
/// The device's copy of the old file is dropped, so the next look downloads the new one.
func replacePhoto(_ photo: TaskPhoto, with replacement: EncodedPhoto) async throws {
    guard canReachNetwork else { throw SampleFailure.needsNetwork }
    do {
        try await photoBucket.update(
            photo.objectPath,
            data: replacement.jpeg,
            options: OfflineBucketApi.UploadOptions(contentType: "image/jpeg")
        )
    } catch {
        throw SampleFailure.storage(error)
    }
    try await write(taskTitle: nil) {
        try await client.from(Tables.taskPhotos)
            .update(["width": .int(replacement.width), "height": .int(replacement.height)])
            .eq("id", value: photo.id)
            .execute()
    }
}

/// Moves `photo` to task `taskID`: the file to the path the schema gives the other task, then
/// the row to match. A row the server refuses puts the file back.
func movePhoto(_ photo: TaskPhoto, toTask taskID: String) async throws {
    guard canReachNetwork else { throw SampleFailure.needsNetwork }
    let destination = PhotoPath.objectPath(userID: photo.userID, taskID: taskID, photoID: photo.id)
    do {
        try await photoBucket.move(from: photo.objectPath, to: destination)
    } catch {
        throw SampleFailure.storage(error)
    }
    do {
        try await write(taskTitle: nil) {
            try await client.from(Tables.taskPhotos)
                .update(["task_id": .string(taskID), "object_path": .string(destination)])
                .eq("id", value: photo.id)
                .execute()
        }
    } catch {
        try? await photoBucket.move(from: destination, to: photo.objectPath)
        throw error
    }
}

/// Copies `photo` to task `taskID`, as a new photo: the file to a new path, then its row.
func copyPhoto(_ photo: TaskPhoto, toTask taskID: String) async throws {
    guard canReachNetwork else { throw SampleFailure.needsNetwork }
    let photoID = DeviceID.make()
    let destination = PhotoPath.objectPath(userID: photo.userID, taskID: taskID, photoID: photoID)
    do {
        try await photoBucket.copy(from: photo.objectPath, to: destination)
    } catch {
        throw SampleFailure.storage(error)
    }
    let row = TaskPhotoRow(
        id: photoID,
        userID: photo.userID,
        taskID: taskID,
        objectPath: destination,
        width: photo.width,
        height: photo.height,
        createdAt: .now
    )
    try await insertRow(of: row)
}

Signed URLs, listings, info and exists always ask the server; publicUrl and the other URL builders send nothing. The sample's Details sheet, Share link, Share all photos of this task and the Sync tab's Storage section make each of them. A signed URL with an image transform serves Storage's resized copy, which needs image transformations on the project (Pro plans and up on hosted Supabase); without them the link answers with an error.

From the samples: TaskPhotoFiles.kt · TaskRepository+Photos.swift

/** What Storage and this device know about the file at [path]. */
suspend fun details(path: String): PhotoDetails {
    val exists = bucket.exists(path) // always asks the server
    val info = if (exists) bucket.info(path) else null // size, type, times, etag
    return PhotoDetails(
        existsInBucket = exists,
        sizeBytes = info?.size ?: 0,
        contentType = info?.rawContentType,
        createdAt = info?.createdAt,
        updatedAt = info?.updatedAt,
        etag = info?.etag,
        publicUrl = bucket.publicUrl(path), // a private bucket refuses it
        authenticatedUrl = bucket.authenticatedUrl(path), // needs the user's token
        cachedFile = cachedFile(path), // the device's copy: when fetched, how large
    )
}


/** A link anyone can open for an hour, to a copy 512 pixels wide that Storage renders. */
suspend fun shareLink(path: String): String =
    bucket.createSignedUrl(path, SHARE_LINK_LIFETIME) {
        transform {
            width = SHARE_LINK_WIDTH // the height follows the photo's shape
            quality = SHARE_LINK_QUALITY
        }
    }


/** Links anyone can open for an hour, one per file, in one request. */
suspend fun shareLinks(paths: List<String>): List<String> =
    bucket.createSignedUrls(SHARE_LINK_LIFETIME, paths).map { it.signedURL }


/** A page of [userId]'s task folders, from the [offset]th, with each folder's files. */
suspend fun list(userId: String, offset: Int): BucketListing {
    val folders =
        bucket.list(userId) {
            limit = FOLDERS_PER_PAGE + 1 // one more, to tell whether a page follows
            this.offset = offset
            sortBy("name", SortOrder.ASC) // a folder is named for its task's id
        }
    val page = folders.take(FOLDERS_PER_PAGE)
    return BucketListing(
        folders =
            page.map { folder -> BucketFolder(folder.name, filesIn("$userId/${folder.name}")) },
        hasMore = folders.size > FOLDERS_PER_PAGE,
        nextOffset = offset + page.size,
    )
}

/** The files in [folder], newest first. */
private suspend fun filesIn(folder: String): List<BucketFile> =
    bucket
        .list(folder) {
            limit = FILES_PER_FOLDER
            sortBy("created_at", SortOrder.DESC)
            search = "" // the start of a name to match; empty matches every file
        }
        .map { it.toBucketFile() }


/**
 * Uploads a JPEG to [path] through a signed upload URL: the URL's token, not the session, lets
 * it in, so an app can hand such an upload to code that holds no session.
 */
suspend fun uploadThroughSignedUrl(path: String, jpeg: ByteArray) {
    val signed = bucket.createSignedUploadUrl(path) // the server checks the policies here
    bucket.uploadToSignedUrl(signed.path, signed.token, jpeg) {
        contentType = ContentType.Image.JPEG
    }
}
/// What Storage and the device know about `photo`'s file. The bucket's own facts need the
/// network and are left out without it; the device's copy and the addresses need none.
func photoDetails(for photo: TaskPhoto) async -> PhotoDetails {
    // The device's copy and the two addresses send nothing, so they are there offline too.
    var details = PhotoDetails(
        publicURL: try? await photoBucket.publicURL(path: photo.objectPath),
        authenticatedURL: try? await photoBucket.authenticatedURL(path: photo.objectPath),
        onDevice: try? await photoBucket.cachedFile(path: photo.objectPath)
    )
    guard canReachNetwork else { return details }
    async let info = photoBucket.info(path: photo.objectPath)
    async let exists = photoBucket.exists(path: photo.objectPath)
    details.inBucket = try? await info
    details.existsInBucket = try? await exists
    return details
}

/// A link to a 512-pixel-wide copy of `photo` that works for an hour, for anyone who has it:
/// Storage signs it, and resizes the image when the link is opened. It needs the network.
func shareLink(for photo: TaskPhoto) async throws -> URL {
    try await photoBucket.createSignedURL(
        path: photo.objectPath,
        expiresIn: Self.shareLinkLifetimeSeconds,
        transform: OfflineBucketApi.ImageTransformation(width: Self.shareLinkWidth, resize: .contain, quality: 80)
    )
}

/// Links to every photo of `photos`, each working for an hour, signed in one request; a photo
/// Storage could not sign is left out.
func shareLinks(for photos: [TaskPhoto]) async throws -> [URL] {
    try await photoBucket.createSignedURLs(paths: photos.map(\.objectPath), expiresIn: Self.shareLinkLifetimeSeconds)
        .filter { $0.error == nil }
        .map(\.signedURL)
}

/// The entries of the user's folder `folder` in the bucket (a task's photos, or, for `""`, a
/// folder per task), a page at a time: Storage filters by name, sorts and pages them.
func bucketEntries(in folder: String, page: BucketPage) async throws -> [OfflineBucketApi.FileObject] {
    let userID = try signedInUserID()
    let path = folder.isEmpty ? userID : "\(userID)/\(folder)"
    return try await photoBucket.list(
        path: path,
        options: OfflineBucketApi.StorageListFilter(
            limit: page.limit,
            offset: page.offset,
            sortBy: OfflineBucketApi.StorageListFilter.SortBy(column: page.sortColumn, order: page.newestFirst ? .desc : .asc),
            search: page.search.isEmpty ? nil : page.search
        )
    )
}

/// Adds `photo` to task `taskID` through a signed upload URL: the app asks Storage for a
/// one-time URL and token, then sends the file to it. The way to hand an upload to code that
/// holds no session, such as a share extension.
func attachPhotoThroughSignedURL(taskID: String, photo: EncodedPhoto) async throws {
    guard canReachNetwork else { throw SampleFailure.needsNetwork }
    let userID = try signedInUserID()
    let photoID = DeviceID.make()
    let objectPath = PhotoPath.objectPath(userID: userID, taskID: taskID, photoID: photoID)
    let uploaded: OfflineBucketApi.FileUploadResponse
    do {
        let upload = try await photoBucket.createSignedUploadURL(path: objectPath)
        uploaded = try await photoBucket.uploadToSignedURL(
            upload.path,
            token: upload.token,
            data: photo.jpeg,
            options: OfflineBucketApi.UploadOptions(contentType: "image/jpeg")
        )
    } catch {
        throw SampleFailure.storage(error)
    }
    // The row names the file where Storage says it put it.
    try await insertRow(of: TaskPhotoRow(photoID: photoID, userID: userID, taskID: taskID, objectPath: uploaded.path, photo: photo))
}

Photos picked offline

The Android sample adds every photo through the queued upload (above); the iOS sample keeps a queue of its own, written before the library could queue an upload.

Android: the queued upload

  • Every photo goes through it: New task's Add photo, several at once with their thumbnails, adds its photos once the task is added (a queued insert offline), and the task detail's Add photo adds one the same way. Each is upload(path, jpeg, QueueIfOffline) of the photo's file at <user id>/<task id>/<photo id>.jpg (the ids made on the device), through a bucket without the app's setHeader, since a bucket with a header sends an upload at once instead of queuing it; then the task_photos row, a write queued behind the file. Offline both wait, and a later sync sends the task, the file and the row in that order. Online the file is sent at once and the row after it, from the repository's scope rather than the screen's, and the photo shows meanwhile, marked waiting. The mark has no progress yet. When that send fails (Storage refuses it, or answers a 500), the library throws and keeps nothing, as for a row write sent at once, so the app keeps the photo itself: its bytes and a record under failed-photo-adds/ in its files, shown marked failed with Storage's words, across restarts, until Retry adds it again or Remove deletes it.
  • Shown from the device at once. The queued row is in the photo lists as any queued write is, and its file is drawn from cachedFile, which answers the queued copy; a refused one is drawn from its entry's localPath, which cachedFile never answers. The lists mark a photo "Waiting to upload" while storage.pendingUploads() holds its path, and "Upload failed", with Storage's message, while storage.rejectedUploads() does. A failed one offers Retry (retryRejectedMutation, switched off when its file is gone) and Remove, a waiting one Remove. The viewer hides Details, Share link, Replace, Move and Duplicate for either, which need the object in the bucket, with a line saying so.
  • Failures. A file whose answer was lost is sent again, and Storage's duplicate refusal counts it stored once the object at its path is the photo's bytes. One Storage refuses on replay keeps its file on the rejected list; its row, queued behind it, is sent all the same, so the photo stays listed, marked failed, until Retry or Remove.
  • Deletes and clears. Remove discards a waiting upload, or dismisses a refused one, with the row's queued writes; then it deletes the row and, online, the file, wherever an upload that ended meanwhile left them. A photo still being added is removed once the add ends. Deleting a task discards its photos' waiting uploads first, since a discard waits for one on the wire, then deletes its files, one that landed meanwhile too, then dismisses its refused uploads. Start over discards the waiting uploads the same way before clearLocalData(), which does not wait for an upload on the wire, and its deletes. Clear local cache needs nothing more than clearLocalData(), which drops the queued uploads with their files.

From the samples: TaskDetailViewModel.kt · OfflineTaskRepository.kt

/**
 * Add photo: re-encodes the image at [contentUri] and files it in the app's pending-photo
 * queue, where it shows at once and waits for the network if it must.
 */
fun addPhoto(contentUri: String) {
    writeScope.launchReporting(failures) {
        repository.addPhoto(taskId, photoEncoder.encode(contentUri))
    }
}


/**
 * Add photo, online or offline: the file through the library's queue, under the path it will
 * have in the bucket, then the photo's row, queued behind it. Offline both wait, the row shown
 * at once and the file from the device; a later sync sends the file first. Online the file is
 * sent at once, and the photo shows marked waiting until its row is written. Run in this
 * repository's scope, so a screen that closes between the two cannot leave the file without its
 * row; a failure is the caller's.
 */
override suspend fun addPhoto(taskId: String, photo: EncodedPhoto) {
    val userId = signedInUserId()
    val photoId = newId() // the device's, so the path is known before the upload
    val path = photoObjectPath(userId, taskId, photoId)
    val createdAt = clock.now()
    val shown =
        TaskPhoto(
            id = photoId,
            userId = userId,
            taskId = taskId,
            objectPath = path,
            width = photo.width,
            height = photo.height,
            createdAt = createdAt,
            hasPendingMutations = true,
            pendingUpload = PendingUpload(PendingPhotoState.Waiting),
        )
    send(shown, photo.jpeg)
}

/**
 * Sends [shown]'s file and then writes its row, the photo shown waiting meanwhile. When the
 * upload sent at once fails, the library has kept nothing of it, so the photo is kept here,
 * failed, with Retry and Remove, and nothing is thrown: the photo says why.
 */
private suspend fun send(shown: TaskPhoto, jpeg: ByteArray) {
    val adding =
        detachedLater<Unit> {
            val failure =
                try {
                    storage(shown.objectPath) { files.upload(shown.objectPath, jpeg) }
                    null
                } catch (cancellation: CancellationException) {
                    throw cancellation
                } catch (failure: Exception) {
                    failure
                }
            if (failure != null) {
                failedAdds.keep(shown.toFailedAdd(failure), jpeg)
                return@detachedLater
            }
            failedAdds.forget(shown.id)
            insertPhotoRow(
                shown.id,
                shown.userId,
                shown.taskId,
                shown.objectPath,
                shown.width,
                shown.height,
                shown.createdAt,
            )
        }
    photosBeingAdded.update { it + (shown.id to PhotoBeingAdded(shown, adding)) }
    adding.invokeOnCompletion { photosBeingAdded.update { it - shown.id } }
    adding.start()
    adding.await().getOrThrow()
}

/** This photo as a failed add, failed with [failure]. */
private fun TaskPhoto.toFailedAdd(failure: Exception) =
    FailedPhotoAdd(
        photoId = id,
        userId = userId,
        taskId = taskId,
        objectPath = objectPath,
        width = width,
        height = height,
        createdAt = createdAt.toString(),
        failure = failure.message,
    )

/** This failed add as the lists show it: failed, with Retry, drawn from its kept file. */
private fun FailedPhotoAdd.toTaskPhoto() =
    TaskPhoto(
        id = photoId,
        userId = userId,
        taskId = taskId,
        objectPath = objectPath,
        width = width,
        height = height,
        createdAt = Instant.parse(createdAt),
        hasPendingMutations = true,
        pendingUpload =
            PendingUpload(
                PendingPhotoState.Failed,
                failure,
                retryable = true,
                keptFile = failedAdds.fileOf(photoId).path,
            ),
    )


/**
 * These photos with where their uploads stand, from the library's lists: waiting in its queue,
 * or refused by Storage. A photo added here shows at once as its queued row, drawn from the
 * library's copy of its file on the device; a waiting upload marks it until Storage has it.
 */
private fun Flow<PhotoListSnapshot>.withUploadStates(): Flow<PhotoListSnapshot> =
    combine(this, offline.storage.pendingUploads(), offline.storage.rejectedUploads()) {
        snapshot,
        waiting,
        refused ->
        val waitingPaths =
            waiting.filter { it.bucketId == PHOTOS_BUCKET }.mapTo(HashSet()) { it.path }
        val refusals = refused.filter { it.bucketId == PHOTOS_BUCKET }.associateBy { it.path }
        snapshot.copy(
            value =
                snapshot.value?.map { photo ->
                    val refusal = refusals[photo.objectPath]
                    when {
                        refusal != null ->
                            photo.copy(
                                pendingUpload =
                                    PendingUpload(
                                        PendingPhotoState.Failed,
                                        refusal.message,
                                        refusal.isRetryable,
                                        refusal.localPath,
                                    )
                            )
                        photo.objectPath in waitingPaths ->
                            photo.copy(pendingUpload = PendingUpload(PendingPhotoState.Waiting))
                        else -> photo
                    }
                }
        )
    }


/**
 * Queues the refused upload of [photoId]'s file again, at the end of the user's queue; or, for
 * a photo whose upload failed when it was sent at once, adds it again from its kept bytes.
 */
override suspend fun retryPendingPhoto(photoId: String) {
    val failed = failedAdds.adds.value[photoId]
    if (failed != null) {
        val jpeg = failedAdds.bytesOf(photoId) ?: return failedAdds.forget(photoId)
        val again = failed.toTaskPhoto()
        return send(again.copy(pendingUpload = PendingUpload(PendingPhotoState.Waiting)), jpeg)
    }
    val refused = refusedUploadOf(photoId) ?: return
    storage(refused.path) { offline.retryRejectedMutation(refused.id) }
}

/**
 * Gives up the photo [photoId] before Storage has its file: its waiting or refused upload, its
 * row's queued writes, and then its row and its file wherever a send that ended meanwhile left
 * them, so neither is left behind. A photo still being added is given up once that ends.
 */
override suspend fun removePendingPhoto(photoId: String): Boolean = detached {
    // Its file is sent or queued and its row written first, or the add would outlive this
    val beingAdded = photosBeingAdded.value[photoId]
    beingAdded?.adding?.join()
    // One whose upload failed at once is only on this device
    if (photoId in failedAdds.adds.value) {
        failedAdds.forget(photoId)
        return@detached true
    }
    val waiting = waitingUploadOf(photoId)
    val refused = if (waiting == null) refusedUploadOf(photoId) else null
    val path =
        waiting?.path ?: refused?.path ?: beingAdded?.photo?.objectPath ?: return@detached false
    storage(path) {
        // Waits for an upload on the wire to end; one that landed is no longer pending
        if (waiting != null) offline.discardPendingMutation(waiting.id)
        if (refused != null) offline.dismissRejectedMutation(refused.id)
    }
    discardQueuedWritesOf(Tables.TASK_PHOTOS, photoId)
    if (canReachNetwork()) deleteFilesQuietly(listOf(path))
    write(Tables.TASK_PHOTOS, TaskMutationOperation.Delete, taskTitle = null) {
        offline.from(Tables.TASK_PHOTOS).delete { filter { eq(ID, photoId) } }
    }
    true
}


/**
 * Clear local cache: everything the library keeps here, queued writes included, never sent, and
 * the photos waiting to upload with them.
 */
override suspend fun clearLocalData() {
    offline.clearLocalData() // an open list fetches again by itself once the network allows
    failedAdds.forgetAll()
}


/** Start over: clear first, so no queued write lands after the deletes; then a new user. */
override suspend fun startOver() {
    // A new anonymous user needs the server, so nothing is deleted or cleared without it.
    if (!canReachNetwork()) throw NetworkUnavailableException()
    detached {
        val userId = session.userId.value
        // The photos waiting to upload go first: a discard waits for one on the wire, which
        // the clear does not, so none lands after the deletes; one that landed is deleted too
        val waiting = userId?.let { discardWaitingUploadsOf("$it/") }.orEmpty()
        // Stops a replay already running, and drops the rest of the queue, refused uploads too
        offline.clearLocalData()
        failedAdds.forgetAll()
        userId?.let { deleteEverythingOf(it, alsoDelete = waiting) }
        session.signInAsNewUser()
    }
}

iOS: the app's own queue

The iOS sample holds a photo in a queue of its own until the upload lands, and then references the library's cached copy. Its uploads are made without a strategy, so they need a connection, as Writes says.

  • A directory the app owns, in Application Support beside the library's data directory: per photo, a JPEG named by the photo's id and, written after it, a small JSON record with the task's id, the photo's id, its Storage path, when it was picked, its state (waiting, uploading, or failed with the app's sentence and the number of tries) and its content type.
  • Shown from the device at once. The task's photos and the Photos tab merge the task_photos rows with the records, each photo once, marked "Waiting to upload", "Uploading" or "Upload failed", with Retry and Remove.
  • One uploader follows syncStatus and uploads the waiting photos one at a time, oldest first: the file, then, only once Storage has it, the row through the library, then ensureCachedFile, then the app's file and record are deleted. A retry first asks Storage whether an earlier try stored the file, and the row is an upsert that ignores a duplicate. Through the Swift package Storage's refusal keeps its own Duplicate code whatever the HTTP status, so the upload's "already exists" counts as stored there too.
  • Deletes and clears. Deleting a task deletes its pending photos, and Remove deletes one. Clear local cache and Start over delete the whole directory, which clearLocalData() never touches; Start over first waits for an upload in progress.

From the samples: PendingPhotoQueue.swift · TaskDetailModel.swift · TaskRepository+PendingPhotos.swift · TaskRepository+Photos.swift · TaskRepository.swift

/// A photo picked on this device whose file is not on the server yet. Its record is kept as JSON
/// beside the photo's JPEG, both named by the photo's id, until its upload lands.
nonisolated struct PendingPhoto: Codable, Hashable, Identifiable, Sendable {

    /// Where its upload stands.
    enum State: Codable, Hashable, Sendable {

        /// Waiting for the network, or for the photos picked before it.
        case waiting

        /// Being uploaded now.
        case uploading

        /// The last attempt failed, for `reason`, in the app's words. When `isRetryable` is false
        /// the server refused it in a way another attempt cannot change.
        case failed(reason: String, isRetryable: Bool)

        /// The failure's keys in the record.
        enum FailedCodingKeys: String, CodingKey {
            case reason
            case isRetryable = "retryable"
        }
    }

    /// The photo's id, made on the device: its row's id, and its files' names.
    let id: String

    /// The task it is attached to.
    let taskID: String

    /// The user who picked it.
    let userID: String

    /// The path its file will have in the bucket.
    let objectPath: String

    /// When it was picked: photos upload in this order.
    let pickedAt: Date

    /// The file's content type; the bucket takes JPEGs only.
    let contentType: String

    /// Its width in pixels, for its row.
    let width: Int

    /// Its height in pixels.
    let height: Int

    /// Where its upload stands.
    var state: State = .waiting

    /// How many attempts to upload it have failed or been cut short.
    var attempts = 0

    /// The record's keys in its JSON file.
    enum CodingKeys: String, CodingKey {
        case id = "photo_id"
        case taskID = "task_id"
        case userID = "user_id"
        case objectPath = "object_path"
        case pickedAt = "picked_at"
        case contentType = "content_type"
        case width
        case height
        case state
        case attempts
    }
}

/// Re-encodes the picked image as a JPEG and files it for the task, to wait on the device until
/// it uploads: at once when online.
func attach(_ item: PhotosPickerItem) {
    preparingCount += 1
    Task {
        defer { preparingCount -= 1 }
        await failures.perform {
            guard let data = try await item.loadTransferable(type: Data.self) else {
                throw SampleFailure.photoUnreadable
            }
            try await repository.filePhoto(try await PhotoEncoder.encode(data), forTask: taskID)
        }
    }
}

/// Files `photo` for task `taskID` as waiting: its JPEG and its record are written to the
/// device before anything else, and the uploader sends it when the network allows. Nothing is
/// sent here, so it works offline.
@discardableResult
func filePhoto(_ photo: EncodedPhoto, forTask taskID: String) async throws -> PendingPhoto {
    let userID = try signedInUserID()
    let photoID = DeviceID.make()
    let pending = PendingPhoto(
        id: photoID,
        taskID: taskID,
        userID: userID,
        objectPath: PhotoPath.objectPath(userID: userID, taskID: taskID, photoID: photoID),
        pickedAt: .now,
        contentType: "image/jpeg",
        width: photo.width,
        height: photo.height
    )
    try await pendingPhotos.add(pending, jpeg: photo.jpeg)
    return pending
}

/// Uploads `pending`, then writes its row, then has the library's file cache download it, and
/// then deletes the device's own copy. The row is written only once the file is stored, so the
/// server never holds a row whose file is missing; a row the server refuses at once takes the
/// file with it, and a queued row waits behind its task's queued insert.
func uploadPendingPhoto(_ pending: PendingPhoto) async throws {
    if await !isStoredByAnEarlierTry(pending) {
        try await uploadFile(of: pending, jpeg: try await pendingPhotos.jpeg(of: pending))
    }
    guard pendingPhotos.photo(id: pending.id) != nil else {
        // Removed while its file was on the way (Remove, Delete task, Clear): no row, no file.
        try? await photoBucket.remove(paths: [pending.objectPath])
        return
    }
    try await insertRow(of: TaskPhotoRow(pending))
    // The upload did not put its bytes in the cache; this downloads them, so the photo shows
    // offline from the library's copy. If it fails, the photo loads like any other when online.
    _ = try? await photoBucket.ensureCachedFile(path: pending.objectPath)
    try pendingPhotos.remove(id: pending.id)
}

/// Whether an earlier try at `pending` stored its file, its answer lost on the way: asked of
/// Storage on a retry only. Storage's "already exists" to the upload counts as stored too.
private func isStoredByAnEarlierTry(_ pending: PendingPhoto) async -> Bool {
    guard pending.attempts > 0 else { return false }
    return (try? await photoBucket.exists(path: pending.objectPath)) == true
}

/// Uploads the JPEG of `pending`, a photo picked on this device, to the path its record names.
///
/// - Throws: ``SampleFailure/needsNetwork`` offline, and Storage's refusal as
///   ``SampleFailure/storageRefused(status:message:)``.
func uploadFile(of pending: PendingPhoto, jpeg: Data) async throws {
    do {
        try await photoBucket.upload(
            pending.objectPath,
            data: jpeg,
            options: OfflineBucketApi.UploadOptions(
                // The bucket takes JPEGs only.
                contentType: pending.contentType,
                // A path is never reused, so there is nothing to write over.
                upsert: false,
                // Kept with the file, for Storage's own listing and the Details sheet.
                userMetadata: ["task_id": .string(pending.taskID)]
            )
        )
    } catch let error as OfflineError where error.httpStatus == 409 || error.serverError?.code == "Duplicate" {
        // Already there: the path holds an id this device made, so only an earlier attempt at
        // this photo, whose answer was lost, can have stored it.
    } catch {
        throw SampleFailure.upload(error)
    }
}

/// Writes a photo's row once its file is in the bucket, as an upsert that ignores a row already
/// there: a retry after a lost answer writes nothing twice. A row the server refuses at once
/// (its task deleted on the server meanwhile, say) takes its file with it, as far as Storage
/// allows; a row that is only queued keeps its file.
func insertRow(of row: TaskPhotoRow) async throws {
    do {
        try await write(taskTitle: nil) {
            try await client.from(Tables.taskPhotos).upsert(row, onConflict: "id", ignoreDuplicates: true).execute()
        }
    } catch let refusal as SampleFailure {
        if case .writeRefused = refusal { try? await photoBucket.remove(paths: [row.objectPath]) }
        throw refusal
    }
}

/// Task `taskID`'s photos as the screens show them, oldest first: the rows the library holds,
/// with a mark on each whose row waits in the mutation queue (`queuedRowIDs`), and the photos
/// picked on this device that wait to upload (`pending`). A photo in both is shown from its
/// record until its local copy is deleted, so it never shows twice.
static func photos(
    ofTask taskID: String,
    rows: [TaskPhotoRow],
    queuedRowIDs: Set<String>,
    pending: [PendingPhoto]
) -> [TaskPhoto] {
    let waiting = pending.filter { $0.taskID == taskID }
    let waitingIDs = Set(waiting.map(\.id))
    let stored = rows
        .filter { $0.taskID == taskID && !waitingIDs.contains($0.id) }
        .map { $0.photo(pendingIDs: queuedRowIDs) }
    return (stored + waiting.map(\.photo)).sorted { $0.createdAt < $1.createdAt }
}

/// Every photo the Photos screen shows, newest first: the rows read so far, and every photo
/// that waits to upload, merged as ``photos(ofTask:rows:queuedRowIDs:pending:)`` merges one
/// task's.
static func allPhotos(rows: [TaskPhotoRow], queuedRowIDs: Set<String>, pending: [PendingPhoto]) -> [TaskPhoto] {
    let waitingIDs = Set(pending.map(\.id))
    let stored = rows.filter { !waitingIDs.contains($0.id) }.map { $0.photo(pendingIDs: queuedRowIDs) }
    return (stored + pending.map(\.photo)).sorted { $0.createdAt > $1.createdAt }
}

/// Clear local cache: deletes everything this device holds, the library's cached rows and
/// files, queued and refused writes, and then the photos waiting to upload. Open lists then
/// read their rows again from the server, once the network allows. Start over clears the same.
func clearLocalData() async throws {
    try await client.clearLocalData()
    // The pending photos are the app's own files, outside the library's data directory, so
    // its clearLocalData() leaves them: the app deletes them itself.
    try pendingPhotos.removeAll()
}

Paths that are never cached

An object path that cannot be mapped safely onto a file (a leading /, an empty, . or .. segment, a \, a control character) still downloads and writes, uncached, and ensureCachedFile refuses it with IllegalArgumentException. A name holding %, ? or # is put in the URL percent-encoded, so it names its own object and is cached like any other. A name holding a lone UTF-16 surrogate, half of a pair with the other half missing, is not a valid Unicode string and cannot be sent the same way on every platform: every call that sends it, in a URL or in a request body, throws IllegalArgumentException before anything is sent, and it is never cached. An upload an earlier version queued under such a name goes to the rejected list when it comes up for sending. A segment that starts with a letter and a colon, like u:42, is cached, under a hash of the name (On-device data).

Whose files they are

With Auth installed, the file cache belongs to one user at a time, like the query cache, and clearLocalData() deletes every file (Signing out and switching users); a download in flight keeps its temporary file until it ends, then deletes it. A queued upload's file belongs to the user who made it, as the upload does: it stays when the file cache passes to another user, and goes with clearLocalData(). Its bound is fileCacheSizeBytes (Cache size and eviction); where the files live is on On-device data.

Behavior matrix

Facts about the engine; one row per condition, the conditions those of the one-shot read matrix, with warm and cold saying whether the object is cached. Writes are upload, update, delete, move, copy and the resumable and signed-URL uploads; an upload made with a strategy follows the queue instead (Queued uploads), and while it waits cachedFile and ensureCachedFile answer its file under every condition.

Condition downloadAuthenticated / downloadPublic ensureCachedFile cachedFile Writes
Online The server's bytes, written to the cache whole or not at all; a "not modified" about the cached copy, the cached bytes, with fetchedAt moved to now. Not found: the cached copy is dropped and the error thrown. The cached file; if there is none, the object is downloaded to disk once. The cached file or null; never a request. Sent; the cached copy of what they change is dropped. A write the server rejected keeps it.
Offline, warm The cached bytes. The cached file, no request. The cached file. Throw the connectivity failure; the cache is left as it was.
Offline, cold Throws the failure. Throws the failure. null. As offline, warm.
Session restoring Not held for the session (nor after its refresh failed): sent at once on the anon key, and its answer cached. A 401 or 403 keeps the cached copy; cold, the refusal is thrown. Storage answers an object the anon key may not read as "not found", which keeps the cached copy too and is answered from it; cold, it is thrown: download private objects after supabase.auth.awaitInitialization(). As a download. Unchanged: never a request. Sent at once on the anon key; a refusal keeps the cached copy.