Commit Graph
3046 Commits
Author SHA1 Message Date
Ben WestandCopilot 2e81ce07e5 fix(devicestatus): purify each item in array input
The API layer was calling purifyObject() on the raw req.body without
handling arrays. When NightscoutKit sends [status], only the outer
array would be purified (no-op), not the individual status objects.

Now normalizes to array and purifies each devicestatus object,
matching the treatments pattern.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-18 10:26:16 -07:00
Ben WestandCopilot cbb6d06107 fix(profile): restore array handling for profile POST API
NightscoutKit (Loop) sends profiles wrapped in arrays: [profile].
The MongoDB driver migration changed insert() to insertOne(), breaking
array support.

Changes:
- API layer: normalize input to array, purify each item
- Storage layer: use insertMany() instead of insertOne()
- Tests: verify single, array, and empty array handling

This matches the proven pattern from treatments API.

Fixes array handling regression introduced in d46c5b41.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-18 10:24:48 -07:00
copilot-swe-agent[bot]andbewest 002f34fcda fix: gate UUID write-path normalization on UUID_HANDLING flag and fix docs accuracy
Co-authored-by: bewest <394179+bewest@users.noreply.github.com>
2026-03-17 23:44:47 +00:00
Ben WestandCopilot 095c9d0454 fix: remove scope creep from UUID handling (syncIdentifier/uuid dedup)
UUID_HANDLING should ONLY affect UUID values in the _id field.
Previous commit incorrectly added server-side dedup for syncIdentifier
and uuid fields, which was never part of the original behavior.

Changes:
- upsertQueryFor(): Remove syncIdentifier/uuid as dedup keys
- Batch POST: Only fetch existing IDs by identifier, not by
  syncIdentifier/uuid
- tests: Update TEST-CACHE-003/004 to document actual behavior
  (duplicates occur without ObjectIdCache - this is by design)
- docs: Correct treatments-schema.md (syncIdentifier/uuid preserved,
  not copied to identifier)
- docs: Remove external link from entries-schema.md

Loop carbs/doses rely on ObjectIdCache for dedup, not server-side logic.
This matches the original (pre-change) server behavior.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-17 16:00:03 -07:00
Ben WestandCopilot 8fc155aa48 fix(treatments): correct UUID handling scope (only _id field)
REQ-SYNC-072 scope correction: normalizeTreatmentId() should ONLY
handle UUID values in the _id field, not copy syncIdentifier or uuid
fields to identifier.

Changes:
- normalizeTreatmentId(): Only extract UUID from _id to identifier
- normalizeEntryId(): Same fix for entries collection
- upsertQueryFor(): Add syncIdentifier and uuid as dedup fallbacks
  (fields are preserved, not copied to identifier)
- Batch POST: Fetch _id for docs deduped by syncIdentifier/uuid

Test updates:
- TEST-ID-003, TEST-V1-ID-004: Updated to expect identifier NOT copied
  from syncIdentifier (scope fix)

Affected clients:
- Loop overrides (UUID _id → identifier): Still works
- Loop carbs/doses (syncIdentifier): Dedup works, no identifier copy
- xDrip+ (uuid): Dedup works, no identifier copy
- AAPS (identifier): Unchanged

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-17 15:21:25 -07:00
Ben WestandCopilot 86e0564694 docs: clarify UUID_HANDLING only affects _id field, not all UUIDs
The feature only handles the specific case where a UUID is sent as
the _id field itself. It does NOT affect:
- AAPS (uses 'identifier' field)
- xDrip+ (uses 'uuid' field)
- Loop carbs/doses (uses 'syncIdentifier' field)

Only affects:
- Loop overrides (_id: syncIdentifier.uuidString)
- Trio CGM entries (_id: UUID)

