Skip to content

Commit 0d7cb82

Browse files
Flix6xclaude
andcommitted
Order the data source listing, let a client limit it, and keep its types unnarrowed
A search from the automation form asked for every source a user may read, in whatever order Postgres returned them, so an instance with many sources sent its whole source table to the browser, and the sources shown could differ between two searches for the same term. The listing is now ordered with the most recently created source first, and takes a limit. The source types in the response are read from every source the user may read, rather than from the sources the call returns, so that narrowing the listing no longer narrows the types a client can offer to narrow it by. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0129WrXeJ5gia2pctFH93BqC Signed-off-by: F.N. Claessen <claessen@seita.nl>
1 parent 4f6755e commit 0d7cb82

3 files changed

Lines changed: 121 additions & 15 deletions

File tree

‎flexmeasures/api/v3_0/sources.py‎

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from flask_classful import FlaskView, route
55
from flask_json import as_json
66
from flask_security import auth_required
7-
from marshmallow import fields, Schema
7+
from marshmallow import fields, Schema, validate
88
from packaging.version import Version, InvalidVersion
99
from sqlalchemy import select, or_, and_
1010
from webargs.flaskparser import use_kwargs
@@ -49,10 +49,20 @@ class SourceQuerySchema(Schema):
4949
"example": "forecaster",
5050
},
5151
)
52+
limit = fields.Int(
53+
required=False,
54+
validate=validate.Range(min=1),
55+
metadata={
56+
"description": "Maximum number of sources to return, the most recently created ones first."
57+
" Without it, every accessible source is returned."
58+
" Note that `only_latest` collapses the sources which this limit let through, so the response can hold fewer sources than the limit allows.",
59+
"example": 25,
60+
},
61+
)
5262

5363

