Skip to content

json_store

panel_flowdash.json_store

A dashboard store that keeps each dashboard as a JSON file in a folder.

DASHBOARD_KIND = 'dashboard' module-attribute

MALFORMED_ERRORS = (KeyError, TypeError, ValueError, AttributeError, RecursionError) module-attribute

REPORT_KIND = 'report' module-attribute

_HISTORY_DIR = '.history' module-attribute

_LOCK_FILE = '.flowdash.lock' module-attribute

_REPLACE_PAUSE = 0.02 module-attribute

_REPLACE_TRIES = 5 module-attribute

_SAFE_ID = re.compile('[A-Za-z0-9][A-Za-z0-9._-]*\\Z') module-attribute

_STALE_RESERVATION_NS = 5000000000 module-attribute

__getattr__ = module_getattr(__name__, old_names(globals())) module-attribute

log = logging.getLogger(__name__) module-attribute

AssetModel dataclass

A persisted dashboard: nodes + edges + tile layout, and the turns that made them.

asset_id instance-attribute

breakpoints = field(default_factory=list) class-attribute instance-attribute

dashboard_id property writable

Deprecated alias of :attr:asset_id.

edges = field(default_factory=list) class-attribute instance-attribute

filters = field(default_factory=list) class-attribute instance-attribute

groups = field(default_factory=list) class-attribute instance-attribute

items = field(default_factory=list) class-attribute instance-attribute

kind = DASHBOARD_KIND class-attribute instance-attribute

owner property

The owner principal: the creating user, unless an admin gave it to someone else.

parameters = field(default_factory=dict) class-attribute instance-attribute

permission = field(default_factory=Permission) class-attribute instance-attribute

reference_width = None class-attribute instance-attribute

report = None class-attribute instance-attribute

responsive_layouts = field(default_factory=dict) class-attribute instance-attribute

revision = None class-attribute instance-attribute

settings = field(default_factory=dict) class-attribute instance-attribute

source = None class-attribute instance-attribute

tile_layout = field(default_factory=list) class-attribute instance-attribute

title instance-attribute

turns = field(default_factory=list) class-attribute instance-attribute

updated_at = field(default=None, compare=False) class-attribute instance-attribute

user_id instance-attribute

version = MODEL_VERSION class-attribute instance-attribute

from_dict(data) classmethod

Read a model from its dict, including one written before the rename with dashboard_id.

to_dict()

AssetStoreError

Bases: Exception

A store refused an operation for a reason the user should see.

Raise it from a :class:BaseAssetStore method to reject a request, for example a duplicate title, a name the backend cannot store or a missing permission. The app shows the message to the user as written and leaves its state unchanged, so phrase it for an end user. Any other exception is treated as a bug or an infrastructure failure and is logged with its traceback.

BaseAssetStore

Bases: ABC

The persistence interface the editor and app shell depend on.

Subclasses implement the six storage primitives below; the access-control and lookup helpers are backend-independent and inherited. Implement this to back dashboards with something other than SQLite.

To refuse a create, save, rename, delete or permission change, raise :class:AssetStoreError with a message for the user.

Stores that detect concurrent edits keep a revision per dashboard: every save stores dashboard.revision + 1 (see :func:check_revision), and a save based on an older revision than the stored one raises :class:AssetConflictError. A store that does not support revisions simply ignores the field and saves last-writer-wins.

Models returned by listings may be shared with a backend cache, so callers treat them as read-only; single-dashboard lookups return private copies.

Set :attr:random_ids to False in a store whose ids can be guessed.

random_ids = True class-attribute instance-attribute

Whether dashboard ids are random, so only someone given a link knows one.

The default :meth:create_asset makes random ids. A store whose ids can be guessed (derived from titles, say) sets this to False, and the app then answers a dashboard someone may not open exactly like a missing one, rather than saying it exists and who owns it. Even with random ids, an id a caller chose when saving (see :meth:guessable_id) is treated so.

all_assets(kind=None)

Every stored dashboard regardless of owner, most recently updated first.

kind keeps only assets of that kind ("dashboard", "report" or "chat"); None keeps every kind. No access check is applied: use :meth:list_accessible for what a user may open. Some stores hand out shared, cached models, so copy one (or load it with :meth:load_asset) before changing it. Custom stores implement :meth:_all_assets, not this method.

