/** * Copyright 2023-present DreamNum Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { BaseDataModel, IDisposable, IMutation, IMutationInfo, Workbook } from '@univerjs/core'; import { CommandType, ICommandService, ILogService, Inject, Injector, IUniverInstanceService, RxDisposable, toDisposable, UniverInstanceType, } from '@univerjs/core'; import { takeUntil } from 'rxjs/operators'; import type { IRemoteSyncMutationOptions } from '../../services/remote-instance/remote-instance.service'; import type { ICreateInstanceParams } from '../../services/remote-instance/snapshot-chunk-coordinator'; import { IRemoteInstanceService, IRemoteSyncService, RemoteInstanceServiceName, RemoteSyncServiceName, } from '../../services/remote-instance/remote-instance.service'; import { SnapshotChunkSender } from '../../services/remote-instance/snapshot-chunk-coordinator'; import { IRPCChannelService } from '../../services/rpc/channel.service'; import { ChannelClientDisposedError, fromModule, toModule } from '../../services/rpc/rpc.service'; /** * This controller is responsible for syncing data from the primary thread to * the worker thread. * * Note that only spreadsheets will be synced to the remote calculation instance by default. */ export class DataSyncPrimaryController extends RxDisposable { private _remoteInstanceService!: IRemoteInstanceService; private _snapshotSender: SnapshotChunkSender | null = null; private readonly _syncingUnits = new Set(); private readonly _unitGenerations = new Map(); private _unitGenerationSeq = 0; private _isDisposed = false; private readonly _syncingMutations = new Set(); private readonly _nonSnapshotMutations = new Set(); private _syncMutationQueue: Promise = Promise.resolve(); private _remoteReady: Promise = Promise.resolve(true); constructor( @Inject(Injector) private readonly _injector: Injector, @ICommandService private readonly _commandService: ICommandService, @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService, @IRPCChannelService private readonly _rpcChannelService: IRPCChannelService, @IRemoteSyncService private readonly _remoteSyncService: IRemoteSyncService, @ILogService private readonly _logService: ILogService ) { super(); this._initRPCChannels(); this._snapshotSender = new SnapshotChunkSender(this._remoteInstanceService); this._init(); } override dispose(): void { this._isDisposed = true; this._snapshotSender?.dispose(); this._snapshotSender = null; this._syncingUnits.clear(); this._unitGenerations.clear(); super.dispose(); } registerSyncingMutations(mutation: IMutation): void { this._syncingMutations.add(mutation.id); } /** * Register a mutation that does not mutate source document snapshots (e.g. calculation * lifecycle signals) so it will not prematurely abort an in-flight chunked snapshot sync. */ registerNonSnapshotMutations(mutation: IMutation): void { this._nonSnapshotMutations.add(mutation.id); } /** * Only spreadsheets would be synced to the web worker in normal situations. If you would like to * sync other types of documents, you should manually call this method with that document's id. */ syncUnit(unitId: string): IDisposable { const alreadySyncing = this._syncingUnits.has(unitId); if (!alreadySyncing) { this._activateUnitSync(unitId); } const unit = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_SHEET) ?? this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE); if (!alreadySyncing && unit) { this._handleRemoteRequest(this._createRemoteInstance({ unitID: unit.getUnitId(), type: unit.type, snapshot: unit.getSnapshot(), }), 'create the remote unit'); } return toDisposable(() => { if (!alreadySyncing) { this._deactivateUnitSync(unitId); } if (!alreadySyncing && unit) { this._snapshotSender?.cancel(unit.getUnitId()); this._handleRemoteRequest(this._remoteInstanceService.disposeInstance({ unitID: unit.getUnitId(), }), 'dispose the remote unit'); } }); } /** Sync registered mutations for a unit without creating a replica unit. */ syncUnitMutations(unitId: string): IDisposable { const alreadySyncing = this._syncingUnits.has(unitId); if (!alreadySyncing) { this._activateUnitSync(unitId); } return toDisposable(() => { if (!alreadySyncing) { this._deactivateUnitSync(unitId); } }); } async syncMutation(commandInfo: IMutationInfo, options?: IRemoteSyncMutationOptions): Promise { const params = commandInfo.params as { unitId?: string; unitID?: string } | undefined; const unitId = params?.unitId || params?.unitID || undefined; const expectedGeneration = unitId ? this._unitGenerations.get(unitId) : undefined; const isStale = (): boolean => this._isDisposed || (expectedGeneration !== undefined && this._unitGenerations.get(unitId!) !== expectedGeneration); const sync = async (): Promise => { if (isStale()) { return false; } await this._remoteReady; if (isStale()) { return false; } if (this._snapshotSender) { const ready = await this._snapshotSender.waitForUnit(unitId); if (!ready || isStale()) { return false; } } return this._remoteInstanceService.syncMutation({ mutationInfo: commandInfo }, options); }; const result = this._syncMutationQueue.then(sync, sync); this._syncMutationQueue = result.catch(() => false); return result; } async waitForPendingMutations(): Promise { await this._syncMutationQueue.catch(() => false); } private _activateUnitSync(unitId: string): void { this._syncingUnits.add(unitId); this._unitGenerations.set(unitId, ++this._unitGenerationSeq); } private _deactivateUnitSync(unitId: string): void { this._syncingUnits.delete(unitId); this._unitGenerations.delete(unitId); } private _initRPCChannels(): void { // for the worker to call this._rpcChannelService.registerChannel(RemoteSyncServiceName, fromModule(this._remoteSyncService)); // to call the worker this._injector.add([ IRemoteInstanceService, // eslint-disable-next-line react/no-unnecessary-use-prefix { useFactory: () => toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)) }, ]); this._remoteInstanceService = this._injector.get(IRemoteInstanceService); this._remoteReady = this._remoteInstanceService.whenReady(); this._handleRemoteRequest(this._remoteReady, 'initialize the remote instance service'); } private _createRemoteInstance(params: ICreateInstanceParams): Promise { if (this._snapshotSender) { return this._snapshotSender.createInstance(params); } return this._remoteInstanceService.createInstance(params); } private _init(): void { this._univerInstanceService.getTypeOfUnitAdded$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((event) => { const { unit: sheet, options } = event; this._activateUnitSync(sheet.getUnitId()); const params: ICreateInstanceParams = { unitID: sheet.getUnitId(), type: UniverInstanceType.UNIVER_SHEET, snapshot: sheet.getSnapshot(), }; if (options?.makeCurrent === false) { params.makeCurrent = false; } // If a sheet is created, it should sync the data to the worker thread. this._handleRemoteRequest(this._createRemoteInstance(params), 'create the remote workbook'); }); this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => { this._deactivateUnitSync(workbook.getUnitId()); this._snapshotSender?.cancel(workbook.getUnitId()); // If a sheet is disposed, it should sync the data to the worker thread. this._handleRemoteRequest(this._remoteInstanceService.disposeInstance({ unitID: workbook.getUnitId(), }), 'dispose the remote workbook'); }); this._registerBeforeMutationGuard(); // Mutations executed on the main thread should be synced to the worker thread. this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => { const { type, params, id } = commandInfo; const unitId = (params as { unitId: string })?.unitId || ''; if (type === CommandType.MUTATION && // only sync mutations to the worker thread (!unitId || this._syncingUnits.has(unitId)) && // do not sync mutations from the web worker back to the web worker !(options as IRemoteSyncMutationOptions)?.fromSync && // do not sync mutations those are not meant to be synced this._syncingMutations.has(id)) { this._handleRemoteRequest( this.syncMutation(commandInfo as IMutationInfo, options), `sync mutation ${id}` ); } })); } private _registerBeforeMutationGuard(): void { if (typeof this._commandService.beforeCommandExecuted !== 'function') { return; } this.disposeWithMe(this._commandService.beforeCommandExecuted((commandInfo, options) => { if (!this._snapshotSender?.hasPendingSessions()) { return; } if ( commandInfo.type === CommandType.MUTATION && !(options as IRemoteSyncMutationOptions)?.fromSync && !this._nonSnapshotMutations.has(commandInfo.id) ) { const params = commandInfo.params as { unitId?: string; unitID?: string } | undefined; this._snapshotSender.beforeMutation(params?.unitId ?? params?.unitID); } })); } private _handleRemoteRequest(request: Promise, operation: string): void { request.catch((error: unknown) => { if (error instanceof ChannelClientDisposedError) { return; } this._logService.error(`[DataSyncPrimaryController]: Failed to ${operation}.`, error); }); } }