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.

fix(formula): sync other formulas before calculation (#7511)

Univerb29eb1170f7c
diff --git a/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts
index ff5ff9b6c7..397ecf8ad6 100644
--- a/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts
+++ b/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts
@@ -35,7 +35,7 @@ import { FormulaController } from '../formula.controller';
type FormulaDataSyncController = Pick<
DataSyncPrimaryController,
- 'registerSyncingMutations' | 'syncUnitMutations'
+ 'registerSyncingMutations' | 'syncUnitMutations' | 'waitForPendingMutations'
>;
function createController(dataSyncPrimaryController?: FormulaDataSyncController): {
@@ -79,6 +79,7 @@ describe('FormulaController', () => {
const dataSyncPrimaryController = {
registerSyncingMutations: vi.fn<DataSyncPrimaryController['registerSyncingMutations']>(),
syncUnitMutations: vi.fn<DataSyncPrimaryController['syncUnitMutations']>(() => toDisposable(dispose)),
+ waitForPendingMutations: vi.fn<DataSyncPrimaryController['waitForPendingMutations']>(() => Promise.resolve()),
};
const { controller, registerOtherFormulaService } = createController(dataSyncPrimaryController);
diff --git a/packages/engine-formula/src/controllers/formula.controller.ts b/packages/engine-formula/src/controllers/formula.controller.ts
index 5e7a369a5e..888f37913c 100644
--- a/packages/engine-formula/src/controllers/formula.controller.ts
+++ b/packages/engine-formula/src/controllers/formula.controller.ts
@@ -53,7 +53,7 @@ import { RegisterOtherFormulaService } from '../services/register-other-formula.
type FormulaDataSyncController = Pick<
DataSyncPrimaryController,
- 'registerSyncingMutations' | 'syncUnitMutations'
+ 'registerSyncingMutations' | 'syncUnitMutations' | 'waitForPendingMutations'
>;
export class FormulaController extends Disposable {
@@ -83,13 +83,12 @@ export class FormulaController extends Disposable {
return;
}
- this.disposeWithMe(this._registerOtherFormulaService.formulaChangeWithRange$.subscribe(({ unitId }) => {
- if (this._syncedOtherFormulaUnits.has(unitId)) {
- return;
+ this.disposeWithMe(this._registerOtherFormulaService.setMutationSyncHandler((unitId) => {
+ if (!this._syncedOtherFormulaUnits.has(unitId)) {
+ this._syncedOtherFormulaUnits.add(unitId);
+ this.disposeWithMe(dataSyncPrimaryController.syncUnitMutations(unitId));
}
-
- this._syncedOtherFormulaUnits.add(unitId);
- this.disposeWithMe(dataSyncPrimaryController.syncUnitMutations(unitId));
+ return () => dataSyncPrimaryController.waitForPendingMutations();
}));
}
diff --git a/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts
index aabc95a725..560e01ce29 100644
--- a/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts
@@ -25,7 +25,7 @@ import {
LifecycleService,
LifecycleStages,
} from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { OtherFormulaMarkDirty } from '../../commands/mutations/formula.mutation';
import { SetFormulaCalculationResultMutation } from '../../commands/mutations/set-formula-calculation.mutation';
import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../../commands/mutations/set-other-formula.mutation';
@@ -35,7 +35,7 @@ import { OtherFormulaBizType, RegisterOtherFormulaService } from '../register-ot
type FormulaResultMatrix = Record<number, Record<number, Array<{ v?: unknown }>>>;
-function createService(registerCommands = true): {
+function createService(registerCommands = true, remoteSync?: () => Promise<void>): {
service: RegisterOtherFormulaService;
commandService: ICommandService;
activeDirtyManagerService: IActiveDirtyManagerService;
@@ -50,6 +50,7 @@ function createService(registerCommands = true): {
injector.add([RegisterOtherFormulaService]);
const commandService = injector.get(ICommandService);
const service = injector.get(RegisterOtherFormulaService);
+ if (remoteSync) service.setMutationSyncHandler(() => remoteSync);
if (registerCommands) {
commandService.registerCommand(SetOtherFormulaMutation);
commandService.registerCommand(RemoveOtherFormulaMutation);
@@ -91,6 +92,25 @@ describe('RegisterOtherFormulaService', () => {
expect(executedIds).toEqual([SetOtherFormulaMutation.id, OtherFormulaMarkDirty.id]);
});
+ it('marks a formula dirty only after its Worker definition is synchronized', async () => {
+ let releaseSync!: () => void;
+ const remoteSync = vi.fn<() => Promise<void>>(() => new Promise<void>((resolve) => {
+ releaseSync = resolve;
+ }));
+ const { service, commandService } = createService(true, remoteSync);
+ const executedIds: string[] = [];
+ commandService.onCommandExecuted((command) => executedIds.push(command.id));
+
+ service.registerFormulaWithRange('doc-1', 'body-1', '=1');
+ await flushCommandChain();
+ expect(executedIds).toEqual([SetOtherFormulaMutation.id]);
+ expect(remoteSync).toHaveBeenCalledOnce();
+
+ releaseSync();
+ await flushCommandChain();
+ expect(executedIds).toEqual([SetOtherFormulaMutation.id, OtherFormulaMarkDirty.id]);
+ });
+
it('should register every formula once without a second lifecycle gate', async () => {
const { service, commandService } = createService();
const executedIds: string[] = [];
diff --git a/packages/engine-formula/src/services/register-other-formula.service.ts b/packages/engine-formula/src/services/register-other-formula.service.ts
index d05f054ec1..7faf6bee08 100644
--- a/packages/engine-formula/src/services/register-other-formula.service.ts
+++ b/packages/engine-formula/src/services/register-other-formula.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IRange, Nullable } from '@univerjs/core';
+import type { IDisposable, IRange, Nullable } from '@univerjs/core';
import type { IOtherFormulaMarkDirtyParams } from '../commands/mutations/formula.mutation';
import type { ISetFormulaCalculationResultMutation } from '../commands/mutations/set-formula-calculation.mutation';
import type {
@@ -30,6 +30,7 @@ import {
LifecycleService,
LifecycleStages,
ObjectMatrix,
+ toDisposable,
} from '@univerjs/core';
import { Subject } from 'rxjs';
import { OtherFormulaMarkDirty } from '../commands/mutations/formula.mutation';
@@ -51,6 +52,8 @@ export enum OtherFormulaBizType {
export class RegisterOtherFormulaService extends Disposable {
private _formulaCacheMap: Map<string, Map<string, Map<string, IOtherFormulaResult>>> = new Map();
+ private _mutationSyncHandler?: (unitId: string) => () => Promise<void>;
+
private _formulaChangeWithRange$ = new Subject<{ unitId: string; subUnitId: string; formulaText: string; formulaId: string; ranges: IRange[] }>();
public formulaChangeWithRange$ = this._formulaChangeWithRange$.asObservable();
@@ -133,12 +136,12 @@ export class RegisterOtherFormulaService extends Disposable {
},
},
};
+ const waitForMutationSync = this._mutationSyncHandler?.(unitId);
- this._commandService.executeCommand(SetOtherFormulaMutation.id, params, { onlyLocal: true }).then(() => {
- if (this._disposed) {
- return;
- }
-
+ this._commandService.executeCommand(SetOtherFormulaMutation.id, params, { onlyLocal: true }).then(async () => {
+ if (this._disposed) return;
+ await waitForMutationSync?.();
+ if (this._disposed) return;
this._commandService.executeCommand(
OtherFormulaMarkDirty.id,
{ [unitId]: { [subUnitId]: { [formulaId]: true } } },
@@ -164,6 +167,13 @@ export class RegisterOtherFormulaService extends Disposable {
}));
}
+ setMutationSyncHandler(handler: (unitId: string) => () => Promise<void>): IDisposable {
+ this._mutationSyncHandler = handler;
+ return toDisposable(() => {
+ if (this._mutationSyncHandler === handler) this._mutationSyncHandler = undefined;
+ });
+ }
+
private _initFormulaCalculationResultChange() {
// Gets the result of the formula calculation and caches it
this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {
@@ -259,6 +269,7 @@ export class RegisterOtherFormulaService extends Disposable {
subUnitId,
formulaIdList,
};
+ this._mutationSyncHandler?.(unitId);
this._commandService.executeCommand(RemoveOtherFormulaMutation.id, params, { onlyLocal: true });
const cacheMap = this._ensureCacheMap(unitId, subUnitId);
formulaIdList.forEach((id) => cacheMap.delete(id));
diff --git a/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts b/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts
index 93dc0cbb05..89e2c095f6 100644
--- a/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts
+++ b/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts
@@ -59,6 +59,7 @@ describe('data-sync controllers', () => {
createInstance: vi.fn(async () => true),
disposeInstance: vi.fn(async () => true),
syncMutation: vi.fn(async () => true),
+ whenReady: vi.fn(async () => true as const),
};
const remoteChannel = buildRemoteChannel(remoteInstanceImpl);
@@ -219,6 +220,7 @@ describe('data-sync controllers', () => {
createInstance: vi.fn(async () => true),
disposeInstance: vi.fn(async () => true),
syncMutation: vi.fn(() => new Promise<boolean>((resolve) => resolvers.push(resolve))),
+ whenReady: vi.fn(async () => true as const),
};
const remoteChannel = buildRemoteChannel(remoteInstanceImpl);
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
index c73aa2838f..bd6335a060 100644
--- a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts
+++ b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts
@@ -51,6 +51,8 @@ export class DataSyncPrimaryController extends RxDisposable {
private _syncMutationQueue: Promise<unknown> = Promise.resolve();
+ private _remoteReady: Promise<true> = Promise.resolve(true);
+
constructor(
@Inject(Injector) private readonly _injector: Injector,
@ICommandService private readonly _commandService: ICommandService,
@@ -108,6 +110,19 @@ export class DataSyncPrimaryController extends RxDisposable {
});
}
+ async syncMutation(commandInfo: IMutationInfo, options?: IRemoteSyncMutationOptions): Promise<boolean> {
+ const sync = () => this._remoteReady.then(() =>
+ this._remoteInstanceService.syncMutation({ mutationInfo: commandInfo }, options)
+ );
+ const result = this._syncMutationQueue.then(sync, sync);
+ this._syncMutationQueue = result.catch(() => false);
+ return result;
+ }
+
+ async waitForPendingMutations(): Promise<void> {
+ await this._syncMutationQueue.catch(() => false);
+ }
+
private _initRPCChannels(): void {
// for the worker to call
this._rpcChannelService.registerChannel(RemoteSyncServiceName, fromModule(this._remoteSyncService));
@@ -119,6 +134,7 @@ export class DataSyncPrimaryController extends RxDisposable {
{ useFactory: () => toModule<IRemoteInstanceService>(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)) },
]);
this._remoteInstanceService = this._injector.get(IRemoteInstanceService);
+ this._remoteReady = this._remoteInstanceService.whenReady();
}
private _init(): void {
@@ -154,8 +170,7 @@ export class DataSyncPrimaryController extends RxDisposable {
!(options as IRemoteSyncMutationOptions)?.fromSync &&
// do not sync mutations those are not meant to be synced
this._syncingMutations.has(id)) {
- const sync = () => this._remoteInstanceService.syncMutation({ mutationInfo: commandInfo as IMutationInfo }, options);
- this._syncMutationQueue = this._syncMutationQueue.then(sync, sync).catch(() => false);
+ void this.syncMutation(commandInfo as IMutationInfo, options);
}
}));
}
diff --git a/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts b/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts
index 41dfdf6e5a..3f2085cce0 100644
--- a/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts
+++ b/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { ICommandService, ILogService, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { ICommandService, ILogService, Injector, IUniverInstanceService, LifecycleService, LifecycleStages, UniverInstanceType } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { IRemoteInstanceService, IRemoteSyncService, RemoteSyncPrimaryService, WebWorkerRemoteInstanceService } from '../remote-instance.service';
@@ -83,10 +83,17 @@ describe('remote-instance.service', () => {
injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
injector.add([ICommandService, { useClass: TestCommandService as never }]);
injector.add([ILogService, { useClass: TestLogService as never }]);
+ injector.add([LifecycleService]);
injector.add([IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }]);
const service = injector.get(IRemoteInstanceService);
- await expect(service.whenReady()).resolves.toBe(true);
+ const ready = service.whenReady();
+ let readyResolved = false;
+ ready.then(() => readyResolved = true);
+ await Promise.resolve();
+ expect(readyResolved).toBe(false);
+ injector.get(LifecycleService).stage = LifecycleStages.Ready;
+ await expect(ready).resolves.toBe(true);
await expect(service.syncMutation(
{
diff --git a/packages/rpc/src/services/remote-instance/remote-instance.service.ts b/packages/rpc/src/services/remote-instance/remote-instance.service.ts
index fdc50039c0..a6c7200f44 100644
--- a/packages/rpc/src/services/remote-instance/remote-instance.service.ts
+++ b/packages/rpc/src/services/remote-instance/remote-instance.service.ts
@@ -15,7 +15,7 @@
*/
import type { IBaseSnapshot, IExecutionOptions, IMutationInfo, IWorkbookData } from '@univerjs/core';
-import { createIdentifier, ICommandService, ILogService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { createIdentifier, ICommandService, ILogService, Inject, IUniverInstanceService, LifecycleService, LifecycleStages, UniverInstanceType } from '@univerjs/core';
export interface IRemoteSyncMutationOptions extends IExecutionOptions {
/** If this mutation is executed after it was sent from the peer univer instance (e.g. in a web worker). */
@@ -69,13 +69,15 @@ export class WebWorkerRemoteInstanceService implements IRemoteInstanceService {
constructor(
@IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService,
@ICommandService protected readonly _commandService: ICommandService,
- @ILogService protected readonly _logService: ILogService
+ @ILogService protected readonly _logService: ILogService,
+ @Inject(LifecycleService) protected readonly _lifecycleService: LifecycleService
) {
// empty
}
whenReady(): Promise<true> {
- return Promise.resolve(true);
+ if (this._lifecycleService.stage >= LifecycleStages.Ready) return Promise.resolve(true);
+ return this._lifecycleService.onStage(LifecycleStages.Ready).then(() => true);
}
async syncMutation(params: { mutationInfo: IMutationInfo }, options?: IExecutionOptions): Promise<boolean> {