append_history(asset_id, record)

Add a record to the end of a dashboard's edit history.

Does nothing when the dashboard is not stored, e.g. because it was deleted while an editor still had it open.

can_administer(identity, asset_id, admin_groups=frozenset())

Whether identity may administer (rename/delete/share) the dashboard.

Administering includes editing, see :meth:can_edit.

can_administer_model(identity, dashboard, admin_groups=frozenset())

Like :meth:can_administer, for a dashboard that is already loaded.

Listings use it to avoid loading every dashboard a second time. Override this method, not :meth:can_administer, to change who may administer a dashboard.

can_edit(identity, asset_id, admin_groups=frozenset())

Whether identity may edit and save the dashboard's contents and settings.

can_edit_model(identity, dashboard, admin_groups=frozenset())

Like :meth:can_edit, for a dashboard that is already loaded.

Administrators (see :meth:can_administer_model) may always edit; anyone else needs an allow_edit_users/allow_edit_groups grant on the dashboard's permission. Override this method, not :meth:can_edit, to change who may edit a dashboard. A chat is edited only by its owner, administrators included.

create_asset(user_id, title, kind=DASHBOARD_KIND)

Create, persist and return a new empty dashboard (or chat or report, with kind).

A report starts with an empty document, so it never reads as the report a dashboard derives from its tiles.

delete_asset(user_id, asset_id) abstractmethod

Delete a dashboard owned by user_id. Returns whether one was removed.

delete_history(asset_id)

Drop a dashboard's edit history.

find_by_id_or_title(ref, identity=None, *, default_allow=True)

Resolve a dashboard by its id first, then by title.

Titles are only unique per user, so a title can match several dashboards. Without identity (trusted code, such as :meth:FlowDash.load) the most recently updated match is returned.

With identity, as when resolving the operator-configured home dashboard, a dashboard the identity may not open is never returned. The identity's own dashboard with that title wins. Otherwise a title owned by a single user resolves to that user's most recently updated dashboard, while a title owned by several users is ambiguous and resolves to None (the app then shows the launcher) with an error logged asking for the dashboard id. Picking one of them instead would let any user take over everyone's home page by creating a dashboard with the same title.

get_owner(asset_id)

Return the owner (user_id) of a dashboard, or None if missing.

guessable_id(asset_id)

Whether asset_id could be guessed rather than only learned from a link.

Only ids of the form :meth:create_asset makes count as random in a store with :attr:random_ids. Any store saves whatever id a model carries, so one chosen by the caller, like the slug an example seeds its dashboards under, can be guessed. A store whose own ids look different overrides this.

list_accessible(identity, *, default_allow=True, kind=DASHBOARD_KIND)

List dashboards of kind the identity owns or has been granted access to.

Chats are left out unless kind is "chat" or None, and only the identity's own chats are ever listed. Owned dashboards sort first (both groups by recency), so a user's own dashboards stay visually grouped ahead of ones shared with them.

list_assets(user_id, kind=DASHBOARD_KIND)

Dashboards of kind owned by user_id, most recently updated first.

Pass kind="chat" for the user's chats, kind="report" for their reports, or None for every kind.

load_asset(user_id, asset_id)

Load a dashboard, but only if user_id owns it.

load_for_access(identity, asset_id, *, default_allow=True)

Load a dashboard if identity is authorized, else None.

Returns None both when the dashboard does not exist and when access is denied, so callers render a single "not found / denied" view.

load_history(asset_id)

Return the edit history records of a dashboard, oldest first.

rename_asset(user_id, asset_id, new_title) abstractmethod

Retitle a dashboard owned by user_id. Returns whether one was updated.

replace_history(asset_id, records)

Replace a dashboard's edit history, e.g. with what retention keeps of it.

rewrite_history(asset_id, rewrite)

Replace a dashboard's history with what rewrite returns for it, and return that.

rewrite returns its argument itself when nothing changes, which writes nothing. Stores used by several sessions at once override this to read and write in one transaction, so no record appended meanwhile is lost.

save_asset(dashboard) abstractmethod

Insert or update a dashboard.

