-
Notifications
You must be signed in to change notification settings - Fork 371
Realtime gateway: sharee access-check endpoint + SSE reconnect cursor #2336
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
316344a
feat: implement gateway access-check tokens and related endpoint for …
mrkoreye be9709b
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye bf6ce6c
feat: enhance hosted SSE reconnect logic and add tests for stream URL…
mrkoreye 62abd07
Merge branch 'korey/moar-updates-realtime' of github.com:BuilderIO/ag…
mrkoreye 4ea7687
feat: enhance gateway access-check tokens and improve SSE reconnect l…
mrkoreye ab35669
feat: implement DB-assigned version allocation and related tests for …
mrkoreye 00d38a6
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye c6d4e3c
Merge branch 'korey/moar-updates-realtime' of github.com:BuilderIO/ag…
mrkoreye eca6b4f
fix: adjust timeout expectation in runMonitorCheck test for CI consis…
mrkoreye 1de8f8c
fix: increase timer step for polling in tests to improve CI performance
mrkoreye fe532ce
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye 09b32ef
feat: implement recovery of committed version for failed allocations …
mrkoreye 07a5166
Merge branch 'korey/moar-updates-realtime' of github.com:BuilderIO/ag…
mrkoreye 496bdd3
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye 83603f2
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye 81d3823
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye a7dd1d7
test: improve timer handling in A2AClient tests for better CI perform…
mrkoreye fe29b67
Merge branch 'korey/moar-updates-realtime' of github.com:BuilderIO/ag…
mrkoreye 431a3e9
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye 6678ba5
fix: enhance ssrfSafeFetch to block private/internal address requests
mrkoreye 41ba919
Merge branch 'korey/moar-updates-realtime' of github.com:BuilderIO/ag…
mrkoreye 2ed6193
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye aaa3e2e
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye 904d27e
Merge branch 'main' into korey/moar-updates-realtime
mrkoreye File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| --- | ||
| "@agent-native/core": minor | ||
| --- | ||
|
|
||
| Realtime sync: two hosted-gateway follow-ups. Both are opt-in and leave apps without hosted-realtime config unchanged. | ||
|
|
||
| - Hosted SSE reconnect now sends the client's cursor (`&since=`) on the gateway stream URL, so the gateway's connect-time catch-up replays events written during the reconnect gap immediately instead of deferring them to the next poll. First connect (cursor 0) is unaffected. Because a `since=` only takes effect when a new `EventSource` is constructed (the browser's own auto-reconnect reuses the URL frozen at construction), the hosted transport now owns reconnects: on a stream error it closes the stream and schedules its own reconnect so the next connect rebuilds the URL from the current cursor, keeping the token on transient errors and reminting on a closed stream. A late error from a replaced (stale) stream is ignored so it cannot tear down the current one. Local mode keeps native EventSource reconnect. | ||
| - New gateway access-check tokens (`signGatewayAccessToken`/`verifyGatewayAccessToken`, exported from `./server/short-lived-token`): per-project HMAC key, a `typ` discriminator (not interchangeable with subscribe or media tokens), and the full access query (`resourceType`/`resourceId`/`userEmail`/`orgId`) bound into the signature so the app authenticates the params, not just the caller. `verifyGatewayAccessToken` also accepts an optional expected `projectId` to bind the channel (mirroring `verifyRealtimeSubscribeToken`); the `can-see` endpoint passes its own project id when known. | ||
| - New endpoint `GET /_agent-native/can-see` mounted by core-routes. The hosted Realtime Gateway has no copy of an app's shareable-resource registry, so it calls this to resolve sharee visibility: the endpoint verifies a gateway access-check token against the app's per-project secret, runs the app's registry-based `resolveAccess`, and returns `{ allowed }`. Fails closed (`allowed: false`) on an unknown resource type or lookup error; 404 when the app has no realtime secret; `Cache-Control: private, no-store`. | ||
| - New `AppSyncStateOptions.dbAssignedVersions` (default off): allocate durable-event versions from the app's Postgres DB — a one-row allocator advanced with `GREATEST(v + 1, epoch_ms_now)` inside the same autocommit insert statement — instead of the per-writer in-memory clock counter. Hosted realtime has multiple writers per app DB (the app's serverless instances plus gateway instances), where clock skew can assign a LOWER version to a LATER event and a client whose cursor passed the higher value filters the later event out permanently; DB allocation serializes on the allocator row's lock so version order equals commit order across all writers. Buffer/emit defer until the allocated version returns (no provisional version ever reaches clients); a deterministic-id dedupe loser adopts the winner's version via `ON CONFLICT DO UPDATE ... RETURNING`; on DB failure the writer falls back to clock allocation (logged) so the in-process fast path never stalls. Versions stay epoch-ms scale, so existing cursors, seeds, and lag metrics are unaffected. The default instance enables this automatically when `AGENT_NATIVE_REALTIME_TRANSPORT=hosted` with a gateway URL; self-hosted apps are byte-identical. Postgres only; ignored on SQLite. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
132 changes: 132 additions & 0 deletions
132
packages/core/src/client/use-db-sync.gateway-reconnect.spec.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| // @vitest-environment happy-dom | ||
|
|
||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { | ||
| _resetSyncTransportRegistryForTests, | ||
| subscribeSyncEvents, | ||
| } from "./use-db-sync"; | ||
|
|
||
| /** Minimal EventSource stand-in that records every constructed instance so the | ||
| * test can inspect the URL each connect was built with. */ | ||
| class FakeEventSource { | ||
| static readonly CONNECTING = 0; | ||
| static readonly OPEN = 1; | ||
| static readonly CLOSED = 2; | ||
| static instances: FakeEventSource[] = []; | ||
| readyState = FakeEventSource.CONNECTING; | ||
| onopen: (() => void) | null = null; | ||
| onerror: (() => void) | null = null; | ||
| onmessage: ((message: { data: string }) => void) | null = null; | ||
| addEventListener(): void {} | ||
| constructor(readonly url: string) { | ||
| FakeEventSource.instances.push(this); | ||
| } | ||
| close(): void { | ||
| this.readyState = FakeEventSource.CLOSED; | ||
| } | ||
| } | ||
|
|
||
| describe("hosted SSE reconnect ownership", () => { | ||
| beforeEach(() => { | ||
| vi.useFakeTimers(); | ||
| FakeEventSource.instances = []; | ||
| _resetSyncTransportRegistryForTests(); | ||
| vi.stubGlobal("EventSource", FakeEventSource); | ||
| vi.stubGlobal( | ||
| "fetch", | ||
| vi.fn(async (input: RequestInfo | URL) => { | ||
| const url = String(input); | ||
| if (url.includes("/_agent-native/realtime-token")) { | ||
| return { | ||
| ok: true, | ||
| json: async () => ({ token: "tok-1", ttlSeconds: 600 }), | ||
| }; | ||
| } | ||
| return { ok: true, json: async () => ({ version: 0, events: [] }) }; | ||
| }), | ||
| ); | ||
| ( | ||
| window as unknown as { __AGENT_NATIVE_CONFIG__: unknown } | ||
| ).__AGENT_NATIVE_CONFIG__ = { | ||
| realtime: { transport: "hosted", gatewayBaseUrl: "https://gw.example" }, | ||
| }; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| _resetSyncTransportRegistryForTests(); | ||
| delete (window as unknown as { __AGENT_NATIVE_CONFIG__?: unknown }) | ||
| .__AGENT_NATIVE_CONFIG__; | ||
| vi.unstubAllGlobals(); | ||
| vi.useRealTimers(); | ||
| }); | ||
|
|
||
| it("rebuilds the stream URL with the current cursor on a browser-managed reconnect", async () => { | ||
| const unsub = subscribeSyncEvents({ onEvents: () => {} }); | ||
|
|
||
| // Mint resolves, then the first stream opens with the token and no cursor. | ||
| await vi.advanceTimersByTimeAsync(200); | ||
| const first = FakeEventSource.instances.at(-1)!; | ||
| expect(first.url).toContain("token=tok-1"); | ||
| expect(first.url).not.toContain("since="); | ||
|
|
||
| first.readyState = FakeEventSource.OPEN; | ||
| first.onopen?.(); | ||
|
|
||
| // A delivered batch advances the transport cursor to 100. | ||
| first.onmessage?.({ | ||
| data: JSON.stringify({ | ||
| type: "batch", | ||
| version: 100, | ||
| events: [ | ||
| { version: 100, source: "app-state", type: "change", key: "*" }, | ||
| ], | ||
| }), | ||
| }); | ||
|
|
||
| // Transient (CONNECTING) error: the browser would auto-reconnect this same | ||
| // instance with its frozen URL. We must own it and close the stream. | ||
| first.readyState = FakeEventSource.CONNECTING; | ||
| first.onerror?.(); | ||
| expect(first.readyState).toBe(FakeEventSource.CLOSED); | ||
|
|
||
| // The owned reconnect builds a NEW stream carrying the current cursor and | ||
| // the still-valid token (no re-mint on a transient error). | ||
| await vi.advanceTimersByTimeAsync(1500); | ||
| const second = FakeEventSource.instances.at(-1)!; | ||
| expect(second).not.toBe(first); | ||
| expect(second.url).toContain("since=100"); | ||
| expect(second.url).toContain("token=tok-1"); | ||
|
|
||
| unsub(); | ||
| }); | ||
|
|
||
| it("ignores a late error from a replaced (stale) stream", async () => { | ||
| const unsub = subscribeSyncEvents({ onEvents: () => {} }); | ||
| await vi.advanceTimersByTimeAsync(200); | ||
| const first = FakeEventSource.instances.at(-1)!; | ||
| first.readyState = FakeEventSource.OPEN; | ||
| first.onopen?.(); | ||
|
|
||
| // Force a reconnect so `first` is replaced by `second`. | ||
| first.readyState = FakeEventSource.CONNECTING; | ||
| first.onerror?.(); | ||
| await vi.advanceTimersByTimeAsync(1500); | ||
| const second = FakeEventSource.instances.at(-1)!; | ||
| expect(second).not.toBe(first); | ||
| second.readyState = FakeEventSource.OPEN; | ||
| second.onopen?.(); | ||
|
|
||
| const countBefore = FakeEventSource.instances.length; | ||
| // The stale `first` fires a late error: the guard must ignore it so the | ||
| // healthy `second` is neither closed nor triggers a spurious reconnect. | ||
| first.readyState = FakeEventSource.CONNECTING; | ||
| first.onerror?.(); | ||
| await vi.advanceTimersByTimeAsync(1500); | ||
|
|
||
| expect(second.readyState).toBe(FakeEventSource.OPEN); | ||
| expect(FakeEventSource.instances.length).toBe(countBefore); | ||
|
|
||
| unsub(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.