Repository navigation
feat(account): construct the session client with identity and add dispose #17831
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
Changes from all commits
c19c893
e211cd3
64ece9e
3aa6c3c
36c5790
c66a653
9348238
b742c75
7184764
d0e3c13
3633eb7
cea548a
61b4451
b7a3541
885faf4
e68e3f0
4db1dbe
d69670b
7a16e1f
6c9c0a5
d5e9fc3
4878540
3ccca0d
d18c716
ce6d000
c265fdb
821bdf6
c31f4ac
f7e2e23
e7153ec
9874cfe
651e277
59b7573
71e38b3
0f96221
612a1bb
44bbc19
84a1ca2
aeb36fc
23c5bb6
df8ea1d
82e272e
65fa927
448c4b9
52054e1
838ae89
386d96d
1b89a09
ffbec33
006f110
df6ffd7
19ae957
d48db49
7d1d4c7
9826d1b
f8e97d4
4d98540
feaeccc
01a3b78
112bec2
f32024e
4fbdc9b
6b17307
7614f52
4fa9efd
2949c2e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,208 @@ | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| import type { SessionSnapshot } from './session.js' | ||
| import { createSessionClient } from './session.js' | ||
| import { makeClient } from './__fixtures__/sessionClientFixture.js' | ||
| import { | ||
| EXCHANGE_URL, | ||
| NINETY_MINUTES_MS, | ||
| deferred, | ||
| manualIdentity, | ||
| memoryStorage, | ||
| mintResponse, | ||
| okFetch, | ||
| testUser | ||
| } from './__fixtures__/sessionFakes.js' | ||
|
|
||
| function phasesOf(client: ReturnType<typeof makeClient>['client']) { | ||
| const phases: SessionSnapshot['phase'][] = [] | ||
| client.subscribe((snapshot) => phases.push(snapshot.phase)) | ||
| return phases | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| vi.useFakeTimers() | ||
| }) | ||
|
|
||
| describe('constructing with identity', () => { | ||
| it.for([ | ||
| { | ||
| name: 'auto-mints on the first delivered user', | ||
| options: {}, | ||
| phases: ['pending', 'minting', 'authenticated'], | ||
| mints: 1 | ||
| }, | ||
| { | ||
| name: 'with autoMint: false sets the user and leaves minting to the host', | ||
| options: { autoMint: false }, | ||
| phases: ['pending', 'minting'], | ||
| mints: 0 | ||
| } | ||
| ] as const)('$name', async ({ options, phases, mints }) => { | ||
| const fetchImpl = okFetch() | ||
| const identity = manualIdentity() | ||
| const { client } = makeClient({ fetchImpl, ...options }, identity.port) | ||
| const seen = phasesOf(client) | ||
| const user = testUser() | ||
|
|
||
| identity.fire(user) | ||
| await vi.waitFor(() => expect(seen).toEqual(phases)) | ||
| await vi.advanceTimersByTimeAsync(0) | ||
|
|
||
| expect(seen).toEqual(phases) | ||
| expect(client.getSnapshot().user?.uid).toBe(user.uid) | ||
| expect(user.getIdToken).toHaveBeenCalledTimes(mints) | ||
| expect(fetchImpl).toHaveBeenCalledTimes(mints) | ||
| }) | ||
|
|
||
| it('settles signed-out without a mint when the first delivery is null', () => { | ||
| const fetchImpl = okFetch() | ||
| const identity = manualIdentity() | ||
| const { client } = makeClient({ fetchImpl }, identity.port) | ||
| const seen = phasesOf(client) | ||
|
|
||
| identity.fire(null) | ||
|
|
||
| expect(seen).toEqual(['pending', 'signed-out']) | ||
| expect(fetchImpl).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('refuses a port that did not come from the package entry or the testing seam', () => { | ||
| expect(() => | ||
| createSessionClient( | ||
| { exchangeUrl: EXCHANGE_URL, storage: memoryStorage() }, | ||
| // @ts-expect-error an unbranded port is not an AccountIdentity | ||
| { onUserChanged: () => () => undefined } | ||
| ) | ||
| ).toThrow('the session client needs the identity') | ||
| }) | ||
| }) | ||
|
|
||
| describe('dispose', () => { | ||
| it('returns the snapshot to pending, stops the armed scheduler, and unsubscribes the port exactly once', async () => { | ||
| const fetchImpl = okFetch() | ||
| const identity = manualIdentity() | ||
| const { client } = makeClient( | ||
| { | ||
| fetchImpl, | ||
| refreshScheduler: {} | ||
| }, | ||
| identity.port | ||
| ) | ||
| identity.fire(testUser()) | ||
| await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) | ||
|
|
||
| client.dispose() | ||
| client.dispose() | ||
|
|
||
| expect(client.getSnapshot().phase).toBe('pending') | ||
| expect(client.getToken()).toBeUndefined() | ||
| expect(identity.unsubscribe).toHaveBeenCalledOnce() | ||
| await vi.advanceTimersByTimeAsync(NINETY_MINUTES_MS * 10) | ||
| expect( | ||
| fetchImpl, | ||
| 'a disposed client re-minting on a timer would resurrect a dead session' | ||
| ).toHaveBeenCalledOnce() | ||
| }) | ||
|
|
||
| it('is a no-op on a client constructed without identity', () => { | ||
| const client = createSessionClient({ | ||
| exchangeUrl: EXCHANGE_URL, | ||
| storage: memoryStorage() | ||
| }) | ||
|
|
||
| client.dispose() | ||
|
|
||
| expect(client.getSnapshot().phase).toBe('pending') | ||
| }) | ||
|
|
||
| it('ignores an identity event delivered after dispose', () => { | ||
| const fetchImpl = okFetch() | ||
| const identity = manualIdentity() | ||
| const { client } = makeClient({ fetchImpl }, identity.port) | ||
|
|
||
| client.dispose() | ||
| identity.fire(testUser()) | ||
|
|
||
| expect(client.getSnapshot().phase).toBe('pending') | ||
| expect(fetchImpl).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('never commits a mint that was in flight when the client was disposed', async () => { | ||
| const mint = deferred<Response>() | ||
| const fetchImpl = vi.fn<typeof fetch>(() => mint.promise) | ||
| const identity = manualIdentity() | ||
| const { client, storage } = makeClient({ fetchImpl }, identity.port) | ||
| identity.fire(testUser()) | ||
| await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()) | ||
|
|
||
| client.dispose() | ||
| mint.resolve(mintResponse('stale-after-dispose')) | ||
| await vi.advanceTimersByTimeAsync(0) | ||
|
|
||
| expect(client.getSnapshot().phase).toBe('pending') | ||
| expect(client.getToken()).toBeUndefined() | ||
| expect( | ||
| storage.raw(), | ||
| 'a mint that outlives its identity must not repopulate the cache' | ||
| ).toBeNull() | ||
| }) | ||
|
|
||
| it('still serves an explicit-user mint after dispose, like a detach, without publishing it', async () => { | ||
| const identity = manualIdentity() | ||
| const { client, storage } = makeClient( | ||
| { fetchImpl: okFetch() }, | ||
| identity.port | ||
| ) | ||
| identity.fire(testUser()) | ||
| await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) | ||
| client.dispose() | ||
|
|
||
| await expect(client.ensureFresh(testUser())).resolves.toMatchObject({ | ||
| status: 'ok' | ||
| }) | ||
|
|
||
| expect(storage.raw()).not.toBeNull() | ||
| expect(client.getSnapshot().phase).toBe('pending') | ||
| expect(client.getToken()).toBeUndefined() | ||
| }) | ||
|
|
||
| it('leaves the client attachable again, like a detach', async () => { | ||
| const identity = manualIdentity() | ||
| const { client } = makeClient( | ||
| { fetchImpl: okFetch('jwt-b') }, | ||
| identity.port | ||
| ) | ||
| client.dispose() | ||
| const replacement = manualIdentity() | ||
|
|
||
| client.attachIdentity(replacement.port) | ||
| replacement.fire(testUser('uid-2')) | ||
|
|
||
| await vi.waitFor(() => expect(client.getToken()).toBe('jwt-b')) | ||
| expect(identity.unsubscribe).toHaveBeenCalledOnce() | ||
| }) | ||
| }) | ||
|
|
||
| describe('attachIdentity on a client constructed with identity', () => { | ||
| it('replaces the constructed subscription', async () => { | ||
| const identity = manualIdentity() | ||
| const { client } = makeClient( | ||
| { fetchImpl: okFetch('jwt-b') }, | ||
| identity.port | ||
| ) | ||
| const replacement = manualIdentity() | ||
|
|
||
| client.attachIdentity(replacement.port) | ||
| replacement.fire(testUser('uid-2')) | ||
| await vi.waitFor(() => expect(client.getToken()).toBe('jwt-b')) | ||
| identity.fire(null) | ||
|
|
||
| expect(identity.unsubscribe).toHaveBeenCalledOnce() | ||
| expect( | ||
| client.getSnapshot().phase, | ||
| 'the constructed port is superseded; its events must not sign the client out' | ||
| ).toBe('authenticated') | ||
| expect(client.getToken()).toBe('jwt-b') | ||
| }) | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -106,6 +106,8 @@ export interface SessionClientOptions extends SessionRequestOptions { | |
| readonly storage: CredentialStorage | ||
| readonly freshMarginMs?: number | ||
| readonly refreshScheduler?: RefreshSchedulerOptions | ||
| /** Applies to the identity passed at construction; see `AttachIdentityOptions.autoMint`. */ | ||
| readonly autoMint?: boolean | ||
| } | ||
|
|
||
| /** | ||
|
|
@@ -150,11 +152,18 @@ export interface AttachIdentityOptions { | |
| } | ||
|
|
||
| export interface SessionClient<TUser extends AccountUser = AccountUser> { | ||
| /** @deprecated Transitional Pinia-adapter seam; package-owned identity replaces it (FE-2171, PoC #16639). */ | ||
| /** @deprecated Transitional Pinia-adapter seam; pass the identity as `createSessionClient`'s second argument instead (FE-2171, PoC #16639). */ | ||
| attachIdentity: ( | ||
| identity: AccountIdentity<TUser>, | ||
| options?: AttachIdentityOptions | ||
| ) => () => void | ||
| /** | ||
| * Detaches the current identity; the persisted credential stays until | ||
| * `clearStoredCredential`. Not terminal, like a detach: an explicit-user | ||
| * mint issued after `dispose()` still commits and can re-arm the scheduler | ||
| * and cross-tab lease, so dispose and then stop calling the client. | ||
| */ | ||
| dispose: () => void | ||
| getSnapshot: () => SessionSnapshot<TUser> | ||
| subscribe: ( | ||
| listener: (snapshot: SessionSnapshot<TUser>) => void | ||
|
|
@@ -210,7 +219,8 @@ const DEFAULT_MINT_TIMEOUT_MS = 15_000 | |
| * production's default branch. | ||
| */ | ||
| export function createSessionClient<TUser extends AccountUser = AccountUser>( | ||
| clientOptions: SessionClientOptions | ||
| clientOptions: SessionClientOptions, | ||
| identity?: AccountIdentity<TUser> | ||
| ): SessionClient<TUser> { | ||
| const { | ||
| exchangeUrl, | ||
|
|
@@ -487,31 +497,42 @@ export function createSessionClient<TUser extends AccountUser = AccountUser>( | |
| return result | ||
| } | ||
|
|
||
| return { | ||
| attachIdentity(identity, attachOptions) { | ||
| if (!isAccountIdentity(identity)) { | ||
| throw new Error( | ||
| 'attachIdentity needs the identity from @comfyorg/account-core/firebase (or /testing)' | ||
| ) | ||
| function subscribeIdentity( | ||
| port: AccountIdentity<TUser>, | ||
| autoMint: boolean | ||
| ): () => void { | ||
| if (!isAccountIdentity(port)) { | ||
| throw new Error( | ||
| 'the session client needs the identity from @comfyorg/account-core/firebase (or /testing)' | ||
| ) | ||
| } | ||
| detachCurrent?.() | ||
| let unsubscribe: () => void = () => undefined | ||
| const detach = () => { | ||
| if (detachCurrent !== detach) return | ||
| detachCurrent = undefined | ||
| unsubscribe() | ||
| commit({ type: 'identity-detached' }) | ||
| } | ||
| detachCurrent = detach | ||
| unsubscribe = port.onUserChanged((next) => { | ||
| if (detachCurrent !== detach) return | ||
| commit({ type: 'identity-changed', user: next }) | ||
| if (detachCurrent === detach && next && autoMint) { | ||
| void refreshWith(ensureCore, next) | ||
| } | ||
| }) | ||
| if (detachCurrent !== detach) unsubscribe() | ||
| return detach | ||
| } | ||
|
|
||
| if (identity) subscribeIdentity(identity, clientOptions.autoMint !== false) | ||
|
MaanilVerma marked this conversation as resolved.
Resolved
|
||
|
|
||
| return { | ||
| attachIdentity: (port, attachOptions) => | ||
| subscribeIdentity(port, attachOptions?.autoMint !== false), | ||
| dispose() { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. question: After The timer itself is harmless — That test uses no Is
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Deliberate: dispose() is non-terminal, like a detach, and the owner confirmed that earlier in this review pass (which is why the test is named "still serves an explicit-user mint after dispose, like a detach, without publishing it"). You are right that the sharp edge is the cross-tab lease, not the timer: a caller-origin mint after dispose re-arms armAfterCommit and re-acquires the lease, and a second dispose is a no-op, so nothing releases it. It is latent today (dispose has no production caller, and it needs an explicit mint plus a configured scheduler), so rather than make dispose terminal now I have documented the contract on the interface: the dispose() JSDoc now says it is not terminal, that an explicit-user mint after dispose can re-arm the scheduler and cross-tab lease, and to dispose then stop calling the client (2949c2e). If we later want it terminal, the caller path can refuse to commit once the identity is gone; happy to file that as its own change if you'd prefer it enforced rather than documented. |
||
| detachCurrent?.() | ||
| let active = true | ||
| const unsubscribe = identity.onUserChanged((next) => { | ||
| if (!active) return | ||
| commit({ type: 'identity-changed', user: next }) | ||
| if (next && attachOptions?.autoMint !== false) { | ||
| void refreshWith(ensureCore, next) | ||
| } | ||
| }) | ||
| const detach = () => { | ||
| if (!active) return | ||
| active = false | ||
| detachCurrent = undefined | ||
| unsubscribe() | ||
| commit({ type: 'identity-detached' }) | ||
| } | ||
| detachCurrent = detach | ||
| return detach | ||
| }, | ||
| getSnapshot, | ||
| subscribe(listener) { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit-pick (non-blocking): the
detachCurrent === detachre-check before the auto-mint is a third behavior tightening that is not in the Changes list. The old code rancommit(...)then unconditionallyif (next && autoMint) void refreshWith(...). Becausecommitpublishes, a subscriber that callsdispose()synchronously during that publish would previously still have gotten an auto-mint fired at a disposed client; now it does not.That is the behavior I would want — just worth a line in the PR body so a future reader knows it was deliberate rather than an artifact of the rewrite.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Body updated: the Changes list names the re-check before the auto-mint (a subscriber that disposes the client during the identity-changed publish no longer gets an auto-mint). Note #17835 later rewrote this seam and lost the guard; it is restored there in e87ba1f with a regression test.