Stores that support revisions refuse a dashboard whose revision is not the stored one with :class:AssetConflictError, as one atomic check and write, and on success set dashboard.revision to the stored revision. Renaming a dashboard or changing its permission does not change its revision.

set_owner(asset_id, owner)

Give a dashboard to owner. Returns whether one was updated.

Only the admin view calls it, after checking that the caller is an admin. Like renaming, it does not change the dashboard's revision. A store that cannot change owners raises :class:AssetStoreError, as this default does.

set_permission(asset_id, permission) abstractmethod

Persist a new permission set on a dashboard. Returns success.

title_exists(user_id, title, exclude_id=None, kind=DASHBOARD_KIND)

Check if a dashboard of kind with the given title already exists for this user.

Identity dataclass

The resolved principal for a session.

groups = field(default_factory=frozenset) class-attribute instance-attribute

oauth_user = None class-attribute instance-attribute

system_user = None class-attribute instance-attribute

user instance-attribute

user_info = field(default_factory=dict) class-attribute instance-attribute

user_names property

All names this identity may be referenced by in a rule.

in_groups(groups)

Whether the identity belongs to any of groups.

is_user(users)

Whether the identity matches any of users (OAuth or system name).

JSONFolderAssetStore

Bases: BaseAssetStore

Stores each dashboard as <folder>/<asset_id>.json.

The files are plain, human-readable AssetModel JSON, so a folder can be reviewed, diffed and versioned alongside the project that serves it, or shipped read-only with a deployment. Every listing scans the folder, so files edited or added outside the application show up on the next request; only files whose size, modification time or inode changed since the last listing are parsed again. Models returned by listings are shared with that cache and must not be mutated; load_asset and the other single dashboard lookups return a private copy.

New dashboards get an id derived from their title (Sales Overview becomes sales-overview, then sales-overview-2 and so on), which keeps file names and /asset/<id> URLs readable. A file whose asset_id differs from its name, or that cannot be parsed, is skipped with one warning.

Writes are atomic, so a reader never sees a half-written file. Several server processes may share a folder: creating a dashboard claims its id exclusively, and the other writes hold an advisory lock on the folder (on Windows on a .flowdash.lock file in it) while they check the file they replace. Saving never replaces a file that belongs to another user, and each file stores a revision that saving checks and increments, so a save based on an outdated copy raises :class:AssetConflictError. Edit the files by hand only while no server writes to the folder; a hand edit that keeps the revision is not detected as a conflict.

A store over several folders, for example a read-only shared folder and a per-user one, can delegate to one store per folder: :meth:scan lists a folder's files with their parsed models and :meth:parse_file parses one file, both skipping unusable files with the warning described above.

Parameters:

Name Type Description Default
path str | Path

The folder holding the dashboard files. Created if missing unless read_only is set or create is False.

required
create bool

Create the folder if it is missing. With False the store never creates it: while it is missing the store lists no dashboards and writes raise an AssetStoreError (also a FileNotFoundError) naming the folder.

True
read_only bool

Serve the dashboards without allowing changes. Writes raise PermissionError (also an AssetStoreError) and nobody may edit or administer a dashboard, so the editor offers no way to modify, rename, share or delete one.

False

path = Path(path) instance-attribute

random_ids = False class-attribute instance-attribute

read_only = read_only instance-attribute

append_history(asset_id, record)

can_administer_model(identity, dashboard, admin_groups=frozenset())

can_edit_model(identity, dashboard, admin_groups=frozenset())

create_asset(user_id, title, kind=DASHBOARD_KIND)

delete_asset(user_id, asset_id)

delete_history(asset_id)

load(asset_id)

Load a dashboard by id whoever owns it, or None if it is missing or unusable.

Ids that cannot be file names give None without touching the disk. No access check is applied.

load_history(asset_id)

parse_file(path)

Parse one dashboard file, or return None if it cannot be used.

A file that is malformed, holds another dashboard id than its name or was left empty by a crashed writer is logged once with its path and the reason. The model is a private copy, not shared with the cache of :meth:scan. Raises OSError if the file cannot be read.

Does not check that path is inside the folder: build paths from :meth:scan, or use :meth:load to look a dashboard up by id.

rename_asset(user_id, asset_id, new_title)

replace_history(asset_id, records)

rewrite_history(asset_id, rewrite)

save_asset(dashboard)

