Skip to content

Commit

Permalink
Use better locking mechanism
Browse files Browse the repository at this point in the history
  • Loading branch information
msujew committed Dec 8, 2023
1 parent 461afba commit 1ed4c2a
Showing 1 changed file with 16 additions and 23 deletions.
39 changes: 16 additions & 23 deletions packages/langium/src/workspace/workspace-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,34 +93,27 @@ export class DefaultWorkspaceLock implements WorkspaceLock {
}
}

private performOperation(entries: LockEntry[]): void {
private async performOperation(entries: LockEntry[]): Promise<void> {
if (!this.done) {
throw new Error('Mutex is not ready to accept new operation');
}
this.done = false;
let completed = 0;
const goToNext = () => {
completed += 1;
// If all specified actions have been completed, we can perform the next operation
if (completed === entries.length) {
this.done = true;
this.performNextOperation();
await Promise.all(entries.map(async ({ action, deferred, cancellationToken }) => {
try {
// Move the execution of the action to the next event loop tick via `Promise.resolve()`
const result = await Promise.resolve().then(() => action(cancellationToken));
deferred.resolve(result);
} catch (err) {
if (isOperationCancelled(err)) {
// If the operation was cancelled, we don't want to reject the promise
deferred.resolve(undefined);
} else {
deferred.reject(err);
}
}
};
for (const entry of entries) {
const { action, deferred, cancellationToken } = entry;
Promise.resolve()
.then(() => action(cancellationToken))
.then(result => deferred.resolve(result))
.catch(err => {
if (isOperationCancelled(err)) {
// If the operation was cancelled, we don't want to reject the promise
deferred.resolve(undefined);
} else {
deferred.reject(err);
}
}).finally(() => goToNext());
}
}));
this.done = true;
this.performNextOperation();
}

cancelWrite(): void {
Expand Down

0 comments on commit 1ed4c2a

Please sign in to comment.