Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(core): initial multiple servers infra #8745

Merged
merged 1 commit into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
DocStorage,
} from '../../../sync';
import type { WorkspaceProfileInfo } from '../entities/profile';
import type { Workspace } from '../entities/workspace';
import type { WorkspaceMetadata } from '../metadata';

export interface WorkspaceEngineProvider {
Expand Down Expand Up @@ -55,6 +56,8 @@ export interface WorkspaceFlavourProvider {
getWorkspaceBlob(id: string, blob: string): Promise<Blob | null>;

getEngineProvider(workspaceId: string): WorkspaceEngineProvider;

onWorkspaceInitialized?(workspace: Workspace): void;
}

export const WorkspaceFlavourProvider =
Expand Down
9 changes: 6 additions & 3 deletions packages/common/infra/src/modules/workspace/services/repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,12 @@ export class WorkspaceRepositoryService extends Service {
logger.info(
`open workspace [${openOptions.metadata.flavour}] ${openOptions.metadata.id} `
);
const flavourProvider = this.providers.find(
p => p.flavour === openOptions.metadata.flavour
);
const provider =
customProvider ??
this.providers
.find(p => p.flavour === openOptions.metadata.flavour)
?.getEngineProvider(openOptions.metadata.id);
flavourProvider?.getEngineProvider(openOptions.metadata.id);
if (!provider) {
throw new Error(
`Unknown workspace flavour: ${openOptions.metadata.flavour}`
Expand All @@ -106,6 +107,8 @@ export class WorkspaceRepositoryService extends Service {

this.framework.emitEvent(WorkspaceInitialized, workspace);

flavourProvider?.onWorkspaceInitialized?.(workspace);

this.profileRepo
.getProfile(openOptions.metadata)
.syncWithWorkspace(workspace);
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/apps/ios/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* for support arraybuffer response type
*/
import { FetchProvider } from '@affine/core/modules/cloud/provider/fetch';
import { RawFetchProvider } from '@affine/core/modules/cloud/provider/fetch';
import { CapacitorHttp } from '@capacitor/core';
import type { Framework } from '@toeverything/infra';

Expand Down Expand Up @@ -121,7 +121,7 @@ function base64ToUint8Array(base64: string) {
return new Uint8Array(binaryArray);
}
export function configureFetchProvider(framework: Framework) {
framework.override(FetchProvider, {
framework.override(RawFetchProvider, {
fetch: async (input, init) => {
const request = new Request(input, init);
const { method } = request;
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ export * from './auth-page-container';
export * from './back-button';
export * from './change-email-page';
export * from './change-password-page';
export * from './confirm-change-email';
export * from './count-down-render';
export * from './email-verified-email';
export * from './modal';
export * from './modal-header';
export * from './onboarding-page';
Expand Down
14 changes: 7 additions & 7 deletions packages/frontend/core/src/components/affine/auth/oauth.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { Skeleton } from '@affine/component';
import { Button } from '@affine/component/ui/button';
import { ServerService } from '@affine/core/modules/cloud';
import { UrlService } from '@affine/core/modules/url';
import { OAuthProviderType } from '@affine/graphql';
import track from '@affine/track';
import { GithubIcon, GoogleDuotoneIcon } from '@blocksuite/icons/rc';
import { useLiveData, useService } from '@toeverything/infra';
import { type ReactElement, useCallback } from 'react';

import { ServerConfigService } from '../../../modules/cloud';

const OAuthProviderMap: Record<
OAuthProviderType,
{
Expand All @@ -30,11 +29,11 @@ const OAuthProviderMap: Record<
};

export function OAuth({ redirectUrl }: { redirectUrl?: string }) {
const serverConfig = useService(ServerConfigService).serverConfig;
const serverService = useService(ServerService);
const urlService = useService(UrlService);
const oauth = useLiveData(serverConfig.features$.map(r => r?.oauth));
const oauth = useLiveData(serverService.server.features$.map(r => r?.oauth));
const oauthProviders = useLiveData(
serverConfig.config$.map(r => r?.oauthProviders)
serverService.server.config$.map(r => r?.oauthProviders)
EYHN marked this conversation as resolved.
Show resolved Hide resolved
);
const scheme = urlService.getClientScheme();

Expand Down Expand Up @@ -66,6 +65,7 @@ function OAuthProvider({
scheme?: string;
popupWindow: (url: string) => void;
}) {
const serverService = useService(ServerService);
const { icon } = OAuthProviderMap[provider];

const onClick = useCallback(() => {
Expand All @@ -85,12 +85,12 @@ function OAuthProvider({
// if (BUILD_CONFIG.isAndroid) {}

const oauthUrl =
BUILD_CONFIG.serverUrlPrefix + `/oauth/login?${params.toString()}`;
serverService.server.baseUrl + `/oauth/login?${params.toString()}`;

track.$.$.auth.signIn({ method: 'oauth', provider });

popupWindow(oauthUrl);
}, [popupWindow, provider, redirectUrl, scheme]);
}, [popupWindow, provider, redirectUrl, scheme, serverService]);

return (
<Button
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { useLiveData, useService } from '@toeverything/infra';
import { useCallback, useState } from 'react';

import { useMutation } from '../../../components/hooks/use-mutation';
import { ServerConfigService } from '../../../modules/cloud';
import { ServerService } from '../../../modules/cloud';
import type { AuthPanelProps } from './index';

const useEmailTitle = (emailType: AuthPanelProps<'sendEmail'>['emailType']) => {
Expand Down Expand Up @@ -142,10 +142,10 @@ export const SendEmail = ({
// todo(@pengx17): impl redirectUrl for sendEmail?
}: AuthPanelProps<'sendEmail'>) => {
const t = useI18n();
const serverConfig = useService(ServerConfigService).serverConfig;
const serverService = useService(ServerService);

const passwordLimits = useLiveData(
serverConfig.credentialsRequirement$.map(r => r?.password)
serverService.server.credentialsRequirement$.map(r => r?.password)
);
const [hasSentEmail, setHasSentEmail] = useState(false);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
import { Tooltip } from '@affine/component/ui/tooltip';
import { SubscriptionPlan } from '@affine/graphql';
import { useI18n } from '@affine/i18n';
import { useLiveData, useServices } from '@toeverything/infra';
import { useLiveData, useService } from '@toeverything/infra';
import { type SyntheticEvent, useEffect } from 'react';

import {
ServerConfigService,
SubscriptionService,
} from '../../../modules/cloud';
import { ServerService, SubscriptionService } from '../../../modules/cloud';
import * as styles from './style.css';

export const UserPlanButton = ({
onClick,
}: {
onClick: (e: SyntheticEvent<Element, Event>) => void;
}) => {
const { serverConfigService, subscriptionService } = useServices({
ServerConfigService,
SubscriptionService,
});
const serverService = useService(ServerService);
const subscriptionService = useService(SubscriptionService);

const hasPayment = useLiveData(
serverConfigService.serverConfig.features$.map(r => r?.payment)
serverService.server.features$.map(r => r?.payment)
);
const plan = useLiveData(
subscriptionService.subscription.pro$.map(subscription =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
useSharingUrl,
} from '@affine/core/components/hooks/affine/use-share-url';
import { useAsyncCallback } from '@affine/core/components/hooks/affine-async-hooks';
import { ServerConfigService } from '@affine/core/modules/cloud';
import { ServerService } from '@affine/core/modules/cloud';
import { GlobalDialogService } from '@affine/core/modules/dialogs';
import { EditorService } from '@affine/core/modules/editor';
import { WorkspacePermissionService } from '@affine/core/modules/permissions';
Expand Down Expand Up @@ -70,13 +70,13 @@ export const AFFiNESharePage = (props: ShareMenuProps) => {
const currentMode = useLiveData(editor.mode$);
const editorContainer = useLiveData(editor.editorContainer$);
const shareInfoService = useService(ShareInfoService);
const serverConfig = useService(ServerConfigService).serverConfig;
const serverService = useService(ServerService);
useEffect(() => {
shareInfoService.shareInfo.revalidate();
}, [shareInfoService]);
const isSharedPage = useLiveData(shareInfoService.shareInfo.isShared$);
const sharedMode = useLiveData(shareInfoService.shareInfo.sharedMode$);
const baseUrl = useLiveData(serverConfig.config$.map(c => c?.baseUrl));
const baseUrl = serverService.server.baseUrl;
const isLoading =
isSharedPage === null || sharedMode === null || baseUrl === null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ import {
cleanupCopilotSessionMutation,
createCopilotMessageMutation,
createCopilotSessionMutation,
fetcher as defaultFetcher,
forkCopilotSessionMutation,
getBaseUrl,
getCopilotHistoriesQuery,
getCopilotHistoryIdsQuery,
getCopilotSessionsQuery,
gqlFetcherFactory,
GraphQLError,
type GraphQLQuery,
type QueryOptions,
Expand All @@ -22,6 +21,26 @@ import {
} from '@blocksuite/affine/blocks';
import { getCurrentStore } from '@toeverything/infra';

/**
* @deprecated will be removed soon
*/
export function getBaseUrl(): string {
if (BUILD_CONFIG.isElectron || BUILD_CONFIG.isIOS || BUILD_CONFIG.isAndroid) {
return BUILD_CONFIG.serverUrlPrefix;
}
if (typeof window === 'undefined') {
// is nodejs
return '';
}
const { protocol, hostname, port } = window.location;
return `${protocol}//${hostname}${port ? `:${port}` : ''}`;
}

/**
* @deprecated will be removed soon
*/
const defaultFetcher = gqlFetcherFactory(getBaseUrl() + '/graphql');

type OptionsField<T extends GraphQLQuery> =
RequestOptions<T>['variables'] extends { options: infer U } ? U : never;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { AIProvider } from '@affine/core/blocksuite/presets/ai';
import { toggleGeneralAIOnboarding } from '@affine/core/components/affine/ai-onboarding/apis';
import { authAtom } from '@affine/core/components/atoms';
import {
getBaseUrl,
type getCopilotHistoriesQuery,
type RequestOptions,
} from '@affine/graphql';
Expand All @@ -11,6 +10,7 @@ import { assertExists } from '@blocksuite/affine/global/utils';
import { getCurrentStore } from '@toeverything/infra';
import { z } from 'zod';

import { getBaseUrl } from './copilot-client';
import type { PromptKey } from './prompt';
import {
cleanupSessions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
generateUrl,
type UseSharingUrl,
} from '@affine/core/components/hooks/affine/use-share-url';
import { getAffineCloudBaseUrl } from '@affine/core/modules/cloud/services/fetch';
import { ServerService } from '@affine/core/modules/cloud';
import { EditorService } from '@affine/core/modules/editor';
import { copyLinkToBlockStdScopeClipboard } from '@affine/core/utils/clipboard';
import { I18n } from '@affine/i18n';
Expand Down Expand Up @@ -41,9 +41,7 @@ function createCopyLinkToBlockMenuItem(
return mode === 'edgeless';
},
select: () => {
const baseUrl = getAffineCloudBaseUrl();
if (!baseUrl) return;

const serverService = framework.get(ServerService);
const pageId = model.doc.id;
const { editor } = framework.get(EditorService);
const mode = editor.mode$.value;
Expand All @@ -58,7 +56,10 @@ function createCopyLinkToBlockMenuItem(
blockIds: [model.id],
};

const str = generateUrl(options);
const str = generateUrl({
...options,
baseUrl: serverService.server.baseUrl,
});
if (!str) return;

const type = model.flavour;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
generateUrl,
type UseSharingUrl,
} from '@affine/core/components/hooks/affine/use-share-url';
import { getAffineCloudBaseUrl } from '@affine/core/modules/cloud/services/fetch';
import { WorkspaceServerService } from '@affine/core/modules/cloud';
import { EditorService } from '@affine/core/modules/editor';
import { copyLinkToBlockStdScopeClipboard } from '@affine/core/utils/clipboard';
import { I18n } from '@affine/i18n';
Expand Down Expand Up @@ -79,11 +79,7 @@ function createCopyLinkToBlockMenuItem(
return {
...item,
action: async (ctx: MenuContext) => {
const baseUrl = getAffineCloudBaseUrl();
if (!baseUrl) {
ctx.close();
return;
}
const workspaceServerService = framework.get(WorkspaceServerService);

const { editor } = framework.get(EditorService);
const mode = editor.mode$.value;
Expand All @@ -109,7 +105,10 @@ function createCopyLinkToBlockMenuItem(
}
}

const str = generateUrl(options);
const str = generateUrl({
...options,
baseUrl: workspaceServerService.server?.baseUrl ?? location.origin,
});
if (!str) {
ctx.close();
return;
Expand Down
Loading
Loading