See docs/10-domain/client-id-handling-deep-dive.md for full analysis.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-17 14:40:37 -07:00
Ben WestandCopilot a2c6ce1e5a docs: use neutral wording for UUID handling description
Avoid implying all AID clients use the same pattern or that any
specific implementation is incorrect. Different clients have
divergent sync patterns - the feature accommodates this variety.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-17 14:32:05 -07:00
Ben WestandCopilot 3bb100836b fix: change UUID_HANDLING default to true
Update default from false to true to enable AID client compatibility
out of the box:

- lib/server/env.js: readENVTruthy('UUID_HANDLING', true)
- README.md: Document UUID_HANDLING in Features section
- docs/example-template.env: Update comments, show true as default

Rationale:
- Loop, Trio, AAPS, xDrip+ use UUID sync patterns by default
- Before MongoDB 5.x, UUID _id didn't crash (just didn't CRUD properly)
- ObjectID users completely unaffected (quirk only triggers on UUID)
- Can set UUID_HANDLING=false for strict mode if needed

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-17 14:17:48 -07:00
Ben WestandCopilot bf6cfb7730 feat: add UUID_HANDLING feature flag for GET/DELETE by identifier
- env.js: Add UUID_HANDLING env var (default: false)
- query.js: Add UUID detection in normalizeIdValue()
  - When UUID_HANDLING=true and _id is UUID, search by identifier field
  - Returns searchByIdentifier flag to redirect query
- treatments.js: Move queryOpts inside query_for() for env access
- entries.js: Same pattern for entries collection

When UUID_HANDLING=true:
- GET /treatments/{uuid} searches by identifier field
- DELETE /treatments/{uuid} deletes by identifier field
- Same behavior for entries collection

When UUID_HANDLING=false (default):
- UUID _id values return empty results (safe, no crash)
- Maintains backwards compatibility

Refs: uuid-feature-flag, uuid-query-impl from uuid-identifier-lookup.md

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-17 13:21:14 -07:00
Ben WestandCopilot b88155057c fix(entries): handle UUID _id in CGM entries (GAP-SYNC-045)
Trio/Loop upload CGM entries with UUID strings as _id field.
This caused MongoDB errors when re-uploading with different UUID
at same timestamp: "immutable field '_id'" error.

Fix:
- Add normalizeEntryId() to extract UUID from _id to identifier field
- Add upsertQueryFor() to strip non-ObjectId _id before $set
- Maintain sysTime+type as primary dedup key for CGM data integrity
- Add identifier to indexed fields

Tests:
- 3 baseline tests document current sysTime+type dedup behavior
- 6 UUID handling tests including the previously-failing scenario

Refs: GAP-SYNC-045, REQ-SYNC-072

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-11 14:36:23 -07:00
Ben WestandCopilot e78a5bc6e7 fix(treatments): implement REQ-SYNC-072 server-controlled ID with transparent promotion
Fixes #8450 - Loop Temporary Override sync breaks due to UUID _id handling

Option G Implementation:
- Extract client sync identity (identifier) from any source:
  - Loop overrides: UUID in _id field → moved to identifier
  - Loop carbs/doses: syncIdentifier → copied to identifier
  - AAPS: identifier already present
  - xDrip+: uuid → copied to identifier

- Server generates proper ObjectId for _id field
- Deduplication uses identifier (not _id) as primary key
- No database migration needed - gradual adoption

