Skip to content

Commit ba73b4d

Browse files
authored
7.1.1 urgent fixes (#40)
* Restore the isotope catalog query (prod was serving sample data) 7819662 changed the isotope list query to `SELECT * FROM c OFFSET/LIMIT` with no ORDER BY. Cosmos rejects `OFFSET LIMIT` without `ORDER BY`, so the query threw on any real database. Azure SWA managed functions run with AZURE_FUNCTIONS_ENVIRONMENT=Development, so the handler's catch fell through to `if (isLocalDevelopmentEnvironment())` and returned the 3 built-in mock isotopes with `mocked: true` instead of a 500 — which is why production showed "sample data". - isotopes.js: query is back to `SELECT TOP <limit> * FROM c` (the form that ran in production for months). limit cap raised 100 -> 1000 so the whole catalog loads without paging; `hasMore` is always false. - isotopes.js + reference-materials.js: the catch-fallback to mock data now also requires `!hasCosmosConfiguration()`. A configured-DB query error is a real error (500) — never silently served as sample data again. - IsotopeViewer requests the full catalog in one go (no server paging to page). - buildSearchQuery is exported + tested to never emit OFFSET / ORDER BY. 44 API tests pass; check + build clean. * Quiet Dependabot CI noise Dependabot PRs don't get repo secrets, so the Azure deploy step always failed on them with "deployment_token was not provided". - azure workflow: skip build_and_deploy_job for dependabot[bot], and add skip_deploy_on_missing_secrets so fork PRs don't fail either. - dependabot.yml: group ALL github-actions updates (majors included) into one weekly PR instead of one PR per action. * Get test files out of the deployed function app; add continuation-token paging ## The sample-data bug (real root cause) `api/package.json` has `"main": "src/functions/*.js"`, and the Azure Functions host imports *every* file that glob matches at startup. The four `api/src/functions/*.test.js` files I had added each run `process.env.MOCK_COSMOS = 'true'` at module scope — so once deployed, the whole function app came up with MOCK_COSMOS set and every endpoint served the 3 built-in sample isotopes regardless of the Cosmos config. (Loading a test file with top-level `await` + `node:test` calls also broke host startup outright on the PR preview → the 404.) Fix: moved all four to `api/test/` (outside the functions glob, still picked up by `node --test`) and added `api/.funcignore` so `*.test.js` is never packaged. ## Proper pagination for /api/isotopes - `buildSearchQuery` now emits a plain `SELECT * FROM c [WHERE …]` — no `TOP`, `ORDER BY`, or `OFFSET` (Cosmos rejects `OFFSET LIMIT` without `ORDER BY`, and an `ORDER BY` on an unindexed path fails). - Paging is the Cosmos SDK continuation token: `query(spec, { maxItemCount, continuationToken }).fetchNext()`. Response carries `continuation` (+ `hasMore`). - `IsotopeViewer` sends `?continuation=…` and loads the next page on scroll; `loadIsotopeCatalog` in the wizard pages through the whole catalog. - Mock path paginates too (token = next offset). 45 API + 60 unit tests; check + build clean. * Never serve sample data when a database is configured `shouldUseMockCatalog()` used to return true when NODE_ENV / AZURE_FUNCTIONS_ENVIRONMENT looked like "development" AND the Cosmos config was incomplete. Azure SWA managed functions default AZURE_FUNCTIONS_ENVIRONMENT to "Development", so on prod the only thing keeping real data on was all four COSMOSDB_* vars being set — and a stray MOCK_COSMOS (from the deployed test files) or a missing COSMOSDB_CONTAINER flipped it to sample data. - shouldUseMockCatalog() is now just: `MOCK_COSMOS set` OR `no COSMOSDB_*`. isLocalDevelopmentEnvironment() is deleted. - hasCosmosConfiguration() needs only endpoint + key (db/container have defaults). - The catch block no longer falls back to mocks — a configured-DB query error is a real 500. - New api/test/mock-detection.test.js locks this in. 48 API + 60 unit tests; check + build clean. * docs: describe the two pagination styles + sample-data behaviour * Warn when a known proxy nuclide is set to report its own element Some nuclides (Np-239, Pa-233) are almost always counted as a delayed stand-in for another element. If someone adds "Pa-233" labelled as protactinium (not thorium), the wizard now shows a warning on the isotope card — "Pa-233 is usually detected to measure thorium … record that relationship" — with the same "Record how this is measured" button as the name/label mismatch prompt. - knownProxyHint(isotope) in catalogWrite.ts, driven by a small KNOWN_PROXY_ISOTOPES map (add pairs there). Suppressed when the entry is already labelled as the target element (isotopeElementMismatch covers that) or a relationship is already recorded. - 63 unit tests; check + build clean. * Drop invalid skip_deploy_on_missing_secrets input (the job-level dependabot guard is enough) * Auto-expand newly added isotope cards A "did you mean" proxy warning (Pa-233 → thorium, Np-239 → uranium) lives inside the isotope's CollapsibleCard, which is collapsed by default for catalog-picked isotopes — so the prompt was never seen. New isotopes (from the catalog picker or "Add custom isotope") now open expanded. * Show the proxy / mismatch warning outside the isotope card The "did you mean X?" prompt (Pa-233 → thorium, Np-239 → uranium) and the name/label mismatch warning were inside the CollapsibleCard body, only visible when expanded. Moved them to a sibling of the card so they show whether it's open or collapsed. Reverts the auto-expand from 916f286. * Also move the 'measured via' proxy note outside the isotope card * Bump APP_VERSION to 7.1.1 BETA * Surface isotope warnings as a summary at the top of Step 1 The name/label mismatch and known-proxy ("did you mean thorium?") prompts now appear in one "⚠ Check these isotopes" box directly under the step heading — above the catalog picker and the isotope list — instead of one per card lower down. Each row keeps its "Record how this is measured" button. * Move the isotope warning box right under the 'Isotopes to analyze' heading
1 parent 4d555a2 commit ba73b4d

16 files changed

Lines changed: 398 additions & 268 deletions

‎.github/dependabot.yml‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,15 @@ updates:
3131
- minor
3232
- patch
3333

34-
# GitHub Actions used by the deploy workflows
34+
# GitHub Actions used by the deploy workflows. First-party actions
35+
# (checkout, setup-node, deploy-pages…) — group every update, majors included,
36+
# into a single weekly PR so they don't arrive one at a time.
3537
- package-ecosystem: github-actions
3638
directory: /
3739
schedule:
3840
interval: weekly
41+
open-pull-requests-limit: 5
3942
groups:
4043
actions:
41-
update-types:
42-
- minor
43-
- patch
44+
patterns:
45+
- '*'
Lines changed: 55 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,55 @@
1-
name: Azure Static Web Apps CI/CD
2-
3-
on:
4-
push:
5-
branches:
6-
- main
7-
pull_request:
8-
types: [opened, synchronize, reopened, closed]
9-
branches:
10-
- main
11-
12-
# .github/workflows/azure-static-web-apps-purple-beach-0c943171e.yml
13-
14-
jobs:
15-
build_and_deploy_job:
16-
runs-on: ubuntu-latest
17-
steps:
18-
- uses: actions/checkout@v3
19-
with:
20-
submodules: true
21-
lfs: false
22-
23-
- uses: actions/setup-node@v4
24-
with:
25-
node-version-file: '.nvmrc'
26-
cache: npm
27-
28-
- name: Install dependencies
29-
run: npm ci
30-
31-
- name: Build And Deploy
32-
id: builddeploy
33-
uses: Azure/static-web-apps-deploy@v1
34-
with:
35-
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_PURPLE_BEACH_0C943171E }}
36-
repo_token: ${{ secrets.GITHUB_TOKEN }}
37-
action: "upload"
38-
app_location: "/"
39-
api_location: "api"
40-
output_location: "build"
41-
# Remove app_build_command (or keep it only if you must; see note below)
42-
43-
close_pull_request_job:
44-
if: github.event_name == 'pull_request' && github.event.action == 'closed'
45-
runs-on: ubuntu-latest
46-
name: Close Pull Request Job
47-
steps:
48-
- name: Close Pull Request
49-
id: closepullrequest
50-
uses: Azure/static-web-apps-deploy@v1
51-
with:
52-
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_PURPLE_BEACH_0C943171E }}
53-
action: "close"
1+
name: Azure Static Web Apps CI/CD
2+
3+
on:
4+
push:
5+
branches:
6+
- main
7+
pull_request:
8+
types: [opened, synchronize, reopened, closed]
9+
branches:
10+
- main
11+
12+
# .github/workflows/azure-static-web-apps-purple-beach-0c943171e.yml
13+
14+
jobs:
15+
build_and_deploy_job:
16+
# Dependabot PRs (and forks) don't get the deployment secret, so the deploy
17+
# step can only fail there. Skip the job for them.
18+
if: github.actor != 'dependabot[bot]'
19+
runs-on: ubuntu-latest
20+
steps:
21+
- uses: actions/checkout@v3
22+
with:
23+
submodules: true
24+
lfs: false
25+
26+
- uses: actions/setup-node@v4
27+
with:
28+
node-version-file: '.nvmrc'
29+
cache: npm
30+
31+
- name: Install dependencies
32+
run: npm ci
33+
34+
- name: Build And Deploy
35+
id: builddeploy
36+
uses: Azure/static-web-apps-deploy@v1
37+
with:
38+
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_PURPLE_BEACH_0C943171E }}
39+
repo_token: ${{ secrets.GITHUB_TOKEN }}
40+
action: 'upload'
41+
app_location: '/'
42+
api_location: 'api'
43+
output_location: 'build'
44+
45+
close_pull_request_job:
46+
if: github.event_name == 'pull_request' && github.event.action == 'closed'
47+
runs-on: ubuntu-latest
48+
name: Close Pull Request Job
49+
steps:
50+
- name: Close Pull Request
51+
id: closepullrequest
52+
uses: Azure/static-web-apps-deploy@v1
53+
with:
54+
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_PURPLE_BEACH_0C943171E }}
55+
action: 'close'

