Skip to content

fix: serialize controller datetimes as UTC JSON#14

Closed
Rerowros wants to merge 1 commit intoPasarGuard:mainfrom
Rerowros:fix/controller-utc-datetimes
Closed

fix: serialize controller datetimes as UTC JSON#14
Rerowros wants to merge 1 commit intoPasarGuard:mainfrom
Rerowros:fix/controller-utc-datetimes

Conversation

@Rerowros
Copy link
Copy Markdown

@Rerowros Rerowros commented May 10, 2026

Summary

This pull request makes datetime handling in controller JSON payloads stricter and more predictable.

Timezone-aware datetime values are now serialized as UTC with a Z suffix. Naive datetimes are rejected before they can be sent in JSON payloads.

JSON Payload Serialization

  • Added UTC-aware datetime normalization for JSON payloads in PasarGuardNodeBridge/controller.py.
  • Rejected naive datetime values before sending JSON requests in PasarGuardNodeBridge/controller.py.
  • Updated controller logging to use UTC timestamps in PasarGuardNodeBridge/controller.py.

Why This Is Better

Naive datetimes are unsafe in API payloads because their meaning depends on local process timezone assumptions. That can cause subtle mismatches between panel, node bridge, and node behavior.

By requiring timezone-aware datetime values and serializing them as UTC, the bridge sends payloads with unambiguous timestamps. This is easier to debug and safer for integrations that compare events across services.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 10, 2026

Walkthrough

This pull request adds UTC datetime formatting to controller logs and JSON serialization for API requests. A new UTCFormatter class provides consistent UTC timestamps in ISO-8601 format for logging. A _json_safe function recursively converts datetime objects to UTC ISO strings (using "Z" suffix) in JSON payloads and rejects naive datetimes with structured errors. Both integrations ensure consistent datetime handling across logging and REST API requests.

Changes

UTC Datetime Formatting and Serialization

Layer / File(s) Summary
Import Dependencies
PasarGuardNodeBridge/controller.py
time, datetime, timezone, and Any type annotation imports are added to enable datetime operations and UTC handling.
UTC Formatter & JSON Serialization
PasarGuardNodeBridge/controller.py
UTCFormatter class formats log records with UTC ISO-8601 timestamps; _json_safe function recursively converts datetime objects to UTC ISO strings and raises NodeAPIError for naive datetimes.
Logger Configuration
PasarGuardNodeBridge/controller.py
Controller logger stream handler is configured to use UTCFormatter with ISO-8601 UTC timestamp format.
API Request Serialization
PasarGuardNodeBridge/controller.py
_make_json_request sanitizes JSON request bodies via _json_safe() before sending to the REST API.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

A rabbit adjusts the clock's grand chime,
UTC timestamps keep perfect time,
Naive datetimes? Rejected with care,
JSON payloads now safely prepare,
Time zones aligned, from here to there! 🐰⏰

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and concisely describes the main change: adding UTC JSON serialization for datetime handling in the controller module.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
PasarGuardNodeBridge/controller.py (1)

38-38: ⚡ Quick win

Strengthen the string replacement to avoid edge cases.

The .replace("+00:00", "Z") could theoretically match "+00:00" appearing elsewhere in the ISO string, though this is unlikely. Using a more precise replacement that only targets the timezone suffix would be safer.

♻️ Proposed fix: use suffix-specific replacement
-        return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
+        iso_string = value.astimezone(timezone.utc).isoformat()
+        if iso_string.endswith("+00:00"):
+            return iso_string[:-6] + "Z"
+        return iso_string
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@PasarGuardNodeBridge/controller.py` at line 38, The current return uses
value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") which may
accidentally replace any "+00:00" substring; change it to compute the ISO string
first (use value.astimezone(timezone.utc).isoformat()), then only replace the
trailing timezone suffix — e.g., check if the ISO string endswith("+00:00") and
if so replace that suffix with "Z" — updating the expression around
value.astimezone(...).isoformat() and removing the global .replace call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@PasarGuardNodeBridge/controller.py`:
- Line 37: The raise of NodeAPIError for naive datetime uses a duplicate code
(-6) already used for "Invalid proxy format"; locate the raise in controller.py
(the NodeAPIError call with detail "Naive datetime values are not supported in
JSON payloads") and change its code to a unique, unused error code (e.g., -7),
and update any centralized error registry, mappings, or tests that reference
this specific error so the new code is recognized; ensure the NodeAPIError
instantiation and any downstream handlers/logging reflect the new code.

---

Nitpick comments:
In `@PasarGuardNodeBridge/controller.py`:
- Line 38: The current return uses
value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") which may
accidentally replace any "+00:00" substring; change it to compute the ISO string
first (use value.astimezone(timezone.utc).isoformat()), then only replace the
trailing timezone suffix — e.g., check if the ISO string endswith("+00:00") and
if so replace that suffix with "Z" — updating the expression around
value.astimezone(...).isoformat() and removing the global .replace call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 15b0e201-bc1d-4f6b-b0d2-7b876b01440b

📥 Commits

Reviewing files that changed from the base of the PR and between a72816c and 5ef5701.

📒 Files selected for processing (1)
  • PasarGuardNodeBridge/controller.py

def _json_safe(value: Any) -> Any:
if isinstance(value, datetime):
if value.tzinfo is None or value.utcoffset() is None:
raise NodeAPIError(code=-6, detail="Naive datetime values are not supported in JSON payloads")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Error code conflict: code=-6 is already used.

The error code -6 is already defined at line 119 for "Invalid proxy format". Using the same code for "Naive datetime values are not supported" creates ambiguity when handling errors.

🐛 Proposed fix: use a unique error code
-            raise NodeAPIError(code=-6, detail="Naive datetime values are not supported in JSON payloads")
+            raise NodeAPIError(code=-7, detail="Naive datetime values are not supported in JSON payloads")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@PasarGuardNodeBridge/controller.py` at line 37, The raise of NodeAPIError for
naive datetime uses a duplicate code (-6) already used for "Invalid proxy
format"; locate the raise in controller.py (the NodeAPIError call with detail
"Naive datetime values are not supported in JSON payloads") and change its code
to a unique, unused error code (e.g., -7), and update any centralized error
registry, mappings, or tests that reference this specific error so the new code
is recognized; ensure the NodeAPIError instantiation and any downstream
handlers/logging reflect the new code.

@M03ED
Copy link
Copy Markdown
Collaborator

M03ED commented May 10, 2026

we have no datetime variable in node response

@Rerowros
Copy link
Copy Markdown
Author

Thanks, you're right. I rechecked the node responses

@Rerowros Rerowros closed this May 10, 2026
@Rerowros Rerowros deleted the fix/controller-utc-datetimes branch May 10, 2026 18:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants