Repository navigation
feat(cloud): native push gateway and dedicated infrastructure (1/3) - #19912
Conversation
|
Too many files changed for review (114 files, 100 file limit). Bypass the limit by tagging |
There was a problem hiding this comment.
ℹ️ No critical issues — one minor observation inline.
Reviewed changes
- Shared PostgreSQL schema startup — extracted the
applyPostgresSchemaretry/collision helper into@orca-cloud/postgres-schemaand rewired Relay'spackage.json/Dockerfile to consume it; behavior-preserving apart from the neweventPrefixoption. - Durable push gateway (
cloud/apps/push+packages/push-contract) — X25519 host-proof authentication, device registry with per-host caps, 300/15-min alert-and-dismissal quotas, per-recipient idempotency, a lease/claim/retry delivery queue, and APNs/FCM adapters with dead-token retirement. - Dedicated infrastructure — Terraform for the Cloud SQL instance, Cloud Run service, IAM/deploy identity and secrets backing the gateway, plus a Cloud Run deploy/recovery model, workflow/recovery/validation checks, and operational docs.
The host-proof protocol, the challenge-consume compare-and-swap, and the session-token hashing are sound against a database-only read attacker and replay; the claim/lease/finish fencing gives correct at-least-once delivery with on-device collapse dedupe. Test coverage is extensive (137 push tests) and the assertions pin real behavior rather than pass-through snapshots.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| return { ok: true, registrationId } | ||
| } | ||
| const [countRow] = await transaction.query( | ||
| 'SELECT COUNT(*) AS devices FROM push_devices WHERE host_fingerprint = ?', |
There was a problem hiding this comment.
This COUNT(*) includes rows already marked dead (dead_at IS NOT NULL) alongside live ones, and nothing in the gateway ever reaps a retired row — markDead only sets the flag. A device that re-registers with a new deviceId (rather than reusing the old one, which upsert would revive) creates a new row that permanently consumes maxDevicesPerHost, so a long-lived host's churn can eventually make a fresh registration return too_many_devices until the Part-2 desktop issues deleteOwned. Worth either excluding dead from the count or documenting/automating dead-row retirement.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (7)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughAdds a mobile push gateway with host authentication, device registration, APNs and FCM delivery, durable queues, retries, quotas, dismissal handling, readiness checks, and graceful shutdown. Adds push contracts, PostgreSQL schema support, Cloud Run and Cloud SQL infrastructure, deployment identities, rollout and recovery tests, production configuration, and operational documentation. Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to This update to the mobile push gateway adds deployment validation for the FCM project id and hardens APNs topic-error handling so device registrations are preserved and notifications are retried instead of lost, which is a safe and well-tested improvement. However, several previously identified issues in the broader push gateway still remain unresolved, including FCM's collapse-key behavior potentially replacing unrelated pending alerts and an inconsistency in how the delivery worker labels expired-before-first-send notifications. Because no Terraform apply or production deployment has occurred yet, these do not block continued development, but they should be resolved before the gateway is deployed to production. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 14.49% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 69 functions across 57 files. (2 skipped: 2 unsupported.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (4)
cloud/dev/scripts/push-gateway-workflow.test.mjs (1)
109-109: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winBound the variable-block match so the default assertion cannot match a different variable.
Both patterns use
[\s\S]*?, which crosses block boundaries. Ifpush_min_instancesloses itsdefault = 1, the lazy match can still succeed against adefault = 1in any later variable block invariables.tf. The same applies topush_database_pool_max. The assertion then passes while the guarantee is gone.Restrict the span to the variable block body.
♻️ Proposed fix
- assert.match(terraform('variables.tf'), /variable "push_min_instances"[\s\S]*?default {5}= 1/) + assert.match(terraform('variables.tf'), /variable "push_min_instances" \{[^}]*?default {5}= 1/)- assert.match(terraform('variables.tf'), /variable "push_database_pool_max"[\s\S]*?default {5}= 2/) + assert.match(terraform('variables.tf'), /variable "push_database_pool_max" \{[^}]*?default {5}= 2/)Also applies to: 136-136
cloud/apps/push/src/durable-push-store.test.ts (1)
169-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThis concurrent-connection assertion queries a different schema than the renamed table.
The fixture scopes
dbto a per-test schema by addingoptions=-c search_path=<schema>to the URL (lines 45-47). Line 170 opensconcurrentwith the rawdatabaseUrland nooptionsparameter, so it resolvespush_delivery_batchesin the defaultsearch_path, not in the test schema. The rename at line 165 applies only to the test schema.The assertion therefore passes because it reads an unrelated copy of the table, not because the rename is isolated from other connections. It also depends on
openPushDatabasehaving created those tables in the default schema as a side effect.Either scope the concurrent connection to the same schema so the assertion tests what it describes, or remove the block. The surrounding rollback assertions at lines 179-181 already carry the value of this test.
cloud/apps/push/src/push-delivery-payload.ts (1)
3-8: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winValidate the decoded payload with
PushNotificationSchemainstead of casting.The parser accepts any non-array object and casts it to
PushNotification.PushNotificationSchemavalidates required fields, rejects unknown fields, and enforces the contract refinements. Reuse it when readingpayload_jsonso malformed persisted data cannot reach delivery code.♻️ Proposed refactor
-import type { PushNotification } from '`@orca-cloud/push-contract`' +import { PushNotificationSchema, type PushNotification } from '`@orca-cloud/push-contract`' export function parsePushDeliveryPayload(payload: string): PushNotification { - const value: unknown = JSON.parse(payload) - if (!value || typeof value !== 'object' || Array.isArray(value)) - throw new Error('invalid_push_delivery_payload') - return value as PushNotification + const parsed = PushNotificationSchema.safeParse(JSON.parse(payload)) + if (!parsed.success) throw new Error('invalid_push_delivery_payload') + return parsed.data }cloud/apps/push/src/push-queued-dismissal.ts (1)
18-19: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAvoid the unused dismissal lookup.
When
notification.kind === 'dismiss',reconcileQueuedDismissalperforms theSELECTbut never usesdismissedbefore the upsert. Move the lookup into the alert branch and share it withisDismissedAlert.♻️ Proposed refactor to share the watermark lookup
+async function dismissedSeq( + tx: PushDatabase, + host: string, + notification: PushNotification +): Promise<number> { + const [dismissed] = await tx.query( + 'SELECT notification_seq FROM push_dismissed_events WHERE host_fingerprint = ? AND notification_epoch = ? AND notification_id = ?', + [host, notification.notificationEpoch, notification.notificationId] + ) + return Number(dismissed?.notification_seq ?? -1) +} + export async function reconcileQueuedDismissal( tx: PushDatabase, host: string, registrationId: string, notification: PushNotification, now: number ): Promise<boolean> { if (!notification.notificationId) return false const key = [host, notification.notificationEpoch, notification.notificationId] - const [dismissed] = await tx.query( - 'SELECT notification_seq FROM push_dismissed_events WHERE host_fingerprint = ? AND notification_epoch = ? AND notification_id = ?', - key - ) if (notification.kind !== 'dismiss') - return Number(dismissed?.notification_seq ?? -1) >= notification.notificationSeq + return (await dismissedSeq(tx, host, notification)) >= notification.notificationSeqexport async function isDismissedAlert( tx: PushDatabase, host: string, notification: PushNotification ): Promise<boolean> { if (notification.kind === 'dismiss' || !notification.notificationId) return false - const rows = await tx.query( - 'SELECT notification_seq FROM push_dismissed_events WHERE host_fingerprint = ? AND notification_epoch = ? AND notification_id = ?', - [host, notification.notificationEpoch, notification.notificationId] - ) - return Number(rows[0]?.notification_seq ?? -1) >= notification.notificationSeq + return (await dismissedSeq(tx, host, notification)) >= notification.notificationSeq }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 189ed032-8d9b-44bb-9aef-5ac57eb2825b
⛔ Files ignored due to path filters (1)
cloud/pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (109)
.github/workflows/cloud-verify.ymlcloud/README.mdcloud/apps/push/Dockerfilecloud/apps/push/package.jsoncloud/apps/push/src/apns-authentication-token.tscloud/apps/push/src/apns-client.test.tscloud/apps/push/src/apns-client.tscloud/apps/push/src/apns-http2-transport.tscloud/apps/push/src/apns-session-replacement.test.tscloud/apps/push/src/apns-stream-response.test.tscloud/apps/push/src/apns-stream-response.tscloud/apps/push/src/canonical-base64.tscloud/apps/push/src/client-ip-rate-limit.test.tscloud/apps/push/src/client-ip-rate-limit.tscloud/apps/push/src/config.test.tscloud/apps/push/src/config.tscloud/apps/push/src/desktop-host-proof-interop.test.tscloud/apps/push/src/device-registration-delete-race.test.tscloud/apps/push/src/device-registry-store.test.tscloud/apps/push/src/device-registry-store.tscloud/apps/push/src/durable-push-schema.tscloud/apps/push/src/durable-push-store.test.tscloud/apps/push/src/durable-push-store.tscloud/apps/push/src/durable-push-worker.test.tscloud/apps/push/src/durable-push-worker.tscloud/apps/push/src/fcm-access-token.tscloud/apps/push/src/fcm-client.test.tscloud/apps/push/src/fcm-client.tscloud/apps/push/src/host-challenge-answering.test-fixture.tscloud/apps/push/src/host-challenge-store.test.tscloud/apps/push/src/host-challenge-store.tscloud/apps/push/src/host-fingerprint.tscloud/apps/push/src/host-proof-concurrency.test.tscloud/apps/push/src/host-session-store.test.tscloud/apps/push/src/host-session-store.tscloud/apps/push/src/index.tscloud/apps/push/src/provider-retry-delay.tscloud/apps/push/src/push-auth-admission.tscloud/apps/push/src/push-background.tscloud/apps/push/src/push-database-postgres-startup.test.tscloud/apps/push/src/push-database.tscloud/apps/push/src/push-delivery-lifecycle.test.tscloud/apps/push/src/push-delivery-message.tscloud/apps/push/src/push-delivery-payload.tscloud/apps/push/src/push-dismissal-provider.test.tscloud/apps/push/src/push-dispatcher.tscloud/apps/push/src/push-notification-sound.test.tscloud/apps/push/src/push-observability.tscloud/apps/push/src/push-provider-outcome.tscloud/apps/push/src/push-queued-dismissal.tscloud/apps/push/src/push-readiness.test.tscloud/apps/push/src/push-readiness.tscloud/apps/push/src/push-request-drain.tscloud/apps/push/src/push-schema.tscloud/apps/push/src/push-send-idempotency.test.tscloud/apps/push/src/push-server-auth.test.tscloud/apps/push/src/push-server-harness.test-fixture.tscloud/apps/push/src/push-server-limits.test.tscloud/apps/push/src/push-server-send.test.tscloud/apps/push/src/push-server.tscloud/apps/push/src/push-session-concurrency.test.tscloud/apps/push/src/push-validation.test.tscloud/apps/push/tsconfig.build.jsoncloud/apps/push/tsconfig.jsoncloud/apps/push/vitest.config.tscloud/apps/relay/Dockerfilecloud/apps/relay/package.jsoncloud/apps/relay/src/postgres-schema-startup.tscloud/dev/fixtures/terraform-root-partition/families.jsoncloud/dev/scripts/push-cloud-run-model.mjscloud/dev/scripts/push-gateway-recovery.test.mjscloud/dev/scripts/push-gateway-workflow.test.mjscloud/dev/scripts/push-validation-workflow.test.mjscloud/dev/scripts/relay-cloud-sql-connection-budget.test.mjscloud/dev/scripts/render-workload-identity-conditions.mjscloud/dev/scripts/workload-identity-attribute-conditions.test.mjscloud/docs/push-database-cutover.mdcloud/docs/push-gateway.mdcloud/docs/relay-workflows.mdcloud/infra/terraform/environments/production.tfvarscloud/infra/terraform/environments/staging.tfvarscloud/infra/terraform/outputs.tfcloud/infra/terraform/push-dedicated-database.tfcloud/infra/terraform/push-deploy-identity.tfcloud/infra/terraform/push-gateway.tfcloud/infra/terraform/relay-github-actions.tfcloud/infra/terraform/relay-github-workflow-trust.tfcloud/infra/terraform/variables.tfcloud/package.jsoncloud/packages/postgres-schema/package.jsoncloud/packages/postgres-schema/src/index.tscloud/packages/postgres-schema/tsconfig.build.jsoncloud/packages/postgres-schema/tsconfig.jsoncloud/packages/push-contract/package.jsoncloud/packages/push-contract/src/apns-token-length.test.tscloud/packages/push-contract/src/contract.test.tscloud/packages/push-contract/src/device-registration-messages.tscloud/packages/push-contract/src/host-auth-messages.tscloud/packages/push-contract/src/index.tscloud/packages/push-contract/src/notification-identity-limits.test.tscloud/packages/push-contract/src/push-host-proof-transcript.test.tscloud/packages/push-contract/src/push-host-proof-transcript.tscloud/packages/push-contract/src/push-host-proof-vector.jsoncloud/packages/push-contract/src/push-limits.tscloud/packages/push-contract/src/send-messages.test.tscloud/packages/push-contract/src/send-messages.tscloud/packages/push-contract/src/wire-scalars.tscloud/packages/push-contract/tsconfig.build.jsoncloud/packages/push-contract/tsconfig.json
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| if ((this.options.now ?? Date.now)() >= queued.expiresAt) { | ||
| await this.store.finish(queued) | ||
| continue | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Preserve expired for deliveries that expire before dispatch.
When a claimed delivery expires before drain dispatches it, finish(queued) writes the default done outcome. The expiry pruner writes expired for the same terminal condition, and push_delivery_batches retains delivery outcomes. This loses the expiry reason from the durable row, even though recovery and observability do not currently branch on it.
🐛 Proposed fix
if ((this.options.now ?? Date.now)() >= queued.expiresAt) {
- await this.store.finish(queued)
+ await this.store.finish(queued, undefined, 'expired')
continue
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if ((this.options.now ?? Date.now)() >= queued.expiresAt) { | |
| await this.store.finish(queued) | |
| continue | |
| } | |
| if ((this.options.now ?? Date.now)() >= queued.expiresAt) { | |
| await this.store.finish(queued, undefined, 'expired') | |
| continue | |
| } |
| ...(delivery.orca.kind === 'dismiss' | ||
| ? {} | ||
| : { notification: { title: delivery.title, body: delivery.body } }), |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- target file ---'
sed -n '1,130p' cloud/apps/push/src/fcm-client.ts
printf '%s\n' '--- related FCM symbols and tests ---'
rg -n -C 3 --glob '!node_modules' --glob '!dist' 'collapse_key|notification:|orca.kind|fcm-client|send' cloud/apps/pushRepository: stablyai/orca
Length of output: 50369
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings
Length of output: 7707
🌐 Web query:
site:firebase.google.com/docs/cloud-messaging collapse_key notification messages HTTP v1 AndroidConfig collapse_key
💡 Result:
In Firebase Cloud Messaging (FCM) HTTP v1, the collapse_key is a parameter used to group messages so that only the latest message is delivered when the device is offline or restricted [1][2]. Key details regarding the use of collapse_key within AndroidConfig: 1. Functionality: When you set a collapse_key for a message, FCM identifies messages with the same key and the same registration token. If the device is offline or in a restricted state (e.g., Doze mode), FCM will store only the most recent message for that specific collapse_key, discarding any older pending messages [2][3]. 2. Default Behavior: If no collapse_key is provided, all messages are treated as non-collapsible (unless they are notification messages) and will be queued individually for delivery [1]. 3. Notification Messages: Notification messages are always considered collapsible by default [1][4]. Consequently, they ignore the collapse_key parameter entirely; FCM handles them according to its internal notification collapsing logic [1]. 4. Capacity: FCM can store up to four different collapsible messages per device simultaneously, each with a unique collapse_key [1]. If more than four unique keys are sent, FCM does not guarantee which keys will be retained [1]. To implement this in the HTTP v1 API, you include the collapseKey field within the android block of your message payload [1]. Example structure: { "message": { "token": "YOUR_DEVICE_TOKEN", "android": { "collapseKey": "your_collapse_key_string" } } }
Citations:
- 1: https://firebase.google.com/docs/cloud-messaging/customize-messages/collapsible-message-types
- 2: https://firebase.google.com/docs/cloud-messaging/understand-delivery
- 3: https://firebase.google.com/docs/cloud-messaging/customize-messages/setting-message-lifespan
- 4: https://firebase.google.com/docs/cloud-messaging/customize-messages/set-message-type
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- burst behavior test ---'
sed -n '118,188p' cloud/apps/push/src/push-server-send.test.ts
printf '%s\n' '--- delivery construction and collapse identity ---'
sed -n '1,240p' cloud/apps/push/src/push-delivery-message.ts
printf '%s\n' '--- FCM transport remainder ---'
sed -n '120,220p' cloud/apps/push/src/fcm-client.tsRepository: stablyai/orca
Length of output: 6246
Do not rely on android.collapse_key for notification messages.
For non-dismiss deliveries, fcmMessageBody sends a top-level notification and sets android.collapse_key from delivery.collapseId. FCM treats these as collapsible notification messages and ignores the supplied collapse key. A newer alert may therefore replace a pending alert with a different notification identity.
If each identity requires its own collapse group, use a data-only message with client-side display handling. Otherwise, document and test the intended global collapse behavior.
| expect(results.filter((result) => result.ok)).toEqual([ | ||
| { ok: true, hostFingerprint: challenges[0]!.hostFingerprint }, | ||
| { ok: true, hostFingerprint: challenges[0]!.hostFingerprint } | ||
| ]) | ||
| expect(results.filter((result) => !result.ok)).toEqual( | ||
| Array.from({ length: 8 }, () => ({ ok: false, reason: 'already_consumed' })) | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert one successful proof for each challenge.
These assertions check only the aggregate result counts. Both challenges have the same hostFingerprint. A regression can accept one challenge twice and reject the other challenge, while this test still passes.
Assert the results for each five-call challenge group separately.
Proposed test change
- expect(results.filter((result) => result.ok)).toEqual([
- { ok: true, hostFingerprint: challenges[0]!.hostFingerprint },
- { ok: true, hostFingerprint: challenges[0]!.hostFingerprint }
- ])
- expect(results.filter((result) => !result.ok)).toEqual(
- Array.from({ length: 8 }, () => ({ ok: false, reason: 'already_consumed' }))
- )
+ for (const [index, challenge] of challenges.entries()) {
+ const challengeResults = results.slice(index * 5, index * 5 + 5)
+ expect(challengeResults.filter((result) => result.ok)).toEqual([
+ { ok: true, hostFingerprint: challenge!.hostFingerprint }
+ ])
+ expect(challengeResults.filter((result) => !result.ok)).toEqual(
+ Array.from({ length: 4 }, () => ({ ok: false, reason: 'already_consumed' }))
+ )
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| expect(results.filter((result) => result.ok)).toEqual([ | |
| { ok: true, hostFingerprint: challenges[0]!.hostFingerprint }, | |
| { ok: true, hostFingerprint: challenges[0]!.hostFingerprint } | |
| ]) | |
| expect(results.filter((result) => !result.ok)).toEqual( | |
| Array.from({ length: 8 }, () => ({ ok: false, reason: 'already_consumed' })) | |
| ) | |
| for (const [index, challenge] of challenges.entries()) { | |
| const challengeResults = results.slice(index * 5, index * 5 + 5) | |
| expect(challengeResults.filter((result) => result.ok)).toEqual([ | |
| { ok: true, hostFingerprint: challenge!.hostFingerprint } | |
| ]) | |
| expect(challengeResults.filter((result) => !result.ok)).toEqual( | |
| Array.from({ length: 4 }, () => ({ ok: false, reason: 'already_consumed' })) | |
| ) | |
| } |
|
|
||
| async function check(): Promise<boolean> { | ||
| try { | ||
| await database.query('SELECT 1 AS ready') |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -a '^push-database\.ts$' . | head -n1)"
test -n "$file"
ast-grep outline "$file" --items all --type function,class
rg -n -C5 'query_timeout|statement_timeout|connectionTimeoutMillis|query\s*\(' "$file"Repository: stablyai/orca
Length of output: 7675
🏁 Script executed:
#!/bin/bash
set -euo pipefail
readiness="$(fd -a '^push-readiness\.ts$' . | head -n1)"
database="$(fd -a '^push-database\.ts$' . | head -n1)"
test -n "$readiness"
test -n "$database"
cat -n "$readiness"
sed -n '1,180p' "$database"Repository: stablyai/orca
Length of output: 7866
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C3 '"pg"|"node-postgres"|query_timeout|statement_timeout|connectionTimeoutMillis' \
--glob 'package.json' --glob 'pnpm-lock.yaml' --glob 'package-lock.json' --glob 'yarn.lock' .Repository: stablyai/orca
Length of output: 1039
🌐 Web query:
node-postgres pg 8.22.0 query_timeout statement_timeout connectionTimeoutMillis official documentation
💡 Result:
In node-postgres version 8.22.0, these settings are part of the client configuration object used when initializing a Client or a Pool [1][2]. They are defined in milliseconds and default to no timeout if not specified [1][2]. 1. statement_timeout: This is passed to the PostgreSQL server. It specifies the maximum duration a statement is allowed to run before the database aborts it and returns an error [1][2][3]. 2. query_timeout: This is handled by the node-postgres driver itself. It specifies how long the client will wait for a response from the server after sending a query. If this timeout is reached, the driver stops listening for a response, but the database may continue executing the query [1][2][3]. 3. connectionTimeoutMillis: This specifies the maximum number of milliseconds to wait for a new connection to be established with the database before failing [1][2]. For robust error handling, it is often recommended to configure both statement_timeout and query_timeout, with the query_timeout set slightly longer than the statement_timeout to allow the database sufficient time to process and return its own timeout error [4][3].
Citations:
- 1: https://node-postgres.com/apis/client
- 2: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx
- 3: https://stackoverflow.com/questions/59155572/how-to-set-query-timeout-in-relation-to-statement-timeout
- 4: GitHub pull request 1760 in brianc/node-postgres (link omitted to avoid creating a cross-reference)
Add a client-side query timeout. statement_timeout is enforced by PostgreSQL, and connectionTimeoutMillis only bounds new connections. Neither bounds an established client.query() during a network failure. A stalled query leaves pending set, so later /ready requests wait on the same promise. Configure query_timeout on the serving pool.
| if (!invalidBearerIps.available(ip)) return null | ||
| const result = await sessions.resolve(bearer) | ||
| if (!result.ok) invalidBearerIps.allow(ip) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -a '^push-auth-admission\.ts$' . | head -n1)"
test -n "$file"
ast-grep outline "$file" --items all --type class,function
sed -n '1,240p' "$file"
rg -n -C8 \
'invalidBearerIps|PushAuthAdmission|sessions\.resolve|parallel|concurr|invalid_token' \
cloud/apps/push/srcRepository: stablyai/orca
Length of output: 27955
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -a '^client-ip-rate-limit\.ts$' cloud/apps/push/src | head -n1)"
test -n "$file"
cat -n "$file"
rg -n -C5 'invalidBearerIps|invalidBearer|authAdmission|PushAuthAdmission' \
cloud/apps/push/src --glob '*.test.ts' --glob '*.ts'Repository: stablyai/orca
Length of output: 8775
Denial of Service
Reachability: External
Exploitability: Moderate
CWE: CWE-770 — Allocation of Resources Without Limits or Throttling
Make invalid-bearer admission atomic per IP.
PushAuthAdmission permits four concurrent callbacks, while available() does not reserve a token. Parallel invalid bearer requests can start multiple sessions.resolve() calls before invalidBearerIps.allow(ip) consumes tokens. Reserve the token before the lookup and release it only for valid sessions, or serialize these callbacks.
| const end = workflow.indexOf('\n - ', start + 1) | ||
| const block = workflow.slice(start, end === -1 ? undefined : end) | ||
| return block | ||
| .slice(block.indexOf(' run: |\n') + ' run: |\n'.length) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert that the step declares run: | before slicing.
If a step loses run: |, step() still extracts the indented body lines. run() can therefore execute the script, and the recovery test can pass without enforcing the workflow contract.
♻️ Proposed fix
+ const marker = ' run: |\n'
+ const offset = block.indexOf(marker)
+ assert.notEqual(offset, -1, `the "${name}" step no longer declares a run block`)
return block
- .slice(block.indexOf(' run: |\n') + ' run: |\n'.length)
+ .slice(offset + marker.length)| assert.match(workflow.slice(deploy, activation), /\.mode == "validation"/) | ||
| assert.ok(position('Prove the runtime identity can reach FCM') < activation) | ||
| const active = workflow.slice(activation, shift) | ||
| assert.ok(active.indexOf('gcloud run deploy') < active.indexOf('gcloud run revisions delete')) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert presence before comparing positions, or the ordering checks can pass vacuously.
String.prototype.indexOf returns -1 when the needle is absent. On Line 39, if ACTIVATION_ATTEMPTED=true is deleted from the workflow, the comparison becomes -1 < <index of deploy>, which is true, and the test still passes. The marker that gates rollback then loses its only assertion here. Line 33 has the same shape for gcloud run deploy.
Use the existing position-style guard, or assert the substring exists first.
♻️ Proposed fix
+ const at = (haystack, needle) => {
+ const index = haystack.indexOf(needle)
+ assert.notEqual(index, -1, `the activation step no longer contains "${needle}"`)
+ return index
+ }
- assert.ok(active.indexOf('gcloud run deploy') < active.indexOf('gcloud run revisions delete'))
+ assert.ok(at(active, 'gcloud run deploy') < at(active, 'gcloud run revisions delete'))
@@
- assert.ok(active.indexOf('ACTIVATION_ATTEMPTED=true') < active.indexOf('gcloud run deploy'))
+ assert.ok(at(active, 'ACTIVATION_ATTEMPTED=true') < at(active, 'gcloud run deploy'))Also applies to: 39-39
There was a problem hiding this comment.
ℹ️ No new issues in this follow-up commit — one prior minor observation remains open.
Reviewed changes
- Cross-host admission budget — added a shared 6,000 req/min per-instance client-IP rate limit to the authenticated
/v1/devices*and/v1/sendroutes so generating fresh host keys can't reset admission, and rewrote the limiter's eviction from a full-map scan/sort to Map-insertion-order LRU eviction with a test pinning that no full-map iteration occurs. - Fail-closed FCM project —
ORCA_PUSH_FCM_PROJECT_IDis now required instead of silently defaulting to a hardcoded project; Terraform suppliesvar.project_idand the unusedpush_fcm_project_idoverride plus the gateway/FCM defaults were removed. - Device list bounded by host cap — the list query now reuses
maxDevicesPerHostand drops the redundantmaxDevicesPerListResponse.
The new push-authenticated-ip-limit.test.ts asserts real behavior (exact 6,000/600 exhaustion, key-rotation can't reset the budget, per-IP isolation, window refill) rather than pass-through snapshots, and the LRU rewrite keeps the map bounded on every call including denials.
ℹ️ Prior observation still open
The earlier dead-device-cap note (device-registry-store.upsert counts dead_at IS NOT NULL rows toward maxDevicesPerHost, with no automatic reap until Part 2's deleteOwned) is unchanged by these commits and stays an open thread. Left unresolved intentionally — it's a defer-able, non-blocking note aligned with the Part 2 sequence, not a regression introduced here.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 799ef3dc-e4ec-4c18-8d52-be28fbc3694a
📒 Files selected for processing (15)
cloud/README.mdcloud/apps/push/src/client-ip-rate-limit.test.tscloud/apps/push/src/client-ip-rate-limit.tscloud/apps/push/src/config.test.tscloud/apps/push/src/config.tscloud/apps/push/src/device-registry-store.test.tscloud/apps/push/src/device-registry-store.tscloud/apps/push/src/push-authenticated-ip-limit.test.tscloud/apps/push/src/push-server.tscloud/apps/push/src/push-validation.test.tscloud/docs/push-gateway.mdcloud/infra/terraform/push-gateway.tfcloud/infra/terraform/variables.tfcloud/packages/push-contract/src/contract.test.tscloud/packages/push-contract/src/push-limits.ts
💤 Files with no reviewable changes (2)
- cloud/infra/terraform/variables.tf
- cloud/packages/push-contract/src/contract.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- cloud/apps/push/src/device-registry-store.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| const limiter = new ClientIpRateLimiter({ capacity: 1, maxTrackedIps: 2, now: () => 1_000 }) | ||
| limiter.allow('old') | ||
| limiter.allow('recent') | ||
| expect(limiter.allow('old')).toBe(false) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert that a denied allow() refreshes LRU recency.
ClientIpRateLimiter.allow reinserts the bucket even when it denies the request. Keep allow('old'); it makes old most recent, so new must evict recent.
Proposed fix
- expect(limiter.available('old')).toBe(false)
- expect(limiter.available('recent')).toBe(true)
+ expect(limiter.available('old')).toBe(true)
+ expect(limiter.available('recent')).toBe(false)There was a problem hiding this comment.
ℹ️ No new issues in this follow-up commit — the prior dead-device-cap observation remains open and unchanged.
Reviewed changes
- APNs topic-error handling —
DeviceTokenNotForTopicno longer retires a device registration; it is now classified as a non-retryable provider error, so correcting the topic or environment resumes delivery without re-registering the phone, pinned by the newapns-topic-recovery.test.ts. - Deploy preflight pin — the inert-validation preflight in
.github/workflows/cloud-push-deploy.ymlnow supplies the requiredORCA_PUSH_FCM_PROJECT_ID, and a newpush-deploy-preflight.test.tsexecutes that exact workflow script against the realloadPushConfigloader. - Contract default lock —
contract.test.tsnow assertsauthenticatedRequestsPerMinutePerIp: 6_000alongside the other normative limits.
The DeviceTokenNotForTopic reclassification matches Apple's semantics (a topic/environment mismatch, not a dead token) and is a strict improvement: retiring the device on a config error was destructive, while the new behavior drops only the affected notification (five-minute TTL) and keeps the registration live. The deploy-preflight test can genuinely fail — it fails closed if the required FCM project or the validation-mode rejection regresses — and the topic-recovery test asserts the real apnsRequests count and delivery_sent counter rather than a pass-through shape.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

ELI5
Adds the server that accepts a notification from a paired desktop and delivers it through Apple or Google, with a durable queue so accepted work survives restarts. This is the cloud layer of the mobile-push split; desktop and mobile integration follow separately.
What Changed
Three commits provide the review order:
No desktop/mobile source or cross-client design document is included. The push deployment workflow is already on main. Existing mainline identity/census changes are preserved.
Why
The existing mobile socket path cannot provide notifications when the app is closed. The gateway supplies the backend independently of the client changes. Shared schema startup preserves the existing Relay implementation rather than introducing a second copy.
Linked Issue
Split from #19204, which remains the complete reference PR. This is PR 1 of the planned cloud → desktop → mobile sequence.
Visual Proof
N/A — backend and infrastructure only; no user interface changes in this PR.
Testing
pnpm testpassed: 1,677 tests, including 140 push tests and 632 Relay tests with isolated PostgreSQL 16 on port 55440. Shared-PostgreSQL Relay tests use the existing serialized project; push tests retain normal parallelism.cloud/docs/push-database-cutover.md; it must be resolved separately before an infrastructure apply. No Terraform apply or production deployment occurred for this split.Review
Code/protocol matches the reviewed cloud portion of
8eea3ee9d5, apart from preserving newer mainline changes, removing omitted-document references and correcting stale comments. Start with the three commits above. Runtime queue/claim/retry behavior was not redesigned during extraction.Agent skill upstream boundary
Checklist
Review follow-up
Adds a 6,000-request/minute per-instance IP budget across authenticated routes so rotating host keys cannot reset all admission limits. Existing 600/minute host and 300-alert/300-dismissal per-15-minute event limits remain. This budget is shared behind NAT and is not a global spending cap.
Replaces full-map rate-limiter scans/sorts with Map-order eviction, removes the unused cross-project FCM override and gateway/project defaults, reuses the enforced device cap for list queries, and corrects dead-token guidance. Standalone startup now requires an explicit FCM project; Terraform already supplies the deployment project. No database migration or deployment in this follow-up.
Diff size
Added/deleted diff lines, including comments and blank lines: