Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(rpc): sync sheet between main and worker thread (#450)

Wenzhao Huc711f0a53add
diff --git a/examples/univer-sheet-ts/src/worker.ts b/examples/univer-sheet-ts/src/worker.ts
index 382a69944b..b09111d61c 100644
--- a/examples/univer-sheet-ts/src/worker.ts
+++ b/examples/univer-sheet-ts/src/worker.ts
@@ -11,3 +11,6 @@ const univer = new Univer({
univer.registerPlugin(SheetPlugin);
univer.registerPlugin(UniverRPCWorkerThreadPlugin);
+
+declare let self: WorkerGlobalScope & typeof globalThis & { univer: Univer };
+self.univer = univer;
diff --git a/packages/base-sheets/src/controllers/basic-worksheet.controller.ts b/packages/base-sheets/src/controllers/basic-worksheet.controller.ts
index cff095791f..ed1bd9fe1c 100644
--- a/packages/base-sheets/src/controllers/basic-worksheet.controller.ts
+++ b/packages/base-sheets/src/controllers/basic-worksheet.controller.ts
@@ -108,7 +108,7 @@ export interface IStyleTypeValue<T> {
/**
* The controller to provide the most basic sheet CRUD methods to other modules of sheet modules.
*/
-@OnLifecycle(LifecycleStages.Rendered, BasicWorksheetController)
+@OnLifecycle(LifecycleStages.Ready, BasicWorksheetController)
export class BasicWorksheetController extends Disposable implements IDisposable {
constructor(@ICommandService private readonly _commandService: ICommandService) {
super();
diff --git a/packages/core/src/basics/univer.ts b/packages/core/src/basics/univer.ts
index d54c305e07..eb74a30bad 100644
--- a/packages/core/src/basics/univer.ts
+++ b/packages/core/src/basics/univer.ts
@@ -42,7 +42,7 @@ export class Univer {
private _univerDoc: UniverDoc | null = null;
private _univerSlide: UniverSlide | null = null;
- private get _currentUniverService(): IUniverInstanceService {
+ private get _univerInstanceService(): IUniverInstanceService {
return this._rootInjector.get(IUniverInstanceService);
}
@@ -89,7 +89,7 @@ export class Univer {
let workbook: Workbook;
const addSheet = () => {
workbook = this._univerSheet!.createSheet(config);
- this._currentUniverService.addSheet(workbook);
+ this._univerInstanceService.addSheet(workbook);
};
if (!this._univerSheet) {
@@ -115,7 +115,7 @@ export class Univer {
let doc: DocumentModel;
const addDoc = () => {
doc = this._univerDoc!.createDoc(config);
- this._currentUniverService.addDoc(doc);
+ this._univerInstanceService.addDoc(doc);
};
if (!this._univerDoc) {
@@ -141,7 +141,7 @@ export class Univer {
let slide: Slide;
const addSlide = () => {
slide = this._univerSlide!.createSlide(config);
- this._currentUniverService.addSlide(slide);
+ this._univerInstanceService.addSlide(slide);
};
if (!this._univerSlide) {
diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.ts
index 32ae549b70..9d848242b3 100644
--- a/packages/core/src/services/command/command.service.ts
+++ b/packages/core/src/services/command/command.service.ts
@@ -88,6 +88,8 @@ export interface IMutationInfo<T extends object = object> {
export interface IExecutionOptions {
local?: boolean;
+
+ [key: PropertyKey]: string | number | boolean | undefined;
}
export type CommandListener = (commandInfo: Readonly<ICommandInfo>, options?: IExecutionOptions) => void;
diff --git a/packages/core/src/sheets/workbook.ts b/packages/core/src/sheets/workbook.ts
index 29e1ba6637..4ce5cf9724 100644
--- a/packages/core/src/sheets/workbook.ts
+++ b/packages/core/src/sheets/workbook.ts
@@ -86,6 +86,10 @@ export class Workbook extends Disposable {
return typeof range === 'string' || 'startRow' in range || 'row' in range;
}
+ getSnapshot(): IWorkbookConfig {
+ return this._snapshot;
+ }
+
getUnitId() {
return this._unitId;
}
diff --git a/packages/rpc/src/controllers/controller.ts b/packages/rpc/src/controllers/controller.ts
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts
new file mode 100644
index 0000000000..8b8d9bb788
--- /dev/null
+++ b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts
@@ -0,0 +1,62 @@
+import {
+ CommandType,
+ DocumentType,
+ ICommandService,
+ IMutationInfo,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ RxDisposable,
+} from '@univerjs/core';
+import { takeUntil } from 'rxjs/operators';
+
+import {
+ IRemoteInstanceService,
+ IRemoteSyncMutationOptions,
+} from '../../services/remote-instance/remote-instance.service';
+
+/**
+ * This controller is responsible for syncing data from the primary thread to
+ * the worker thread.
+ */
+@OnLifecycle(LifecycleStages.Starting, DataSyncPrimaryController)
+export class DataSyncPrimaryController extends RxDisposable {
+ constructor(
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IRemoteInstanceService private readonly _remoteInstanceService: IRemoteInstanceService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._univerInstanceService.sheetAdded$.pipe(takeUntil(this.dispose$)).subscribe((sheet) => {
+ // If a sheet is created, it should sync the data to the worker thread.
+ this._remoteInstanceService.createInstance({
+ unitID: sheet.getUnitId(),
+ type: DocumentType.SHEET,
+ snapshot: sheet.getSnapshot(),
+ });
+ });
+
+ this._univerInstanceService.sheetDisposed$.pipe(takeUntil(this.dispose$)).subscribe((workbook) => {
+ // If a sheet is disposed, it should sync the data to the worker thread.
+ this._remoteInstanceService.disposeInstance({
+ unitID: workbook.getUnitId(),
+ });
+ });
+
+ this.disposeWithMe(
+ // Mutations executed on the main thread should be synced to the worker thread.
+ this._commandService.onCommandExecuted((commandInfo, options) => {
+ if (commandInfo.type === CommandType.MUTATION && !(options as IRemoteSyncMutationOptions)?.fromSync) {
+ this._remoteInstanceService.syncMutation({
+ mutationInfo: commandInfo as IMutationInfo,
+ });
+ }
+ })
+ );
+ }
+}
diff --git a/packages/rpc/src/controllers/data-sync/data-sync-replica.controller.ts b/packages/rpc/src/controllers/data-sync/data-sync-replica.controller.ts
new file mode 100644
index 0000000000..99882c22f2
--- /dev/null
+++ b/packages/rpc/src/controllers/data-sync/data-sync-replica.controller.ts
@@ -0,0 +1,17 @@
+import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+
+import { IRemoteInstanceService } from '../../services/remote-instance/remote-instance.service';
+
+/**
+ * This controller is responsible for syncing data from the worker thread to
+ * the primary thread.
+ */
+@OnLifecycle(LifecycleStages.Starting, DataSyncReplicaController)
+export class DataSyncReplicaController extends Disposable {
+ constructor(
+ @IRemoteInstanceService private readonly: IRemoteInstanceService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+ }
+}
diff --git a/packages/rpc/src/plugin.ts b/packages/rpc/src/plugin.ts
index 0383bf4553..85c624ee17 100644
--- a/packages/rpc/src/plugin.ts
+++ b/packages/rpc/src/plugin.ts
@@ -1,10 +1,20 @@
import { Plugin, PluginType } from '@univerjs/core';
-import { createIdentifier, Inject, Injector } from '@wendellhu/redi';
+import { createIdentifier, Dependency, Inject, Injector } from '@wendellhu/redi';
+import { DataSyncPrimaryController } from './controllers/data-sync/data-sync-primary.controller';
+import { DataSyncReplicaController } from './controllers/data-sync/data-sync-replica.controller';
import {
createWebWorkerMessagePortOnMain,
createWebWorkerMessagePortOnWorker,
-} from './services/implementations/web-worker-message-port';
+} from './services/implementations/web-worker-rpc.service';
+import {
+ IRemoteInstanceService,
+ IRemoteSyncService,
+ RemoteInstanceReplicaService,
+ RemoteInstanceServiceName,
+ RemoteSyncPrimaryService,
+ RemoteSyncServiceName,
+} from './services/remote-instance/remote-instance.service';
import { ChannelClient, ChannelServer, fromModule, toModule } from './services/rpc/rpc.service';
export interface IUniverRPCMainThreadPluginConfig {
@@ -34,11 +44,19 @@ export class UniverRPCMainThreadPlugin extends Plugin {
const worker = new Worker(this._config.workerURL);
const messageProtocol = createWebWorkerMessagePortOnMain(worker);
const client = new ChannelClient(messageProtocol);
+ const server = new ChannelServer(messageProtocol);
+
+ const dependencies: Dependency[] = [
+ [DataSyncPrimaryController],
+ [
+ IRemoteInstanceService,
+ { useFactory: () => toModule<IRemoteInstanceService>(client.getChannel(RemoteInstanceServiceName)) },
+ ],
+ [IRemoteSyncService, { useClass: RemoteSyncPrimaryService }],
+ ];
+ dependencies.forEach((dependency) => injector.add(dependency));
- // Register services / controllers here over RPC.
- injector.add([ITestService, { useValue: toModule<ITestService>(client.getChannel('test')) }]);
- const name = await this._injector.get<ITestService>(ITestService).getName();
- console.log('debug', name);
+ server.registerChannel(RemoteSyncServiceName, fromModule(injector.get(IRemoteSyncService)));
}
}
@@ -57,17 +75,21 @@ export class UniverRPCWorkerThreadPlugin extends Plugin {
super('UNIVER_RPC_WORKER_THREAD_PLUGIN');
}
- override onStarting(): void {
+ override onStarting(injector: Injector): void {
const messageProtocol = createWebWorkerMessagePortOnWorker();
+ const client = new ChannelClient(messageProtocol);
const server = new ChannelServer(messageProtocol);
- server.registerChannel(
- 'test',
- fromModule({
- getName(): Promise<string> {
- return Promise.resolve('Univer');
- },
- })
- );
+ const dependencies: Dependency[] = [
+ [DataSyncReplicaController],
+ [
+ IRemoteSyncService,
+ { useFactory: () => toModule<IRemoteSyncService>(client.getChannel(RemoteSyncServiceName)) },
+ ],
+ [IRemoteInstanceService, { useClass: RemoteInstanceReplicaService }],
+ ];
+ dependencies.forEach((dependency) => injector.add(dependency));
+
+ server.registerChannel(RemoteInstanceServiceName, fromModule(injector.get(IRemoteInstanceService)));
}
}
diff --git a/packages/rpc/src/services/data-sync/data-sync-primary.service.ts b/packages/rpc/src/services/data-sync/data-sync-primary.service.ts
deleted file mode 100644
index 612fe24cae..0000000000
--- a/packages/rpc/src/services/data-sync/data-sync-primary.service.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { Disposable } from '@univerjs/core';
-
-/**
- * This service is responsible for syncing
- */
-export class DataSyncPrimaryService extends Disposable {}
diff --git a/packages/rpc/src/services/data-sync/data-sync-replica.service.ts b/packages/rpc/src/services/data-sync/data-sync-replica.service.ts
deleted file mode 100644
index e9221478f6..0000000000
--- a/packages/rpc/src/services/data-sync/data-sync-replica.service.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { Disposable } from '@univerjs/core';
-
-export class DataSyncReplicaService extends Disposable {}
diff --git a/packages/rpc/src/services/data-sync/data-sync.ts b/packages/rpc/src/services/data-sync/data-sync.ts
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/packages/rpc/src/services/implementations/web-worker-message-port.ts b/packages/rpc/src/services/implementations/web-worker-rpc.service.ts
similarity index 86%
rename from packages/rpc/src/services/implementations/web-worker-message-port.ts
rename to packages/rpc/src/services/implementations/web-worker-rpc.service.ts
index c6059f7d73..96922faeb1 100644
--- a/packages/rpc/src/services/implementations/web-worker-message-port.ts
+++ b/packages/rpc/src/services/implementations/web-worker-rpc.service.ts
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Observable, shareReplay } from 'rxjs';
-import { IMessageProtocol } from '../rpc/rpc.service';
+import { IMessageProtocol, IRPCService } from '../rpc/rpc.service';
/**
* Generate an `IMessageProtocol` on the web worker.
@@ -40,3 +40,7 @@ export function createWebWorkerMessagePortOnMain(worker: Worker): IMessageProtoc
}).pipe(shareReplay(1)),
};
}
+
+export class WebWorkerMainThreadRPCService implements IRPCService {}
+
+export class WebWorkerThreadRPCService implements IRPCService {}
diff --git a/packages/rpc/src/services/remote-instance/remote-instance.service.ts b/packages/rpc/src/services/remote-instance/remote-instance.service.ts
new file mode 100644
index 0000000000..7d07b9fda7
--- /dev/null
+++ b/packages/rpc/src/services/remote-instance/remote-instance.service.ts
@@ -0,0 +1,82 @@
+import {
+ DocumentType,
+ ICommandService,
+ IExecutionOptions,
+ IMutationInfo,
+ IUniverInstanceService,
+ IWorkbookConfig,
+} from '@univerjs/core';
+import { createIdentifier } from '@wendellhu/redi';
+import { type } from 'os';
+
+export interface IRemoteSyncMutationOptions extends IExecutionOptions {
+ /** If this mutation is executed after it was sent from the peer univer instance. */
+ fromSync?: boolean;
+}
+
+export const RemoteSyncServiceName = 'univer.remote-sync-service';
+/** This service is provided by the primary Univer.. */
+export const IRemoteSyncService = createIdentifier<IRemoteSyncService>(RemoteSyncServiceName);
+export interface IRemoteSyncService {
+ syncMutation(params: { mutationInfo: IMutationInfo }): Promise<boolean>;
+}
+
+export class RemoteSyncPrimaryService implements IRemoteSyncService {
+ constructor(@ICommandService private readonly _commandService: ICommandService) {}
+
+ async syncMutation(params: { mutationInfo: IMutationInfo }): Promise<boolean> {
+ return this._commandService.syncExecuteCommand(params.mutationInfo.id, params.mutationInfo.params, {
+ fromSync: true,
+ });
+ }
+}
+
+export const RemoteInstanceServiceName = 'univer.remote-instance-service';
+/** This service is provided by the replica Univer. */
+export const IRemoteInstanceService = createIdentifier<IRemoteInstanceService>(RemoteInstanceServiceName);
+export interface IRemoteInstanceService {
+ createInstance(params: { unitID: string; type: DocumentType; snapshot: IWorkbookConfig }): Promise<boolean>;
+ disposeInstance(params: { unitID: string }): Promise<boolean>;
+ syncMutation(params: { mutationInfo: IMutationInfo }): Promise<boolean>;
+}
+
+/**
+ * This service runs on replica Univer and is responsible for syncing data
+ * between the replica and the primary Univer.
+ */
+export class RemoteInstanceReplicaService implements IRemoteInstanceService {
+ constructor(
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {}
+
+ async syncMutation(params: { mutationInfo: IMutationInfo }): Promise<boolean> {
+ return this._commandService.syncExecuteCommand(params.mutationInfo.id, params.mutationInfo.params, {
+ fromSync: true,
+ });
+ }
+
+ async createInstance(params: { unitID: string; type: DocumentType; snapshot: IWorkbookConfig }): Promise<boolean> {
+ const { type, snapshot } = params;
+ try {
+ switch (type) {
+ case DocumentType.SHEET:
+ return !!this._univerInstanceService.createSheet(snapshot);
+ default:
+ throw new Error(
+ `[RemoteInstanceReplicaService]: cannot create replica for document type: ${type}.`
+ );
+ }
+ } catch (err: unknown) {
+ if (err instanceof Error) {
+ throw err;
+ } else {
+ throw new Error(`${err}`);
+ }
+ }
+ }
+
+ async disposeInstance(params: { unitID: string }): Promise<boolean> {
+ return this._univerInstanceService.disposeDocument(params.unitID);
+ }
+}
diff --git a/packages/rpc/src/services/rpc/rpc.service.ts b/packages/rpc/src/services/rpc/rpc.service.ts
index eb2e8fbe1b..f1667644da 100644
--- a/packages/rpc/src/services/rpc/rpc.service.ts
+++ b/packages/rpc/src/services/rpc/rpc.service.ts
@@ -2,8 +2,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { RxDisposable } from '@univerjs/core';
+import { createIdentifier } from '@wendellhu/redi';
import { BehaviorSubject, firstValueFrom, isObservable, Observable, of, Subscriber, Subscription } from 'rxjs';
-/* eslint-disable @typescript-eslint/no-explicit-any */
import { filter, take, takeUntil } from 'rxjs/operators';
/** This protocol is for transferring data from the two peer univer instance running in different locations. */
@@ -39,7 +39,7 @@ export function fromModule(module: unknown): IChannel {
call<T>(method: string, args?: any): Promise<T> {
const target = handler[method];
if (typeof target === 'function') {
- let res = target.apply(handler, args);
+ let res = target.apply(handler, [args]);
if (!(res instanceof Promise)) {
res = Promise.resolve(res);
}
@@ -401,3 +401,9 @@ export class ChannelServer extends RxDisposable implements IChannelServer {
this._protocol.send(response);
}
}
+
+/**
+ * This service is for other service to register channels to the RPC framework.
+ */
+export interface IRPCService {}
+export const IRPCService = createIdentifier<IRPCService>('IRPCService');