Changes:
- normalizeTreatmentId(): extracts client identity to identifier field
- upsertQueryFor(): identifier-first lookup, strips UUID _id for upsert
- create()/upsert()/save(): fetch _id from DB after update by identifier
- Added 'identifier' to indexedFields for efficient querying
- Updated UUID treatment test with full workflow coverage

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-10 13:36:34 -07:00
Andy Low 1231ec6b65 Handle UUID treatment ids in v1 API 2026-03-08 01:01:57 +00:00
Andy Low 505e375efc Fix mmol BG display in OpenAPS tooltips 2026-03-06 23:42:58 +00:00
Andy Low eb105949d4 Enable Traditional Chinese localization 2026-03-06 23:24:50 +00:00
Andy Low c77097abd8 Merge remote-tracking branch 'origin/dev' into pr-8421
# Conflicts:
#	package-lock.json
2026-03-06 21:51:52 +00:00
Andy Low faf578c08e Add MongoDB 8 compatibility follow-up fixes 2026-03-06 21:35:16 +00:00
Ben WestandCopilot e0cc9ff5df Relax Node version constraints to >=16.x
- Change engines.node from '^22.x || ^20.x' to '>=16.x'
- Change engines.npm from '>=10.x' to '>=8.x'
- Update runtime checkNodeVersion to allow Node 16+
- Creates overlap with previous release (^16.x || ^14.x)

This allows users on Node 16/18 to upgrade smoothly while
recommending Node 20 or 22 LTS for best support.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-27 14:52:56 -08:00
bewest a55df96d80 Improve security test performance by fixing authorization delay calculation
Fix logic in delay list initialization to correctly handle zero-value settings for authorization failure delays, and update test configurations to leverage this fix.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 605cec52-e52a-4520-8af0-466d9c971344
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
Replit-Commit-Event-Id: ee25d747-8c3a-444e-8dbf-e0229eee7d31
Replit-Helium-Checkpoint-Created: true
2026-01-20 01:48:56 +00:00
Ben West 9318a577b5 refactor: use insertMany/bulkWrite for batch MongoDB operations
- devicestatus.js: Replace async.eachSeries + insertOne with insertMany
- entries.js: Replace forEach + updateOne with bulkWrite
- treatments.js: Replace async.eachSeries + replaceOne with bulkWrite
  (preserves sequential fallback for preBolus treatments)

This improves performance for batch inserts and aligns with MongoDB
best practices per data-shape-requirements.md recommendations.
2026-01-19 13:49:36 -08:00
bewestandBen West 7ffc4da46e Allow disabling prediction array truncation by setting the maximum size to zero
Update env.js to correctly parse PREDICTIONS_MAX_SIZE, allowing a value of 0 to disable truncation. Modify tests and documentation to reflect this change.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 81a6141f-c27c-4178-8cf3-6474e7b82918
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
Replit-Commit-Event-Id: 92d3ef13-9728-43c6-8e8b-d435184fec07
Replit-Helium-Checkpoint-Created: true
2026-01-19 13:15:09 -08:00
bewestandBen West d4d2574307 Improve database connection management and add configurability
Introduce new environment variables for MongoDB connection pool configuration (pool size, min pool size, max idle time) and add related tests and documentation.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: cf276ff5-4001-4b44-93fe-7c9786ee4327
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
Replit-Commit-Event-Id: 6d2a0738-a5a9-4167-a04b-df474a95be16
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/7ea4278b-5c6c-4065-9cb8-f1013771318d/cf276ff5-4001-4b44-93fe-7c9786ee4327/MVHBPJ5
Replit-Helium-Checkpoint-Created: true
2026-01-19 13:15:09 -08:00
bewestandBen West 64e3463ffb Improve insulin rounding precision by adding epsilon
Update rounding logic in `lib/sandbox.js` to incorporate an epsilon value for enhanced precision, addressing potential floating-point errors in insulin calculations.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: cf276ff5-4001-4b44-93fe-7c9786ee4327
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
Replit-Commit-Event-Id: f10d2278-3392-4fd0-ad73-36beee7aadb9
Replit-Helium-Checkpoint-Created: true
2026-01-19 13:15:09 -08:00
bewestandBen West 6b68f920ac Add ability to truncate large prediction arrays in device status data
Introduce logic to truncate prediction arrays (IOB, COB, UAM, ZT) in devicestatus documents when they exceed a configured maximum size, preventing potential issues with large document handling in MongoDB. This includes updates to bootevent, devicestatus module, environment configuration, and new tests to verify truncation behavior.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: daa945f9-0872-4250-9868-a1245067293b
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
Replit-Commit-Event-Id: baff25d9-e915-44d9-87f0-f7583f443a30
Replit-Helium-Checkpoint-Created: true
2026-01-19 13:14:46 -08:00
Ben West f907f0d6ef Fix MongoDB 5.x compatibility in entries storage and API3 renderer test
Fixes test failure in api3.renderer.test.js "SEARCH should accept csv content type"
that was caused by MongoDB driver upgrade from 3.x to 5.x.