‎README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,12 @@ and `POST` are registered; other methods 404.
7575
The frontend isotope viewer calls `/api/isotopes` by default. You can override that by setting `PUBLIC_ISOTOPE_API_URL`.
7676
The reference material viewer calls `/api/reference-materials` by default. You can override that by setting `PUBLIC_REFERENCE_MATERIAL_API_URL`.
7777

78-
Both GET endpoints accept `q` (search), `limit` (clamped to 100), and `offset` query parameters, and respond with `{ items, count, search, hasMore }`. `hasMore` signals that another batch is available at `offset + items.length`; the catalog viewers use it to fetch the next batch when the user scrolls to the bottom of the list.
78+
Both GET endpoints accept `q` (search) and `limit` (page size) and respond with `{ items, count, search, hasMore, ... }`; the catalog viewers fetch the next page when the user scrolls to the bottom.
79+
80+
- `/api/isotopes` pages with a **Cosmos continuation token**: the response carries `continuation` (an opaque string, `null` on the last page); send it back as `?continuation=…` for the next page. The query is a plain `SELECT * FROM c` — no `ORDER BY`/`OFFSET`, so it needs no index.
81+
- `/api/reference-materials` pages with `?offset=…` (`ORDER BY c._ts DESC OFFSET … LIMIT …`).
82+
83+
When no `COSMOSDB_*` settings are present (or `MOCK_COSMOS=true`), both endpoints serve a small built-in sample catalog with `"mocked": true`, and the app shows a "sample data" banner. A configured database is always used.
7984