5464
def source_search_term_filter(term: str):
55-
"""Match a search term against what identifies a source: its name, its model, its description and its id."""
65+
"""Match a search term against what identifies a source: its name, its model and its id."""
5666
filters = [
5767
DataSource.name.ilike(f"%{term}%"),
5868
DataSource.model.ilike(f"%{term}%"),
@@ -112,6 +122,7 @@ def index(
112122
only_latest: bool = True,
113123
filter: list[str] | None = None,
114124
type: str | None = None,
125+
limit: int | None = None,
115126
):
116127
"""List accessible data sources and defined source types.
117128
@@ -125,7 +136,12 @@ def index(
125136
the defined source types.
126137
127138
The ``filter`` parameter searches the sources by name, by model and by id prefix,
128-
and the ``type`` parameter narrows the list to one source type, such as ``forecaster``.
139+
the ``type`` parameter narrows the list to one source type, such as ``forecaster``,
140+
and the ``limit`` parameter returns only the most recently created ones.
141+
142+
The ``types`` in the response are those of every source the user may read,
143+
rather than only those of the sources this call returns,
144+
so that one call can both search the sources and offer the types to search by.
129145
130146
**Access rules:**
131147
@@ -173,25 +189,32 @@ def index(
173189
"""
174190
accessible_account_ids = get_readable_source_account_ids()
175191

176-
query = select(DataSource)
192+
readable_sources = None
177193
if accessible_account_ids is not None:
178194
# Sources owned by one of the accessible accounts, OR sources
179195
# with no account_id AND no user_id (system / public sources).
180-
query = query.where(
181-
or_(
182-
DataSource.account_id.in_(accessible_account_ids),
183-
and_(
184-
DataSource.account_id.is_(None),
185-
DataSource.user_id.is_(None),
186-
),
187-
)
196+
readable_sources = or_(
197+
DataSource.account_id.in_(accessible_account_ids),
198+
and_(
199+
DataSource.account_id.is_(None),
200+
DataSource.user_id.is_(None),
201+
),
188202
)
203+
204+
query = select(DataSource)
205+
if readable_sources is not None:
206+
query = query.where(readable_sources)
189207
if type is not None:
190208
query = query.where(DataSource.type == type)
191209
if filter is not None:
192210
query = query.where(
193211
or_(*(source_search_term_filter(term) for term in filter))
194212
)
213+
# The listing is ordered so that a limited one holds the same sources each time it is asked for,
214+
# and so that a source which was just created is in it rather than behind the limit.
215+
query = query.order_by(DataSource.id.desc())
216+
if limit is not None:
217+
query = query.limit(limit)
195218

196219
sources: list[DataSource] = list(db.session.scalars(query).all())
197220

@@ -200,8 +223,17 @@ def index(
200223

201224
serialized = [_serialize_source(s) for s in sources]
202225

203-
# Collect any extra types present in the DB but not in the defaults
204-
db_types = {s.type for s in sources if s.type}
226+
# Collect any extra types present in the DB but not in the defaults.
227+
# These are read from every source the user may read, rather than from the sources returned above,
228+
# so that narrowing the listing does not also narrow the types a client can offer to narrow it by.
229+
type_query = select(DataSource.type).distinct()
230+
if readable_sources is not None:
231+
type_query = type_query.where(readable_sources)
232+
db_types = {
233+
source_type
234+
for source_type in db.session.scalars(type_query).all()
235+
if source_type
236+
}
205237
all_types = list(DEFAULT_DATASOURCE_TYPES) + sorted(
206238
db_types - set(DEFAULT_DATASOURCE_TYPES)
207239
)

‎flexmeasures/api/v3_0/tests/test_sources_api.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,3 +417,66 @@ def test_get_sources_filtered_by_type_and_search_term(
417417
)
418418
assert by_id.status_code == 200
419419
assert forecaster.id in {source["id"] for source in by_id.json["sources"]}
420+
421+
422+
@pytest.mark.parametrize(
423+
"requesting_user",
424+
["test_prosumer_user@seita.nl"],
425+
indirect=True,
426+
)
427+
def test_get_sources_limit_returns_the_newest_ones(
428+
client, setup_api_test_data, requesting_user, db
429+
):
430+
"""A limited listing holds that many sources, the most recently created ones, in a stable order."""
431+
sources = [
432+
DataSource(name=f"LimitedSeita{index}", type="forecaster", model="Pipeline")
433+
for index in range(4)
434+
]
435+
db.session.add_all(sources)
436+
db.session.flush()
437+
newest_two = [source.id for source in sorted(sources, key=lambda s: -s.id)][:2]
438+
439+
limited = client.get(
440+
url_for("SourceAPI:index"),
441+
query_string={"filter": "LimitedSeita", "only_latest": "false", "limit": 2},
442+
)
443+
assert limited.status_code == 200
444+
assert [source["id"] for source in limited.json["sources"]] == newest_two
445+
446+
unlimited = client.get(
447+
url_for("SourceAPI:index"),
448+
query_string={"filter": "LimitedSeita", "only_latest": "false"},
449+
)
450+
assert unlimited.status_code == 200
451+
assert len(unlimited.json["sources"]) == 4
452+
453+
454+
@pytest.mark.parametrize(
455+
"requesting_user",
456+
["test_prosumer_user@seita.nl"],
457+
indirect=True,
458+
)
459+
def test_get_sources_types_are_not_narrowed_by_the_filters(
460+
client, setup_api_test_data, requesting_user, db
461+
):
462+
"""The types cover every source the user may read, so that one call can both search and offer the types to search by."""
463+
db.session.add(
464+
DataSource(
465+
name="TypedSeita",
466+
type="soothsayer",
467+
model="CrystalBall",
468+
account_id=requesting_user.account_id,
469+
)
470+
)
471+
db.session.flush()
472+
473+
unfiltered = client.get(url_for("SourceAPI:index"))
474+
assert unfiltered.status_code == 200
475+
assert "soothsayer" in unfiltered.json["types"]
476+
477+
filtered = client.get(
478+
url_for("SourceAPI:index"), query_string={"type": "scheduler"}
479+
)
480+
assert filtered.status_code == 200
481+
assert "soothsayer" not in {source["type"] for source in filtered.json["sources"]}
482+
assert "soothsayer" in filtered.json["types"]

‎flexmeasures/ui/static/openapi-specs.json‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5539,7 +5539,7 @@
55395539
"/api/v3_0/sources": {
55405540
"get": {
55415541
"summary": "List accessible data sources and defined source types.",
5542-
"description": "Returns the list of data sources accessible to the current user and\nthe defined source types.\n\nThe <code>filter</code> parameter searches the sources by name, by model and by id prefix,\nand the <code>type</code> parameter narrows the list to one source type, such as <code>forecaster</code>.\n\n<strong>Access rules:</strong>\n\n- Admins see all data sources.\n- Users with the <code>consultant</code> role see sources belonging to their\n own account and to any consultancy-client accounts for which their\n account is the consultancy.\n- All other authenticated users see only sources belonging to their\n own account, plus sources that have neither a <code>user_id</code> nor an\n <code>account_id</code> (i.e. system/public sources).\n",
5542+
"description": "Returns the list of data sources accessible to the current user and\nthe defined source types.\n\nThe <code>filter</code> parameter searches the sources by name, by model and by id prefix,\nthe <code>type</code> parameter narrows the list to one source type, such as <code>forecaster</code>,\nand the <code>limit</code> parameter returns only the most recently created ones.\n\nThe <code>types</code> in the response are those of every source the user may read,\nrather than only those of the sources this call returns,\nso that one call can both search the sources and offer the types to search by.\n\n<strong>Access rules:</strong>\n\n- Admins see all data sources.\n- Users with the <code>consultant</code> role see sources belonging to their\n own account and to any consultancy-client accounts for which their\n account is the consultancy.\n- All other authenticated users see only sources belonging to their\n own account, plus sources that have neither a <code>user_id</code> nor an\n <code>account_id</code> (i.e. system/public sources).\n",
55435543
"security": [
55445544
{
55455545
"ApiKeyAuth": []
@@ -5575,6 +5575,17 @@
55755575
"example": "forecaster"
55765576
},
55775577
"required": false
5578+
},
5579+
{
5580+
"in": "query",
5581+
"name": "limit",
5582+
"description": "Maximum number of sources to return, the most recently created ones first. Without it, every accessible source is returned. Note that `only_latest` collapses the sources which this limit let through, so the response can hold fewer sources than the limit allows.",
5583+
"schema": {
5584+
"type": "integer",
5585+
"minimum": 1,
5586+
"example": 25
5587+
},
5588+
"required": false
55785589
}
55795590
],
55805591
"responses": {

0 commit comments

Comments
 (0)