Atomic-write JSON configuration backend. More...
#include <PhosphorConfig/JsonBackend.h>
Public Types | |
| enum class | Load { Now , Deferred } |
| When the constructor reads the file. More... | |
| enum class | SyncPolicy { Synchronous , Deferred } |
Sync timing policy. See setSyncPolicy for the full contract. More... | |
Public Member Functions | |
| JsonBackend (QString filePath, Load load=Load::Now) | |
Construct a backend backed by filePath. | |
| ~JsonBackend () override | |
| std::unique_ptr< IGroup > | group (const QString &name) override |
| Return a scoped view into the named group. | |
| std::unique_ptr< IGroup > | persistedGroup (const QString &name) override |
A JsonGroup opened as JsonGroup::View::Persisted: the file's values without the overlay. | |
| void | reparseConfiguration () override |
| Reloads the file. | |
| QString | reload () |
Reloads the file as reparseConfiguration does, for a caller that reports problems itself: nothing is logged, and the reason the file could not be read is returned (empty when it could). | |
| bool | loadFailed () const override |
Whether the most recent load (construction or reparseConfiguration), or a flush that found the store rewritten since, found a backing store it could not read: unreadable, malformed, or of the wrong shape. | |
| bool | blankFile () const |
| The most recent load found a file of only white space, which reads as an empty document. | |
| void | setOverwriteUnreadable (bool overwrite) |
| Let writes replace an unreadable file instead of refusing. | |
| bool | sync () override |
| Request that pending writes reach disk. | |
| bool | commit () override |
| Bypasses the Deferred sync policy's debounce so the return value is a real commit result under every policy. | |
| void | deleteGroup (const QString &name) override |
| Delete an entire group and everything inside it. | |
| QString | readRootString (const QString &key, const QString &defaultValue={}) const override |
| Sees the overlay's root-group values over the file's. | |
| void | writeRootString (const QString &key, const QString &value) override |
| void | removeRootKey (const QString &key) override |
| QStringList | groupList () const override |
| Enumerates the file's groups and the overlay's together, as one document with the overlay merged in. | |
| void | setOverlay (const QJsonObject &overlay) |
Lay overlay over the file for every read, without ever writing it. | |
| QJsonObject | overlay () const |
| The overlay last set, or an empty object. | |
| void | setPathResolver (std::shared_ptr< IGroupPathResolver > resolver) override |
| Attach a custom path resolver. | |
| std::shared_ptr< IGroupPathResolver > | pathResolver () const override |
Currently-installed resolver, or nullptr when none is set (also the default for backends that ignore setPathResolver). | |
| void | setRootGroupName (const QString &name) |
Change the JSON object that receives ungrouped writeRootString calls. | |
| QString | rootGroupName () const |
| void | setVersionStamp (const QString &key, int version) override |
Stamp-on-sync: if non-empty, every sync() that writes the file will insert key = version when the key is absent from the root. | |
| std::pair< QString, int > | versionStamp () const override |
Currently-installed version stamp as {key, version}. | |
| void | applyVersionStamp (QJsonObject &root) const |
Insert the installed version stamp into root when a stamp is configured and root does not already carry the key. | |
| bool | applyMigration (const Schema &schema) override |
Run schema's migration chain against the in-memory root, and if any step bumps the version stamp, atomically rewrite the backing file and refresh the in-memory state. | |
| QJsonObject | jsonRootSnapshot () const |
| Read-only access to the in-memory document. | |
| QString | filePath () const |
Backing file path (useful for migration-chain callers that need to rewrite via writeJsonAtomically during schema upgrades). | |
| void | clearDirty () |
| Clear the dirty flag without writing. | |
| bool | isDirty () const override |
| Whether the in-memory document carries changes that have not been committed to disk. | |
| void | replaceRoot (QJsonObject root) |
Replace the in-memory document with root. | |
| void | setSyncPolicy (SyncPolicy policy, int debounceMs=500) |
Configure when sync() commits to disk. | |
| SyncPolicy | syncPolicy () const |
| bool | flushPending () |
| Flush to disk now, cancelling any pending deferred-sync timer first. | |
| Public Member Functions inherited from PhosphorConfig::IBackend | |
| virtual | ~IBackend ()=default |
| IBackend (const IBackend &)=delete | |
| IBackend & | operator= (const IBackend &)=delete |
Static Public Member Functions | |
| static bool | writeJsonAtomically (const QString &filePath, const QJsonObject &root) |
Atomically write root to filePath (temp file + rename via QSaveFile). | |
Additional Inherited Members | |
| Protected Member Functions inherited from PhosphorConfig::IBackend | |
| IBackend ()=default | |
Atomic-write JSON configuration backend.
Reads and writes a single JSON document. Writes are deferred until sync() is called and then committed via QSaveFile (temp file + rename, safe against crashes and power loss).
Group resolution order:
IGroupPathResolver is installed and returns a path, use it.The "root group" (see rootGroupName) holds ungrouped keys written via writeRootString. Defaults to "General" for compatibility with QSettings INI behaviour.
An optional in-memory overlay (see setOverlay) supplies values that win over the file's for every read but are never written to it.
|
strong |
When the constructor reads the file.
| Enumerator | |
|---|---|
| Now | In the constructor, logging a file it cannot read. |
| Deferred | Not until reparseConfiguration() or reload(): for a caller that reloads at once and reports problems itself, so the file is read once. Until then the backend is empty and refuses writes. |
|
strong |
Sync timing policy. See setSyncPolicy for the full contract.
| Enumerator | |
|---|---|
| Synchronous |
Default — matches the pre-policy behaviour so switching an existing consumer requires no change. |
| Deferred |
The actual flush happens on the timer's timeout, on the same thread that owns the backend (i.e. whichever thread is pumping the event loop that owns the timer). Callers that need a guaranteed-committed state before proceeding (e.g. closing a save dialog, shutting down a daemon) call Requires a running event loop to actually fire. Tests that exercise this path must call |
Construct a backend backed by filePath.
The file is loaded now, or with load Deferred at the first reload. A missing file, or one that holds only white space, starts with an empty root object and accepts writes. An unreadable one (open failure, parse error, a non-object root) also starts empty but reports loadFailed() and refuses writes (unless setOverwriteUnreadable), with a warning logged. A flush also refuses when the file has been rewritten since this backend last read or wrote it and no longer reads.
|
override |
|
overridevirtual |
Run schema's migration chain against the in-memory root, and if any step bumps the version stamp, atomically rewrite the backing file and refresh the in-memory state.
Returns true unless the atomic disk rewrite fails or is refused because loadFailed() is set. In either case the backend stays at the unmigrated state, and the chain runs again from the next Store built over a fresh load. Consumers that need the "did migrations actually apply" bit should check versionStamp() before and after, not this return value.
Reimplemented from PhosphorConfig::IBackend.
| void PhosphorConfig::JsonBackend::applyVersionStamp | ( | QJsonObject & | root | ) | const |
Insert the installed version stamp into root when a stamp is configured and root does not already carry the key.
No-op otherwise.
This is the same step sync() applies on its way to disk, exposed so that a caller writing a root snapshot out of band (an export, say) can stamp it identically. A document written without the stamp reads back as version-less and re-runs the whole migration chain when it is imported.
| bool PhosphorConfig::JsonBackend::blankFile | ( | ) | const |
The most recent load found a file of only white space, which reads as an empty document.
An editor that saves in place empties the file before it writes, so a caller can keep its settings rather than take that for a file with no settings.
| void PhosphorConfig::JsonBackend::clearDirty | ( | ) |
Clear the dirty flag without writing.
Used by migration (applyMigration) and by callers that stage something into the root, take a snapshot of it, then restore the root and need to put the flag back the way they found it (see isDirty()).
|
overridevirtual |
Bypasses the Deferred sync policy's debounce so the return value is a real commit result under every policy.
Equivalent to flushPending().
Reimplemented from PhosphorConfig::IBackend.
|
overridevirtual |
Delete an entire group and everything inside it.
Intermediate parents are pruned if they become empty (dot-path groups only).
Implements PhosphorConfig::IBackend.
| QString PhosphorConfig::JsonBackend::filePath | ( | ) | const |
Backing file path (useful for migration-chain callers that need to rewrite via writeJsonAtomically during schema upgrades).
| bool PhosphorConfig::JsonBackend::flushPending | ( | ) |
Flush to disk now, cancelling any pending deferred-sync timer first.
No-op only when the backend is not dirty — under Synchronous policy there is no timer to cancel, but a dirty root is still written, so this is a commit under every policy rather than a Deferred-only escape hatch. Returns the commit result (or true when there was nothing to flush). Safe to call from any context that could call sync().
|
overridevirtual |
Return a scoped view into the named group.
Caller owns the pointer; destroy it before asking for another group on this backend.
Implements PhosphorConfig::IBackend.
|
overridevirtual |
Enumerates the file's groups and the overlay's together, as one document with the overlay merged in.
Implements PhosphorConfig::IBackend.
|
overridevirtual |
Whether the in-memory document carries changes that have not been committed to disk.
Pairs with clearDirty() for callers that snapshot/restore the root (see jsonRootSnapshot / replaceRoot) and need to put the flag back the way they found it.
Reimplemented from PhosphorConfig::IBackend.
| QJsonObject PhosphorConfig::JsonBackend::jsonRootSnapshot | ( | ) | const |
Read-only access to the in-memory document.
Implicitly shared (COW), so the copy is cheap and isolated from future mutations. This is the backend's own document: the file as last read or written, or, while loadFailed() is set, the last good document standing in for it. The overlay is not merged in.
|
overridevirtual |
Whether the most recent load (construction or reparseConfiguration), or a flush that found the store rewritten since, found a backing store it could not read: unreadable, malformed, or of the wrong shape.
A missing store is a first run, not a failure.
While this is set the in-memory document is a stand-in, not what the store holds, so implementations refuse sync() / commit() rather than overwrite the unreadable content, and readers should not treat what they read as a fresh view of disk. Default false, for backends with no load step to fail.
Reimplemented from PhosphorConfig::IBackend.
| QJsonObject PhosphorConfig::JsonBackend::overlay | ( | ) | const |
The overlay last set, or an empty object.
|
overridevirtual |
Currently-installed resolver, or nullptr when none is set (also the default for backends that ignore setPathResolver).
Reimplemented from PhosphorConfig::IBackend.
|
overridevirtual |
A JsonGroup opened as JsonGroup::View::Persisted: the file's values without the overlay.
Reimplemented from PhosphorConfig::IBackend.
|
overridevirtual |
Sees the overlay's root-group values over the file's.
Implements PhosphorConfig::IBackend.
| QString PhosphorConfig::JsonBackend::reload | ( | ) |
Reloads the file as reparseConfiguration does, for a caller that reports problems itself: nothing is logged, and the reason the file could not be read is returned (empty when it could).
A clean read ends the refusal that an earlier unreadable load or flush set, and takes the file's stamp, so the next flush compares against this read.
|
overridevirtual |
Implements PhosphorConfig::IBackend.
|
overridevirtual |
Reloads the file.
The overlay is kept and keeps winning over the reloaded values. On an unreadable file the root falls back to the last document this backend read or wrote successfully (empty if none), and loadFailed() turns on until a later reparse reads the file cleanly.
Implements PhosphorConfig::IBackend.
| void PhosphorConfig::JsonBackend::replaceRoot | ( | QJsonObject | root | ) |
Replace the in-memory document with root.
Marks the backend dirty — callers who paired this with a successful writeJsonAtomically may call clearDirty() immediately after to restore the "in-memory matches disk" invariant. Must not be called while any JsonGroup views are alive.
| QString PhosphorConfig::JsonBackend::rootGroupName | ( | ) | const |
| void PhosphorConfig::JsonBackend::setOverlay | ( | const QJsonObject & | overlay | ) |
Lay overlay over the file for every read, without ever writing it.
overlay has the same shape as the file's document: group objects keyed by name (nested for dot-path groups, under rootGroupName for root keys, wherever an installed IGroupPathResolver maps a group), holding keys and values. Reads behave as if overlay had been merged into the document, objects merging key by key at every depth (an object-valued key included) and any other overlay value replacing the file's outright. That covers every read: the JsonGroup readers, hasKey and keyList, readRootString, groupList, and so everything Store reads through them.
Nothing else sees it. Writes, deleteKey, deleteGroup and the root key mutators act on the file's values alone, so writing one key of a group never carries the group's overlay values to disk with it. sync, commit, jsonRootSnapshot, replaceRoot and applyMigration work on the backend's own document alone (the file as last read or written, or the last good stand-in while loadFailed() is set), so the overlay must already be in the current schema's shape. It is not dirtying: setting it schedules no write. It survives reparseConfiguration and lasts until replaced; an empty object removes it.
Safe to call while a group view is alive: views resolve the overlay on every read rather than caching it.
| void PhosphorConfig::JsonBackend::setOverwriteUnreadable | ( | bool | overwrite | ) |
Let writes replace an unreadable file instead of refusing.
For a file only machines write, such as session state, where an unreadable copy holds nothing worth protecting and refusing would only lose the next save. Off by default: a file a user may edit by hand is protected.
|
overridevirtual |
Attach a custom path resolver.
Passing nullptr removes it. Safe to call at any time; the resolver is consulted on every group access, so it should be cheap.
Reimplemented from PhosphorConfig::IBackend.
| void PhosphorConfig::JsonBackend::setRootGroupName | ( | const QString & | name | ) |
Change the JSON object that receives ungrouped writeRootString calls.
Defaults to "General". Call before the first write.
| void PhosphorConfig::JsonBackend::setSyncPolicy | ( | SyncPolicy | policy, |
| int | debounceMs = 500 ) |
Configure when sync() commits to disk.
debounceMs is only consulted for Deferred policy; it sets the coalescing window during which repeated sync() calls restart the same timer. Values <= 0 are clamped to 1 ms.
Safe to call at any time. Switching from Deferred back to Synchronous also flushes any pending deferred write so the in-memory and on-disk state agree on return.
|
overridevirtual |
Stamp-on-sync: if non-empty, every sync() that writes the file will insert key = version when the key is absent from the root.
Used by consumers who pair a JsonBackend with a Schema so fresh stores carry the current version from day one. Default disables the behaviour (empty key).
Reimplemented from PhosphorConfig::IBackend.
|
overridevirtual |
Request that pending writes reach disk.
No-op when nothing is dirty. Returns true on success (or when there was nothing to flush), false on an I/O error or a refusal while loadFailed() is set — backends log the reason before returning.
true means "accepted", NOT "committed": a backend is free to satisfy this by scheduling the write (JsonBackend's Deferred sync policy debounces it), in which case the write has not happened yet and may still fail. Callers that must know the bytes landed — anything moving a baseline or reporting success to a user — call commit() instead.
Implements PhosphorConfig::IBackend.
| SyncPolicy PhosphorConfig::JsonBackend::syncPolicy | ( | ) | const |
|
overridevirtual |
Currently-installed version stamp as {key, version}.
Returns an empty key when no stamp is installed. Used by shared-backend safety checks (see Store::Store) to detect a clobber.
Reimplemented from PhosphorConfig::IBackend.
|
static |
Atomically write root to filePath (temp file + rename via QSaveFile).
Exposed for use by MigrationRunner and other external callers that already have a QJsonObject in hand. Returns true on success.
|
overridevirtual |
Implements PhosphorConfig::IBackend.