Repository navigation
Delta Sync
The SDK exposes PikPak's incremental file-change stream, server watermarks, and task-backed batch mutations as atomic suspend primitives without owning a local database or background sync loop.
API priorities are ApiRequestPriority.INTERACTIVE (10), DEFAULT (0), and BACKGROUND (-10). Endpoint defaults preserve any explicitly supplied withApiPriority(...) context:
- Full scans (
sinceSyncTime = "") default toBACKGROUND; nonempty-cursor deltas andgetFiledetail lookups default toINTERACTIVE. - Folder creation, rename, and batch mutations default to
INTERACTIVE. - When a
TransferDemandis present in the coroutine context, queued API entries track its livepriorityFlow(INTERACTIVEatSTREAMING_PRIORITY50and above,BACKGROUNDotherwise), including promotion while already queued inRateLimiter. Closing theTransferDemandcancels the queued waiter immediately and refunds its token reservation.
Token buckets with capacity >= 8 reserve min(8, capacity / 3) tokens from BACKGROUND traffic (backgroundReserve). RateLimiter.default() (capacity = 24, refillPerSecond = 20.0) therefore keeps 8 tokens available for interactive and default bursts while a full drive scan runs in the background. Passing backgroundReserve = 0 disables the reserve.
On the CDN side, direct range reads up to 64 KiB (including sampleCid windows) default to PikPakStreamReader.MICRO_PROBE_PRIORITY (12) unless an explicit priority or TransferDemand overrides it. Waiting playback reads run at 100, steady playback at 50, near look-ahead at 10, next-file prefetch warming at 8, comfortable far look-ahead at 6, background blocking reads at 5, downloads/paused look-ahead at 1, and FinishInFlight tail completion at -1. Far look-ahead is demoted to 6 only once the near comfort window is continuously cached in memory (not merely in flight).
listFileChangesPage(sinceSyncTime, pageToken, pageSize) queries GET /drive/v1/files with parent_id=*, with_audit=true, and phase == PHASE_TYPE_COMPLETE, deliberately omitting trashed so trash and permanent-deletion tombstones arrive in the stream. On the server, modified_time.gt compares params.db_modify_time, capturing metadata changes such as starring that leave the visible modified_time unchanged.
FileStat.dbModifyTime and FileDetail.dbModifyTime expose that timestamp. Read isStarred on either model: it combines the raw starred boolean with the STAR entry in tags.
val checkpoint = client.consumeFileChanges(savedCursor) { page ->
// Stage complete rows, including trashed rows, in a local transaction/staging table.
stage(page.files)
}
// Atomically commit staged rows and persist checkpoint.syncTime (checkpoint.lastSyncTime).-
Sequential pages, server-controlled page sizes.
pageSizedefaults to500(1..500), but the server may ignore small limits (limit=2returned400rows in the 2026-11-10 live probe). Always consume every row returned and follownextPageTokenwhile keeping thesinceSyncTimelower bound fixed across pages. -
Watermarks (
FileSyncCheckpoint). BothfirstSyncTimeandlastSyncTimeare returned;checkpoint.syncTimeislastSyncTime. The 2026-11-10 cross-page live probe verified thatsync_timeadvances withdb_modify_timescan order and that rows mutated after being read on page 1 reappear with their updated state on later pages (Measurements). Deduplicate/upsert byfile.id. -
Commit rules. Never advance the durable cursor or sweep missing rows after cancellation, a failed page, a failed local write, or
FileSyncVersionOutdatedException. When the server reportsversion_outdated = true, discard the delta cursor and run a fresh full scan. RepeatednextPageTokenvalues or blanksync_timefields fail explicitly. -
In-memory convenience.
syncFileChanges(sinceSyncTime)collects all pages into aFileDeltaSyncResult(upserted, deletedIds, trashed, checkpoint).deletedIdsmeans removal from the active non-trashed view: both recycle-bin moves and permanent deletions arrive withtrashed = true, sodeletedIdsalone is not proof of permanent deletion. Large SQLite replicas should stream viaconsumeFileChangesinstead.
scanFilesPages(pageSize = 500) streams all completed rows (including trashed markers) as a Flow<FileListPage>; consumeFileChanges("") does the same and returns the completion FileSyncCheckpoint. Stage into a candidate generation, publish only after normal completion, and do not overwrite newer local optimistic mutation state with older scan pages.
getFileSyncWatermark(sinceSyncTime) fetches a single small page (pageSize = 1) for a conservative watermark; getCurrentSyncTime(sinceSyncTime) drains all matching pages without retaining rows to read lastSyncTime (scanning the full drive if sinceSyncTime is empty). Never fabricate a sync cursor from the client clock: an empty delta response can echo its input sinceSyncTime.
batchMove, batchCopy, batchTrash, batchUntrash, and batchDelete split inputs into chunks of 500 unique IDs (BATCH_ID_LIMIT, matching the official desktop client) and await each chunk's server task by default (awaitCompletion = true). Earlier chunks remain applied if a later chunk fails; coroutine cancellation or timeout does not cancel an accepted server task.
- Pass
awaitCompletion = falsefor fire-and-forget submission. - For crash-durable recovery, call
submitFileBatch(ids, operation, toParentId, onSubmitted = { receipt -> ... })to persist eachFileBatchReceipt(taskId, ids)before the next chunk goes out, then callawaitTasks(taskIds). A crash before receiving a receipt still requires checking remote state. -
getTasks(ids)looks up tasks in filtered batches.awaitTasksnever treats a missing task ID as complete, preserves already-completed tasks, throwsDriveTaskFailedExceptionon terminal task error, and throwsDriveTasksTimeoutException(carryingunresolvedTaskIds) on timeout. When thewith=reference_resourcetask listing reports"File deleted"because the output file was subsequently removed,awaitTasksverifies viagetTask(id)so a completed transfer is not misreported as failed.
For bulk metadata reads via GET /drive/v1/files:batchGet (chunked by 100 repeated ids= parameters, never comma-joined):
-
batchGetFiles(ids, usage = null)returnsList<FileStat>in the caller's deduplicated ID order (missing IDs omitted;FileStatpreserves anymediasandlinksreturned). -
batchGetFileDetails(ids, usage = "PLAY")returnsList<FileDetail>with fullmediasvariants and signedlinks, feeding bothAccountStateandHostHealth.observe(~130 msper video across 100 files vs1.95–3.6 sper serialgetFile; see Measurements).
DownloadLink.isLimited and VariantLink.isLimited detect x_limited=1 (and 101); maxSpeedBytesPerSec parses the ms query parameter, and expiresAt parses wire and URL signature expiries. Flag detection itself never loops on refreshes automatically; PikPakFileHandle avoids unexpectedly limited links on confirmed premium accounts (client.isFreeAccount == false) up to its bounded remint cap (MAX_HOST_REMINTS = 2).
Using the SDK
- Getting Started
- Best Practices
- Playback
- Original Link Pools
- Magnets and Instant Create
- Drive Operations
- Delta Sync
- Uploads and Offline Tasks
- Errors and Retries
Understanding it
Working on it