diff --git a/packages/common/nbstore/src/realtime/manager.ts b/packages/common/nbstore/src/realtime/manager.ts index 588abcc0b2..1084003a3f 100644 --- a/packages/common/nbstore/src/realtime/manager.ts +++ b/packages/common/nbstore/src/realtime/manager.ts @@ -414,6 +414,15 @@ export class RealtimeManager { } } + dispose() { + this.resetConnection(); + for (const subject$ of Array.from(this.subscriptions.keys())) { + subject$.complete(); + } + this.subscriptions.clear(); + this.context = undefined; + } + private resetConnection() { this.handleDisconnect(); if (this.socketConnection) { diff --git a/packages/common/nbstore/src/worker/__tests__/consumer-realtime.spec.ts b/packages/common/nbstore/src/worker/__tests__/consumer-realtime.spec.ts new file mode 100644 index 0000000000..1ecd470660 --- /dev/null +++ b/packages/common/nbstore/src/worker/__tests__/consumer-realtime.spec.ts @@ -0,0 +1,288 @@ +import 'fake-indexeddb/auto'; + +import { OpClient, OpConsumer } from '@toeverything/infra/op'; +import { beforeEach, expect, test, vi } from 'vitest'; + +import { StoreManagerClient } from '../client'; +import { StoreManagerConsumer } from '../consumer'; +import type { WorkerManagerOps } from '../ops'; + +type Handler = (payload?: unknown) => void; + +class FakeSocket { + readonly handlers = new Map(); + readonly emitted: Array<{ event: string; payload: unknown }> = []; + connected = true; + id: string; + + constructor(readonly endpoint: string) { + this.id = `${endpoint}:socket`; + } + + on(event: string, handler: Handler) { + this.handlers.set(event, [...(this.handlers.get(event) ?? []), handler]); + } + + off(event: string, handler: Handler) { + this.handlers.set( + event, + (this.handlers.get(event) ?? []).filter(current => current !== handler) + ); + } + + emitWithAck(event: string, payload: unknown) { + this.emitted.push({ event, payload }); + if (event === 'realtime:subscribe') { + return Promise.resolve({ + data: { subscriptionId: `${this.id}:sub` }, + }); + } + if (event === 'realtime:unsubscribe') { + return Promise.resolve({ data: { ok: true } }); + } + return Promise.resolve({ + data: { + access: { + role: 'Owner', + permissions: { Workspace_Delete: true }, + team: false, + }, + }, + }); + } + + disconnect() { + this.connected = false; + for (const handler of this.handlers.get('disconnect') ?? []) { + handler('transport close'); + } + } +} + +const { resetSharedConnection, sockets } = vi.hoisted(() => ({ + resetSharedConnection: vi.fn(), + sockets: new Map(), +})); + +function getSocket(endpoint: string) { + let socket = sockets.get(endpoint); + if (!socket) { + socket = new FakeSocket(endpoint); + sockets.set(endpoint, socket); + } + return socket; +} + +vi.mock('../../impls/cloud/socket', () => ({ + SocketConnection: class { + static resetSharedConnection = resetSharedConnection; + readonly inner: { socket: FakeSocket }; + + constructor(endpoint: string) { + this.inner = { socket: getSocket(endpoint) }; + } + + get status() { + return this.inner.socket.connected ? 'connected' : 'closed'; + } + + get maybeConnection() { + return this.inner.socket.connected ? this.inner : undefined; + } + + connect() {} + + async waitForConnected() {} + + disconnect() { + this.inner.socket.disconnect(); + } + }, +})); + +beforeEach(() => { + vi.stubGlobal('BUILD_CONFIG', { appVersion: 'test' }); + sockets.clear(); + resetSharedConnection.mockClear(); +}); + +test('isolates realtime contexts and requests across multiple server endpoints', async () => { + const { port1, port2 } = new MessageChannel(); + const consumer = new OpConsumer(port2); + const storeManager = new StoreManagerConsumer([]); + storeManager.bindConsumer(consumer); + const client = new StoreManagerClient(new OpClient(port1)); + + try { + await client.realtime.configure({ + endpoint: 'https://selfhosted.example.com', + isSelfHosted: true, + authenticated: true, + }); + // Configuring an unauthenticated default cloud server (e.g. local workspace + // or another tab) must not overwrite or deauthenticate the self-hosted server. + await client.realtime.configure({ + endpoint: 'https://app.affine.pro', + isSelfHosted: false, + authenticated: false, + }); + + const response = await client.realtime.request( + 'workspace.access.get', + { workspaceId: 'ws-selfhosted' }, + { endpoint: 'https://selfhosted.example.com' } + ); + + expect(response.access.role).toBe('Owner'); + expect( + sockets.get('https://selfhosted.example.com')?.emitted + ).toContainEqual({ + event: 'realtime:request', + payload: { + op: 'workspace.access.get', + input: { workspaceId: 'ws-selfhosted' }, + clientVersion: 'test', + }, + }); + expect(sockets.has('https://app.affine.pro')).toBe(false); + expect(resetSharedConnection).not.toHaveBeenCalled(); + } finally { + consumer.destroy(); + port1.close(); + port2.close(); + } +}); + +test('deauthenticating one server does not disconnect another server subscription', async () => { + const { port1, port2 } = new MessageChannel(); + const consumer = new OpConsumer(port2); + const storeManager = new StoreManagerConsumer([]); + storeManager.bindConsumer(consumer); + const client = new StoreManagerClient(new OpClient(port1)); + + try { + await client.realtime.configure({ + endpoint: 'https://selfhosted.example.com', + isSelfHosted: true, + authenticated: true, + }); + await client.realtime.configure({ + endpoint: 'https://app.affine.pro', + isSelfHosted: false, + authenticated: true, + }); + + const ready = vi.fn(); + const subscription = client.realtime + .subscribe( + 'workspace.access.changed', + { workspaceId: 'ws-selfhosted' }, + { endpoint: 'https://selfhosted.example.com' } + ) + .subscribe({ + next: event => { + if ('type' in event) { + ready(); + } + }, + }); + + await vi.waitFor(() => expect(ready).toHaveBeenCalledTimes(1)); + + await client.realtime.configure({ + endpoint: 'https://app.affine.pro', + isSelfHosted: false, + authenticated: false, + }); + + expect(resetSharedConnection).toHaveBeenCalledTimes(1); + expect(resetSharedConnection).toHaveBeenCalledWith( + 'https://app.affine.pro', + false + ); + expect(sockets.get('https://selfhosted.example.com')?.connected).toBe(true); + + const status = await client.realtime.status({ + endpoint: 'https://selfhosted.example.com', + }); + expect(status.endpoint).toBe('https://selfhosted.example.com'); + expect(status.connected).toBe(true); + expect(status.subscriptions).toBe(1); + + subscription.unsubscribe(); + } finally { + consumer.destroy(); + port1.close(); + port2.close(); + } +}); + +test('disposes a removed server endpoint without disconnecting other endpoints or active shared tabs', async () => { + const channel1 = new MessageChannel(); + const channel2 = new MessageChannel(); + const consumer1 = new OpConsumer(channel1.port2); + const consumer2 = new OpConsumer(channel2.port2); + const storeManager = new StoreManagerConsumer([]); + storeManager.bindConsumer(consumer1); + storeManager.bindConsumer(consumer2); + const client1 = new StoreManagerClient( + new OpClient(channel1.port1) + ); + const client2 = new StoreManagerClient( + new OpClient(channel2.port1) + ); + + try { + await client1.realtime.configure({ + endpoint: 'https://selfhosted.example.com///', + isSelfHosted: true, + authenticated: true, + }); + await client2.realtime.configure({ + endpoint: 'https://selfhosted.example.com', + isSelfHosted: true, + authenticated: true, + }); + await client1.realtime.configure({ + endpoint: 'https://app.affine.pro', + isSelfHosted: false, + authenticated: true, + }); + + await client1.realtime.request( + 'workspace.access.get', + { workspaceId: 'ws-selfhosted' }, + { endpoint: 'https://selfhosted.example.com' } + ); + await client1.realtime.request( + 'workspace.access.get', + { workspaceId: 'ws-cloud' }, + { endpoint: 'https://app.affine.pro' } + ); + + expect(sockets.get('https://selfhosted.example.com')?.connected).toBe(true); + expect(sockets.get('https://app.affine.pro')?.connected).toBe(true); + + // Disposing one tab must keep the shared endpoint alive for the other tab. + await client1.realtime.dispose({ + endpoint: 'https://selfhosted.example.com/', + }); + expect(sockets.get('https://selfhosted.example.com')?.connected).toBe(true); + + // Disposing the last owner disconnects only that endpoint and preserves others. + await client2.realtime.dispose({ + endpoint: 'https://selfhosted.example.com', + }); + expect(sockets.get('https://selfhosted.example.com')?.connected).toBe( + false + ); + expect(sockets.get('https://app.affine.pro')?.connected).toBe(true); + } finally { + consumer1.destroy(); + consumer2.destroy(); + channel1.port1.close(); + channel1.port2.close(); + channel2.port1.close(); + channel2.port2.close(); + } +}); diff --git a/packages/common/nbstore/src/worker/client.ts b/packages/common/nbstore/src/worker/client.ts index b51566c080..9cabcf6fbc 100644 --- a/packages/common/nbstore/src/worker/client.ts +++ b/packages/common/nbstore/src/worker/client.ts @@ -56,6 +56,7 @@ type RealtimeWorkerClient = { call( name: 'realtime.request', payload: { + endpoint?: string; op: Op; input: RealtimeRequestInputOf; timeoutMs?: number; @@ -64,6 +65,7 @@ type RealtimeWorkerClient = { ob$( name: 'realtime.subscribe', payload: { + endpoint?: string; topic: Topic; input: RealtimeTopicInputOf; } @@ -195,11 +197,12 @@ export class RealtimeClient { request( op: Op, input: RealtimeRequestInputOf, - options?: { timeoutMs?: number; signal?: AbortSignal } + options?: { endpoint?: string; timeoutMs?: number; signal?: AbortSignal } ): Promise> { const request = (this.client as unknown as RealtimeWorkerClient).call( 'realtime.request', { + endpoint: options?.endpoint, op, input, timeoutMs: options?.timeoutMs, @@ -225,19 +228,30 @@ export class RealtimeClient { subscribe( topic: Topic, - input: RealtimeTopicInputOf + input: RealtimeTopicInputOf, + options?: { endpoint?: string } ): Observable | RealtimeSubscriptionReady> { return (this.client as unknown as RealtimeWorkerClient).ob$( 'realtime.subscribe', { + endpoint: options?.endpoint, topic, input, } ); } - status(): Promise { - return this.client.call('realtime.status'); + status(options?: { endpoint?: string }): Promise { + return this.client.call( + 'realtime.status', + options?.endpoint ? { endpoint: options.endpoint } : undefined + ); + } + + dispose(options: { endpoint: string }): Promise { + return this.client.call('realtime.dispose', { + endpoint: options.endpoint, + }); } } diff --git a/packages/common/nbstore/src/worker/consumer.ts b/packages/common/nbstore/src/worker/consumer.ts index 30e8cba0a3..2b04741150 100644 --- a/packages/common/nbstore/src/worker/consumer.ts +++ b/packages/common/nbstore/src/worker/consumer.ts @@ -35,7 +35,47 @@ export class StoreManagerConsumer { } private readonly telemetry = new TelemetryManager(); - private readonly realtime = new RealtimeManager(); + private readonly realtimeManagers = new Map< + string, + { + manager: RealtimeManager; + owners: Set>; + } + >(); + private readonly fallbackRealtime = new RealtimeManager(); + private defaultRealtimeEndpoint?: string; + + private normalizeRealtimeEndpoint(endpoint?: string) { + if (!endpoint) { + return undefined; + } + const trimmed = endpoint.trim(); + if (!trimmed) { + return undefined; + } + return trimmed.replace(/\/+$/, ''); + } + + private getRealtimeEntry(endpoint?: string) { + const key = + this.normalizeRealtimeEndpoint(endpoint) ?? this.defaultRealtimeEndpoint; + if (!key) { + return undefined; + } + let entry = this.realtimeManagers.get(key); + if (!entry) { + entry = { + manager: new RealtimeManager(), + owners: new Set(), + }; + this.realtimeManagers.set(key, entry); + } + return entry; + } + + private getRealtimeManager(endpoint?: string) { + return this.getRealtimeEntry(endpoint)?.manager ?? this.fallbackRealtime; + } constructor( private readonly availableStorageImplementations: StorageConstructor[], @@ -105,12 +145,49 @@ export class StoreManagerConsumer { 'telemetry.pageview': event => this.telemetry.pageview(event), 'telemetry.flush': () => this.telemetry.flush(), 'telemetry.getQueueState': () => this.telemetry.getQueueState(), - 'realtime.configure': context => this.realtime.setContext(context), - 'realtime.request': ({ op, input, timeoutMs }) => - this.realtime.request(op, input, { timeoutMs }), - 'realtime.subscribe': ({ topic, input }) => - this.realtime.subscribe(topic, input), - 'realtime.status': () => this.realtime.getStatus(), + 'realtime.configure': context => { + const key = this.normalizeRealtimeEndpoint(context.endpoint); + if (!key) { + return; + } + this.defaultRealtimeEndpoint = key; + const entry = this.getRealtimeEntry(key); + if (!entry) { + return; + } + entry.owners.add(consumer); + entry.manager.setContext({ + ...context, + endpoint: key, + }); + }, + 'realtime.request': ({ endpoint, op, input, timeoutMs }) => + this.getRealtimeManager(endpoint).request(op, input, { timeoutMs }), + 'realtime.subscribe': ({ endpoint, topic, input }) => + this.getRealtimeManager(endpoint).subscribe(topic, input), + 'realtime.status': payload => + this.getRealtimeManager(payload?.endpoint).getStatus(), + 'realtime.dispose': ({ endpoint }) => { + const key = this.normalizeRealtimeEndpoint(endpoint); + if (!key) { + return; + } + const entry = this.realtimeManagers.get(key); + if (!entry) { + return; + } + entry.owners.delete(consumer); + if (entry.owners.size > 0) { + return; + } + entry.manager.dispose(); + this.realtimeManagers.delete(key); + if (this.defaultRealtimeEndpoint === key) { + this.defaultRealtimeEndpoint = this.realtimeManagers + .keys() + .next().value; + } + }, }); } } diff --git a/packages/common/nbstore/src/worker/ops.ts b/packages/common/nbstore/src/worker/ops.ts index 496784ce04..666d7a1fad 100644 --- a/packages/common/nbstore/src/worker/ops.ts +++ b/packages/common/nbstore/src/worker/ops.ts @@ -220,6 +220,7 @@ export type WorkerManagerOps = { 'realtime.request': [ { [Op in RealtimeRequestName]: { + endpoint?: string; op: Op; input: RealtimeRequestInputOf; timeoutMs?: number; @@ -230,11 +231,13 @@ export type WorkerManagerOps = { 'realtime.subscribe': [ { [Topic in RealtimeTopicName]: { + endpoint?: string; topic: Topic; input: RealtimeTopicInputOf; }; }[RealtimeTopicName], RealtimeTopicEventOf | RealtimeSubscriptionReady, ]; - 'realtime.status': [void, RealtimeStatus]; + 'realtime.status': [{ endpoint?: string } | void, RealtimeStatus]; + 'realtime.dispose': [{ endpoint: string }, void]; }; diff --git a/packages/frontend/core/src/__tests__/auth-client-nonce.spec.ts b/packages/frontend/core/src/__tests__/auth-client-nonce.spec.ts index 1054659c42..34b99c7910 100644 --- a/packages/frontend/core/src/__tests__/auth-client-nonce.spec.ts +++ b/packages/frontend/core/src/__tests__/auth-client-nonce.spec.ts @@ -1,10 +1,10 @@ import { AuthSession } from '@affine/core/modules/cloud/entities/session'; import { AuthService } from '@affine/core/modules/cloud/services/auth'; import { FetchService } from '@affine/core/modules/cloud/services/fetch'; +import { ServerRealtimeService } from '@affine/core/modules/cloud/services/realtime'; import { ServerService } from '@affine/core/modules/cloud/services/server'; import { AuthStore } from '@affine/core/modules/cloud/stores/auth'; import { GlobalDialogService } from '@affine/core/modules/dialogs/services/dialog'; -import { NbstoreService } from '@affine/core/modules/storage'; import { UrlService } from '@affine/core/modules/url/services/url'; import { ServerDeploymentType } from '@affine/graphql'; import { Framework } from '@toeverything/infra'; @@ -40,8 +40,8 @@ describe('AuthService oauthPreflight', () => { } as any); framework.service(UrlService, { getClientScheme: () => null } as any); framework.service(GlobalDialogService, { open: vi.fn() } as any); - framework.service(NbstoreService, { - realtime: { subscribe: () => of() }, + framework.service(ServerRealtimeService, { + subscribe: () => of(), } as any); framework.service(ServerService, { server: { @@ -58,7 +58,7 @@ describe('AuthService oauthPreflight', () => { AuthStore, UrlService, GlobalDialogService, - NbstoreService, + ServerRealtimeService, ServerService, ]); diff --git a/packages/frontend/core/src/__tests__/auth-native-sign-in.spec.ts b/packages/frontend/core/src/__tests__/auth-native-sign-in.spec.ts index b413037ac7..ec2a409028 100644 --- a/packages/frontend/core/src/__tests__/auth-native-sign-in.spec.ts +++ b/packages/frontend/core/src/__tests__/auth-native-sign-in.spec.ts @@ -1,10 +1,10 @@ import { AuthSession } from '@affine/core/modules/cloud/entities/session'; import { AuthService } from '@affine/core/modules/cloud/services/auth'; import { FetchService } from '@affine/core/modules/cloud/services/fetch'; +import { ServerRealtimeService } from '@affine/core/modules/cloud/services/realtime'; import { ServerService } from '@affine/core/modules/cloud/services/server'; import { AuthStore } from '@affine/core/modules/cloud/stores/auth'; import { GlobalDialogService } from '@affine/core/modules/dialogs/services/dialog'; -import { NbstoreService } from '@affine/core/modules/storage'; import { UrlService } from '@affine/core/modules/url/services/url'; import { ServerDeploymentType } from '@affine/graphql'; import { Framework } from '@toeverything/infra'; @@ -41,8 +41,8 @@ describe('AuthService native password sign-in', () => { } as any); framework.service(UrlService, { getClientScheme: () => null } as any); framework.service(GlobalDialogService, { open: vi.fn() } as any); - framework.service(NbstoreService, { - realtime: { subscribe: () => of() }, + framework.service(ServerRealtimeService, { + subscribe: () => of(), } as any); framework.service(ServerService, { server: { @@ -59,7 +59,7 @@ describe('AuthService native password sign-in', () => { AuthStore, UrlService, GlobalDialogService, - NbstoreService, + ServerRealtimeService, ServerService, ]); diff --git a/packages/frontend/core/src/components/providers/workspace-side-effects.tsx b/packages/frontend/core/src/components/providers/workspace-side-effects.tsx index fd5277ce04..3b9e9d4558 100644 --- a/packages/frontend/core/src/components/providers/workspace-side-effects.tsx +++ b/packages/frontend/core/src/components/providers/workspace-side-effects.tsx @@ -16,6 +16,7 @@ import { EventSourceService, GraphQLService, RealtimeService, + ServerRealtimeService, } from '@affine/core/modules/cloud'; import { GlobalDialogService, @@ -25,7 +26,6 @@ import { DocsService } from '@affine/core/modules/doc'; import { EditorSettingService } from '@affine/core/modules/editor-setting'; import { useRegisterNavigationCommands } from '@affine/core/modules/navigation/view/use-register-navigation-commands'; import { QuickSearchContainer } from '@affine/core/modules/quicksearch'; -import { NbstoreService } from '@affine/core/modules/storage'; import { WorkbenchService } from '@affine/core/modules/workbench'; import { getAFFiNEWorkspaceSchema, @@ -143,7 +143,7 @@ export const WorkspaceSideEffects = () => { const graphqlService = useService(GraphQLService); const eventSourceService = useService(EventSourceService); const authService = useService(AuthService); - const nbstoreService = useService(NbstoreService); + const serverRealtimeService = useService(ServerRealtimeService); const realtimeConnectionError = useLiveData( useService(RealtimeService).connectionError$ ); @@ -174,7 +174,7 @@ export const WorkspaceSideEffects = () => { createAIRequestService( graphqlService.gql, eventSourceService.eventSource, - nbstoreService.realtime, + serverRealtimeService, async docIds => { await Promise.all( [currentWorkspace.id, 'db$docProperties', ...docIds].map(docId => @@ -193,7 +193,7 @@ export const WorkspaceSideEffects = () => { currentWorkspace.engine.doc, currentWorkspace.id, eventSourceService, - nbstoreService, + serverRealtimeService, graphqlService, globalDialogService, authService, diff --git a/packages/frontend/core/src/components/workspace-selector/workspace-card/index.spec.tsx b/packages/frontend/core/src/components/workspace-selector/workspace-card/index.spec.tsx index 1a71289601..14c3e273d9 100644 --- a/packages/frontend/core/src/components/workspace-selector/workspace-card/index.spec.tsx +++ b/packages/frontend/core/src/components/workspace-selector/workspace-card/index.spec.tsx @@ -9,10 +9,18 @@ import { afterEach, expect, test, vi } from 'vitest'; import { WorkspaceCard } from './index'; +type MockWorkspaceInfo = { + name?: string; + isOwner?: boolean; + isTeam?: boolean; + isEmpty?: boolean; +} | null; + const mocks = vi.hoisted(() => ({ copy: vi.fn().mockResolvedValue(true), navigate: vi.fn(), workspace: undefined as unknown, + workspaceInfo: { name: 'Test workspace' } as MockWorkspaceInfo, })); vi.mock('@affine/i18n', async importOriginal => ({ @@ -24,7 +32,7 @@ vi.mock('@affine/core/components/hooks/use-workspace', () => ({ useWorkspace: () => mocks.workspace, })); vi.mock('@affine/core/components/hooks/use-workspace-info', () => ({ - useWorkspaceInfo: () => ({ name: 'Test workspace' }), + useWorkspaceInfo: () => mocks.workspaceInfo, })); vi.mock('@affine/core/components/hooks/use-system-online', () => ({ useSystemOnline: () => true, @@ -59,6 +67,7 @@ vi.mock('@affine/component', async importOriginal => ({ afterEach(() => { mocks.copy.mockClear(); mocks.navigate.mockClear(); + mocks.workspaceInfo = { name: 'Test workspace' }; vi.unstubAllGlobals(); }); @@ -165,3 +174,44 @@ test('syncing status shows progress tooltip without nested hover button', async view.unmount(); } }); + +test.each([ + { label: 'loading profile', info: null, expectJoined: false }, + { + label: 'unknown ownership', + info: { name: 'My workspace' }, + expectJoined: false, + }, + { + label: 'owned workspace', + info: { name: 'My workspace', isOwner: true }, + expectJoined: false, + }, + { + label: 'joined workspace', + info: { name: 'Shared workspace', isOwner: false }, + expectJoined: true, + }, +])( + 'shows joined workspace icon only when isOwner is false ($label)', + ({ info, expectJoined }) => { + mocks.workspaceInfo = info; + const view = render( + + ); + try { + const joinedTooltip = screen.queryByText( + 'com.affine.settings.workspace.state.joined' + ); + if (expectJoined) { + expect(joinedTooltip).not.toBeNull(); + } else { + expect(joinedTooltip).toBeNull(); + } + } finally { + view.unmount(); + } + } +); diff --git a/packages/frontend/core/src/components/workspace-selector/workspace-card/index.tsx b/packages/frontend/core/src/components/workspace-selector/workspace-card/index.tsx index 65ef53b61f..cc61d706be 100644 --- a/packages/frontend/core/src/components/workspace-selector/workspace-card/index.tsx +++ b/packages/frontend/core/src/components/workspace-selector/workspace-card/index.tsx @@ -492,7 +492,7 @@ export const WorkspaceCard = forwardRef<
- {hideCollaborationIcon || information?.isOwner ? null : ( + {hideCollaborationIcon || information?.isOwner !== false ? null : ( diff --git a/packages/frontend/core/src/desktop/dialogs/setting/workspace-setting/preference/labels.tsx b/packages/frontend/core/src/desktop/dialogs/setting/workspace-setting/preference/labels.tsx index 2eae0d924b..6bb612a495 100644 --- a/packages/frontend/core/src/desktop/dialogs/setting/workspace-setting/preference/labels.tsx +++ b/packages/frontend/core/src/desktop/dialogs/setting/workspace-setting/preference/labels.tsx @@ -44,7 +44,7 @@ const getConditions = ( isTeam: boolean | null ): labelConditionsProps[] => { return [ - { condition: !isOwner, label: 'joinedWorkspace' }, + { condition: isOwner === false, label: 'joinedWorkspace' }, { condition: flavour === 'local', label: 'local' }, { condition: flavour === 'affine-cloud', diff --git a/packages/frontend/core/src/desktop/pages/workspace/chat/index.tsx b/packages/frontend/core/src/desktop/pages/workspace/chat/index.tsx index 6057c23345..4c66891377 100644 --- a/packages/frontend/core/src/desktop/pages/workspace/chat/index.tsx +++ b/packages/frontend/core/src/desktop/pages/workspace/chat/index.tsx @@ -25,13 +25,13 @@ import { import { EventSourceService, GraphQLService, + ServerRealtimeService, ServerService, SubscriptionService, } from '@affine/core/modules/cloud'; import { WorkspaceDialogService } from '@affine/core/modules/dialogs'; import { FeatureFlagService } from '@affine/core/modules/feature-flag'; import { PeekViewService } from '@affine/core/modules/peek-view'; -import { NbstoreService } from '@affine/core/modules/storage'; import { AppThemeService } from '@affine/core/modules/theme'; import { ViewBody, @@ -60,7 +60,7 @@ import * as styles from './index.css'; function useAIRequestService() { const graphqlService = useService(GraphQLService); const eventSourceService = useService(EventSourceService); - const nbstoreService = useService(NbstoreService); + const serverRealtimeService = useService(ServerRealtimeService); const workspace = useService(WorkspaceService).workspace; return useMemo( @@ -68,7 +68,7 @@ function useAIRequestService() { createAIRequestService( graphqlService.gql, eventSourceService.eventSource, - nbstoreService.realtime, + serverRealtimeService, async docIds => { await Promise.all( [workspace.id, 'db$docProperties', ...docIds].map(docId => @@ -77,7 +77,7 @@ function useAIRequestService() { ); } ), - [graphqlService, eventSourceService, nbstoreService, workspace] + [graphqlService, eventSourceService, serverRealtimeService, workspace] ); } diff --git a/packages/frontend/core/src/desktop/pages/workspace/detail-page/tabs/chat.tsx b/packages/frontend/core/src/desktop/pages/workspace/detail-page/tabs/chat.tsx index 94781d7226..7b7662bc4f 100644 --- a/packages/frontend/core/src/desktop/pages/workspace/detail-page/tabs/chat.tsx +++ b/packages/frontend/core/src/desktop/pages/workspace/detail-page/tabs/chat.tsx @@ -30,6 +30,7 @@ import { import { EventSourceService, GraphQLService, + ServerRealtimeService, ServerService, SubscriptionService, } from '@affine/core/modules/cloud'; @@ -37,7 +38,6 @@ import { WorkspaceDialogService } from '@affine/core/modules/dialogs'; import { useSignalValue } from '@affine/core/modules/doc-info/utils'; import { FeatureFlagService } from '@affine/core/modules/feature-flag'; import { PeekViewService } from '@affine/core/modules/peek-view'; -import { NbstoreService } from '@affine/core/modules/storage'; import { AppThemeService } from '@affine/core/modules/theme'; import { WorkbenchService } from '@affine/core/modules/workbench'; import { WorkspaceService } from '@affine/core/modules/workspace'; @@ -78,7 +78,7 @@ export const EditorChatPanel = ({ const framework = useFramework(); const graphqlService = useService(GraphQLService); const eventSourceService = useService(EventSourceService); - const nbstoreService = useService(NbstoreService); + const serverRealtimeService = useService(ServerRealtimeService); const workbench = useService(WorkbenchService).workbench; const workspace = useService(WorkspaceService).workspace; const t = useI18n(); @@ -114,7 +114,7 @@ export const EditorChatPanel = ({ createAIRequestService( graphqlService.gql, eventSourceService.eventSource, - nbstoreService.realtime, + serverRealtimeService, async docIds => { await Promise.all( [workspace.id, 'db$docProperties', ...docIds].map(docId => @@ -126,7 +126,7 @@ export const EditorChatPanel = ({ [ eventSourceService.eventSource, graphqlService.gql, - nbstoreService, + serverRealtimeService, workspace, ] ); @@ -168,7 +168,7 @@ export const EditorChatPanel = ({ requestService.setActiveEditorFactory( sessionId => new DelegatedEditorHost({ - realtime: nbstoreService.realtime, + realtime: serverRealtimeService, host, sessionId, workspaceId, @@ -184,7 +184,7 @@ export const EditorChatPanel = ({ }, [ doc.id, host, - nbstoreService.realtime, + serverRealtimeService, requestService, session?.sessionId, workspaceId, diff --git a/packages/frontend/core/src/mobile/components/workspace-selector/menu.tsx b/packages/frontend/core/src/mobile/components/workspace-selector/menu.tsx index 4a4f11d5c3..0aea7a586e 100644 --- a/packages/frontend/core/src/mobile/components/workspace-selector/menu.tsx +++ b/packages/frontend/core/src/mobile/components/workspace-selector/menu.tsx @@ -56,7 +56,7 @@ const WorkspaceItem = ({ colorfulFallback />
{name}
- {!isOwner ? : null} + {isOwner === false ? : null} ); diff --git a/packages/frontend/core/src/mobile/dialogs/sign-in/index.spec.tsx b/packages/frontend/core/src/mobile/dialogs/sign-in/index.spec.tsx index 3fe492e9e4..2e5f3cd6fe 100644 --- a/packages/frontend/core/src/mobile/dialogs/sign-in/index.spec.tsx +++ b/packages/frontend/core/src/mobile/dialogs/sign-in/index.spec.tsx @@ -51,6 +51,8 @@ describe('SignInDialog', () => { afterEach(() => { cleanup(); delete window.showNativeSignIn; + delete (window as { getCurrentServerBaseUrl?: () => string }) + .getCurrentServerBaseUrl; vi.unstubAllGlobals(); }); @@ -106,4 +108,30 @@ describe('SignInDialog', () => { }); expect(screen.queryByText('mobile-sign-in-panel')).toBeNull(); }); + + test('uses the web sign-in panel when signing in to a different self-hosted server', async () => { + const close = vi.fn(); + const nativeSignIn = vi.fn().mockResolvedValue('user-id'); + setNativeSignIn(nativeSignIn); + Object.defineProperty(window, 'getCurrentServerBaseUrl', { + configurable: true, + writable: true, + value: () => 'https://apple.getaffineapp.com', + }); + + render( + + ); + + await waitFor(() => { + expect(screen.getByText('mobile-sign-in-panel')).not.toBeNull(); + }); + expect(screen.getByText('https://selfhosted.example.com')).not.toBeNull(); + expect(nativeSignIn).not.toHaveBeenCalled(); + expect(close).not.toHaveBeenCalled(); + }); }); diff --git a/packages/frontend/core/src/mobile/dialogs/sign-in/index.tsx b/packages/frontend/core/src/mobile/dialogs/sign-in/index.tsx index a043c55c5f..c935f01817 100644 --- a/packages/frontend/core/src/mobile/dialogs/sign-in/index.tsx +++ b/packages/frontend/core/src/mobile/dialogs/sign-in/index.tsx @@ -12,6 +12,17 @@ import { MobileSignInPanel } from '../../components/sign-in'; declare global { interface Window { showNativeSignIn?: () => Promise; + getCurrentServerBaseUrl?: () => string; + } +} + +function normalizeServerBaseUrl(url?: string) { + if (!url) return undefined; + try { + const normalized = new URL(url).toString(); + return normalized.endsWith('/') ? normalized.slice(0, -1) : normalized; + } catch { + return url.endsWith('/') ? url.slice(0, -1) : url; } } @@ -20,7 +31,16 @@ export const SignInDialog = ({ server: initialServerBaseUrl, step, }: DialogComponentProps) => { - const shouldUseNativeSignIn = step !== 'addSelfhosted'; + const nativeServerBaseUrl = + typeof window.getCurrentServerBaseUrl === 'function' + ? window.getCurrentServerBaseUrl() + : undefined; + const targetsDifferentServer = + Boolean(initialServerBaseUrl && nativeServerBaseUrl) && + normalizeServerBaseUrl(initialServerBaseUrl) !== + normalizeServerBaseUrl(nativeServerBaseUrl); + const shouldUseNativeSignIn = + step !== 'addSelfhosted' && !targetsDifferentServer; const [useWebFallback, setUseWebFallback] = useState(!shouldUseNativeSignIn); const didRequestNativeSignIn = useRef(false); const closeRef = useRef(close); diff --git a/packages/frontend/core/src/mobile/modules/navigation-projection/shell-data-projection.spec.ts b/packages/frontend/core/src/mobile/modules/navigation-projection/shell-data-projection.spec.ts index 0d749f7d16..032ed1182a 100644 --- a/packages/frontend/core/src/mobile/modules/navigation-projection/shell-data-projection.spec.ts +++ b/packages/frontend/core/src/mobile/modules/navigation-projection/shell-data-projection.spec.ts @@ -303,7 +303,6 @@ describe('MobileShellDataProjection', () => { ...([ { workspace: { id: 'space' } }, { server: { gql } }, - {}, ] as unknown as ConstructorParameters) ) ); diff --git a/packages/frontend/core/src/modules/cloud/entities/server.ts b/packages/frontend/core/src/modules/cloud/entities/server.ts index aa6d425a33..1d0fbb98e6 100644 --- a/packages/frontend/core/src/modules/cloud/entities/server.ts +++ b/packages/frontend/core/src/modules/cloud/entities/server.ts @@ -14,6 +14,7 @@ import { ServerScope } from '../scopes/server'; import { AuthService } from '../services/auth'; import { FetchService } from '../services/fetch'; import { GraphQLService } from '../services/graphql'; +import { ServerRealtimeService } from '../services/realtime'; import { ServerConfigStore } from '../stores/server-config'; import type { ServerListStore } from '../stores/server-list'; import type { ServerConfig, ServerMetadata } from '../types'; @@ -35,6 +36,7 @@ export class Server extends Entity<{ readonly serverConfigStore = this.scope.framework.get(ServerConfigStore); readonly fetch = this.scope.framework.get(FetchService).fetch; readonly gql = this.scope.framework.get(GraphQLService).gql; + readonly realtime = this.scope.framework.get(ServerRealtimeService); get account$() { return this.scope.framework.get(AuthService).session.account$; } diff --git a/packages/frontend/core/src/modules/cloud/index.ts b/packages/frontend/core/src/modules/cloud/index.ts index a075da923f..0ded80c46a 100644 --- a/packages/frontend/core/src/modules/cloud/index.ts +++ b/packages/frontend/core/src/modules/cloud/index.ts @@ -28,7 +28,11 @@ export { InvoicesService } from './services/invoices'; export { McpCredentialService } from './services/mcp-credential'; export type { PublicUserInfo } from './services/public-user'; export { PublicUserService } from './services/public-user'; -export { RealtimeService } from './services/realtime'; +export { + type RealtimeConnectionError, + RealtimeService, + ServerRealtimeService, +} from './services/realtime'; export { SelfhostGenerateLicenseService } from './services/selfhost-generate-license'; export { SelfhostLicenseService } from './services/selfhost-license'; export { ServerService } from './services/server'; @@ -80,7 +84,7 @@ import { FetchService } from './services/fetch'; import { GraphQLService } from './services/graphql'; import { InvoicesService } from './services/invoices'; import { PublicUserService } from './services/public-user'; -import { RealtimeService } from './services/realtime'; +import { RealtimeService, ServerRealtimeService } from './services/realtime'; import { SelfhostGenerateLicenseService } from './services/selfhost-generate-license'; import { SelfhostLicenseService } from './services/selfhost-license'; import { ServerService } from './services/server'; @@ -123,11 +127,7 @@ export function configureCloudModule(framework: Framework) { framework .service(ServersService, [ServerListStore, ServerConfigStore]) - .service(RealtimeService, [ - GlobalContextService, - ServersService, - NbstoreService, - ]) + .service(RealtimeService, [GlobalContextService, ServersService]) .service(DefaultServerService, [ServersService]) .store(ServerListStore, [GlobalStateService]) .store(ServerConfigStore) @@ -137,6 +137,11 @@ export function configureCloudModule(framework: Framework) { .service(FetchService, [ServerService]) .service(EventSourceService, [ServerService]) .service(GraphQLService, [FetchService]) + .service(ServerRealtimeService, [ + ServerService, + NbstoreService, + GlobalState, + ]) .service(CaptchaService, f => { return new CaptchaService( f.get(ServerService), @@ -149,7 +154,7 @@ export function configureCloudModule(framework: Framework) { AuthStore, UrlService, GlobalDialogService, - NbstoreService, + ServerRealtimeService, ServerService, ]) .store(AuthStore, [ @@ -158,7 +163,7 @@ export function configureCloudModule(framework: Framework) { GlobalState, ServerService, AuthProvider, - NbstoreService, + ServerRealtimeService, ]) .entity(AuthSession, [AuthStore]) .service(SubscriptionService, [SubscriptionStore]) @@ -171,7 +176,7 @@ export function configureCloudModule(framework: Framework) { .entity(Subscription, [AuthService, ServerService, SubscriptionStore]) .entity(SubscriptionPrices, [ServerService, SubscriptionStore]) .service(UserQuotaService) - .store(UserQuotaStore, [NbstoreService]) + .store(UserQuotaStore, [ServerRealtimeService]) .entity(UserQuota, [AuthService, UserQuotaStore]) .service(UserCopilotQuotaService) .store(UserCopilotQuotaStore, [GraphQLService]) @@ -193,7 +198,7 @@ export function configureCloudModule(framework: Framework) { .service(PublicUserService, [PublicUserStore]) .store(PublicUserStore, [GraphQLService]) .service(UserSettingsService, [UserSettingsStore]) - .store(UserSettingsStore, [GraphQLService, NbstoreService]) + .store(UserSettingsStore, [GraphQLService, ServerRealtimeService]) .service(McpCredentialService, [McpCredentialStore]) .store(McpCredentialStore, [GraphQLService]); diff --git a/packages/frontend/core/src/modules/cloud/server-url.ts b/packages/frontend/core/src/modules/cloud/server-url.ts new file mode 100644 index 0000000000..dd9d7bc537 --- /dev/null +++ b/packages/frontend/core/src/modules/cloud/server-url.ts @@ -0,0 +1,3 @@ +export function normalizeServerBaseUrl(baseUrl: string) { + return baseUrl.trim().replace(/\/+$/, ''); +} diff --git a/packages/frontend/core/src/modules/cloud/services/auth.ts b/packages/frontend/core/src/modules/cloud/services/auth.ts index a7bdc22efc..12c04fa629 100644 --- a/packages/frontend/core/src/modules/cloud/services/auth.ts +++ b/packages/frontend/core/src/modules/cloud/services/auth.ts @@ -7,7 +7,6 @@ import { distinctUntilChanged, map, skip, type Subscription } from 'rxjs'; import type { GlobalDialogService } from '../../dialogs'; import { ApplicationFocused } from '../../lifecycle'; -import type { NbstoreService } from '../../storage'; import type { UrlService } from '../../url'; import { AuthSession } from '../entities/session'; import { AccountChanged } from '../events/account-changed'; @@ -17,6 +16,7 @@ import { ServerStarted } from '../events/server-started'; import type { AuthStore } from '../stores/auth'; import { assertSupportedServerVersion } from '../stores/server-config'; import type { FetchService } from './fetch'; +import type { ServerRealtimeService } from './realtime'; import type { ServerService } from './server'; export interface DeviceAuthSession { @@ -52,7 +52,7 @@ export class AuthService extends Service { private readonly store: AuthStore, private readonly urlService: UrlService, private readonly dialogService: GlobalDialogService, - private readonly nbstoreService: NbstoreService, + private readonly serverRealtimeService: ServerRealtimeService, private readonly serverService: ServerService ) { super(); @@ -94,15 +94,14 @@ export class AuthService extends Service { this.profileSubscription?.unsubscribe(); this.profileSubscription = undefined; if (!this.session.account$.value) return; - this.profileSubscription = this.nbstoreService.realtime + this.profileSubscription = this.serverRealtimeService .subscribe('user.profile.changed', {}) .subscribe({ - next: () => { - void (async () => { - this.session.revalidate(); - await this.session.waitForRevalidation(); - this.eventBus.emit(AccountChanged, this.session.account$.value); - })().catch(() => {}); + next: event => { + if ('type' in event && event.type === 'ready') { + return; + } + this.session.revalidate(); }, error: () => { this.profileSubscription = undefined; diff --git a/packages/frontend/core/src/modules/cloud/services/realtime.spec.ts b/packages/frontend/core/src/modules/cloud/services/realtime.spec.ts new file mode 100644 index 0000000000..62612f2d04 --- /dev/null +++ b/packages/frontend/core/src/modules/cloud/services/realtime.spec.ts @@ -0,0 +1,497 @@ +// @vitest-environment happy-dom +import { ServerDeploymentType } from '@affine/graphql'; +import { Framework, LiveData, MemoryMemento } from '@toeverything/infra'; +import { Observable, Subject } from 'rxjs'; +import { describe, expect, test, vi } from 'vitest'; + +import { GlobalDialogService } from '../../dialogs'; +import { GlobalContextService } from '../../global-context'; +import { + GlobalCache, + GlobalState, + GlobalStateService, + NbstoreService, +} from '../../storage'; +import { UrlService } from '../../url'; +import type { Server } from '../entities/server'; +import { AccountChanged } from '../events/account-changed'; +import { ServerStarted } from '../events/server-started'; +import { configureCloudModule } from '../index'; +import { AuthService } from './auth'; +import { RealtimeService, ServerRealtimeService } from './realtime'; +import { ServerService } from './server'; +import { ServersService } from './servers'; + +function createServerHarness({ + id, + baseUrl, + type, + account = null, + nbstoreRealtime, +}: { + id: string; + baseUrl: string; + type: ServerDeploymentType; + account?: { id: string } | null; + nbstoreRealtime: { + configure: ReturnType; + request: ReturnType; + subscribe: ReturnType; + status: ReturnType; + dispose?: ReturnType; + }; +}) { + const globalState = new MemoryMemento(); + if (account) { + globalState.set(`${id}-auth`, { account }); + } + const config$ = new LiveData({ type }); + const framework = new Framework(); + const server = { + id, + baseUrl, + config$, + } as unknown as Server; + + framework + .impl(GlobalState, globalState) + .service(ServerService, { server } as ServerService) + .service(NbstoreService, { + realtime: nbstoreRealtime, + } as unknown as NbstoreService) + .service(ServerRealtimeService, [ + ServerService, + NbstoreService, + GlobalState, + ]); + + const provider = framework.provider(); + const realtime = provider.get(ServerRealtimeService); + (server as unknown as { realtime: ServerRealtimeService }).realtime = + realtime; + + return { server, globalState, config$, realtime, provider }; +} + +describe('ServerRealtimeService & RealtimeService', () => { + test('routes requests and subscriptions to each server endpoint independently of active serverId', async () => { + const events$ = new Subject< + { type: 'ready' } | { changed: true; reason: string } + >(); + const nbstoreRealtime = { + configure: vi.fn().mockResolvedValue(undefined), + request: vi.fn().mockResolvedValue({ + access: { role: 'Owner', permissions: {}, team: false }, + }), + subscribe: vi.fn().mockReturnValue(events$), + status: vi.fn().mockResolvedValue({ + endpoint: 'https://selfhosted.example.com', + connected: true, + connecting: false, + subscriptions: 1, + }), + dispose: vi.fn().mockResolvedValue(undefined), + }; + + const cloud = createServerHarness({ + id: 'affine-cloud', + baseUrl: 'https://app.affine.pro', + type: ServerDeploymentType.Affine, + account: null, + nbstoreRealtime, + }); + const selfHosted = createServerHarness({ + id: 'self-hosted-1', + baseUrl: 'https://selfhosted.example.com', + type: ServerDeploymentType.Selfhosted, + account: { id: 'user-self' }, + nbstoreRealtime, + }); + + const serverId$ = new LiveData('affine-cloud'); + const servers$ = new LiveData([cloud.server, selfHosted.server]); + const globalFramework = new Framework(); + globalFramework + .service(GlobalContextService, { + globalContext: { + serverId: { $: serverId$ }, + }, + } as unknown as GlobalContextService) + .service(ServersService, { + servers$, + server$: (id: string) => + servers$.map(list => list.find(item => item.id === id)), + } as unknown as ServersService) + .service(RealtimeService, [GlobalContextService, ServersService]); + + const globalRealtime = globalFramework.provider().get(RealtimeService); + + cloud.provider.eventBus.emit(ServerStarted, cloud.server); + selfHosted.provider.eventBus.emit(ServerStarted, selfHosted.server); + + expect(nbstoreRealtime.configure).toHaveBeenCalledWith({ + endpoint: 'https://app.affine.pro', + isSelfHosted: false, + authenticated: false, + }); + expect(nbstoreRealtime.configure).toHaveBeenCalledWith({ + endpoint: 'https://selfhosted.example.com', + isSelfHosted: true, + authenticated: true, + }); + + await selfHosted.realtime.request('workspace.access.get', { + workspaceId: 'ws-self', + }); + expect(nbstoreRealtime.request).toHaveBeenCalledWith( + 'workspace.access.get', + { workspaceId: 'ws-self' }, + { endpoint: 'https://selfhosted.example.com' } + ); + + const subscription = selfHosted.realtime + .subscribe('workspace.access.changed', { workspaceId: 'ws-self' }) + .subscribe(); + await vi.waitFor(() => + expect(nbstoreRealtime.subscribe).toHaveBeenCalledWith( + 'workspace.access.changed', + { workspaceId: 'ws-self' }, + { endpoint: 'https://selfhosted.example.com' } + ) + ); + + await cloud.realtime.deauthenticate(); + expect(nbstoreRealtime.configure).not.toHaveBeenCalledWith( + expect.objectContaining({ + endpoint: 'https://selfhosted.example.com', + authenticated: false, + }) + ); + + const selfHostedError = { + endpoint: 'https://selfhosted.example.com', + error: new Error('network failed'), + type: 'network' as const, + }; + selfHosted.realtime.connectionError$.next(selfHostedError); + expect(globalRealtime.connectionError$.value).toBeNull(); + + serverId$.next('self-hosted-1'); + expect(globalRealtime.connectionError$.value).toEqual(selfHostedError); + + subscription.unsubscribe(); + globalRealtime.dispose(); + cloud.realtime.dispose(); + selfHosted.realtime.dispose(); + }); + + test('ensures server context is configured before request or subscribe even before ServerStarted', async () => { + const order: string[] = []; + const events$ = new Subject< + { type: 'ready' } | { changed: true; reason: string } + >(); + const nbstoreRealtime = { + configure: vi.fn(async () => { + order.push('configure'); + }), + request: vi.fn(async () => { + order.push('request'); + return { count: 2 }; + }), + subscribe: vi.fn(() => { + order.push('subscribe'); + return events$; + }), + status: vi.fn(), + dispose: vi.fn().mockResolvedValue(undefined), + }; + + const selfHosted = createServerHarness({ + id: 'self-hosted-1', + baseUrl: 'https://selfhosted.example.com', + type: ServerDeploymentType.Selfhosted, + account: { id: 'user-self' }, + nbstoreRealtime, + }); + + await selfHosted.realtime.request('notification.count.get', {}); + const sub = selfHosted.realtime + .subscribe('user.profile.changed', {}) + .subscribe(); + + expect(order).toEqual(['configure', 'request', 'subscribe']); + expect(nbstoreRealtime.configure).toHaveBeenCalledTimes(1); + expect(nbstoreRealtime.configure).toHaveBeenCalledWith({ + endpoint: 'https://selfhosted.example.com', + isSelfHosted: true, + authenticated: true, + }); + + sub.unsubscribe(); + selfHosted.realtime.dispose(); + expect(nbstoreRealtime.dispose).toHaveBeenCalledWith({ + endpoint: 'https://selfhosted.example.com', + }); + }); + + test('does not recursively construct AuthService or storm /api/auth/session when starting with cached auth', async () => { + const events$ = new Subject< + { type: 'ready' } | { changed: true; reason: string } + >(); + let activeProfileSubscriptions = 0; + const configureCalls: Array<{ + endpoint?: string; + authenticated?: boolean; + isSelfHosted?: boolean; + }> = []; + const nbstoreRealtime = { + configure: vi.fn(async input => { + configureCalls.push(input); + }), + request: vi.fn().mockResolvedValue({}), + subscribe: vi.fn((topic: string) => { + if (topic === 'user.profile.changed') { + return new Observable(observer => { + activeProfileSubscriptions++; + const sub = events$.subscribe(observer); + return () => { + activeProfileSubscriptions--; + sub.unsubscribe(); + }; + }); + } + return events$; + }), + status: vi.fn(), + dispose: vi.fn().mockResolvedValue(undefined), + }; + + const globalState = new MemoryMemento(); + const globalCache = new MemoryMemento(); + globalState.set('serverList', [ + { id: 'self-hosted-1', baseUrl: 'https://selfhosted.example.com' }, + ]); + globalState.set('serverConfig:self-hosted-1', { + serverName: 'Self Hosted', + features: [], + oauthProviders: [], + type: ServerDeploymentType.Selfhosted, + version: '0.27.2', + initialized: true, + credentialsRequirement: { + password: { minLength: 8, maxLength: 32 }, + }, + }); + globalState.set('self-hosted-1-auth', { + account: { + id: 'user-self', + email: 'lin@example.com', + label: 'Lin', + }, + }); + + let selfHostedSessionFetches = 0; + let cloudSessionFetches = 0; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((async ( + input: string | URL | Request + ) => { + const url = typeof input === 'string' ? input : input.toString(); + if (url.endsWith('/api/auth/session')) { + const isSelfHosted = + new URL(url).origin === 'https://selfhosted.example.com'; + if (isSelfHosted) { + selfHostedSessionFetches++; + } else { + cloudSessionFetches++; + } + return new Response( + JSON.stringify({ + user: isSelfHosted ? { id: 'user-self' } : null, + }), + { status: 200, headers: { 'content-type': 'application/json' } } + ); + } + if (url.endsWith('/graphql')) { + return new Response( + JSON.stringify({ + data: { + currentUser: { + id: 'user-self', + email: 'lin@example.com', + name: 'Lin', + avatarUrl: null, + hasPassword: true, + emailVerified: true, + features: [], + }, + }, + }), + { status: 200, headers: { 'content-type': 'application/json' } } + ); + } + if (url.endsWith('/api/auth/methods')) { + return new Response(JSON.stringify({}), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + } + if (url.endsWith('/api/info')) { + return new Response( + JSON.stringify({ + name: 'Self Hosted', + features: [], + oauthProviders: [], + type: ServerDeploymentType.Selfhosted, + version: '0.27.2', + initialized: true, + credentialsRequirement: { + password: { minLength: 8, maxLength: 32 }, + }, + }), + { status: 200, headers: { 'content-type': 'application/json' } } + ); + } + return new Response('{}', { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }) as typeof fetch); + + const framework = new Framework(); + configureCloudModule(framework); + framework + .impl(GlobalState, globalState) + .impl(GlobalCache, globalCache) + .service(GlobalStateService, { + globalState, + } as unknown as GlobalStateService) + .service(GlobalContextService, { + globalContext: { + serverId: { $: new LiveData('self-hosted-1') }, + }, + } as unknown as GlobalContextService) + .service(UrlService, { + getClientScheme: () => null, + } as unknown as UrlService) + .service(GlobalDialogService, { + open: vi.fn(), + } as unknown as GlobalDialogService) + .service(NbstoreService, { + realtime: nbstoreRealtime, + } as unknown as NbstoreService); + + const provider = framework.provider(); + const serversService = provider.get(ServersService); + const serversSub = serversService.servers$.subscribe(); + + try { + const selfHosted = serversService.servers$.value.find( + s => s.id === 'self-hosted-1' + ); + expect(selfHosted).toBeDefined(); + + // Resolving AuthService after ServerStarted must return the single cached instance. + const auth1 = selfHosted!.scope.get(AuthService); + const auth2 = selfHosted!.scope.get(AuthService); + expect(auth1).toBe(auth2); + + const accountChanged = vi.fn(); + const unsubscribeAccountChanged = selfHosted!.scope.eventBus.on( + AccountChanged, + accountChanged + ); + + // Flush microtasks for configure -> subscribe('user.profile.changed') + await vi.waitFor(() => { + expect(activeProfileSubscriptions).toBe(1); + }); + + // Emit realtime ready event and verify there is no /api/auth/session storm + // and no spurious AccountChanged (which would close open cloud workspaces). + events$.next({ type: 'ready' }); + await new Promise(resolve => setTimeout(resolve, 50)); + + expect(activeProfileSubscriptions).toBe(1); + expect(cloudSessionFetches).toBe(1); + expect(accountChanged).not.toHaveBeenCalled(); + expect(selfHostedSessionFetches).toBe(1); + + // A real profile update for the same user must revalidate without emitting AccountChanged. + events$.next({ changed: true, reason: 'user-updated' }); + await vi.waitFor(() => { + expect(selfHostedSessionFetches).toBe(2); + }); + await new Promise(resolve => setTimeout(resolve, 50)); + expect(accountChanged).not.toHaveBeenCalled(); + + // Trailing-slash alias must resolve to the existing server rather than a duplicate. + expect( + serversService.getServerByBaseUrl('https://selfhosted.example.com/') + ).toBe(selfHosted); + await expect( + serversService.addOrGetServerByBaseUrl( + 'https://selfhosted.example.com/' + ) + ).resolves.toBe(selfHosted); + + unsubscribeAccountChanged(); + expect( + configureCalls.filter( + c => c.endpoint === 'https://selfhosted.example.com' + ) + ).toEqual([ + { + endpoint: 'https://selfhosted.example.com', + isSelfHosted: true, + authenticated: true, + }, + ]); + expect( + configureCalls.filter( + c => c.endpoint !== 'https://selfhosted.example.com' + ) + ).toContainEqual( + expect.objectContaining({ + authenticated: false, + }) + ); + + // Clearing cached auth session must transition realtime context to unauthenticated. + globalState.set('self-hosted-1-auth', null); + await vi.waitFor(() => { + expect( + configureCalls.filter( + c => c.endpoint === 'https://selfhosted.example.com' + ) + ).toEqual([ + { + endpoint: 'https://selfhosted.example.com', + isSelfHosted: true, + authenticated: true, + }, + { + endpoint: 'https://selfhosted.example.com', + isSelfHosted: true, + authenticated: false, + }, + ]); + }); + + // Removing a server must dispose only its endpoint's realtime manager. + serversService.removeServer('self-hosted-1'); + await vi.waitFor( + () => { + expect(nbstoreRealtime.dispose).toHaveBeenCalledWith({ + endpoint: 'https://selfhosted.example.com', + }); + }, + { timeout: 2500 } + ); + expect(nbstoreRealtime.dispose).toHaveBeenCalledTimes(1); + } finally { + serversSub.unsubscribe(); + provider.dispose(); + fetchSpy.mockRestore(); + } + }); +}); diff --git a/packages/frontend/core/src/modules/cloud/services/realtime.ts b/packages/frontend/core/src/modules/cloud/services/realtime.ts index 2ef28505d1..21e0b01882 100644 --- a/packages/frontend/core/src/modules/cloud/services/realtime.ts +++ b/packages/frontend/core/src/modules/cloud/services/realtime.ts @@ -1,17 +1,43 @@ -import { shallowEqual } from '@affine/component'; import { ServerDeploymentType } from '@affine/graphql'; +import type { + RealtimeConfigureInput, + RealtimeRequestInputOf, + RealtimeRequestName, + RealtimeRequestOutputOf, + RealtimeStatus, + RealtimeSubscriptionReady, + RealtimeTopicEventOf, + RealtimeTopicInputOf, + RealtimeTopicName, +} from '@affine/realtime'; import { LiveData, OnEvent, Service } from '@toeverything/infra'; +import { defer, from, type Observable, switchMap } from 'rxjs'; import type { GlobalContextService } from '../../global-context'; import { ApplicationStarted } from '../../lifecycle'; -import type { NbstoreService } from '../../storage'; +import type { GlobalState, NbstoreService } from '../../storage'; import type { Server } from '../entities/server'; +import type { AuthSessionInfo } from '../entities/session'; +import { ServerStarted } from '../events/server-started'; +import { normalizeServerBaseUrl } from '../server-url'; +import type { ServerService } from './server'; import type { ServersService } from './servers'; const CONNECTION_FAILURE_THRESHOLD = 3; const INITIAL_RETRY_DELAY = 3000; const MAX_RETRY_DELAY = 60000; +function isSameRealtimeContext( + a: RealtimeConfigureInput, + b: RealtimeConfigureInput +) { + return ( + a.endpoint === b.endpoint && + a.isSelfHosted === b.isSelfHosted && + a.authenticated === b.authenticated + ); +} + function getConnectionErrorType(error: unknown) { if (!(error instanceof Error)) { return 'server'; @@ -41,6 +67,12 @@ function getConnectionErrorType(error: unknown) { return 'server'; } +export type RealtimeConnectionError = { + endpoint: string; + error: unknown; + type: ReturnType; +}; + function waitForRetry(delay: number, signal: AbortSignal) { return new Promise(resolve => { const onAbort = () => { @@ -55,76 +87,202 @@ function waitForRetry(delay: number, signal: AbortSignal) { }); } -@OnEvent(ApplicationStarted, service => service.onApplicationStarted) -export class RealtimeService extends Service { - readonly connectionError$ = new LiveData<{ - endpoint: string; - error: unknown; - type: ReturnType; - } | null>(null); +@OnEvent(ServerStarted, service => service.onServerStarted) +export class ServerRealtimeService extends Service { + readonly connectionError$ = new LiveData( + null + ); + private configured = false; + private configuredContext?: RealtimeConfigureInput; + private configurePromise?: Promise; private contextGeneration = 0; + private deauthenticated = false; private probeAbort?: AbortController; - - private readonly currentServer$ = - this.globalContextService.globalContext.serverId.$.selector(id => - id - ? this.serversService.server$(id) - : new LiveData(undefined) - ) - .flat() - .selector( - server => - [ - server, - server?.account$, - server?.config$.selector( - c => c.type === ServerDeploymentType.Selfhosted - ), - ] as const - ) - .flat() - .map(([server, account, selfHosted]) => ({ - endpoint: server?.baseUrl ?? '', - authenticated: !!account, - isSelfHosted: !!selfHosted, - })) - .distinctUntilChanged(shallowEqual); + private started = false; constructor( - private readonly globalContextService: GlobalContextService, - private readonly serversService: ServersService, - private readonly nbstoreService: NbstoreService + private readonly serverService: ServerService, + private readonly nbstoreService: NbstoreService, + private readonly globalState: GlobalState ) { super(); - const subscription = this.currentServer$.subscribe(context => { - const generation = ++this.contextGeneration; - this.probeAbort?.abort(); - const probeAbort = new AbortController(); - this.probeAbort = probeAbort; - this.configure(context, generation, probeAbort.signal).catch(error => { - console.error('Failed to configure realtime context', error); - }); - }); this.disposables.push(() => { - subscription.unsubscribe(); this.probeAbort?.abort(); + const endpoint = this.endpoint; + if (this.configured && endpoint) { + this.configured = false; + this.configuredContext = undefined; + Promise.resolve( + this.nbstoreService.realtime.dispose?.({ endpoint }) + ).catch(() => {}); + } }); } - onApplicationStarted() {} + private get endpoint() { + return normalizeServerBaseUrl(this.serverService.server.baseUrl); + } - private async configure( - context: { - endpoint: string; - authenticated: boolean; - isSelfHosted: boolean; - }, + private get authCacheKey() { + return `${this.serverService.server.id}-auth`; + } + + private isCachedAuthenticated() { + return Boolean( + this.globalState.get(this.authCacheKey)?.account + ); + } + + onServerStarted() { + if (this.started) { + return; + } + this.started = true; + + const server = this.serverService.server; + const session$ = LiveData.from( + this.globalState.watch(this.authCacheKey), + this.globalState.get(this.authCacheKey) + ); + let prevSession = session$.value; + const subscription = LiveData.computed(get => { + const session = get(session$); + if (session !== prevSession) { + prevSession = session; + this.deauthenticated = false; + } + const config = get(server.config$); + return { + endpoint: this.endpoint, + authenticated: !this.deauthenticated && Boolean(session?.account), + isSelfHosted: config?.type === ServerDeploymentType.Selfhosted, + }; + }) + .distinctUntilChanged(isSameRealtimeContext) + .subscribe(context => { + const generation = ++this.contextGeneration; + this.probeAbort?.abort(); + const probeAbort = new AbortController(); + this.probeAbort = probeAbort; + this.configureAndProbe(context, generation, probeAbort.signal).catch( + error => { + console.error('Failed to configure realtime context', error); + } + ); + }); + + this.disposables.push(() => { + subscription.unsubscribe(); + }); + } + + private getContext( + overrides?: Partial + ): RealtimeConfigureInput { + const server = this.serverService.server; + return { + endpoint: this.endpoint, + authenticated: !this.deauthenticated && this.isCachedAuthenticated(), + isSelfHosted: + server.config$?.value?.type === ServerDeploymentType.Selfhosted, + ...overrides, + }; + } + + private applyContext(context: RealtimeConfigureInput) { + if (!context.endpoint) { + return undefined; + } + if ( + this.configuredContext && + isSameRealtimeContext(this.configuredContext, context) + ) { + return this.configurePromise; + } + + this.configured = true; + this.configuredContext = context; + const promise = Promise.resolve( + this.nbstoreService.realtime.configure(context) + ) + .catch(error => { + if (this.configuredContext === context) { + this.configuredContext = undefined; + } + throw error; + }) + .finally(() => { + if (this.configurePromise === promise) { + this.configurePromise = undefined; + } + }); + this.configurePromise = promise; + return promise; + } + + private ensureContext(overrides?: Partial) { + return this.applyContext(this.getContext(overrides)); + } + + async deauthenticate() { + this.contextGeneration++; + this.probeAbort?.abort(); + this.connectionError$.next(null); + this.deauthenticated = true; + await this.ensureContext({ authenticated: false }); + } + + async request( + op: Op, + input: RealtimeRequestInputOf, + options?: { timeoutMs?: number; signal?: AbortSignal } + ): Promise> { + const pending = this.ensureContext(); + if (pending) { + await pending; + } + return await this.nbstoreService.realtime.request(op, input, { + ...options, + endpoint: this.endpoint, + }); + } + + subscribe( + topic: Topic, + input: RealtimeTopicInputOf + ): Observable | RealtimeSubscriptionReady> { + return defer(() => { + const endpoint = this.endpoint; + const pending = this.ensureContext(); + if (!pending) { + return this.nbstoreService.realtime.subscribe(topic, input, { + endpoint, + }); + } + return from(pending).pipe( + switchMap(() => + this.nbstoreService.realtime.subscribe(topic, input, { + endpoint, + }) + ) + ); + }); + } + + status(): Promise { + return this.nbstoreService.realtime.status({ + endpoint: this.endpoint, + }); + } + + private async configureAndProbe( + context: RealtimeConfigureInput, generation: number, signal: AbortSignal ) { - await this.nbstoreService.realtime.configure(context); - if (generation !== this.contextGeneration) return; + await this.applyContext(context); + if (generation !== this.contextGeneration || signal.aborted) return; if (!context.endpoint || !context.authenticated) { this.connectionError$.next(null); return; @@ -137,7 +295,7 @@ export class RealtimeService extends Service { await this.nbstoreService.realtime.request( 'user.profile.get', {}, - { timeoutMs: 10_000, signal } + { endpoint: context.endpoint, timeoutMs: 10_000, signal } ); if (generation === this.contextGeneration && !signal.aborted) { this.connectionError$.next(null); @@ -161,3 +319,34 @@ export class RealtimeService extends Service { } } } + +@OnEvent(ApplicationStarted, service => service.onApplicationStarted) +export class RealtimeService extends Service { + readonly connectionError$ = + this.globalContextService.globalContext.serverId.$.selector(id => + id + ? this.serversService.server$(id) + : new LiveData(undefined) + ) + .flat() + .selector(server => + server + ? server.realtime.connectionError$ + : new LiveData(null) + ) + .flat(); + + constructor( + private readonly globalContextService: GlobalContextService, + private readonly serversService: ServersService + ) { + super(); + + const subscription = this.serversService.servers$.subscribe(); + this.disposables.push(() => { + subscription.unsubscribe(); + }); + } + + onApplicationStarted() {} +} diff --git a/packages/frontend/core/src/modules/cloud/services/servers.ts b/packages/frontend/core/src/modules/cloud/services/servers.ts index 97bac0ae3e..1d32b2dda4 100644 --- a/packages/frontend/core/src/modules/cloud/services/servers.ts +++ b/packages/frontend/core/src/modules/cloud/services/servers.ts @@ -5,6 +5,7 @@ import { Observable, switchMap } from 'rxjs'; import { Server } from '../entities/server'; import { ServerStarted } from '../events/server-started'; +import { normalizeServerBaseUrl } from '../server-url'; import type { ServerConfigStore } from '../stores/server-config'; import type { ServerListStore } from '../stores/server-list'; import type { ServerConfig, ServerMetadata } from '../types'; @@ -65,8 +66,11 @@ export class ServersService extends Service { } serverByBaseUrl$(url: string) { + const normalizedUrl = normalizeServerBaseUrl(url); return this.servers$.map(servers => - servers.find(server => server.baseUrl === url) + servers.find( + server => normalizeServerBaseUrl(server.baseUrl) === normalizedUrl + ) ); } @@ -85,10 +89,12 @@ export class ServersService extends Service { } async addServerByBaseUrl(baseUrl: string) { - const config = await this.serverConfigStore.fetchServerConfig(baseUrl); + const normalizedBaseUrl = normalizeServerBaseUrl(baseUrl); + const config = + await this.serverConfigStore.fetchServerConfig(normalizedBaseUrl); const id = nanoid(); this.serverListStore.addServer( - { id, baseUrl }, + { id, baseUrl: normalizedBaseUrl }, { credentialsRequirement: config.credentialsRequirement, features: config.features, @@ -102,7 +108,10 @@ export class ServersService extends Service { } getServerByBaseUrl(baseUrl: string) { - return this.servers$.value.find(s => s.baseUrl === baseUrl); + const normalizedBaseUrl = normalizeServerBaseUrl(baseUrl); + return this.servers$.value.find( + s => normalizeServerBaseUrl(s.baseUrl) === normalizedBaseUrl + ); } async addOrGetServerByBaseUrl(baseUrl: string) { diff --git a/packages/frontend/core/src/modules/cloud/stores/auth.spec.ts b/packages/frontend/core/src/modules/cloud/stores/auth.spec.ts index 91ed3e28d1..1a15cbfee2 100644 --- a/packages/frontend/core/src/modules/cloud/stores/auth.spec.ts +++ b/packages/frontend/core/src/modules/cloud/stores/auth.spec.ts @@ -1,9 +1,10 @@ import { AuthProvider } from '@affine/core/modules/cloud/provider/auth'; import { FetchService } from '@affine/core/modules/cloud/services/fetch'; import { GraphQLService } from '@affine/core/modules/cloud/services/graphql'; +import { ServerRealtimeService } from '@affine/core/modules/cloud/services/realtime'; import { ServerService } from '@affine/core/modules/cloud/services/server'; import { AuthStore } from '@affine/core/modules/cloud/stores/auth'; -import { GlobalState, NbstoreService } from '@affine/core/modules/storage'; +import { GlobalState } from '@affine/core/modules/storage'; import { Framework } from '@toeverything/infra'; import { describe, expect, test, vi } from 'vitest'; @@ -25,8 +26,8 @@ function createStore({ }, } as any); framework.impl(AuthProvider, {} as any); - framework.service(NbstoreService, { - realtime: {}, + framework.service(ServerRealtimeService, { + deauthenticate: vi.fn(), } as any); framework.store(AuthStore, [ FetchService, @@ -34,7 +35,7 @@ function createStore({ GlobalState, ServerService, AuthProvider, - NbstoreService, + ServerRealtimeService, ]); return framework.provider().get(AuthStore); } diff --git a/packages/frontend/core/src/modules/cloud/stores/auth.ts b/packages/frontend/core/src/modules/cloud/stores/auth.ts index 49951c7cfa..c1a6d137a8 100644 --- a/packages/frontend/core/src/modules/cloud/stores/auth.ts +++ b/packages/frontend/core/src/modules/cloud/stores/auth.ts @@ -2,7 +2,6 @@ import { deleteAccountMutation, getCurrentUserQuery, removeAvatarMutation, - ServerDeploymentType, updateUserProfileMutation, uploadAvatarMutation, } from '@affine/graphql'; @@ -10,11 +9,12 @@ import type { CurrentUserProfileSnapshot } from '@affine/realtime'; import { Store } from '@toeverything/infra'; import { z } from 'zod'; -import type { GlobalState, NbstoreService } from '../../storage'; +import type { GlobalState } from '../../storage'; import type { AuthSessionInfo } from '../entities/session'; import type { AuthProvider, SignInUserInfo } from '../provider/auth'; import type { FetchService } from '../services/fetch'; import type { GraphQLService } from '../services/graphql'; +import type { ServerRealtimeService } from '../services/realtime'; import type { ServerService } from '../services/server'; import { createUnsupportedServerVersionError } from './server-config'; @@ -49,7 +49,7 @@ export class AuthStore extends Store { private readonly globalState: GlobalState, private readonly serverService: ServerService, private readonly authProvider: AuthProvider, - private readonly nbstoreService: NbstoreService + private readonly serverRealtimeService: ServerRealtimeService ) { super(); } @@ -171,13 +171,7 @@ export class AuthStore extends Store { } private async deauthenticateRealtime() { - await this.nbstoreService.realtime.configure({ - endpoint: this.serverService.server.baseUrl, - authenticated: false, - isSelfHosted: - this.serverService.server.config$.value.type === - ServerDeploymentType.Selfhosted, - }); + await this.serverRealtimeService.deauthenticate(); } async uploadAvatar(file: File) { diff --git a/packages/frontend/core/src/modules/cloud/stores/server-list.ts b/packages/frontend/core/src/modules/cloud/stores/server-list.ts index 690a2851a6..c061efa148 100644 --- a/packages/frontend/core/src/modules/cloud/stores/server-list.ts +++ b/packages/frontend/core/src/modules/cloud/stores/server-list.ts @@ -3,6 +3,7 @@ import { map } from 'rxjs'; import type { GlobalStateService } from '../../storage'; import { BUILD_IN_SERVERS } from '../constant'; +import { normalizeServerBaseUrl } from '../server-url'; import type { ServerConfig, ServerMetadata } from '../types'; export class ServerListStore extends Store { @@ -34,17 +35,26 @@ export class ServerListStore extends Store { const oldServers = this.globalStateService.globalState.get('serverList') ?? []; + const normalizedBaseUrl = normalizeServerBaseUrl(server.baseUrl); + const normalizedServer = { + ...server, + baseUrl: normalizedBaseUrl, + }; - if (oldServers.some(s => s.baseUrl === server.baseUrl)) { + if ( + oldServers.some( + s => normalizeServerBaseUrl(s.baseUrl) === normalizedBaseUrl + ) + ) { throw new Error( - 'Server with same base url already exists, ' + server.baseUrl + 'Server with same base url already exists, ' + normalizedBaseUrl ); } - this.updateServerConfig(server.id, serverConfig); + this.updateServerConfig(normalizedServer.id, serverConfig); this.globalStateService.globalState.set('serverList', [ ...oldServers, - server, + normalizedServer, ]); } diff --git a/packages/frontend/core/src/modules/cloud/stores/user-quota.ts b/packages/frontend/core/src/modules/cloud/stores/user-quota.ts index a603b9a86b..ca6f76c2d6 100644 --- a/packages/frontend/core/src/modules/cloud/stores/user-quota.ts +++ b/packages/frontend/core/src/modules/cloud/stores/user-quota.ts @@ -1,14 +1,14 @@ import { Store } from '@toeverything/infra'; -import type { NbstoreService } from '../../storage'; +import type { ServerRealtimeService } from '../services/realtime'; export class UserQuotaStore extends Store { - constructor(private readonly nbstoreService: NbstoreService) { + constructor(private readonly serverRealtimeService: ServerRealtimeService) { super(); } async fetchUserQuotaState(abortSignal?: AbortSignal) { - const response = await this.nbstoreService.realtime.request( + const response = await this.serverRealtimeService.request( 'user.quota-state.get', {}, { signal: abortSignal, timeoutMs: 10000 } @@ -17,9 +17,6 @@ export class UserQuotaStore extends Store { } subscribeUserQuotaState() { - return this.nbstoreService.realtime.subscribe( - 'user.quota-state.changed', - {} - ); + return this.serverRealtimeService.subscribe('user.quota-state.changed', {}); } } diff --git a/packages/frontend/core/src/modules/cloud/stores/user-settings.ts b/packages/frontend/core/src/modules/cloud/stores/user-settings.ts index 9abb730eec..767764ee4f 100644 --- a/packages/frontend/core/src/modules/cloud/stores/user-settings.ts +++ b/packages/frontend/core/src/modules/cloud/stores/user-settings.ts @@ -5,8 +5,8 @@ import { import type { UserSettingsSnapshot } from '@affine/realtime'; import { Store } from '@toeverything/infra'; -import type { NbstoreService } from '../../storage'; import type { GraphQLService } from '../services/graphql'; +import type { ServerRealtimeService } from '../services/realtime'; export type UserSettings = UserSettingsSnapshot; @@ -15,7 +15,7 @@ export type { UpdateUserSettingsInput }; export class UserSettingsStore extends Store { constructor( private readonly gqlService: GraphQLService, - private readonly nbstoreService: NbstoreService + private readonly serverRealtimeService: ServerRealtimeService ) { super(); } @@ -23,7 +23,7 @@ export class UserSettingsStore extends Store { async getUserSettings( signal?: AbortSignal ): Promise { - const { settings } = await this.nbstoreService.realtime.request( + const { settings } = await this.serverRealtimeService.request( 'user.settings.get', {}, { signal, timeoutMs: 10000 } @@ -32,7 +32,7 @@ export class UserSettingsStore extends Store { } subscribeUserSettings() { - return this.nbstoreService.realtime.subscribe('user.settings.changed', {}); + return this.serverRealtimeService.subscribe('user.settings.changed', {}); } async updateUserSettings(settings: UpdateUserSettingsInput) { diff --git a/packages/frontend/core/src/modules/comment/entities/doc-comment-store.ts b/packages/frontend/core/src/modules/comment/entities/doc-comment-store.ts index 46f6eddb06..a6f2694fe6 100644 --- a/packages/frontend/core/src/modules/comment/entities/doc-comment-store.ts +++ b/packages/frontend/core/src/modules/comment/entities/doc-comment-store.ts @@ -16,11 +16,11 @@ import type { RealtimeTopicEventOf, } from '@affine/realtime'; import { Entity } from '@toeverything/infra'; -import type { Observable } from 'rxjs'; +import { type Observable, throwError } from 'rxjs'; import type { DefaultServerService, WorkspaceServerService } from '../../cloud'; import { GraphQLService } from '../../cloud/services/graphql'; -import type { NbstoreService } from '../../storage'; +import { ServerRealtimeService } from '../../cloud/services/realtime'; import type { WorkspaceService } from '../../workspace'; import type { DocComment, @@ -80,8 +80,7 @@ export class DocCommentStore extends Entity<{ constructor( private readonly workspaceService: WorkspaceService, private readonly workspaceServerService: WorkspaceServerService, - private readonly defaultServerService: DefaultServerService, - private readonly nbstoreService: NbstoreService + private readonly defaultServerService: DefaultServerService ) { super(); } @@ -96,6 +95,10 @@ export class DocCommentStore extends Entity<{ return this.serverService?.scope.get(GraphQLService); } + private get realtimeService() { + return this.serverService?.scope.get(ServerRealtimeService); + } + private get currentWorkspaceId() { return this.workspaceService.workspace.id; } @@ -143,10 +146,15 @@ export class DocCommentStore extends Entity<{ }: { after?: string; }): Promise { - const commentChanges = await this.nbstoreService.realtime.request( - 'comment.changes.get', - { after, workspaceId: this.currentWorkspaceId, docId: this.props.docId } - ); + const realtime = this.realtimeService; + if (!realtime) { + throw new Error('Realtime service not found'); + } + const commentChanges = await realtime.request('comment.changes.get', { + after, + workspaceId: this.currentWorkspaceId, + docId: this.props.docId, + }); return { changes: commentChanges.changes.map(change => ({ id: change.id, @@ -164,7 +172,11 @@ export class DocCommentStore extends Entity<{ subscribeCommentChanged(): Observable< RealtimeTopicEventOf<'comment.changed'> | RealtimeSubscriptionReady > { - return this.nbstoreService.realtime.subscribe('comment.changed', { + const realtime = this.realtimeService; + if (!realtime) { + return throwError(() => new Error('Realtime service not found')); + } + return realtime.subscribe('comment.changed', { workspaceId: this.currentWorkspaceId, docId: this.props.docId, }); diff --git a/packages/frontend/core/src/modules/comment/index.ts b/packages/frontend/core/src/modules/comment/index.ts index b29e9aaee8..8c45467d8b 100644 --- a/packages/frontend/core/src/modules/comment/index.ts +++ b/packages/frontend/core/src/modules/comment/index.ts @@ -2,7 +2,6 @@ import type { Framework } from '@toeverything/infra'; import { DefaultServerService, WorkspaceServerService } from '../cloud'; import { DocDisplayMetaService } from '../doc-display-meta'; -import { NbstoreService } from '../storage'; import { WorkbenchService } from '../workbench'; import { WorkspaceScope, WorkspaceService } from '../workspace'; import { DocCommentEntity } from './entities/doc-comment'; @@ -26,6 +25,5 @@ export function configureCommentModule(framework: Framework) { WorkspaceService, WorkspaceServerService, DefaultServerService, - NbstoreService, ]); } diff --git a/packages/frontend/core/src/modules/media/entities/audio-transcription-job-store.spec.ts b/packages/frontend/core/src/modules/media/entities/audio-transcription-job-store.spec.ts index 90466213aa..a56f916351 100644 --- a/packages/frontend/core/src/modules/media/entities/audio-transcription-job-store.spec.ts +++ b/packages/frontend/core/src/modules/media/entities/audio-transcription-job-store.spec.ts @@ -7,8 +7,8 @@ import { describe, expect, test, vi } from 'vitest'; import { DefaultServerService } from '../../cloud/services/default-server'; import { GraphQLService } from '../../cloud/services/graphql'; +import { ServerRealtimeService } from '../../cloud/services/realtime'; import { WorkspaceServerService } from '../../cloud/services/workspace-server'; -import { NbstoreService } from '../../storage'; import { WorkspaceService } from '../../workspace'; import { AudioTranscriptionJobStore } from './audio-transcription-job-store'; @@ -27,15 +27,19 @@ function createStore( .mockResolvedValue({ task: { id: 'task-2' } }) ) { const framework = new Framework(); - const server = { - scope: { - get: (key: unknown) => (key === GraphQLService ? { gql } : null), - }, - }; const realtime = { request: realtimeRequest, subscribe: vi.fn(), }; + const server = { + scope: { + get: (key: unknown) => { + if (key === GraphQLService) return { gql }; + if (key === ServerRealtimeService) return realtime; + return null; + }, + }, + }; framework .service(WorkspaceService, { workspace: { id: 'workspace-1' }, @@ -48,14 +52,10 @@ function createStore( .service(DefaultServerService, { server: null, } as unknown as DefaultServerService) - .service(NbstoreService, { - realtime, - } as unknown as NbstoreService) .entity(AudioTranscriptionJobStore, [ WorkspaceService, WorkspaceServerService, DefaultServerService, - NbstoreService, ]); return framework.provider().createEntity(AudioTranscriptionJobStore, { blobId: 'blob-1', diff --git a/packages/frontend/core/src/modules/media/entities/audio-transcription-job-store.ts b/packages/frontend/core/src/modules/media/entities/audio-transcription-job-store.ts index bff9813516..2fadd1b7e3 100644 --- a/packages/frontend/core/src/modules/media/entities/audio-transcription-job-store.ts +++ b/packages/frontend/core/src/modules/media/entities/audio-transcription-job-store.ts @@ -4,10 +4,11 @@ import { type TranscriptionResultType, } from '@affine/graphql'; import { Entity } from '@toeverything/infra'; +import { throwError } from 'rxjs'; import type { DefaultServerService, WorkspaceServerService } from '../../cloud'; import { GraphQLService } from '../../cloud/services/graphql'; -import type { NbstoreService } from '../../storage'; +import { ServerRealtimeService } from '../../cloud/services/realtime'; import type { WorkspaceService } from '../../workspace'; export class AudioTranscriptionJobStore extends Entity<{ @@ -20,8 +21,7 @@ export class AudioTranscriptionJobStore extends Entity<{ constructor( private readonly workspaceService: WorkspaceService, private readonly workspaceServerService: WorkspaceServerService, - private readonly defaultServerService: DefaultServerService, - private readonly nbstoreService: NbstoreService + private readonly defaultServerService: DefaultServerService ) { super(); } @@ -36,6 +36,10 @@ export class AudioTranscriptionJobStore extends Entity<{ return this.serverService?.scope.get(GraphQLService); } + private get realtimeService() { + return this.serverService?.scope.get(ServerRealtimeService); + } + private get currentWorkspaceId() { return this.workspaceService.workspace.id; } @@ -63,7 +67,11 @@ export class AudioTranscriptionJobStore extends Entity<{ }; retryTranscriptTask = async (taskId: string) => { - const response = await this.nbstoreService.realtime.request( + const realtimeService = this.realtimeService; + if (!realtimeService) { + throw new Error('No realtime service available'); + } + const response = await realtimeService.request( 'copilot.transcript.task.retry', { taskId, workspaceId: this.currentWorkspaceId } ); @@ -81,7 +89,11 @@ export class AudioTranscriptionJobStore extends Entity<{ if (!currentWorkspaceId) { throw new Error('No current workspace id'); } - const response = await this.nbstoreService.realtime.request( + const realtimeService = this.realtimeService; + if (!realtimeService) { + throw new Error('No realtime service available'); + } + const response = await realtimeService.request( 'copilot.transcript.task.get', { workspaceId: currentWorkspaceId, taskId, blobId }, { timeoutMs: 10000 } @@ -90,10 +102,14 @@ export class AudioTranscriptionJobStore extends Entity<{ }; subscribeTranscriptTask = (taskId: string) => { - return this.nbstoreService.realtime.subscribe( - 'copilot.transcript.task.changed', - { workspaceId: this.currentWorkspaceId, taskId } - ); + const realtimeService = this.realtimeService; + if (!realtimeService) { + return throwError(() => new Error('No realtime service available')); + } + return realtimeService.subscribe('copilot.transcript.task.changed', { + workspaceId: this.currentWorkspaceId, + taskId, + }); }; settleTranscriptTask = async (taskId: string) => { const graphqlService = this.graphqlService; diff --git a/packages/frontend/core/src/modules/media/entities/audio-transcription-job.spec.ts b/packages/frontend/core/src/modules/media/entities/audio-transcription-job.spec.ts index b3a052f6ef..d0c6f51c66 100644 --- a/packages/frontend/core/src/modules/media/entities/audio-transcription-job.spec.ts +++ b/packages/frontend/core/src/modules/media/entities/audio-transcription-job.spec.ts @@ -7,8 +7,8 @@ import { describe, expect, test, vi } from 'vitest'; import { AuthService } from '../../cloud/services/auth'; import { DefaultServerService } from '../../cloud/services/default-server'; +import { ServerRealtimeService } from '../../cloud/services/realtime'; import { WorkspaceServerService } from '../../cloud/services/workspace-server'; -import { NbstoreService } from '../../storage'; import { WorkspaceService } from '../../workspace'; import { AudioTranscriptionJob } from './audio-transcription-job'; import { AudioTranscriptionJobStore } from './audio-transcription-job-store'; @@ -28,7 +28,8 @@ describe('AudioTranscriptionJob', () => { }); const server = { scope: { - get: () => null, + get: (key: unknown) => + key === ServerRealtimeService ? { request } : null, getOptional: (key: unknown) => key === AuthService ? { session: { account$: { value: { id: 'user-1' } } } } @@ -46,14 +47,10 @@ describe('AudioTranscriptionJob', () => { .service(DefaultServerService, { server: null, } as unknown as DefaultServerService) - .service(NbstoreService, { - realtime: { request }, - } as unknown as NbstoreService) .entity(AudioTranscriptionJobStore, [ WorkspaceService, WorkspaceServerService, DefaultServerService, - NbstoreService, ]) .entity(AudioTranscriptionJob, [ WorkspaceServerService, diff --git a/packages/frontend/core/src/modules/media/index.ts b/packages/frontend/core/src/modules/media/index.ts index b78e831ebc..e9ce8272a5 100644 --- a/packages/frontend/core/src/modules/media/index.ts +++ b/packages/frontend/core/src/modules/media/index.ts @@ -1,7 +1,7 @@ import type { Framework } from '@toeverything/infra'; import { DefaultServerService, WorkspaceServerService } from '../cloud'; -import { GlobalState, GlobalStateService, NbstoreService } from '../storage'; +import { GlobalState, GlobalStateService } from '../storage'; import { WorkbenchService } from '../workbench'; import { WorkspaceScope, WorkspaceService } from '../workspace'; import { AudioAttachmentBlock } from './entities/audio-attachment-block'; @@ -35,7 +35,6 @@ export function configureMediaModule(framework: Framework) { WorkspaceService, WorkspaceServerService, DefaultServerService, - NbstoreService, ]) .service(AudioAttachmentService) .service(AudioMediaManagerService, [ diff --git a/packages/frontend/core/src/modules/notification/index.ts b/packages/frontend/core/src/modules/notification/index.ts index 13343277a1..1096ef75df 100644 --- a/packages/frontend/core/src/modules/notification/index.ts +++ b/packages/frontend/core/src/modules/notification/index.ts @@ -9,10 +9,11 @@ import type { Framework } from '@toeverything/infra'; import { AuthService, GraphQLService, + ServerRealtimeService, ServerScope, ServerService, } from '../cloud'; -import { GlobalSessionState, NbstoreService } from '../storage'; +import { GlobalSessionState } from '../storage'; import { NotificationCountService } from './services/count'; import { NotificationListService } from './services/list'; import { NotificationService } from './services/notification'; @@ -25,7 +26,7 @@ export function configureNotificationModule(framework: Framework) { .service(NotificationCountService, [ NotificationStore, AuthService, - NbstoreService, + ServerRealtimeService, ]) .service(NotificationListService, [ NotificationStore, diff --git a/packages/frontend/core/src/modules/notification/services/count.spec.ts b/packages/frontend/core/src/modules/notification/services/count.spec.ts index 06a4dc0f60..2b7ddbb932 100644 --- a/packages/frontend/core/src/modules/notification/services/count.spec.ts +++ b/packages/frontend/core/src/modules/notification/services/count.spec.ts @@ -3,7 +3,7 @@ import { Subject } from 'rxjs'; import { describe, expect, test, vi } from 'vitest'; import { AuthService } from '../../cloud/services/auth'; -import { NbstoreService } from '../../storage/services/nbstore'; +import { ServerRealtimeService } from '../../cloud/services/realtime'; import { NotificationStore } from '../stores/notification'; import { NotificationCountService } from './count'; @@ -25,21 +25,19 @@ function createCountService() { ), }, } as unknown as AuthService; - const nbstore = { - realtime: { - request, - subscribe: () => events$, - }, - } as unknown as NbstoreService; + const serverRealtime = { + request, + subscribe: () => events$, + } as unknown as ServerRealtimeService; const framework = new Framework(); framework.service(AuthService, auth); framework.store(NotificationStore, store); - framework.service(NbstoreService, nbstore); + framework.service(ServerRealtimeService, serverRealtime); framework.service(NotificationCountService, [ NotificationStore, AuthService, - NbstoreService, + ServerRealtimeService, ]); return { diff --git a/packages/frontend/core/src/modules/notification/services/count.ts b/packages/frontend/core/src/modules/notification/services/count.ts index 2427e61efb..4dc84b1e00 100644 --- a/packages/frontend/core/src/modules/notification/services/count.ts +++ b/packages/frontend/core/src/modules/notification/services/count.ts @@ -4,8 +4,8 @@ import { AccountChanged } from '../../cloud/events/account-changed'; import { ServerStarted } from '../../cloud/events/server-started'; import { RealtimeLiveQuery } from '../../cloud/realtime/live-query'; import type { AuthService } from '../../cloud/services/auth'; +import type { ServerRealtimeService } from '../../cloud/services/realtime'; import { ApplicationFocused } from '../../lifecycle'; -import type { NbstoreService } from '../../storage'; import type { NotificationStore } from '../stores/notification'; @OnEvent(ApplicationFocused, s => s.handleApplicationFocused) @@ -15,7 +15,7 @@ export class NotificationCountService extends Service { constructor( private readonly store: NotificationStore, private readonly authService: AuthService, - private readonly nbstoreService: NbstoreService + private readonly serverRealtimeService: ServerRealtimeService ) { super(); } @@ -31,7 +31,7 @@ export class NotificationCountService extends Service { private readonly liveQuery = new RealtimeLiveQuery({ request: signal => this.requestCount(signal), subscribe: () => - this.nbstoreService.realtime.subscribe('notification.count.changed', {}), + this.serverRealtimeService.subscribe('notification.count.changed', {}), applySnapshot: result => this.setCount(result.count), applyEvent: event => { this.setCount(event.count); @@ -84,7 +84,7 @@ export class NotificationCountService extends Service { private async requestCount(signal: AbortSignal) { this.isLoading$.setValue(true); try { - return await this.nbstoreService.realtime.request( + return await this.serverRealtimeService.request( 'notification.count.get', {}, { signal, timeoutMs: 10000 } diff --git a/packages/frontend/core/src/modules/permissions/index.ts b/packages/frontend/core/src/modules/permissions/index.ts index ab6be0c456..0205d98800 100644 --- a/packages/frontend/core/src/modules/permissions/index.ts +++ b/packages/frontend/core/src/modules/permissions/index.ts @@ -16,7 +16,6 @@ import { type Framework } from '@toeverything/infra'; import { WorkspaceServerService } from '../cloud/services/workspace-server'; import { DocScope, DocService } from '../doc'; -import { NbstoreService } from '../storage'; import { WorkspaceLocalState, WorkspaceScope, @@ -47,24 +46,19 @@ export function configurePermissionsModule(framework: Framework) { .store(WorkspacePermissionStore, [ WorkspaceServerService, WorkspaceLocalState, - NbstoreService, ]) .entity(WorkspacePermission, [WorkspaceService, WorkspacePermissionStore]) .service(WorkspaceMembersService, [WorkspaceMembersStore, WorkspaceService]) - .store(WorkspaceMembersStore, [WorkspaceServerService, NbstoreService]) + .store(WorkspaceMembersStore, [WorkspaceServerService]) .entity(WorkspaceMembers, [WorkspaceMembersStore, WorkspaceService]) .service(MemberSearchService, [MemberSearchStore, WorkspaceService]) - .store(MemberSearchStore, [NbstoreService]) + .store(MemberSearchStore, [WorkspaceServerService]) .service(GuardService, [ GuardStore, WorkspaceService, WorkspacePermissionService, ]) - .store(GuardStore, [ - WorkspaceService, - WorkspaceServerService, - NbstoreService, - ]); + .store(GuardStore, [WorkspaceService, WorkspaceServerService]); framework .scope(WorkspaceScope) @@ -74,5 +68,5 @@ export function configurePermissionsModule(framework: Framework) { WorkspaceService, DocService, ]) - .store(DocGrantedUsersStore, [WorkspaceServerService, NbstoreService]); + .store(DocGrantedUsersStore, [WorkspaceServerService]); } diff --git a/packages/frontend/core/src/modules/permissions/stores/doc-granted-users.ts b/packages/frontend/core/src/modules/permissions/stores/doc-granted-users.ts index ae88bf6f99..e7e3d667e1 100644 --- a/packages/frontend/core/src/modules/permissions/stores/doc-granted-users.ts +++ b/packages/frontend/core/src/modules/permissions/stores/doc-granted-users.ts @@ -9,15 +9,12 @@ import { updateDocUserRoleMutation, } from '@affine/graphql'; import { Store } from '@toeverything/infra'; +import { throwError } from 'rxjs'; -import type { NbstoreService } from '../../storage'; import { mapDocGrantedUserSnapshot } from './realtime-mappers'; export class DocGrantedUsersStore extends Store { - constructor( - private readonly workspaceServerService: WorkspaceServerService, - private readonly nbstoreService: NbstoreService - ) { + constructor(private readonly workspaceServerService: WorkspaceServerService) { super(); } @@ -27,7 +24,10 @@ export class DocGrantedUsersStore extends Store { pagination: PaginationInput, signal?: AbortSignal ) { - return await this.nbstoreService.realtime + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + return await this.workspaceServerService.server.realtime .request( 'doc.grants.get', { @@ -50,10 +50,16 @@ export class DocGrantedUsersStore extends Store { } subscribeDocGrants(workspaceId: string, docId: string) { - return this.nbstoreService.realtime.subscribe('doc.grants.changed', { - workspaceId, - docId, - }); + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( + 'doc.grants.changed', + { + workspaceId, + docId, + } + ); } async grantDocUserRoles(input: GrantDocUserRolesInput) { diff --git a/packages/frontend/core/src/modules/permissions/stores/guard.ts b/packages/frontend/core/src/modules/permissions/stores/guard.ts index aae859f8bf..c6352b8ea2 100644 --- a/packages/frontend/core/src/modules/permissions/stores/guard.ts +++ b/packages/frontend/core/src/modules/permissions/stores/guard.ts @@ -6,7 +6,6 @@ import { import { Store } from '@toeverything/infra'; import type { WorkspaceServerService } from '../../cloud'; -import type { NbstoreService } from '../../storage'; import type { WorkspaceService } from '../../workspace'; export type WorkspacePermissionActions = string; @@ -19,8 +18,7 @@ export type DocPermissionActions = keyof Omit< export class GuardStore extends Store { constructor( private readonly workspaceService: WorkspaceService, - private readonly workspaceServerService: WorkspaceServerService, - private readonly nbstoreService: NbstoreService + private readonly workspaceServerService: WorkspaceServerService ) { super(); } @@ -28,11 +26,15 @@ export class GuardStore extends Store { async getWorkspacePermissions(): Promise< Record > { - const { access } = await this.nbstoreService.realtime.request( - 'workspace.access.get', - { workspaceId: this.workspaceService.workspace.id }, - { timeoutMs: 10000 } - ); + if (!this.workspaceServerService.server) { + throw new Error('No server'); + } + const { access } = + await this.workspaceServerService.server.realtime.request( + 'workspace.access.get', + { workspaceId: this.workspaceService.workspace.id }, + { timeoutMs: 10000 } + ); return access.permissions as Record; } diff --git a/packages/frontend/core/src/modules/permissions/stores/member-search.ts b/packages/frontend/core/src/modules/permissions/stores/member-search.ts index a0ac49b293..f6bb15e253 100644 --- a/packages/frontend/core/src/modules/permissions/stores/member-search.ts +++ b/packages/frontend/core/src/modules/permissions/stores/member-search.ts @@ -1,10 +1,11 @@ import { Store } from '@toeverything/infra'; +import { throwError } from 'rxjs'; -import type { NbstoreService } from '../../storage'; +import type { WorkspaceServerService } from '../../cloud'; import { mapWorkspaceMemberSnapshot } from './realtime-mappers'; export class MemberSearchStore extends Store { - constructor(private readonly nbstoreService: NbstoreService) { + constructor(private readonly workspaceServerService: WorkspaceServerService) { super(); } @@ -15,7 +16,10 @@ export class MemberSearchStore extends Store { take?: number, signal?: AbortSignal ) { - return await this.nbstoreService.realtime + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + return await this.workspaceServerService.server.realtime .request( 'workspace.members.get', { workspaceId, skip, take, query }, @@ -28,8 +32,14 @@ export class MemberSearchStore extends Store { } subscribeMembers(workspaceId: string) { - return this.nbstoreService.realtime.subscribe('workspace.members.changed', { - workspaceId, - }); + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( + 'workspace.members.changed', + { + workspaceId, + } + ); } } diff --git a/packages/frontend/core/src/modules/permissions/stores/members.ts b/packages/frontend/core/src/modules/permissions/stores/members.ts index 85af13c527..103a7a6e2e 100644 --- a/packages/frontend/core/src/modules/permissions/stores/members.ts +++ b/packages/frontend/core/src/modules/permissions/stores/members.ts @@ -9,16 +9,13 @@ import { type WorkspaceInviteLinkExpireTime, } from '@affine/graphql'; import { Store } from '@toeverything/infra'; +import { throwError } from 'rxjs'; import type { WorkspaceServerService } from '../../cloud'; -import type { NbstoreService } from '../../storage'; import { mapWorkspaceMemberSnapshot } from './realtime-mappers'; export class WorkspaceMembersStore extends Store { - constructor( - private readonly workspaceServerService: WorkspaceServerService, - private readonly nbstoreService: NbstoreService - ) { + constructor(private readonly workspaceServerService: WorkspaceServerService) { super(); } @@ -28,7 +25,10 @@ export class WorkspaceMembersStore extends Store { take: number, signal?: AbortSignal ) { - return await this.nbstoreService.realtime + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + return await this.workspaceServerService.server.realtime .request( 'workspace.members.get', { workspaceId, skip, take }, @@ -41,9 +41,15 @@ export class WorkspaceMembersStore extends Store { } subscribeMembers(workspaceId: string) { - return this.nbstoreService.realtime.subscribe('workspace.members.changed', { - workspaceId, - }); + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( + 'workspace.members.changed', + { + workspaceId, + } + ); } async inviteBatch(workspaceId: string, emails: string[]) { diff --git a/packages/frontend/core/src/modules/permissions/stores/permission.ts b/packages/frontend/core/src/modules/permissions/stores/permission.ts index c65d3ee685..a14d07e749 100644 --- a/packages/frontend/core/src/modules/permissions/stores/permission.ts +++ b/packages/frontend/core/src/modules/permissions/stores/permission.ts @@ -1,32 +1,41 @@ import type { WorkspaceServerService } from '@affine/core/modules/cloud'; import { leaveWorkspaceMutation } from '@affine/graphql'; import { Store } from '@toeverything/infra'; +import { throwError } from 'rxjs'; -import type { NbstoreService } from '../../storage'; import type { WorkspaceLocalState } from '../../workspace'; export class WorkspacePermissionStore extends Store { constructor( private readonly workspaceServerService: WorkspaceServerService, - private readonly workspaceLocalState: WorkspaceLocalState, - private readonly nbstoreService: NbstoreService + private readonly workspaceLocalState: WorkspaceLocalState ) { super(); } async fetchWorkspaceInfo(workspaceId: string, signal?: AbortSignal) { - const { access } = await this.nbstoreService.realtime.request( - 'workspace.access.get', - { workspaceId }, - { signal, timeoutMs: 10000 } - ); + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + const { access } = + await this.workspaceServerService.server.realtime.request( + 'workspace.access.get', + { workspaceId }, + { signal, timeoutMs: 10000 } + ); return { workspace: access }; } subscribeWorkspaceAccess(workspaceId: string) { - return this.nbstoreService.realtime.subscribe('workspace.access.changed', { - workspaceId, - }); + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( + 'workspace.access.changed', + { + workspaceId, + } + ); } /** diff --git a/packages/frontend/core/src/modules/quota/index.ts b/packages/frontend/core/src/modules/quota/index.ts index 135cb9c519..db5b5bc2bc 100644 --- a/packages/frontend/core/src/modules/quota/index.ts +++ b/packages/frontend/core/src/modules/quota/index.ts @@ -3,7 +3,7 @@ export { QuotaCheck } from './views/quota-check'; import { type Framework } from '@toeverything/infra'; -import { NbstoreService } from '../storage'; +import { WorkspaceServerService } from '../cloud'; import { WorkspaceScope, WorkspaceService } from '../workspace'; import { WorkspaceQuota } from './entities/quota'; import { WorkspaceQuotaService } from './services/quota'; @@ -13,6 +13,6 @@ export function configureQuotaModule(framework: Framework) { framework .scope(WorkspaceScope) .service(WorkspaceQuotaService) - .store(WorkspaceQuotaStore, [NbstoreService]) + .store(WorkspaceQuotaStore, [WorkspaceServerService]) .entity(WorkspaceQuota, [WorkspaceService, WorkspaceQuotaStore]); } diff --git a/packages/frontend/core/src/modules/quota/stores/quota.ts b/packages/frontend/core/src/modules/quota/stores/quota.ts index 2d1d3c2461..37ecaf4dd6 100644 --- a/packages/frontend/core/src/modules/quota/stores/quota.ts +++ b/packages/frontend/core/src/modules/quota/stores/quota.ts @@ -1,14 +1,18 @@ import { Store } from '@toeverything/infra'; +import { throwError } from 'rxjs'; -import type { NbstoreService } from '../../storage'; +import type { WorkspaceServerService } from '../../cloud'; export class WorkspaceQuotaStore extends Store { - constructor(private readonly nbstoreService: NbstoreService) { + constructor(private readonly workspaceServerService: WorkspaceServerService) { super(); } async fetchWorkspaceQuotaState(workspaceId: string, signal?: AbortSignal) { - const response = await this.nbstoreService.realtime.request( + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + const response = await this.workspaceServerService.server.realtime.request( 'workspace.quota-state.get', { workspaceId }, { signal, timeoutMs: 10000 } @@ -17,7 +21,10 @@ export class WorkspaceQuotaStore extends Store { } subscribeWorkspaceQuotaState(workspaceId: string) { - return this.nbstoreService.realtime.subscribe( + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( 'workspace.quota-state.changed', { workspaceId } ); diff --git a/packages/frontend/core/src/modules/share-doc/index.ts b/packages/frontend/core/src/modules/share-doc/index.ts index da1037b0c8..772b11b6cb 100644 --- a/packages/frontend/core/src/modules/share-doc/index.ts +++ b/packages/frontend/core/src/modules/share-doc/index.ts @@ -5,7 +5,6 @@ import { type Framework } from '@toeverything/infra'; import { WorkspaceServerService } from '../cloud'; import { DocScope, DocService } from '../doc'; -import { NbstoreService } from '../storage'; import { WorkspaceLocalCache, WorkspaceScope, @@ -31,5 +30,5 @@ export function configureShareDocsModule(framework: Framework) { .scope(DocScope) .service(ShareInfoService) .entity(ShareInfo, [WorkspaceService, DocService, ShareStore]) - .store(ShareStore, [WorkspaceServerService, NbstoreService]); + .store(ShareStore, [WorkspaceServerService]); } diff --git a/packages/frontend/core/src/modules/share-doc/stores/share.ts b/packages/frontend/core/src/modules/share-doc/stores/share.ts index bc97e2618b..ff8a6f9a8f 100644 --- a/packages/frontend/core/src/modules/share-doc/stores/share.ts +++ b/packages/frontend/core/src/modules/share-doc/stores/share.ts @@ -5,16 +5,13 @@ import { revokePublicPageMutation, } from '@affine/graphql'; import { Store } from '@toeverything/infra'; +import { throwError } from 'rxjs'; import type { WorkspaceServerService } from '../../cloud'; import { mapRealtimeEnum } from '../../cloud/realtime/enum'; -import type { NbstoreService } from '../../storage'; export class ShareStore extends Store { - constructor( - private readonly workspaceServerService: WorkspaceServerService, - private readonly nbstoreService: NbstoreService - ) { + constructor(private readonly workspaceServerService: WorkspaceServerService) { super(); } @@ -23,7 +20,10 @@ export class ShareStore extends Store { docId: string, signal?: AbortSignal ) { - const { state } = await this.nbstoreService.realtime.request( + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + const { state } = await this.workspaceServerService.server.realtime.request( 'doc.share-state.get', { workspaceId, docId }, { signal, timeoutMs: 10000 } @@ -41,10 +41,16 @@ export class ShareStore extends Store { } subscribeShareState(workspaceId: string, docId: string) { - return this.nbstoreService.realtime.subscribe('doc.share-state.changed', { - workspaceId, - docId, - }); + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( + 'doc.share-state.changed', + { + workspaceId, + docId, + } + ); } async enableSharePage( diff --git a/packages/frontend/core/src/modules/share-setting/index.ts b/packages/frontend/core/src/modules/share-setting/index.ts index acde9f6300..7297c8db90 100644 --- a/packages/frontend/core/src/modules/share-setting/index.ts +++ b/packages/frontend/core/src/modules/share-setting/index.ts @@ -3,7 +3,6 @@ export { WorkspaceShareSettingService } from './services/share-setting'; import { type Framework } from '@toeverything/infra'; import { WorkspaceServerService } from '../cloud'; -import { NbstoreService } from '../storage'; import { WorkspaceScope, WorkspaceService } from '../workspace'; import { WorkspaceShareSetting } from './entities/share-setting'; import { WorkspaceShareSettingService } from './services/share-setting'; @@ -13,7 +12,7 @@ export function configureShareSettingModule(framework: Framework) { framework .scope(WorkspaceScope) .service(WorkspaceShareSettingService) - .store(WorkspaceShareSettingStore, [WorkspaceServerService, NbstoreService]) + .store(WorkspaceShareSettingStore, [WorkspaceServerService]) .entity(WorkspaceShareSetting, [ WorkspaceService, WorkspaceShareSettingStore, diff --git a/packages/frontend/core/src/modules/share-setting/stores/share-setting.ts b/packages/frontend/core/src/modules/share-setting/stores/share-setting.ts index ae3bf6ce7e..4c51289c39 100644 --- a/packages/frontend/core/src/modules/share-setting/stores/share-setting.ts +++ b/packages/frontend/core/src/modules/share-setting/stores/share-setting.ts @@ -5,43 +5,56 @@ import { setEnableUrlPreviewMutation, } from '@affine/graphql'; import { Store } from '@toeverything/infra'; - -import type { NbstoreService } from '../../storage'; +import { throwError } from 'rxjs'; export class WorkspaceShareSettingStore extends Store { - constructor( - private readonly workspaceServerService: WorkspaceServerService, - private readonly nbstoreService: NbstoreService - ) { + constructor(private readonly workspaceServerService: WorkspaceServerService) { super(); } async fetchWorkspaceConfig(workspaceId: string, signal?: AbortSignal) { - const { config } = await this.nbstoreService.realtime.request( - 'workspace.config.get', - { workspaceId }, - { signal, timeoutMs: 10000 } - ); + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + const { config } = + await this.workspaceServerService.server.realtime.request( + 'workspace.config.get', + { workspaceId }, + { signal, timeoutMs: 10000 } + ); return config; } subscribeWorkspaceConfig(workspaceId: string) { - return this.nbstoreService.realtime.subscribe('workspace.config.changed', { - workspaceId, - }); + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( + 'workspace.config.changed', + { + workspaceId, + } + ); } async fetchInviteLink(workspaceId: string, signal?: AbortSignal) { - const { inviteLink } = await this.nbstoreService.realtime.request( - 'workspace.invite-link.get', - { workspaceId }, - { signal, timeoutMs: 10000 } - ); + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + const { inviteLink } = + await this.workspaceServerService.server.realtime.request( + 'workspace.invite-link.get', + { workspaceId }, + { signal, timeoutMs: 10000 } + ); return inviteLink; } subscribeInviteLink(workspaceId: string) { - return this.nbstoreService.realtime.subscribe( + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( 'workspace.invite-link.changed', { workspaceId } ); diff --git a/packages/frontend/core/src/modules/workspace-engine/impls/cloud.ts b/packages/frontend/core/src/modules/workspace-engine/impls/cloud.ts index e428316ddf..d756b19c66 100644 --- a/packages/frontend/core/src/modules/workspace-engine/impls/cloud.ts +++ b/packages/frontend/core/src/modules/workspace-engine/impls/cloud.ts @@ -72,7 +72,7 @@ import { AFFiNE_WORKSPACE_DB_SCHEMA, AFFiNE_WORKSPACE_USERDATA_DB_SCHEMA, } from '../../db/schema'; -import { type GlobalState, NbstoreService } from '../../storage'; +import type { GlobalState } from '../../storage'; import type { Workspace, WorkspaceFlavourProvider, @@ -96,7 +96,6 @@ const logger = new DebugLogger('affine:cloud-workspace-flavour-provider'); class CloudWorkspaceFlavourProvider implements WorkspaceFlavourProvider { private readonly authService: AuthService; private readonly graphqlService: GraphQLService; - private readonly nbstoreService: NbstoreService; private readonly unsubscribeAccountChanged: () => void; constructor( @@ -105,7 +104,6 @@ class CloudWorkspaceFlavourProvider implements WorkspaceFlavourProvider { ) { this.authService = server.scope.get(AuthService); this.graphqlService = server.scope.get(GraphQLService); - this.nbstoreService = server.scope.get(NbstoreService); this.unsubscribeAccountChanged = this.server.scope.eventBus.on( AccountChanged, () => { @@ -515,7 +513,7 @@ class CloudWorkspaceFlavourProvider implements WorkspaceFlavourProvider { } private async getWorkspaceInfo(workspaceId: string, signal?: AbortSignal) { - const { access } = await this.nbstoreService.realtime.request( + const { access } = await this.server.realtime.request( 'workspace.access.get', { workspaceId }, { signal, timeoutMs: 10000 } diff --git a/packages/frontend/core/src/modules/workspace-indexer-embedding/index.ts b/packages/frontend/core/src/modules/workspace-indexer-embedding/index.ts index 78f7c06032..fdb3321b14 100644 --- a/packages/frontend/core/src/modules/workspace-indexer-embedding/index.ts +++ b/packages/frontend/core/src/modules/workspace-indexer-embedding/index.ts @@ -1,5 +1,4 @@ import { WorkspaceServerService } from '@affine/core/modules/cloud'; -import { NbstoreService } from '@affine/core/modules/storage'; import { WorkspaceScope, WorkspaceService, @@ -17,7 +16,7 @@ export function configureIndexerEmbeddingModule(framework: Framework) { framework .scope(WorkspaceScope) .service(EmbeddingService) - .store(EmbeddingStore, [WorkspaceServerService, NbstoreService]) + .store(EmbeddingStore, [WorkspaceServerService]) .entity(EmbeddingEnabled, [WorkspaceService, EmbeddingStore]) .entity(AdditionalAttachments, [WorkspaceService, EmbeddingStore]) .entity(IgnoredDocs, [WorkspaceService, EmbeddingStore]) diff --git a/packages/frontend/core/src/modules/workspace-indexer-embedding/stores/embedding.ts b/packages/frontend/core/src/modules/workspace-indexer-embedding/stores/embedding.ts index c4392bda0e..da2980fb7f 100644 --- a/packages/frontend/core/src/modules/workspace-indexer-embedding/stores/embedding.ts +++ b/packages/frontend/core/src/modules/workspace-indexer-embedding/stores/embedding.ts @@ -1,5 +1,4 @@ import type { WorkspaceServerService } from '@affine/core/modules/cloud'; -import type { NbstoreService } from '@affine/core/modules/storage'; import { addWorkspaceArtifactMutation, addWorkspaceEmbeddingIgnoredDocsMutation, @@ -11,21 +10,23 @@ import { setEnableDocEmbeddingMutation, } from '@affine/graphql'; import { Store } from '@toeverything/infra'; +import { throwError } from 'rxjs'; export class EmbeddingStore extends Store { - constructor( - private readonly workspaceServerService: WorkspaceServerService, - private readonly nbstoreService: NbstoreService - ) { + constructor(private readonly workspaceServerService: WorkspaceServerService) { super(); } async getEnabled(workspaceId: string, signal?: AbortSignal) { - const { config } = await this.nbstoreService.realtime.request( - 'workspace.config.get', - { workspaceId }, - { signal, timeoutMs: 10000 } - ); + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + const { config } = + await this.workspaceServerService.server.realtime.request( + 'workspace.config.get', + { workspaceId }, + { signal, timeoutMs: 10000 } + ); return config.enableDocEmbedding; } @@ -173,7 +174,10 @@ export class EmbeddingStore extends Store { } async getEmbeddingProgress(workspaceId: string, signal?: AbortSignal) { - return await this.nbstoreService.realtime.request( + if (!this.workspaceServerService.server) { + throw new Error('No Server'); + } + return await this.workspaceServerService.server.realtime.request( 'workspace.embedding.progress.get', { workspaceId }, { signal, timeoutMs: 10000 } @@ -181,7 +185,10 @@ export class EmbeddingStore extends Store { } subscribeEmbeddingProgress(workspaceId: string) { - return this.nbstoreService.realtime.subscribe( + if (!this.workspaceServerService.server) { + return throwError(() => new Error('No Server')); + } + return this.workspaceServerService.server.realtime.subscribe( 'workspace.embedding.progress.changed', { workspaceId } );