8085
### API access control
8186

‎api/.funcignore‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Files never deployed with the function app. The Azure Functions host imports
2+
# every file matched by package.json "main" to discover `app.http()` calls, so a
3+
# stray test file in the functions dir would be loaded into the running app.
4+
*.test.js
5+
**/*.test.js
6+
test/
7+
.vscode/

‎api/src/functions/isotopes.js‎

Lines changed: 57 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -46,62 +46,46 @@ function isMockCosmosEnabled() {
4646
return value === '1' || value === 'true' || value === 'yes';
4747
}
4848

49-
function isLocalDevelopmentEnvironment() {
50-
const runtime = process.env.AZURE_FUNCTIONS_ENVIRONMENT?.trim().toLowerCase();
51-
const nodeEnv = process.env.NODE_ENV?.trim().toLowerCase();
52-
return runtime === 'development' || nodeEnv === 'development';
53-
}
54-
5549
function hasCosmosConfiguration() {
50+
// Only endpoint + key are required — database and container names have
51+
// defaults in cosmosClient.js.
5652
const endpoint = process.env.COSMOSDB_ENDPOINT?.trim();
5753
const key = process.env.COSMOSDB_KEY?.trim();
58-
const database = process.env.COSMOSDB_DATABASE?.trim();
59-
const container = process.env.COSMOSDB_CONTAINER?.trim();
6054

61-
return Boolean(endpoint && key && database && container);
55+
return Boolean(endpoint && key);
6256
}
6357

58+
/**
59+
* Serve the built-in sample catalog only when `MOCK_COSMOS` is set, or when no
60+
* database is configured at all. If a database IS configured it is always used —
61+
* no guessing from `NODE_ENV` / `AZURE_FUNCTIONS_ENVIRONMENT` (Azure SWA managed
62+
* functions default that to "Development", which previously masked prod).
63+
*/
6464
function shouldUseMockCatalog() {
65-
if (isMockCosmosEnabled()) {
66-
return true;
67-
}
68-
69-
return isLocalDevelopmentEnvironment() && !hasCosmosConfiguration();
65+
return isMockCosmosEnabled() || !hasCosmosConfiguration();
7066
}
7167