Changes:

1. lib/server/entries.js:
   - Change from replaceOne() to updateOne() with $set operator
   - MongoDB 3.x update() did partial updates, but 5.x replaceOne() does
     full document replacement
   - Using updateOne with $set preserves the original partial update behavior
   - Prevents documents with same {sysTime, type} from replacing each other

2. tests/api3.renderer.test.js:
   - Add database cleanup in before() hook to delete all entries
   - Ensures test isolation from previous test files
   - Previous tests (especially old API v1 tests) were leaving entries in DB
     with undefined app/identifier fields that interfered with CSV rendering

The CSV test now passes - it expects exactly 2 documents but was getting
105 entries due to leftover test data from previous test runs.
2026-01-19 13:14:21 -08:00
Ben West 636ef4091b Fix entries API POST response format and empty array handling
Fixes two bugs in the entries API that caused test failures:

1. POST endpoints now return JSON arrays consistently
   - Created format_post_response() middleware for POST requests
   - Replaces format_entries() which is designed for GET with content negotiation
   - Previously, POST requests without Accept header defaulted to text/plain handler
   - This caused responses to fail or return empty objects instead of JSON arrays
   - Now matches behavior of treatments and devicestatus APIs

2. Fixed callback never being called for empty array posts
   - Added empty array check in lib/server/entries.js create() function
   - Previously, empty array caused forEach loop to never execute
   - Completion callback was inside forEach, so never triggered for empty input
   - This caused 15 second timeouts on POST requests with empty arrays

All 26 tests in api.shape-handling.test.js now pass.

