Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

perf(api): $select/$filter/$orderby/$skip/$top, and opt /apps in

Juan Deniscf7c20864f65
diff --git a/backend/app/api/_query.py b/backend/app/api/_query.py
new file mode 100644
index 00000000..9e0879bd
--- /dev/null
+++ b/backend/app/api/_query.py
@@ -0,0 +1,294 @@
+"""Shared list-query layer: ``$select`` / ``$filter`` / ``$orderby`` / ``$skip`` / ``$top``.
+
+Ported from the author's ``conuco_v2`` query layer, with two deliberate changes.
+
+**ORM, not Core.** conuco resolves columns through ``table.c``; ServerKit is
+Flask-SQLAlchemy ORM, so fields resolve against the mapper's column set. That
+set is also the allowlist — a field that is not a real mapped column is a 400,
+never an ``getattr`` into arbitrary model attributes.
+
+**``$select`` is not only a column narrowing.** This is where the actual win is
+here. ``Application.to_dict()`` costs roughly three extra queries per row on top
+of the row itself: ``image_scans.first()`` and ``image_update_checks.first()``
+are ``lazy='dynamic'`` relationships (immune to eager loading — a dynamic
+attribute *is* a Query), and ``sleep_policy`` / ``server`` / ``project`` /
+``environment`` are lazy scalars. Drawing a 100-app list is ~300 queries. So
+``parse_select`` hands back a *field set* that ``to_dict`` uses to skip the
+loads it was not asked for: ``$select=id,name`` goes from 3 queries per row to
+zero extra ones.
+
+Not implemented here: ``$view``. conuco resolves a named server-side view into
+default ``$filter``/``$orderby``/``$select``, but ServerKit's saved views are
+per-user rows already resolved in the browser (see
+``components/ds/grid/viewState.js``) — the grid knows the concrete config and
+can serialize it, so a second server-side copy of the same concept would be a
+place for the two to disagree.
+
+Usage::
+
+ from app.api._query import apply_query
+
+ q = apply_query(Application.query, Application, request)
+ apps = q.query.all()
+ return jsonify({'apps': [a.to_dict(fields=q.fields) for a in apps]})
+
+Every parameter is optional: with none of them present this is a no-op and the
+endpoint behaves exactly as it did before.
+"""
+
+import re
+from datetime import datetime, timedelta
+
+from sqlalchemy import and_, or_, inspect
+
+# Hard ceiling on ``$top``. A list endpoint that answers "give me everything"
+# is how /apps got to an unbounded ``query.all()``; a caller that genuinely
+# wants more than this should page.
+MAX_TOP = 500
+
+COMPARE_OPS = {
+ 'eq': lambda col, val: col == val,
+ 'ne': lambda col, val: col != val,
+ 'gt': lambda col, val: col > val,
+ 'ge': lambda col, val: col >= val,
+ 'lt': lambda col, val: col < val,
+ 'le': lambda col, val: col <= val,
+}
+
+
+class QueryParseError(ValueError):
+ """A malformed query parameter. API layers turn this into a 400."""
+
+
+def _columns(model):
+ """The model's real mapped columns — and the field allowlist."""
+ return {c.key: getattr(model, c.key) for c in inspect(model).mapper.column_attrs}
+
+
+def _column(model, field):
+ field = (field or '').strip()
+ cols = _columns(model)
+ if field not in cols:
+ raise QueryParseError(f"Unknown field '{field}' for '{model.__tablename__}'.")
+ return cols[field]
+
+
+def _coerce(value):
+ """Literal -> Python. Quoted stays a string; bare words get typed."""
+ value = value.strip()
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
+ return value[1:-1]
+ low = value.lower()
+ if low == 'true':
+ return True
+ if low == 'false':
+ return False
+ if low in ('null', 'none'):
+ return None
+ try:
+ return int(value)
+ except ValueError:
+ pass
+ try:
+ return float(value)
+ except ValueError:
+ return value
+
+
+# ---------------------------------------------------------------- $filter
+
+_FUNCS = (
+ ('contains', r"contains\(([^,]+),\s*['\"]([^'\"]*)['\"]\)",
+ lambda col, v: col.ilike(f'%{v}%')),
+ ('startswith', r"startswith\(([^,]+),\s*['\"]([^'\"]*)['\"]\)",
+ lambda col, v: col.ilike(f'{v}%')),
+ ('endswith', r"endswith\(([^,]+),\s*['\"]([^'\"]*)['\"]\)",
+ lambda col, v: col.ilike(f'%{v}')),
+)
+
+
+def _parse_function(condition, model):
+ """A function-call condition, or None if this isn't one."""
+ for _name, pattern, build in _FUNCS:
+ match = re.findall(pattern, condition)
+ if match:
+ field, value = match[0]
+ return build(_column(model, field), value)
+
+ match = re.findall(r'notempty\(([^)]+)\)', condition)
+ if match:
+ col = _column(model, match[0])
+ return and_(col.isnot(None), col != '')
+
+ match = re.findall(r"date\(([^,]+),\s*['\"]([^'\"]*)['\"]\)", condition)
+ if match:
+ field, value = match[0]
+ try:
+ day = datetime.strptime(value.strip(), '%Y-%m-%d')
+ except ValueError as exc:
+ raise QueryParseError(f"date() needs YYYY-MM-DD, got '{value}'.") from exc
+ col = _column(model, field)
+ return and_(col >= day, col < day + timedelta(days=1))
+
+ match = re.findall(r'daysAgo\(([^,]+),\s*([^)]+)\)', condition)
+ if match:
+ field, raw = match[0]
+ try:
+ days = int(raw.strip())
+ except ValueError as exc:
+ raise QueryParseError(f"daysAgo() needs an integer, got '{raw}'.") from exc
+ return _column(model, field) >= datetime.utcnow() - timedelta(days=days)
+
+ return None
+
+
+def _parse_condition(condition, model):
+ built = _parse_function(condition, model)
+ if built is not None:
+ return built
+
+ match = re.match(r'^\s*(\S+)\s+(eq|ne|gt|ge|lt|le)\s+(.+?)\s*$', condition)
+ if not match:
+ raise QueryParseError(f"Could not parse condition '{condition.strip()}'.")
+ field, op, raw = match.groups()
+ return COMPARE_OPS[op](_column(model, field), _coerce(raw))
+
+
+def parse_filter(filter_str, model):
+ """``$filter`` -> a WHERE clause, or None.
+
+ One combiner per string (``and`` OR ``or``, not both) — same restriction as
+ the original. Mixing them without parentheses is ambiguous, and silently
+ picking a precedence is worse than refusing.
+ """
+ if not filter_str or not filter_str.strip():
+ return None
+
+ has_and = re.search(r'\s+and\s+', filter_str, re.IGNORECASE)
+ has_or = re.search(r'\s+or\s+', filter_str, re.IGNORECASE)
+ if has_and and has_or:
+ raise QueryParseError("Mixing 'and' with 'or' needs separate requests — it is ambiguous here.")
+
+ combiner, pattern = (or_, r'\s+or\s+') if has_or else (and_, r'\s+and\s+')
+ parts = [p for p in re.split(pattern, filter_str, flags=re.IGNORECASE) if p.strip()]
+ clauses = [_parse_condition(p, model) for p in parts]
+ if not clauses:
+ return None
+ return clauses[0] if len(clauses) == 1 else combiner(*clauses)
+
+
+# --------------------------------------------------------------- $orderby
+
+def parse_orderby(orderby_str, model):
+ """``$orderby=name asc,created_at desc`` -> a list of ORDER BY clauses."""
+ if not orderby_str or not orderby_str.strip():
+ return []
+ out = []
+ for part in orderby_str.split(','):
+ bits = part.strip().split()
+ if not bits:
+ continue
+ col = _column(model, bits[0])
+ direction = (bits[1] if len(bits) > 1 else 'asc').lower()
+ if direction not in ('asc', 'desc'):
+ raise QueryParseError(f"Sort direction must be asc or desc, got '{direction}'.")
+ out.append(col.desc() if direction == 'desc' else col.asc())
+ return out
+
+
+# ---------------------------------------------------------------- $select
+
+def parse_select(select_str, model, extra=()):
+ """``$select`` -> the requested field set, or None for "everything".
+
+ `extra` names DERIVED fields a model's ``to_dict`` can emit that are not
+ mapped columns (``project_name``, ``image_scan``, ``domains``…). They are
+ accepted here so a caller can ask for one, and it is precisely by NOT
+ asking that the caller skips its lazy load.
+ """
+ if not select_str or not select_str.strip():
+ return None
+ allowed = set(_columns(model)) | set(extra)
+ fields = set()
+ for raw in select_str.split(','):
+ name = raw.strip()
+ if not name:
+ continue
+ if name not in allowed:
+ raise QueryParseError(f"Unknown field '{name}' for '{model.__tablename__}'.")
+ fields.add(name)
+ # The primary key always comes back — a row the client cannot identify is
+ # not much use, and every UI keys its rows on it.
+ pk = inspect(model).mapper.primary_key
+ for col in pk:
+ fields.add(col.key)
+ return fields
+
+
+# ------------------------------------------------------------- apply_query
+
+class QueryResult:
+ """The narrowed query plus what the caller needs to serialize it."""
+
+ __slots__ = ('query', 'fields', 'skip', 'top', 'total')
+
+ def __init__(self, query, fields, skip, top, total):
+ self.query = query
+ self.fields = fields
+ self.skip = skip
+ self.top = top
+ self.total = total
+
+ def as_meta(self):
+ """Paging metadata for the response envelope."""
+ return {'total': self.total, 'skip': self.skip, 'top': self.top}
+
+
+def apply_query(query, model, request, *, default_top=None, select_extra=()):
+ """Apply the query params present on `request` to `query`.
+
+ Returns a :class:`QueryResult`. With no params present this is a no-op and
+ ``.fields`` is None, so an endpoint can adopt it without changing any
+ existing caller's response.
+
+ `default_top` bounds an endpoint that has no explicit ``$top``; leave it
+ None to keep today's unbounded behaviour while callers migrate.
+ """
+ args = request.args
+ where = parse_filter(args.get('$filter'), model)
+ if where is not None:
+ query = query.filter(where)
+
+ order = parse_orderby(args.get('$orderby'), model)
+ if order:
+ query = query.order_by(*order)
+
+ fields = parse_select(args.get('$select'), model, extra=select_extra)
+
+ # `total` is the count BEFORE paging — the client needs it to render "12 of
+ # 340", and computing it after .limit() would just return the page size.
+ total = None
+ skip = _int_arg(args.get('$skip'), 0, '$skip')
+ top = _int_arg(args.get('$top'), default_top, '$top')
+ if top is not None:
+ top = max(0, min(top, MAX_TOP))
+ if skip or top is not None:
+ total = query.order_by(None).count()
+ if skip:
+ query = query.offset(skip)
+ if top is not None:
+ query = query.limit(top)
+
+ return QueryResult(query, fields, skip, top, total)
+
+
+def _int_arg(raw, fallback, name):
+ if raw is None or raw == '':
+ return fallback
+ try:
+ value = int(raw)
+ except (TypeError, ValueError) as exc:
+ raise QueryParseError(f'{name} must be an integer.') from exc
+ if value < 0:
+ raise QueryParseError(f'{name} cannot be negative.')
+ return value
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index 31e04fed..661e3356 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -8,7 +8,9 @@ import shutil
from datetime import datetime
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
+from sqlalchemy.orm import joinedload
from app import db
+from app.api._query import apply_query, QueryParseError
from app.models import Application, User
from app.utils.slug import slugify
from app.services.build_service import BuildService
@@ -436,15 +438,49 @@ def get_apps():
if environment_filter:
query = query.filter_by(environment_type=environment_filter)
+ # $select / $filter / $orderby / $skip / $top. All optional: with none of
+ # them present this is a no-op and the response is byte-identical to before.
+ try:
+ narrowed = apply_query(query, Application, request,
+ select_extra=Application.DERIVED_FIELDS)
+ except QueryParseError as exc:
+ return jsonify({'error': str(exc)}), 400
+ query = narrowed.query
+ fields = narrowed.fields
+
+ # Eager-load the scalar relationships to_dict resolves names through, but
+ # ONLY when this request actually asked for those names — a joinedload for a
+ # field nobody selected is a wider row for nothing. `image_scans` and
+ # `image_update_checks` are deliberately absent: they are lazy='dynamic',
+ # so the attribute IS a Query and no loader option can hoist it. Declining
+ # them via $select is the only way to avoid their per-row cost.
+ eager = []
+ if fields is None or 'server_name' in fields:
+ eager.append(joinedload(Application.server))
+ if fields is None or 'project_name' in fields:
+ eager.append(joinedload(Application.project))
+ if fields is None or 'environment_name' in fields:
+ eager.append(joinedload(Application.environment))
+ if include_linked and (fields is None or 'linked_app' in fields):
+ eager.append(joinedload(Application.linked_app))
+ if eager:
+ query = query.options(*eager)
+
apps = query.all()
deploy_configs = GitService.get_config().get('apps', {})
- return jsonify({
+ payload = {
'apps': [
- _attach_deploy_config(app.to_dict(include_linked=include_linked), deploy_configs)
+ _attach_deploy_config(
+ app.to_dict(include_linked=include_linked, fields=fields), deploy_configs)
for app in apps
]
- }), 200
+ }
+ # Paging metadata only appears once a caller pages, so the existing
+ # response shape is untouched for everyone who does not.
+ if narrowed.total is not None:
+ payload['meta'] = narrowed.as_meta()
+ return jsonify(payload), 200
@apps_bp.route('/<int:app_id>/workspace', methods=['PUT'])
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index 193b24c4..42f48022 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -131,8 +131,33 @@ class Application(db.Model):
"""
return [d for d in self.domains if getattr(d, 'deleted_at', None) is None]
- def to_dict(self, include_linked=False):
+ # Fields to_dict() can emit that are NOT mapped columns. Each one costs a
+ # query (or a collection walk) to produce, so `$select` has to know they
+ # exist in order to let a caller decline them. Kept next to to_dict so the
+ # two cannot drift.
+ DERIVED_FIELDS = (
+ 'project_name', 'environment_name', 'server_name', 'domains',
+ 'image_scan', 'image_update', 'sleep', 'linked_app', 'has_linked_app',
+ 'ingress_plane', 'ingress_proxy_eligible',
+ )
+
+ def to_dict(self, include_linked=False, fields=None):
+ """Serialize the app.
+
+ `fields` (a set, normally from ``$select``) is not only a payload
+ narrowing — it decides which DERIVED fields get computed, and those are
+ where the cost is. ``image_scan`` and ``image_update`` read
+ ``lazy='dynamic'`` relationships, so they issue a query EACH, per row,
+ and no amount of eager loading can hoist them; ``sleep``, ``server``,
+ ``project`` and ``environment`` are lazy scalars. Unnarrowed, drawing a
+ 100-app list costs roughly 300 extra queries. A caller that asks for
+ ``$select=id,name`` now costs none of them.
+
+ `fields=None` keeps the full legacy payload, so every existing caller
+ is unaffected.
+ """
import json
+ want = fields.__contains__ if fields is not None else (lambda _key: True)
result = {
'id': self.id,
'name': self.name,
@@ -155,8 +180,6 @@ class Application(db.Model):
'compose_file': self.compose_file,
'systemd_unit': self.systemd_unit,
'managed_by': self.managed_by,
- 'ingress_plane': self.ingress_plane or _default_ingress_plane(self.app_type, self.managed_by),
- 'ingress_proxy_eligible': _proxy_eligible(self.app_type, self.managed_by),
'version': self.version,
'upload_path': self.upload_path,
'private_slug': self.private_slug,
@@ -165,7 +188,6 @@ class Application(db.Model):
'environment_type': self.environment_type,
'linked_app_id': self.linked_app_id,
'shared_config': json.loads(self.shared_config) if self.shared_config else None,
- 'has_linked_app': self.linked_app_id is not None,
'created_at': self.created_at.isoformat(),
'updated_at': self.updated_at.isoformat(),
'last_deployed_at': self.last_deployed_at.isoformat() if self.last_deployed_at else None,
@@ -174,49 +196,62 @@ class Application(db.Model):
'workspace_id': self.workspace_id,
'project_id': self.project_id,
'environment_id': self.environment_id,
- # Derived display names for the project/environment this app lives in
- # (null when unassigned). Resolved via the viewonly relationships above
- # and guarded for None so unassigned apps keep working.
- 'project_name': self.project.name if self.project else None,
- 'environment_name': self.environment.name if self.environment else None,
- 'server_name': self.server.name if self.server else 'Local server',
- 'domains': [d.to_dict() for d in self.live_domains]
}
- # Lightweight image-scan badge (latest scan only)
- latest_scan = self.image_scans.first()
- if latest_scan:
+ # Narrow the plain columns. These are already loaded on the instance, so
+ # dropping them saves payload, not queries — the queries are below.
+ if fields is not None:
+ result = {key: value for key, value in result.items() if key in fields}
+
+ # Pure derivations off already-loaded columns — cheap, but still elided
+ # when unasked so `$select` means one thing everywhere.
+ if want('ingress_plane'):
+ result['ingress_plane'] = self.ingress_plane or _default_ingress_plane(self.app_type, self.managed_by)
+ if want('ingress_proxy_eligible'):
+ result['ingress_proxy_eligible'] = _proxy_eligible(self.app_type, self.managed_by)
+ if want('has_linked_app'):
+ result['has_linked_app'] = self.linked_app_id is not None
+
+ # Derived display names for the project/environment/server this app
+ # lives in (null when unassigned). Each is a lazy relationship load.
+ if want('project_name'):
+ result['project_name'] = self.project.name if self.project else None
+ if want('environment_name'):
+ result['environment_name'] = self.environment.name if self.environment else None
+ if want('server_name'):
+ result['server_name'] = self.server.name if self.server else 'Local server'
+ if want('domains'):
+ result['domains'] = [d.to_dict() for d in self.live_domains]
+
+ # Lightweight image-scan badge (latest scan only).
+ if want('image_scan'):
+ latest_scan = self.image_scans.first()
result['image_scan'] = {
'status': latest_scan.status,
'highest_severity': latest_scan.highest_severity,
'severity_counts': latest_scan.get_counts(),
'scanned_at': latest_scan.completed_at.isoformat() if latest_scan.completed_at else None,
- }
- else:
- result['image_scan'] = None
+ } if latest_scan else None
- # Lightweight image-update badge (latest digest check only)
- latest_update = self.image_update_checks.first()
- if latest_update:
+ # Lightweight image-update badge (latest digest check only).
+ if want('image_update'):
+ latest_update = self.image_update_checks.first()
result['image_update'] = {
'status': latest_update.status,
'update_available': latest_update.update_available,
'checked_at': latest_update.checked_at.isoformat() if latest_update.checked_at else None,
- }
- else:
- result['image_update'] = None
+ } if latest_update else None
- # Lightweight auto-sleep badge
- sleep_policy = self.sleep_policy
- if sleep_policy:
+ # Lightweight auto-sleep badge.
+ if want('sleep'):
+ sleep_policy = self.sleep_policy
result['sleep'] = {
'enabled': sleep_policy.enabled,
'asleep': sleep_policy.asleep,
'idle_timeout_minutes': sleep_policy.idle_timeout_minutes,
- }
- else:
- result['sleep'] = None
- if include_linked and self.linked_app:
+ } if sleep_policy else None
+
+ if include_linked and want('linked_app') and self.linked_app:
result['linked_app'] = {
'id': self.linked_app.id,
'name': self.linked_app.name,
diff --git a/backend/tests/test_query_layer.py b/backend/tests/test_query_layer.py
new file mode 100644
index 00000000..18316d8f
--- /dev/null
+++ b/backend/tests/test_query_layer.py
@@ -0,0 +1,186 @@
+"""Tests for the shared $select/$filter/$orderby/$skip/$top layer."""
+
+import pytest
+
+from app.api._query import (
+ QueryParseError, apply_query, parse_filter, parse_orderby, parse_select,
+)
+from app.models import Application
+
+
+class FakeRequest:
+ def __init__(self, **args):
+ self.args = args
+
+
+def sample_app(app):
+ """One persisted Application — to_dict needs a real row to walk."""
+ from app import db
+ from app.models import User
+ from werkzeug.security import generate_password_hash
+ with app.app_context():
+ # applications.user_id is NOT NULL, so the row needs an owner.
+ owner = User.query.first() or User(
+ email='[email protected]', username='probe',
+ password_hash=generate_password_hash('x'), role='admin', is_active=True)
+ if owner.id is None:
+ db.session.add(owner)
+ db.session.commit()
+ row = Application(name='probe-app', app_type='static', status='stopped',
+ user_id=owner.id)
+ db.session.add(row)
+ db.session.commit()
+ db.session.refresh(row)
+ yield row
+
+
+# ---------------------------------------------------------------- $filter
+
+def test_filter_none_when_absent(app):
+ with app.app_context():
+ assert parse_filter('', Application) is None
+ assert parse_filter(None, Application) is None
+
+
+def test_filter_comparison_operators(app):
+ with app.app_context():
+ for op in ('eq', 'ne', 'gt', 'ge', 'lt', 'le'):
+ assert parse_filter(f"name {op} 'demo'", Application) is not None
+
+
+def test_filter_rejects_unknown_field(app):
+ """The mapped-column set is the allowlist — not a getattr into the model."""
+ with app.app_context():
+ with pytest.raises(QueryParseError):
+ parse_filter("query eq 'x'", Application)
+ with pytest.raises(QueryParseError):
+ parse_filter("__class__ eq 'x'", Application)
+
+
+def test_filter_string_functions(app):
+ with app.app_context():
+ for expr in ("contains(name, 'ap')", "startswith(name, 'a')",
+ "endswith(name, 'p')", 'notempty(name)'):
+ assert parse_filter(expr, Application) is not None
+
+
+def test_filter_date_helpers(app):
+ with app.app_context():
+ assert parse_filter("date(created_at, '2026-01-02')", Application) is not None
+ assert parse_filter('daysAgo(created_at, 7)', Application) is not None
+ with pytest.raises(QueryParseError):
+ parse_filter("date(created_at, 'nope')", Application)
+ with pytest.raises(QueryParseError):
+ parse_filter('daysAgo(created_at, soon)', Application)
+
+
+def test_filter_refuses_mixed_combiners(app):
+ """`a and b or c` has no unambiguous reading; guessing one is worse."""
+ with app.app_context():
+ with pytest.raises(QueryParseError):
+ parse_filter("name eq 'a' and status eq 'b' or port eq 1", Application)
+
+
+def test_filter_malformed_condition(app):
+ with app.app_context():
+ with pytest.raises(QueryParseError):
+ parse_filter('name', Application)
+
+
+# --------------------------------------------------------------- $orderby
+
+def test_orderby_defaults_to_asc_and_accepts_desc(app):
+ with app.app_context():
+ assert parse_orderby('name', Application)
+ assert len(parse_orderby('name asc, created_at desc', Application)) == 2
+ with pytest.raises(QueryParseError):
+ parse_orderby('name sideways', Application)
+ with pytest.raises(QueryParseError):
+ parse_orderby('nope asc', Application)
+
+
+# ---------------------------------------------------------------- $select
+
+def test_select_none_means_everything(app):
+ with app.app_context():
+ assert parse_select('', Application) is None
+
+
+def test_select_always_includes_the_primary_key(app):
+ """A row the client cannot identify is not useful; every UI keys on id."""
+ with app.app_context():
+ assert parse_select('name', Application) == {'name', 'id'}
+
+
+def test_select_accepts_declared_derived_fields(app):
+ with app.app_context():
+ fields = parse_select('name,project_name,image_scan', Application,
+ extra=Application.DERIVED_FIELDS)
+ assert {'name', 'project_name', 'image_scan', 'id'} == fields
+
+
+def test_select_rejects_underived_unknown_field(app):
+ with app.app_context():
+ with pytest.raises(QueryParseError):
+ parse_select('name,not_a_field', Application)
+
+
+# ------------------------------------------------------------- apply_query
+
+def test_apply_query_is_a_noop_without_params(app):
+ """Adoption must not change any existing caller's response."""
+ with app.app_context():
+ result = apply_query(Application.query, Application, FakeRequest())
+ assert result.fields is None
+ assert result.total is None
+ assert result.top is None
+
+
+def test_apply_query_caps_top(app):
+ with app.app_context():
+ result = apply_query(Application.query, Application, FakeRequest(**{'$top': '99999'}))
+ assert result.top == 500
+
+
+def test_apply_query_rejects_non_integer_paging(app):
+ with app.app_context():
+ with pytest.raises(QueryParseError):
+ apply_query(Application.query, Application, FakeRequest(**{'$top': 'ten'}))
+ with pytest.raises(QueryParseError):
+ apply_query(Application.query, Application, FakeRequest(**{'$skip': '-1'}))
+
+
+def test_apply_query_counts_before_paging(app):
+ """`total` must be the unpaged count, or "12 of 340" reads "12 of 12"."""
+ with app.app_context():
+ result = apply_query(Application.query, Application, FakeRequest(**{'$top': '1'}))
+ assert result.total is not None
+ assert result.top == 1
+
+
+# ------------------------------------------------- to_dict field narrowing
+
+def test_to_dict_full_payload_is_unchanged_by_default(app, sample_app):
+ with app.app_context():
+ data = sample_app.to_dict()
+ for key in ('id', 'name', 'project_name', 'server_name', 'domains',
+ 'image_scan', 'image_update', 'sleep', 'has_linked_app',
+ 'ingress_plane'):
+ assert key in data
+
+
+def test_to_dict_narrows_to_requested_fields(app, sample_app):
+ """The point of $select: the expensive derived fields are not computed."""
+ with app.app_context():
+ data = sample_app.to_dict(fields={'id', 'name'})
+ assert set(data) == {'id', 'name'}
+ for skipped in ('image_scan', 'image_update', 'sleep', 'domains',
+ 'project_name', 'server_name'):
+ assert skipped not in data
+
+
+def test_to_dict_can_opt_into_one_derived_field(app, sample_app):
+ with app.app_context():
+ data = sample_app.to_dict(fields={'id', 'name', 'image_scan'})
+ assert set(data) == {'id', 'name', 'image_scan'}