Files Offline Copies Developer Guide - edmozley/freeitsm GitHub Wiki
5.15.0 · Issue #285 · PR #488 by @cloudcogsio · User guide: Files § Make available offline · Review: Files offline copies - PR review · Storage underneath: Files storage - Developer Guide
When Files is in S3, a person can mark a file or folder. A background job keeps a copy of every covered file's current bytes at <storage root>/offline/<key>, and the read path uses a complete copy (right size) before the store. S3 stays the master: a copy is only ever a cache, so every failure here falls back to S3 and never breaks the action that caused it.
🗄️ schema · 🧠 coverage / service · 🔌 endpoint · ⏰ job · 🖥️ UI · 🧪 test
| 🎨 | File | What |
|---|---|---|
| 🧠 | includes/files/offline.php |
Reads only. FilesOfflineCoverage (what the marks cover), the state SQL, the folder ticks, paths, the limit and usage |
| 🧠 | includes/services/files_offline.php |
The only write path. FilesOfflineService: mark(), unmark(), exclude(), include(), clearAll(), setLimit(), copyKey(), keepUploadCopy() / commitUploadCopy(), foldersChanged(), forgetKey(), storageFolderChanged(), removeOldRoot(), sync()
|
| 🧠 | includes/files/storage.php |
filesServeBytes() and the new filesReadToLocal() read a copy first |
| 🔌 | api/files/offline.php |
POST only: on / off / exclude / include (Modify on the folder, checked by the service), clear_all, limit, remove_old_folder (Cap::FILES_STORAGE) |
| 🔌 |
api/files/list.php, properties.php
|
offline / offline_status on each entry; the Offline row |
| 🔌 |
api/files/upload.php, transfer.php
|
Keep a copy of an upload into a covered folder; mark folders pending after a move or copy in |
| 🧠 |
files_recycle.php, files_versions.php
|
Bytes deleted for good call forgetKey(); restores call foldersChanged()
|
| ⏰ | cron/files_offline_sync.php |
The files_offline_sync job (every 5 minutes, up to 8 minutes a run) |
| ⏰ | includes/job_registry.php |
needed: only while there are marks and S3 is (or was) in use, copies to tidy, or a proven old folder |
| 🖥️ | assets/js/files-desktop.js |
The right-click options, the ticks (offlineLabel()), Properties |
| 🖥️ | assets/js/files-settings.js |
The Storage tab: usage, marks, limit, Clear, old folders |
| 🗄️ |
files_offline, files_offline_copies, files_offline_folders
|
Below |
| 🧠 | includes/analyst_lifecycle.php |
files_offline.marked_by is an analyst reference (history) |
| 🧪 | tests/files-offline.php |
177 checks, fake S3, one rolled-back transaction |
files_offline -- the marks
target_type VARCHAR(10) -- folder | item
target_id INT
excluded TINYINT(1) -- 1 = "Don't keep offline"
marked_by INT NULL -- whose permissions decide what the mark covers
UNIQUE (target_type, target_id)
files_offline_copies -- one row per stored key that has a copy (or a failed try)
storage_path VARCHAR(255) -- the files_versions key, yyyy/mm/dd/<hex>.bin
size_bytes BIGINT
state VARCHAR(10) -- ready | failed
failed_datetime DATETIME NULL
UNIQUE (storage_path)
files_offline_folders -- each folder's tick, written by the job
folder_id INT UNIQUE
state TINYINT -- 0 ready, 1 failed, 2 pending
updated_datetime DATETIME(3)Settings (system_settings): files_offline_max_bytes (the limit, absent = none), files_offline_limit_reached, files_offline_old_roots (JSON list of {root, proven}).
Copies are recorded per key, not per file, because keys are shared: a copied file shares its source's stored bytes, exactly as files_versions rows do. Keys are never rewritten (a new version gets a new key), so a copy with the right size holds the right bytes - that is what lets every read trust filesOfflineHasCopy().
Worked out over the folder tree, never over files. A folder's state is self, folder (kept by one above), excluded or null. The walk goes up from the folder, and the nearest effective mark wins:
for ($a = $id, $depth = 0; $a !== null && isset($this->tree[$a]) && $depth < 1000; $a = $this->tree[$a]['parent_id'], $depth++) {
if (isset($this->marks['folder'][$a])) {
if (!$this->markerSees($this->marks['folder'][$a], $id)) continue; // not effective here: the next one above counts
if (!$exclusions) return $this->state[$id] = $a === $id ? 'self' : 'folder';
return $this->state[$id] = $exclusions === [$id] ? 'excluded' : null;
}
if (isset($this->marks['exclude']['folder'][$a])) $exclusions[] = $a;
}Effective means the maker is an active analyst who can see this folder (markerSees() - FilesAcl::levels() of marked_by, at least View). So:
- a subfolder that stops inheriting and is closed to the maker is not copied - the job never does what the person could not do by hand;
- a deactivated maker's mark is skipped and the mark above takes over. The row stays: anyone with Modify can mark it again, which makes it theirs.
The job and the read side ask the same object, so the tick and the copies can never disagree about coverage.
filesServeBytes() (view and download) and filesReadToLocal() (Attach as a copy) try a complete copy when the key's store is not a LocalDriver:
if (filesOfflineHasCopy($conn, $key, (int)($version['size_bytes'] ?? -1))) {
try {
(new LocalDriver(filesOfflineRoot($conn)))->readRange($key, $start, $end, $sink);
$served = true;
} catch (StorageNotFound $e) {
// Removed between the check and the read (the job, or a purge): use the store.
if ($started) throw $e;
}
}
if (!$served) $store->readRange($key, $start, $end, $sink);filesOfflineRoot() creates nothing - every S3 download asks it, including on installs that never used this.
Every change to the marks runs under one named lock (GET_LOCK('freeitsm_offline_<db hash>')) and one transaction that reads the mark row FOR UPDATE. Copies are deleted only after the commit, and the instant copy of a single file is fetched after the lock is released, so a slow download from S3 never holds up anyone else:
- The limit is checked before anything is written (
bytesToCopy()over-estimates: shared bytes once, left-out files counted). - A file up to
$instantMaxBytes(64 MB) is copied straight away; folders and bigger files go to the job. - Marking a folder sets its folders' ticks to pending (
rollupPending()). - Removing a mark (
unmark(),exclude()) deletes only copies nothing else covers (tidyScope()→coveredKeys()).
Changing marks needs Modify on the folder (for a file, its folder) or Cap::FILES_STORAGE; something the person cannot see is "not found".
In order, each step stopping at the deadline:
- Forget marks on folders and files deleted for good, and exclusions nothing is left to exclude from.
- Empty old storage folders that were proven to be another place (below).
-
Stop if the offline folder is also a store's own folder (
filesOfflineOverlapsStore()- storage moved from<P>/offlineto<P>): those are real stored files. -
Tidy rows - copies nothing covers are deleted (never one recorded after this run started); a
readyrow whose file is gone or the wrong size is forgotten, so the fill makes it again. -
Fill - covered files without a ready copy, in id order,
$batch(500) at a time. Failures are told apart:
| Failure | What happens |
|---|---|
FilesOfflineOutOfTime |
A big file: the .part is kept, the next run carries on from its size |
StorageUnavailable |
An outage: stop, every other copy would fail the same way. The .part is kept |
FilesOfflineDiskFull |
Stop and say so; the job always leaves $minFreeBytes (1 GB) |
| Anything else | This file's own problem (missing in S3, wrong checksum): failed, tried again after FILES_OFFLINE_RETRY_AFTER (a day) |
| The limit | Stop, set files_offline_limit_reached for the Storage tab |
-
Tidy the disk - files under
offline/no row records, and temporary copies older than a day. -
Roll up the folder ticks into
files_offline_folders: one grouped query (filesOfflineFolderRollup()), run even after the deadline.
filesStorageRoot($conn); // creates and guards the root (see Traps)
$tmp = $resume ? self::partFor($final) : self::tmpFor($final);
...
filesStoreFor($conn, $key)->readRange($key, $have, $size - 1, function (string $c) use ($fh, $deadlineUnix, &$outOfTime, &$writeFailed) { ... });
...
if ($got !== $size) throw new RuntimeException('copy did not match (size)');
if ($sha !== null && $sha !== '' && !hash_equals(strtolower($sha), hash_file('sha256', $tmp))) { ... }
if (!@rename($tmp, $final) && !filesOfflineHasCopy($conn, $key, $size)) { ... }
@touch($final);The job writes <key>.part and resumes it with a range read; a one-off copy writes <key>.<12 hex>.tmp. Only a copy that matches its size and SHA-256 is renamed into place.
A folder's tick is read from files_offline_folders - one indexed lookup of the viewer's folders below those on screen, never the files (300,000 files: 0.001 s per folder). Anything that can bring a file into a folder without a copy - a restore from the recycle bin, a move or copy in, Restore version, an upload whose copy did not land - calls:
FilesOfflineService::foldersChanged($conn, $folderIds); // state = 2 (pending) until the job has runupdated_datetime is to the millisecond so the rollup keeps a row marked pending after it began.
keepUploadCopy() runs before the upload is stored (the store may move the part away): a hard link when possible, otherwise a copy up to 64 MB, under a temporary name. commitUploadCopy() renames it into place only once the upload is saved, so a failed upload leaves no copy. Neither ever throws.
storageFolderChanged() runs inside the settings save, so it only writes rows. storageLocationRelation() decides:
| Relation | What happens |
|---|---|
same / none
|
Nothing |
different (proved) |
Copy rows forgotten; the old folder queued proven: true - the job deletes its copies in batches |
unknown |
Rows kept; the old folder queued proven: false - never emptied by itself. The Storage tab lists it with Remove, which probes again (removeOldRoot()) |
"Cannot tell" is never "different" - the same rule as the storage move (Files storage - The cleanup).
Nothing breaks. filesOfflineMarks() and filesOfflineUsage() return null on a missing table (filesOfflineMissingTable(): error 1146 / 42S02), so coverage is empty and the job does nothing; any change to a mark answers Run System → Database Verification first. (NEEDS_VERIFICATION). tests/files-offline.php proves it by renaming the tables for a while (and always putting them back).
-
TRAP: guard the storage root before creating
offline/. On an S3 install a custom storage folder may never have been created, because nothing local was ever stored. The first copy'smkdirthen made<root>/offlinewith no deny rules.copyKey()andkeepUploadCopy()callfilesStorageRoot($conn)first, which creates the root and runsuploadPrepareDir()on it, as a local store would. Added on merge (d18c6c94c). The defaultuploads/files/was already safe - its.htaccessandweb.configare in the repo. -
filesOfflineRoot()must stay side-effect free. Every S3 download calls it; creating the root there would make folders on installs that never use offline copies. - Never delete a copy inside the transaction. A rollback would bring the row back without the file. Delete after the commit.
-
A copy is trusted only at the right size. Anything that could leave a wrong-sized file at the final path must delete it (
tidyRows()does). -
Ids are written into SQL as integers, not placeholders, in
candidateSql()and the rollup: a big tree can cover more folders than a prepared statement allows placeholders (65,535). -
Paths are compared with forward slashes. The code normalises; a test comparing against
sys_get_temp_dir()must too (zzTempDir()- 4 checks failed on Windows before it).
tests/files-offline.php - 177 checks on ZZ fixtures in one rolled-back transaction, with a stand-in S3 driver that can be switched off. It covers coverage and the nearest effective mark (deactivated maker, access taken away), who may change marks, reads and the fallback when a copy vanishes, the job (fill, retries, outages, orphans, a run racing a change), uploads (hard link, limit, disk floor), exclusions, the Storage tab summary, ticks per viewer, moves back from S3, large copies over several runs, Overwrite / Restore version / the versions tidy-up, a new storage folder (proven and unproven), the lock, and bounded memory with 25,000 files. Two parts run on their own afterwards: before Database Verification (tables renamed and put back) and the endpoint over HTTP (FREEITSM_TEST_URL).
FREEITSM_TEST_DATABASE=<test db> FREEITSM_TEST_URL=http://localhost/<test install> php tests/files-offline.phpRun it on a test install only: it renames tables.
See also: Files - Developer Guide · Files storage - Developer Guide · Files recycle bin - Developer Guide · Code traps