68+
/** Page size. Paging is via Cosmos continuation tokens, not the query text. */
7269
function clampLimit(rawValue) {
73-
const parsed = Number.parseInt(rawValue ?? '25', 10);
74-
if (!Number.isFinite(parsed)) {
75-
return 25;
76-
}
77-
78-
return Math.min(Math.max(parsed, 1), 100);
79-
}
80-
81-
function clampOffset(rawValue) {
82-
const parsed = Number.parseInt(rawValue ?? '0', 10);
70+
const parsed = Number.parseInt(rawValue ?? '100', 10);
8371
if (!Number.isFinite(parsed)) {
84-
return 0;
72+
return 100;
8573
}
86-
87-
return Math.max(parsed, 0);
74+
return Math.min(Math.max(parsed, 1), 200);
8875
}
8976

90-
function buildSearchQuery(rawSearch, rawLimit, rawOffset) {
91-
const limit = clampLimit(rawLimit);
92-
const offset = clampOffset(rawOffset);
77+
/**
78+
* Plain `SELECT` — no `TOP`, `ORDER BY` or `OFFSET`. Paging is done with the
79+
* Cosmos SDK's continuation token (`fetchNext()` + `maxItemCount`), which needs
80+
* no index and has no per-page RU penalty. Cosmos rejects `OFFSET LIMIT` without
81+
* an `ORDER BY`, and an `ORDER BY` on an unindexed path fails — hence neither.
82+
*/
83+
function buildSearchQuery(rawSearch) {
9384
const normalizedSearch = rawSearch?.trim().toLowerCase() ?? '';
94-
const pagingParameters = [
95-
{ name: '@offset', value: offset },
96-
{ name: '@limit', value: limit }
97-
];
9885

9986
if (!normalizedSearch) {
100-
// No ORDER BY: it requires the sort path to be indexed, and an unindexed
101-
// path silently drops rows. OFFSET/LIMIT is valid without ORDER BY.
10287
return {
103-
query: 'SELECT * FROM c OFFSET @offset LIMIT @limit',
104-
parameters: pagingParameters
88+
query: 'SELECT * FROM c'
10589
};
10690
}
10791

@@ -130,8 +114,8 @@ function buildSearchQuery(rawSearch, rawLimit, rawOffset) {
130114
}
131115

132116
return {
133-
query: `SELECT * FROM c WHERE ${conditions.join(' OR ')} OFFSET @offset LIMIT @limit`,
134-
parameters: [...parameters, ...pagingParameters]
117+
query: `SELECT * FROM c WHERE ${conditions.join(' OR ')}`,
118+
parameters
135119
};
136120
}
137121

@@ -172,15 +156,18 @@ function matchesMockSearch(item, normalizedSearch) {
172156
return false;
173157
}
174158

175-
function getMockSearchResults(rawSearch, rawLimit, rawOffset) {
159+
/** Mock paging: the "continuation token" is just the next offset as a string. */
160+
function getMockSearchResults(rawSearch, rawLimit, rawContinuation) {
176161
const normalizedSearch = rawSearch?.trim().toLowerCase() ?? '';
177162
const limit = clampLimit(rawLimit);
178-
const offset = clampOffset(rawOffset);
163+
const offset = Math.max(Number.parseInt(rawContinuation ?? '0', 10) || 0, 0);
179164
const matches = MOCK_ISOTOPES.filter((item) => matchesMockSearch(item, normalizedSearch));
165+
const page = matches.slice(offset, offset + limit);
166+
const nextOffset = offset + page.length;
180167

181168
return {
182-
items: matches.slice(offset, offset + limit),
183-
hasMore: offset + limit < matches.length
169+
items: page,
170+
continuation: nextOffset < matches.length ? String(nextOffset) : null
184171
};
185172
}
186173

@@ -197,18 +184,22 @@ async function isotopesHandler(request, context) {
197184
};
198185
}
199186

187+
const url = new URL(request.url);
188+
const search = url.searchParams.get('q') ?? '';
189+
const rawLimit = url.searchParams.get('limit');
190+
const continuation = url.searchParams.get('continuation') || undefined;
191+
200192
if (shouldUseMockCatalog()) {
201-
const url = new URL(request.url);
202-
const search = url.searchParams.get('q') ?? '';
203-
const limit = url.searchParams.get('limit');
204-
const offset = url.searchParams.get('offset');
205-
const { items: mockItems, hasMore } = getMockSearchResults(search, limit, offset);
193+
const { items: mockItems, continuation: nextToken } = getMockSearchResults(
194+
search,
195+
rawLimit,
196+
continuation
197+
);
206198

207199
context.log('Returning mock isotope catalog results.', {
208200
search,
209201
count: mockItems.length,
210-
mockCosmos: isMockCosmosEnabled(),
211-
fallbackLocal: !isMockCosmosEnabled() && isLocalDevelopmentEnvironment()
202+
reason: isMockCosmosEnabled() ? 'MOCK_COSMOS' : 'no COSMOSDB_* configured'
212203
});
213204

214205
return {
@@ -217,61 +208,37 @@ async function isotopesHandler(request, context) {
217208
items: mockItems.map(mapIsotopeItem),
218209
count: mockItems.length,
219210
search,
220-
hasMore,
211+
continuation: nextToken,
212+
hasMore: Boolean(nextToken),
221213
mocked: true
222214
}
223215
};
224216
}
225217

226218
try {
227-
const url = new URL(request.url);
228-
const search = url.searchParams.get('q') ?? '';
229-
const limit = url.searchParams.get('limit');
230-
const offset = url.searchParams.get('offset');
231-
const queryText = buildSearchQuery(search, limit, offset);
219+
const queryText = buildSearchQuery(search);
232220
const container = getCosmosContainer();
233-
const query = container.items.query(queryText);
234-
const { resources } = await query.fetchAll();
221+
const iterator = container.items.query(queryText, {
222+
maxItemCount: clampLimit(rawLimit),
223+
continuationToken: continuation
224+
});
225+
const page = await iterator.fetchNext();
226+
const resources = Array.isArray(page.resources) ? page.resources : [];
227+
const nextToken = page.hasMoreResults ? (page.continuationToken ?? null) : null;
235228

236229
return {
237230
status: 200,
238231
jsonBody: {
239232
items: resources.map(mapIsotopeItem),
240233
count: resources.length,
241234
search,
242-
hasMore: resources.length === clampLimit(limit)
235+
continuation: nextToken,
236+
hasMore: Boolean(nextToken)
243237
}
244238
};
245239
} catch (error) {
246-
if (isLocalDevelopmentEnvironment()) {
247-
const url = new URL(request.url);
248-
const search = url.searchParams.get('q') ?? '';
249-
const limit = url.searchParams.get('limit');
250-
const offset = url.searchParams.get('offset');
251-
const { items: mockItems, hasMore } = getMockSearchResults(search, limit, offset);
252-
253-
context.warn(
254-
'Cosmos query failed in local development. Falling back to mock isotope catalog.',
255-
{
256-
search,
257-
count: mockItems.length,
258-
error: error instanceof Error ? error.message : String(error)
259-
}
260-
);
261-
262-
return {
263-
status: 200,
264-
jsonBody: {
265-
items: mockItems.map(mapIsotopeItem),
266-
count: mockItems.length,
267-
search,
268-
hasMore,
269-
mocked: true,
270-
fallback: 'local-cosmos-error'
271-
}
272-
};
273-
}
274-
240+
// A database is configured (we would not be here otherwise) but the query
241+
// failed — a real error. Surface it; never silently serve sample data.
275242
context.error('Failed to load isotopes from Cosmos DB.', error);
276243

277244
return {
@@ -412,4 +379,4 @@ app.http('isotopes', {
412379
handler: isotopesHandler
413380
});
414381

415-
export { isotopesHandler };
382+
export { isotopesHandler, buildSearchQuery, shouldUseMockCatalog };

0 commit comments

Comments
 (0)