Write dashboard, refusing to replace a file another user owns.

Raises :class:AssetConflictError if the file holds a different revision than dashboard was loaded at.

scan()

Every usable dashboard file in the folder with its model, most recently updated first.

Only files whose size, modification time or inode changed since the last scan are parsed again, so the models are shared with that cache and must not be mutated. Files that cannot be used are left out and logged as :meth:parse_file describes; a missing or unreadable folder gives an empty list.

set_owner(asset_id, owner)

set_permission(asset_id, permission)

Permission dataclass

An allow/deny rule set evaluated against an :class:Identity.

The rule fields match either the resolved user (OAuth login or system user) or one of the identity's groups. An empty Permission declares no constraints and defers entirely to the caller's default policy.

allow_edit_users and allow_edit_groups only apply to dashboards: they grant editing (which includes viewing) on top of the view rules, without restricting who else may view.

allow_edit_groups = field(default_factory=frozenset) class-attribute instance-attribute

allow_edit_users = field(default_factory=frozenset) class-attribute instance-attribute

allow_groups = field(default_factory=frozenset) class-attribute instance-attribute

allow_users = field(default_factory=frozenset) class-attribute instance-attribute

deny_groups = field(default_factory=frozenset) class-attribute instance-attribute

deny_users = field(default_factory=frozenset) class-attribute instance-attribute

is_empty property

Whether the permission declares no allow, deny or edit rules.

from_dict(data) classmethod

Deserialize from a (possibly None or partial) mapping.

from_spec(*, allow_users=None, allow_groups=None, deny_users=None, deny_groups=None, allow_edit_users=None, allow_edit_groups=None) classmethod

Build a :class:Permission from loosely-typed iterables.

grants_edit(identity)

Whether an edit rule names identity; deny rules are not consulted.

to_dict()

Serialize to sorted lists for JSON persistence.

_MissingFolderError

Bases: AssetStoreError, FileNotFoundError

_ReadOnlyError

Bases: AssetStoreError, PermissionError

_claim(tmp, target)

Move tmp to target, raising FileExistsError instead of replacing it.

_decode_revision(value)

Return a stored revision, or None (no conflict check) if it is not an integer.

_lock_file(fd)

_replace(tmp, target)

_slug(title)

_unlock_file(fd)

blank_report()

Return the document a new report starts with: no blocks.

check_revision(dashboard, stored)

Return the revision to store dashboard at, given the stored one.

Raises :class:AssetConflictError if dashboard was loaded at a revision other than the stored one. A model with no revision (None) is saved unconditionally, and stored is None when the dashboard is not stored (new, or deleted since it was loaded).

decode_filters(value)

Return the filters a stored dashboard holds, empty if none; ValueError when malformed.

decode_groups(value)

Return the groups a stored dashboard holds, raising ValueError when malformed.

A node in more than one group stays in the first, and groups left with no node are dropped.

decode_kind(value)

Return the stored value as a dashboard kind; missing reads as a dashboard.

decode_parameters(value)

Return stored parameters, which may be missing (None), by name.

Raises TypeError unless they are a mapping, and :class:ParameterError for a malformed parameter. Parameters are optional, so the stores catch this and drop just the parameters, with a warning.

decode_report(value)

Return the report a stored dashboard holds, None if it has none; ValueError when malformed.

decode_settings(value)

Return a private copy of stored dashboard settings, which may be missing (None).

Raises TypeError unless they are a mapping with string keys. Settings are optional, so the stores catch this and drop just the settings, with a warning, rather than skipping the whole dashboard.

decode_turns(value)

Return stored turns, which may be missing (None), as a list of :class:AssetTurn.

Raises TypeError unless they are a list, and :class:TurnError for a malformed turn or two turns with the same id. Turns are optional, so the stores catch this and drop just the turns, with a warning, rather than skipping the whole dashboard.

initial_permission(user_id, kind)

Return the permission a new dashboard of kind starts with.

A chat starts allowed to its owner alone, so a store that drops kind turns it into a dashboard only its owner may open rather than one everybody may.

module_getattr(module, names)

Return a module __getattr__ resolving deprecated names (old to new) with a warning.

old_names(module_globals)

Return the deprecated class names a module keeps, old to new, for its own new classes.