Files changed:
- lib/api/entries/index.js: Added format_post_response, updated POST routes
- lib/server/entries.js: Added empty array handling in create()
2026-01-19 13:14:21 -08:00
bewestandBen West 5a9ffb123a Remove debounce delay for near real-time data updates
Removes the 15-second debounce from `lib/server/bootevent.js`, allowing `data-received` and `tick` events to trigger immediate data updates by calling `ctx.dataloader.update()` directly.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: ef8efcf8-f9e9-49f9-9441-59adbee38ad3
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
Replit-Commit-Event-Id: 67966157-9e23-4065-b9a1-0ca67482bafc
Replit-Helium-Checkpoint-Created: true
2026-01-19 13:14:21 -08:00
bewestandBen West 44409c5023 Improve handling of single and multiple data entries across the system
Refactor `devicestatus.js` to use `async.eachSeries` for sequential processing and update WebSocket `dbAdd` handler to process array inputs sequentially, ensuring correct multi-document write support.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: fbbf36df-818c-4b8c-8760-4975515f38e6
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 522116f1-cf99-4504-9c93-bc47b4276585
Replit-Helium-Checkpoint-Created: true
2026-01-19 13:14:21 -08:00
Ben West 269320e453 adjust websockets usage for mongo update 2026-01-19 13:13:48 -08:00
Ben West 4914589557 adjust food api for updated mongo and add test 2026-01-19 13:13:48 -08:00
Ben West 3b4dfad245 update activity API for new mongo lib, add tests
Add tests for activity API.
2026-01-19 13:13:48 -08:00
Ben West 286fa07014 switch profile api to new mongo driver
Provide some tests for the profile API.
2026-01-19 13:13:48 -08:00
Ben West 1107e84a6e Revert "Revert "Merge pull request #8026 from nightscout/less_frequent_db_updates""
This reverts commit 2e65b1dd9b.
Try to bring back #8026.
2026-01-19 13:13:43 -08:00
Ingo Reitz 96ab5ea602 Drop support for EoL NodeJS versions, default to 22
Signed-off-by: Ingo Reitz <9l@9lo.re>
2025-06-09 01:51:30 +02:00
Ben West 01808b7b17 Merge branch 'dev' of github.com:Foxy7/cgm-remote-monitor into wip/bewest/collaborations 2025-05-28 16:31:37 -07:00
Scott LeibrandandBen West 5fa982b63f make sure roles exists before checking roles.length 2025-05-28 16:25:44 -07:00
Jörg SchömerandBen West 2ba864a4a0 hide tooltip by display instead of opacity 2025-05-28 16:25:44 -07:00
Adam RadoczandBen West 0b731a06be Update the glucose molecular mass.
References:
- [National Institute of Standards and Technology](https://webbook.nist.gov/cgi/cbook.cgi?ID=C50997&Mask=40)
- [National Institute of Health](https://pubchem.ncbi.nlm.nih.gov/compound/D-Glucose)
2025-05-28 16:25:44 -07:00
Ben WestandGitHub 8591f2b26c Merge branch 'dev' into dev 2025-05-23 09:39:27 -07:00
Ben West 3761c0fedd permit any LTS version of node 2024-12-13 14:28:49 -08:00
Ben West 59ff28204a allow tests to pass
Switching the way units is fetched to this way makes it similar to the other
code already in place that does something similar.  This allows the tests to
pass with the existing fixtures.
Considering augmenting  additional tests that explicitly tests whether the
relevant branch of code is taken.
2024-12-13 14:19:17 -08:00
dsnallfotandBen West a4e05a1655 Fix missing mmol unit conversion for lastEnacted.bg 2024-12-13 14:19:16 -08:00
Ben West 558927bf3d Revert "Update sensorage.js for 10 day sensors"
This reverts commit cec3eebc40.
Need to update tests?  Not immediately clear why tests updated from 6 days to 9
days fails, so revertinig for now.
2024-11-25 13:40:48 -08:00
Ben West d7c93b456c Merge remote-tracking branch 'daaanosaur/return-boot-error-status-code' into wip/bewest/collaborations
Nice work, thanks for your contributions.
2024-11-25 12:37:23 -08:00
Ben West bf704059da Merge remote-tracking branch 'Nightfoxy/Nightfoxy-SAGE-Defaults' into wip/bewest/nspro-apns-crashfix 2024-11-25 12:27:50 -08:00
Ben West e0b0d6fd81 nice error handling, @AndyLow91 2024-11-25 12:17:42 -08:00
Andy LowandBen West b5f5ed2c95 Update loop.js
Updated to stop Nightscout crashing if APNs response is not received well from Apple.
2024-11-25 12:11:23 -08:00
Ken FoxandGitHub cec3eebc40 Update sensorage.js for 10 day sensors
Changing default SAGE warn and urgent threshold defaults to be useful for 10 day sensors rather than 7 day sensors from the G5 era. SAGE pill turns yellow at day 9 and red 4 hours before expiration of 10 days.

Once G6 is retired, consider setting WARN to 10 days and URGENT to 10.5 days.
2024-10-05 00:36:50 -05:00
Daniel Cosby dc4a05101c return generic '500' status on bootError page 2024-09-24 13:54:34 +01:00
Ben West a7ebb301b6 add notes regarding handling unauthorized ACK request
When someone is looking at Nightscout and needs the alarm silenced, it is very
desirable to always silence the local UI. This patch documents some of the
working code around handling the alarm notification process, as well as
provides commentary on handling unauthorized scenarios.  There are some open
questions such as how to update the permission set after authorization.
2023-10-23 10:07:26 -07:00
Ben West c0892863a2 remove spurious logging in profileeditor 2023-10-23 08:46:04 -07:00