diff --git a/zeppelin-common/src/main/java/org/apache/zeppelin/common/Message.java b/zeppelin-common/src/main/java/org/apache/zeppelin/common/Message.java index b7d1ff1d4ab..de2e37d8b77 100644 --- a/zeppelin-common/src/main/java/org/apache/zeppelin/common/Message.java +++ b/zeppelin-common/src/main/java/org/apache/zeppelin/common/Message.java @@ -196,6 +196,7 @@ public enum OP { INTERPRETER_INSTALL_RESULT, // [s-c] Status of an interpreter installation COLLABORATIVE_MODE_STATUS, // [s-c] collaborative mode status PATCH_PARAGRAPH, // [c-s][s-c] patch editor text + GET_PARAGRAPH, // [c-s] resend a single paragraph after a failed patch NOTE_RUNNING_STATUS, // [s-c] sequential run status will be change NOTICE, // [s-c] Notice ASSISTANT_SEND_MESSAGE, // [c-s] send a message to the notebook assistant diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java b/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java index 7b509e8bda2..e87634b35f8 100644 --- a/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java +++ b/zeppelin-server/src/main/java/org/apache/zeppelin/service/NotebookService.java @@ -786,6 +786,23 @@ public void updateParagraph(String noteId, Map config, ServiceContext context, ServiceCallback callback) throws IOException { + updateParagraph(noteId, paragraphId, title, text, params, config, null, context, callback); + } + + /** + * @param baseChecksum checksum of the text the client believed the server held, or null to skip + * the check. When it does not match, the client text is stale or diverged, + * so it is not stored and the server copy is sent back instead. + */ + public void updateParagraph(String noteId, + String paragraphId, + String title, + String text, + Map params, + Map config, + Integer baseChecksum, + ServiceContext context, + ServiceCallback callback) throws IOException { if (!checkPermission(noteId, Permission.WRITER, Message.OP.COMMIT_PARAGRAPH, context, callback)) { return; @@ -802,6 +819,15 @@ public void updateParagraph(String noteId, callback.onFailure(new ParagraphNotFoundException(paragraphId), context); return null; } + // The client edits the paragraph GET_NOTE handed it, which in personalized mode is the + // user's copy, so that is the text its checksum describes and the one to send back. + Paragraph edited = note.isPersonalizedMode() + ? p.getUserParagraph(context.getAutheInfo().getUser()) : p; + if (baseChecksum != null && baseChecksum != checksum(edited.getText())) { + LOGGER.info("Rejecting stale commit of paragraph {} in note {}", paragraphId, noteId); + callback.onSuccess(edited, context); + return null; + } // In personalized mode only the note owner may update the master paragraph, so that // new users inherit the owner's changes while a non-owner's changes stay in their copy. if (!note.isPersonalizedMode() @@ -1507,6 +1533,40 @@ public void patchParagraph(final String noteId, final String paragraphId, String } } + /** + * Resend a single paragraph to a client whose patched text diverged, so that the note as a + * whole does not have to be reloaded. + */ + public void getParagraph(String noteId, String paragraphId, ServiceContext context, + ServiceCallback callback) throws IOException { + if (!checkPermission(noteId, Permission.READER, Message.OP.GET_PARAGRAPH, context, callback)) { + return; + } + notebook.processNote(noteId, + note -> { + if (note == null) { + callback.onFailure(new NoteNotFoundException(noteId), context); + return null; + } + Paragraph p = note.getParagraph(paragraphId); + if (p == null) { + callback.onFailure(new ParagraphNotFoundException(paragraphId), context); + return null; + } + // Answer with the copy the client is editing, matching what GET_NOTE handed it. + callback.onSuccess(note.isPersonalizedMode() + ? p.getUserParagraph(context.getAutheInfo().getUser()) : p, context); + return null; + }); + } + + /** + * Same algorithm as {@link String#hashCode()} so that the client can compute it identically. + */ + static int checksum(String text) { + return text == null ? "".hashCode() : text.hashCode(); + } + enum Permission { READER, diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java b/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java index d9d4e77d8e2..8327ac7e86f 100644 --- a/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java +++ b/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java @@ -609,6 +609,9 @@ public void onMessage(NotebookSocket conn, String msg) { case ASSISTANT_SEND_MESSAGE: sendAssistantMessage(conn, context, receivedMessage); break; + case GET_PARAGRAPH: + getParagraph(conn, context, receivedMessage); + break; default: break; } @@ -1236,8 +1239,11 @@ private void updateParagraph(NotebookSocket conn, ServiceContext context, Messag String text = (String) fromMessage.get("paragraph"); Map params = (Map) fromMessage.get("params"); Map config = (Map) fromMessage.get("config"); + Integer baseChecksum = fromMessage.get("baseChecksum") == null + ? null : ((Number) fromMessage.get("baseChecksum")).intValue(); - getNotebookService().updateParagraph(noteId, paragraphId, title, text, params, config, context, + getNotebookService().updateParagraph(noteId, paragraphId, title, text, params, config, + baseChecksum, context, new WebSocketServiceCallback(conn) { @Override public void onSuccess(Paragraph p, ServiceContext context) throws IOException { @@ -1275,6 +1281,10 @@ private void patchParagraph(NotebookSocket conn, if (patchText == null) { return; } + // checksums of the sender's text before and after the patch, so receivers can tell whether + // their own patchApply produced the same text. Absent for clients that do not send them. + Object baseChecksum = fromMessage.get("baseChecksum"); + Object afterChecksum = fromMessage.get("afterChecksum"); getNotebookService().patchParagraph(noteId, paragraphId, patchText, context, new WebSocketServiceCallback(conn) { @@ -1283,7 +1293,10 @@ public void onSuccess(String result, ServiceContext context) throws IOException super.onSuccess(result, context); Message message = new Message(OP.PATCH_PARAGRAPH) .put("patch", result) - .put("paragraphId", paragraphId); + .put("paragraphId", paragraphId) + .put("noteId", noteId2) + .put("baseChecksum", baseChecksum) + .put("afterChecksum", afterChecksum); connectionManager.broadcastExcept(noteId2, message, conn); } }); @@ -1317,6 +1330,33 @@ private void sendAssistantMessage( ); } + private void getParagraph(NotebookSocket conn, + ServiceContext context, + Message fromMessage) throws IOException { + String paragraphId = fromMessage.getType("id", LOGGER); + if (paragraphId == null) { + return; + } + String noteId = connectionManager.getAssociatedNoteId(conn); + if (noteId == null) { + noteId = fromMessage.getType("noteId", LOGGER); + if (noteId == null) { + return; + } + } + + getNotebookService().getParagraph(noteId, paragraphId, context, + new WebSocketServiceCallback(conn) { + @Override + public void onSuccess(Paragraph p, ServiceContext context) throws IOException { + super.onSuccess(p, context); + conn.send(serializeMessage(new Message(OP.PARAGRAPH) + .withMsgId(fromMessage.msgId) + .put("paragraph", p))); + } + }); + } + private void cloneNote(NotebookSocket conn, ServiceContext context, Message fromMessage) throws IOException { diff --git a/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java b/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java index d9c23718e9e..09ea2ee079b 100644 --- a/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java +++ b/zeppelin-server/src/test/java/org/apache/zeppelin/service/NotebookServiceTest.java @@ -875,4 +875,104 @@ void testNormalizeFolderPath() throws IOException { assertThrows(IOException.class, () -> notebookService.normalizeFolderPath(null)); } + + @Test + void testUpdateParagraphChecksumUsesTheUserCopyInPersonalizedMode() throws IOException { + String noteId = notebookService.createNote("/note_personalized_checksum", "test", true, + context, callback); + // make "admin" the owner so that "user1" below edits only its own copy + authorizationService.setOwners(noteId, Collections.singleton("admin")); + ServiceContext user1Context = new ServiceContext(new AuthenticationInfo("user1"), + new HashSet<>(Collections.singleton("user1"))); + + String paragraphId = notebook.processNote(noteId, + note -> { + note.setPersonalizedMode(true); + Paragraph p = note.getParagraph(0); + p.setText("master text"); + // user1 has already diverged from the master copy, which is what GET_NOTE handed it + p.getUserParagraph("user1").setText("user1 text"); + return p.getId(); + }); + + // a commit based on the user's own text is stored, even though the master text differs + notebookService.updateParagraph(noteId, paragraphId, "user1 title", "user1 edit", + new HashMap<>(), new HashMap<>(), "user1 text".hashCode(), user1Context, callback); + notebook.processNote(noteId, + note -> { + Paragraph p = note.getParagraph(paragraphId); + assertEquals("user1 edit", p.getUserParagraph("user1").getText()); + assertEquals("master text", p.getText()); + return null; + }); + + // the master text is not a valid base for a non-owner, so a commit using it is rejected + notebookService.updateParagraph(noteId, paragraphId, "stale title", "stale edit", + new HashMap<>(), new HashMap<>(), "master text".hashCode(), user1Context, callback); + notebook.processNote(noteId, + note -> { + assertEquals("user1 edit", + note.getParagraph(paragraphId).getUserParagraph("user1").getText()); + return null; + }); + } + + @Test + void testGetParagraphReturnsTheUserCopyInPersonalizedMode() throws IOException { + String noteId = notebookService.createNote("/note_personalized_get", "test", true, + context, callback); + authorizationService.setOwners(noteId, Collections.singleton("admin")); + ServiceContext user1Context = new ServiceContext(new AuthenticationInfo("user1"), + new HashSet<>(Collections.singleton("user1"))); + + String paragraphId = notebook.processNote(noteId, + note -> { + note.setPersonalizedMode(true); + Paragraph p = note.getParagraph(0); + p.setText("master text"); + p.getUserParagraph("user1").setText("user1 text"); + return p.getId(); + }); + + reset(callback); + notebookService.getParagraph(noteId, paragraphId, user1Context, callback); + ArgumentCaptor captor = ArgumentCaptor.forClass(Paragraph.class); + verify(callback).onSuccess(captor.capture(), any(ServiceContext.class)); + assertEquals("user1 text", captor.getValue().getText()); + } + + @Test + void testUpdateParagraphChecksIsBasedOnCurrentServerText() throws IOException { + String noteId = notebookService.createNote("/note_checksum", "test", true, context, callback); + String paragraphId = notebook.processNote(noteId, note -> { + Paragraph p = note.getParagraph(0); + p.setText("server text"); + return p.getId(); + }); + + // a commit based on the text the server holds is stored + notebookService.updateParagraph(noteId, paragraphId, "title", "agreed text", + new HashMap<>(), new HashMap<>(), "server text".hashCode(), context, callback); + notebook.processNote(noteId, note -> { + assertEquals("agreed text", note.getParagraph(paragraphId).getText()); + return null; + }); + + // a commit based on text the server no longer holds is rejected, keeping the server copy + notebookService.updateParagraph(noteId, paragraphId, "stale title", "diverged text", + new HashMap<>(), new HashMap<>(), "text nobody has".hashCode(), context, callback); + notebook.processNote(noteId, note -> { + assertEquals("agreed text", note.getParagraph(paragraphId).getText()); + assertEquals("title", note.getParagraph(paragraphId).getTitle()); + return null; + }); + + // clients that send no checksum keep the previous behaviour + notebookService.updateParagraph(noteId, paragraphId, "no checksum", "text without checksum", + new HashMap<>(), new HashMap<>(), context, callback); + notebook.processNote(noteId, note -> { + assertEquals("text without checksum", note.getParagraph(paragraphId).getText()); + return null; + }); + } } diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/checksum.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/checksum.ts new file mode 100644 index 00000000000..fa28394647c --- /dev/null +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/checksum.ts @@ -0,0 +1,23 @@ +/* + * 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. + */ + +/** + * Same algorithm as java.lang.String#hashCode(), so a checksum computed here matches the one + * NotebookService computes for the same text. + */ +export function textChecksum(text: string): number { + let hash = 0; + for (let i = 0; i < text.length; i++) { + hash = (Math.imul(31, hash) + text.charCodeAt(i)) | 0; + } + return hash; +} diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-data-type-map.interface.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-data-type-map.interface.ts index 1e94acdb846..2d2a3b1bbd0 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-data-type-map.interface.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-data-type-map.interface.ts @@ -77,6 +77,7 @@ import { ParagraphRemoved, ParagraphStatus, ParagraphUpdateOutput, + GetParagraph, ParasInfo, PatchParagraphReceived, PatchParagraphSend, @@ -116,7 +117,7 @@ export interface MessageReceiveDataTypeMap { [OP.PARAGRAPH]: UpdateParagraph; [OP.PARAGRAPH_APPEND_OUTPUT]: ParagraphAppendOutput; [OP.PARAGRAPH_UPDATE_OUTPUT]: ParagraphUpdateOutput; - [OP.PATCH_PARAGRAPH]: PatchParagraphSend; + [OP.PATCH_PARAGRAPH]: PatchParagraphReceived; [OP.PARAGRAPH_REMOVED]: ParagraphRemoved; [OP.EDITOR_SETTING]: EditorSettingReceived; [OP.PROGRESS]: Progress; @@ -168,7 +169,8 @@ export interface MessageSendDataTypeMap { [OP.PARAGRAPH_CLEAR_ALL_OUTPUT]: ParagraphClearAllOutput; [OP.COMPLETION]: Completion; [OP.COMMIT_PARAGRAPH]: CommitParagraph; - [OP.PATCH_PARAGRAPH]: PatchParagraphReceived; + [OP.PATCH_PARAGRAPH]: PatchParagraphSend; + [OP.GET_PARAGRAPH]: GetParagraph; [OP.IMPORT_NOTE]: ImportNote; [OP.CHECKPOINT_NOTE]: CheckpointNote; [OP.SET_NOTE_REVISION]: SetNoteRevision; diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts index a72942b1b97..63b7336f6ce 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-operator.interface.ts @@ -469,6 +469,14 @@ export enum OP { */ PATCH_PARAGRAPH = 'PATCH_PARAGRAPH', + /** + * [c-s] + * resend a single paragraph after a failed patch + * @param id paragraph id + * @param noteId note id + */ + GET_PARAGRAPH = 'GET_PARAGRAPH', + /** * [s-c] * sequential run status will be change diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-paragraph.interface.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-paragraph.interface.ts index 2b98bfc6910..d51a1ec1085 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-paragraph.interface.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/interfaces/message-paragraph.interface.ts @@ -212,6 +212,8 @@ export interface RunParagraph extends SendParagraph { export interface CommitParagraph extends SendParagraph { noteId: string; + // checksum of the text this client believed the server held; absent for older clients + baseChecksum?: number; } export interface RunAllParagraphs { @@ -315,14 +317,26 @@ export interface CompletionReceived { } export interface PatchParagraphReceived { - id: string; + paragraphId: string; noteId: string; patch: string; + // checksums of the sender's text before and after the patch; absent for older clients + baseChecksum?: number; + afterChecksum?: number; +} + +export interface GetParagraph { + id: string; + noteId: string; } export interface PatchParagraphSend { - paragraphId: string; + id: string; + noteId: string; patch: string; + // checksums of this client's text before and after the patch; let receivers verify the result + baseChecksum?: number; + afterChecksum?: number; } export interface ParagraphRemoved { diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts index 2f1ec939fa5..fa0756d5c3c 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/message.ts @@ -419,7 +419,8 @@ export class Message { paragraphData: string, paragraphConfig: ParagraphConfig, paragraphParams: ParagraphConfig, - noteId: string + noteId: string, + baseChecksum?: number ): string { return this.send(OP.COMMIT_PARAGRAPH, { id: paragraphId, @@ -427,18 +428,34 @@ export class Message { title: paragraphTitle, paragraph: paragraphData, config: paragraphConfig, - params: paragraphParams + params: paragraphParams, + baseChecksum }); } - patchParagraph(paragraphId: string, noteId: string, patch: string): void { + patchParagraph( + paragraphId: string, + noteId: string, + patch: string, + baseChecksum?: number, + afterChecksum?: number + ): void { // javascript add "," if change contains several patches // but java library requires patch list without "," const normalPatch = patch.replace(/,@@/g, '@@'); this.send(OP.PATCH_PARAGRAPH, { id: paragraphId, noteId, - patch: normalPatch + patch: normalPatch, + baseChecksum, + afterChecksum + }); + } + + getParagraph(paragraphId: string, noteId: string): string { + return this.send(OP.GET_PARAGRAPH, { + id: paragraphId, + noteId }); } diff --git a/zeppelin-web-angular/projects/zeppelin-sdk/src/public-api.ts b/zeppelin-web-angular/projects/zeppelin-sdk/src/public-api.ts index 7ae587d3811..d24c2a90806 100644 --- a/zeppelin-web-angular/projects/zeppelin-sdk/src/public-api.ts +++ b/zeppelin-web-angular/projects/zeppelin-sdk/src/public-api.ts @@ -13,6 +13,7 @@ export * from './angular-object'; export * from './assistant'; export * from './assistant-ui'; +export * from './checksum'; export * from './interfaces/public-api'; export * from './message'; export * from './paragraph-state'; diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts index 9f0c179f196..dd5f462ba39 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.spec.ts @@ -11,7 +11,7 @@ */ import { ChangeDetectorRef } from '@angular/core'; -import { DatasetType, Message, OP, ParagraphItem, ParagraphState } from '@zeppelin/sdk'; +import { DatasetType, Message, OP, ParagraphItem, ParagraphState, textChecksum } from '@zeppelin/sdk'; import { EMPTY } from 'rxjs'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -269,8 +269,16 @@ class SaveTestParagraph extends ParagraphBase { changeColWidth(): void {} updateParagraphResult(): void {} - trackSave(msgId: string): void { - this.trackParagraphSave(msgId); + trackSave(msgId: string, checked?: boolean): void { + this.trackParagraphSave(msgId, checked); + } + + /** Types `text` in collaborative mode, which sends it to the server as a patch right away. */ + type(text: string): void { + this.recordOwnPatch(this.diffMatchPatch.patch_make(this.originalText!, text)); + this.paragraph!.text = text; + this.originalText = text; + this.dirtyText = text; } } @@ -302,6 +310,88 @@ const createSaveTestParagraph = (text: string, dirtyText?: string): SaveTestPara return paragraph; }; +describe('ParagraphBase recovery responses', () => { + const createRecoveryParagraph = (serverText: string) => { + const getParagraph = vi.fn(() => 'fetch-1'); + const paragraph = new SaveTestParagraph( + { receive: () => EMPTY, receiveEnvelope: () => EMPTY, getParagraph } as unknown as Message, + { isParagraphRunning: () => false, isEntireNoteRunning: () => false }, + { + setContextValue: vi.fn(), + unsetContextValue: vi.fn(), + contextChanged: () => EMPTY, + runParagraphAction: () => EMPTY + } as unknown as AngularContextManager, + { markForCheck: vi.fn() } as unknown as ChangeDetectorRef + ); + paragraph.paragraph = { id: 'A', text: serverText } as ParagraphItem; + paragraph.originalText = serverText; + saveTestParagraphs.push(paragraph); + return { paragraph, getParagraph }; + }; + + // A patch that cannot be reproduced locally makes the client ask for the paragraph again. The + // answer carries text the client has not seen, so an edit typed meanwhile is not in it. + const divergeAndRequestRecovery = (paragraph: SaveTestParagraph) => { + const patch = paragraph.diffMatchPatch.patch_make('server text', 'sender text').toString(); + paragraph.patchParagraph({ + paragraphId: 'A', + noteId: 'note', + patch, + baseChecksum: textChecksum('server text'), + // a checksum the local apply cannot produce, which is what marks the text as diverged + afterChecksum: textChecksum('text nobody holds') + }); + }; + + it('asks for the paragraph again when a patch does not reproduce the sender text', () => { + const { paragraph, getParagraph } = createRecoveryParagraph('server text'); + + divergeAndRequestRecovery(paragraph); + + expect(getParagraph).toHaveBeenCalledWith('A', 'note'); + }); + + it('keeps an edit made while the recovery request was in flight', () => { + const { paragraph } = createRecoveryParagraph('server text'); + divergeAndRequestRecovery(paragraph); + paragraph.type(`${paragraph.paragraph!.text}!`); + + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: 'recovered text' } as ParagraphItem, 'fetch-1'); + + // the server applied the same patch after answering, so both now hold this text + expect(paragraph.paragraph?.text).toBe('recovered text!'); + expect(paragraph.originalText).toBe('recovered text!'); + expect(paragraph.dirtyText).toBeUndefined(); + }); + + it('clears the local edit when the recovery answer already contains it', () => { + const { paragraph } = createRecoveryParagraph('server text'); + divergeAndRequestRecovery(paragraph); + const diverged = paragraph.paragraph!.text; + + paragraph.updateAllScopeTexts( + { text: diverged } as ParagraphItem, + { text: 'recovered text' } as ParagraphItem, + 'fetch-1' + ); + + expect(paragraph.dirtyText).toBeUndefined(); + }); + + it('does not treat an unrelated broadcast as a recovery answer', () => { + const { paragraph } = createRecoveryParagraph('server text'); + divergeAndRequestRecovery(paragraph); + const diverged = paragraph.paragraph!.text; + paragraph.dirtyText = 'local edit'; + + paragraph.updateAllScopeTexts({ text: diverged } as ParagraphItem, { text: 'someone else text' } as ParagraphItem); + + // without a matching msgId this is an ordinary remote edit, which keeps the existing behaviour + expect(paragraph.dirtyText).toBeUndefined(); + }); +}); + describe('ParagraphBase save responses', () => { it.each(['latest edit', ''])('preserves an unsaved edit %j when a broadcast carries the saved text', dirtyText => { const paragraph = createSaveTestParagraph(dirtyText, dirtyText); @@ -480,3 +570,65 @@ describe('ParagraphBase save responses', () => { expect(paragraph.originalText).toBe('previous save'); }); }); + +describe('ParagraphBase rejected commits', () => { + // In collaborative mode a commit carries the checksum of the text it was based on, and the + // server answers a stale one with its own text instead of storing the commit. + const commitInCollaborativeMode = (text: string) => { + const paragraph = createSaveTestParagraph(text, text); + paragraph.originalText = text; + paragraph.trackSave('save-a', true); + return paragraph; + }; + + it('takes the server text when a commit is rejected', () => { + const paragraph = commitInCollaborativeMode('select a'); + + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: 'select a!' } as ParagraphItem, 'save-a'); + + expect(paragraph.paragraph?.text).toBe('select a!'); + expect(paragraph.originalText).toBe('select a!'); + expect(paragraph.dirtyText).toBeUndefined(); + }); + + it('keeps an edit typed while the rejected commit was waiting', () => { + const paragraph = commitInCollaborativeMode('select a'); + paragraph.type('select a, b'); + + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: 'select a -- B' } as ParagraphItem, 'save-a'); + + // the server applied the same patch after answering, so both now hold this text + expect(paragraph.paragraph?.text).toBe('select a, b -- B'); + expect(paragraph.originalText).toBe('select a, b -- B'); + expect(paragraph.dirtyText).toBeUndefined(); + }); + + it('replays each sent patch in order, as the server applies them', () => { + const paragraph = commitInCollaborativeMode('a'); + paragraph.type('ab'); + paragraph.type('abc'); + + // the server text has diverged, so applying both patches as one list lands them wrongly + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: '' } as ParagraphItem, 'save-a'); + + expect(paragraph.paragraph?.text).toBe('bc'); + }); + + it('does not apply a remote edit twice when it arrives before the rejection', () => { + const paragraph = commitInCollaborativeMode('select a'); + paragraph.paragraph!.id = 'A'; + // the server stored this edit before the commit, so the rejection already carries it + paragraph.patchParagraph({ + paragraphId: 'A', + noteId: 'note', + patch: paragraph.diffMatchPatch.patch_make('select a!', 'select a! -- B').toString(), + baseChecksum: textChecksum('select a!'), + afterChecksum: textChecksum('select a! -- B') + }); + + paragraph.updateAllScopeTexts(paragraph.paragraph!, { text: 'select a! -- B' } as ParagraphItem, 'save-a'); + + expect(paragraph.paragraph?.text).toBe('select a! -- B'); + expect(paragraph.originalText).toBe('select a! -- B'); + }); +}); diff --git a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts index aabdd3ecb0d..797db1ff20b 100644 --- a/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts +++ b/zeppelin-web-angular/src/app/core/paragraph-base/paragraph-base.ts @@ -28,7 +28,8 @@ import { isTerminalParagraphState, ParagraphItem, ParagraphIResultsMsgItem, - WebSocketMessage + WebSocketMessage, + textChecksum } from '@zeppelin/sdk'; import { diff_match_patch as DiffMatchPatch } from 'diff-match-patch'; @@ -43,6 +44,9 @@ import { AngularContextManager } from './angular-context-manager'; import { NoteStatus } from './note-status'; import { ParagraphOutputState } from './paragraph-output-state'; +/** The patches of one patch message this client sent. */ +type SentPatch = Array; + export const ParagraphStatus = ParagraphStates; export abstract class ParagraphBase extends MessageListenersManager { @@ -59,8 +63,15 @@ export abstract class ParagraphBase extends MessageListenersManager { colWidthOption = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; editorSetting: ParagraphEditorSetting = {}; private readonly outputState = new ParagraphOutputState(); - private readonly pendingParagraphSaves = new Map(); + // One entry per patch message sent, since the server applies each message on its own. + private readonly pendingParagraphSaves = new Map< + string, + { sequence: number; originalText?: string; checked: boolean; ownPatches: SentPatch[] } + >(); private paragraphSaveSequence = 0; + // Recovery requests are tracked apart from saves: a save acknowledges text this client sent, + // while a recovery answer carries text it has not seen and must not discard edits made since. + private readonly pendingParagraphFetches = new Map(); constructor( public messageService: Message, @@ -206,8 +217,17 @@ export abstract class ParagraphBase extends MessageListenersManager { if (!this.paragraph.text) { this.paragraph.text = ''; } + // patch_apply never throws: it drops a hunk it cannot place, and fuzzy matching can apply + // one at the wrong offset while still reporting success. Comparing against the sender's + // checksums is the only way to tell both apart. + const startedFromSameText = data.baseChecksum === textChecksum(this.paragraph.text); this.paragraph.text = this.diffMatchPatch.patch_apply(patch, this.paragraph.text)[0]; this.originalText = this.paragraph.text; + if (startedFromSameText && data.afterChecksum !== textChecksum(this.paragraph.text)) { + // we no longer hold the text the sender produced, so ask for this paragraph again + const msgId = this.messageService.getParagraph(this.paragraph.id, data.noteId); + this.pendingParagraphFetches.set(msgId, { ownPatches: [] }); + } this.cdr.markForCheck(); } } @@ -336,17 +356,41 @@ export abstract class ParagraphBase extends MessageListenersManager { ); } - protected trackParagraphSave(msgId: string): void { - this.pendingParagraphSaves.set(msgId, { sequence: ++this.paragraphSaveSequence, originalText: this.originalText }); + /** `checked` marks a commit that carries a base checksum, so the server may reject it. */ + protected trackParagraphSave(msgId: string, checked = false): void { + this.pendingParagraphSaves.set(msgId, { + sequence: ++this.paragraphSaveSequence, + originalText: this.originalText, + checked, + ownPatches: [] + }); + } + + protected recordOwnPatch(patches: SentPatch): void { + for (const pending of [...this.pendingParagraphSaves.values(), ...this.pendingParagraphFetches.values()]) { + pending.ownPatches.push(patches); + } + } + + /** The patches sent after `serverText` reached the server after it, so replaying them gives its current text. */ + private rebaseOnServerText(serverText: string, ownPatches: SentPatch[]): void { + if (this.paragraph) { + this.paragraph.text = ownPatches.reduce( + (text, patches) => this.diffMatchPatch.patch_apply(patches, text)[0], + serverText + ); + this.originalText = this.paragraph.text; + this.dirtyText = undefined; + } } private consumeParagraphSave( msgId: string | undefined, savedText: string - ): { acknowledged: boolean; hasNewerSave: boolean } { + ): { acknowledged: boolean; hasNewerSave: boolean; rebased: boolean } { const pendingSave = msgId === undefined ? undefined : this.pendingParagraphSaves.get(msgId); if (pendingSave === undefined) { - return { acknowledged: false, hasNewerSave: false }; + return { acknowledged: false, hasNewerSave: false, rebased: false }; } const hasNewerSave = Array.from(this.pendingParagraphSaves.values()).some( ({ sequence }) => sequence > pendingSave.sequence @@ -358,20 +402,27 @@ export abstract class ParagraphBase extends MessageListenersManager { this.pendingParagraphSaves.delete(pendingMsgId); } } - // Skip when a newer save or a patch has already moved the saved baseline past this acknowledgement. - if (!hasNewerSave && this.originalText === pendingSave.originalText) { + // A checked commit is answered with the text the server held then: the committed text, or its + // own text when it rejected the commit. + if (pendingSave.checked) { + this.rebaseOnServerText(savedText, pendingSave.ownPatches); + } else if (!hasNewerSave && this.originalText === pendingSave.originalText) { + // Skip when a newer save or a patch has already moved the saved baseline past this acknowledgement. this.originalText = savedText; } - return { acknowledged: true, hasNewerSave }; + return { acknowledged: true, hasNewerSave, rebased: pendingSave.checked }; } updateAllScopeTexts(oldPara: ParagraphItem, newPara: ParagraphItem, msgId?: string) { if (!this.paragraph) { throw new Error('paragraph is not defined'); } - const { acknowledged, hasNewerSave } = this.consumeParagraphSave(msgId, newPara.text); + const { acknowledged, hasNewerSave, rebased } = this.consumeParagraphSave(msgId, newPara.text); + const recovery = this.consumeParagraphFetch(msgId); - if (oldPara.text !== newPara.text) { + if (recovery !== undefined) { + this.rebaseOnServerText(newPara.text, recovery.ownPatches); + } else if (!rebased && oldPara.text !== newPara.text) { const hasLocalEdit = this.dirtyText !== undefined && this.dirtyText !== newPara.text; const staleSaveAcknowledgement = acknowledged && (hasLocalEdit || hasNewerSave); const staleBroadcastOfSavedText = hasLocalEdit && this.originalText === newPara.text; @@ -384,6 +435,18 @@ export abstract class ParagraphBase extends MessageListenersManager { this.cdr.markForCheck(); } + /** Reports whether this message answers a recovery request, and the patches sent since then. */ + private consumeParagraphFetch(msgId: string | undefined): { ownPatches: SentPatch[] } | undefined { + if (msgId === undefined) { + return undefined; + } + const pendingFetch = this.pendingParagraphFetches.get(msgId); + if (pendingFetch !== undefined) { + this.pendingParagraphFetches.delete(msgId); + } + return pendingFetch; + } + updateParagraphObjectWhenUpdated(newPara: ParagraphItem) { if (!this.paragraph) { throw new Error('paragraph is not defined'); diff --git a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.spec.ts b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.spec.ts index cb72ffe5144..7e01ce35471 100644 --- a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.spec.ts +++ b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.spec.ts @@ -13,6 +13,8 @@ import { diff_match_patch as DiffMatchPatch } from 'diff-match-patch'; import { describe, expect, it } from 'vitest'; +import { textChecksum } from '@zeppelin/sdk'; + import { makeParagraphPatch } from './paragraph-patch'; describe('makeParagraphPatch', () => { @@ -29,4 +31,21 @@ describe('makeParagraphPatch', () => { it('rejects text that was never set', () => { expect(() => makeParagraphPatch(new DiffMatchPatch(), 'abc', undefined)).toThrow('dirtyText is required'); }); + + it('carries checksums of the text before and after the patch', () => { + const { baseChecksum, afterChecksum } = makeParagraphPatch(new DiffMatchPatch(), 'alpha', 'alpha!'); + + // a receiver compares these against its own text to tell an applied patch from a dropped or + // misapplied one, so they have to describe the sender's text on both sides of the edit + expect(baseChecksum).toBe(textChecksum('alpha')); + expect(afterChecksum).toBe(textChecksum('alpha!')); + expect(baseChecksum).not.toBe(afterChecksum); + }); + + it('treats missing original text as empty when checksumming', () => { + const { baseChecksum } = makeParagraphPatch(new DiffMatchPatch(), undefined, 'alpha'); + + // the server checksums "" for a paragraph it has no text for, so the first patch must agree + expect(baseChecksum).toBe(textChecksum('')); + }); }); diff --git a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts index 0888a70763a..95836d15542 100644 --- a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts +++ b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph-patch.ts @@ -12,21 +12,37 @@ import * as DiffMatchPatch from 'diff-match-patch'; +import { textChecksum } from '@zeppelin/sdk'; + /** * Builds the patch a collaborating client sends after an edit. An empty string is a valid * paragraph state, so only text that was never set is rejected. + * + * The checksums let a receiver tell whether its own patch_apply reached the same text as the + * sender: patch_apply drops a hunk it cannot place and can also apply one at the wrong offset + * while reporting success, neither of which is visible from the result alone. */ export function makeParagraphPatch( diffMatchPatch: DiffMatchPatch, originalText: string | undefined, dirtyText: string | undefined -): { patch: string; originalText: string } { +): { + patch: string; + patches: Array; + originalText: string; + baseChecksum: number; + afterChecksum: number; +} { if (dirtyText === undefined) { throw new Error('dirtyText is required'); } const previousText = originalText ? originalText : ''; + const patches = diffMatchPatch.patch_make(previousText, dirtyText); return { - patch: diffMatchPatch.patch_make(previousText, dirtyText).toString(), - originalText: dirtyText + patch: patches.toString(), + patches, + originalText: dirtyText, + baseChecksum: textChecksum(previousText), + afterChecksum: textChecksum(dirtyText) }; } diff --git a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts index bd788f81890..330ae4cb7a6 100644 --- a/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts +++ b/zeppelin-web-angular/src/app/pages/workspace/notebook/paragraph/paragraph.component.ts @@ -41,7 +41,8 @@ import { Note, ParagraphConfigResult, ParagraphItem, - ParagraphIResultsMsgItem + ParagraphIResultsMsgItem, + textChecksum } from '@zeppelin/sdk'; import { MessageService, @@ -200,9 +201,14 @@ export class NotebookParagraphComponent } sendPatch() { - const { patch, originalText } = makeParagraphPatch(this.diffMatchPatch, this.originalText, this.dirtyText); + const { patch, patches, originalText, baseChecksum, afterChecksum } = makeParagraphPatch( + this.diffMatchPatch, + this.originalText, + this.dirtyText + ); this.originalText = originalText; - this.messageService.patchParagraph(this.paragraph.id, this.note.id, patch); + this.recordOwnPatch(patches); + this.messageService.patchParagraph(this.paragraph.id, this.note.id, patch, baseChecksum, afterChecksum); } startSaveTimer() { @@ -513,8 +519,11 @@ export class NotebookParagraphComponent config, settings: { params } } = this.paragraph; - const msgId = this.messageService.commitParagraph(id, title, text, config, params, this.note.id); - this.trackParagraphSave(msgId); + // in collaborative mode let the server reject this commit when our text is based on a + // paragraph state the server no longer holds + const baseChecksum = this.collaborativeMode ? textChecksum(this.originalText || '') : undefined; + const msgId = this.messageService.commitParagraph(id, title, text, config, params, this.note.id, baseChecksum); + this.trackParagraphSave(msgId, baseChecksum !== undefined); this.cdr.markForCheck(); } diff --git a/zeppelin-web-angular/src/app/services/message.service.ts b/zeppelin-web-angular/src/app/services/message.service.ts index 5559cfbebe3..07ef62498a6 100644 --- a/zeppelin-web-angular/src/app/services/message.service.ts +++ b/zeppelin-web-angular/src/app/services/message.service.ts @@ -255,13 +255,32 @@ export class MessageService extends Message implements OnDestroy { paragraphData: string, paragraphConfig: ParagraphConfig, paragraphParams: ParagraphConfig, - noteId: string + noteId: string, + baseChecksum?: number ): string { - return super.commitParagraph(paragraphId, paragraphTitle, paragraphData, paragraphConfig, paragraphParams, noteId); + return super.commitParagraph( + paragraphId, + paragraphTitle, + paragraphData, + paragraphConfig, + paragraphParams, + noteId, + baseChecksum + ); + } + + patchParagraph( + paragraphId: string, + noteId: string, + patch: string, + baseChecksum?: number, + afterChecksum?: number + ): void { + super.patchParagraph(paragraphId, noteId, patch, baseChecksum, afterChecksum); } - patchParagraph(paragraphId: string, noteId: string, patch: string): void { - super.patchParagraph(paragraphId, noteId, patch); + getParagraph(paragraphId: string, noteId: string): string { + return super.getParagraph(paragraphId, noteId); } importNote(note: ImportNote['note']): void {