Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/Context/FileContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
use Psr\Log\LoggerInterface;

class FileContext implements IContext {
/** Content written by save(), so updating the document afterwards does not read the file again */
private ?string $savedContent = null;

public function __construct(
private readonly FileService $fileService,
Expand Down Expand Up @@ -132,7 +134,7 @@ public function updateDocument(Document $document): void {
}

$file = $this->getFile();
$fileChecksum = $this->computeCheckSum();
$fileChecksum = $this->computeCheckSum($this->savedContent);
$this->logger->debug('computed checksum', ['checksum' => $fileChecksum]);

$document->setChecksum($fileChecksum);
Expand All @@ -147,6 +149,7 @@ public function loadContent(): ?string {
public function save(string $content, callable $afterSave): void {
$this->lockService->runInScope($this->getFile(), function () use ($content, $afterSave): void {
$this->getFile()->putContent($content);
$this->savedContent = $content;
$afterSave();
});
}
Expand Down
29 changes: 18 additions & 11 deletions lib/Service/DocumentService.php
Original file line number Diff line number Diff line change
Expand Up @@ -367,13 +367,22 @@ public function autosave(Document $document, IContext $context, int $version, st
throw new NotPermittedException('Read-only permission cannot save document changes. Please reload the page.');
}

// Only save once every AUTOSAVE_MINIMUM_DELAY seconds
$lastMTime = $document->getLastSavedVersionTime();
if ($lastMTime > time() - self::AUTOSAVE_MINIMUM_DELAY && $manualSave === false) {
return $document;
}

if ($lastMTime > 0 && !$force && !$this->cache->get('document-save-lock-' . $document->id)) {
try {
$context->updateDocument($document);
if (!empty($document->getUpdatedFields())) {
// Content was overwritten in the meantime and content changed.
if (isset($document->getUpdatedFields()['checksum'])) {
if (isset($document->getUpdatedFields()['checksum'])) {
// Another save by Text may have finished after this request loaded the document.
$stored = $this->getDocument($document->id);
if ($stored === null) {
throw new NotFoundException('Document was reset in the meantime');
}
if ($stored->getChecksum() !== $document->getChecksum()) {
$content = $context->loadContent();
if ($content === null) {
// Keep the stored checksum so the next save detects the outside change again.
Expand All @@ -382,7 +391,8 @@ public function autosave(Document $document, IContext $context, int $version, st
}
throw new DocumentSaveConflictException($content);
}
$lastMTime = $document->getLastSavedVersionTime();
$document = $stored;
} elseif (!empty($document->getUpdatedFields())) {
$this->documentMapper->update($document);
}
} catch (LockedException) {
Expand All @@ -406,11 +416,6 @@ public function autosave(Document $document, IContext $context, int $version, st
return $document;
}

// Only save once every AUTOSAVE_MINIMUM_DELAY seconds
if ($lastMTime > time() - self::AUTOSAVE_MINIMUM_DELAY && $manualSave === false) {
return $document;
}

if (empty($autoSaveDocument)) {
$file = $context->getFile();
$this->logger->warning('Saving empty document', [
Expand Down Expand Up @@ -441,10 +446,12 @@ public function autosave(Document $document, IContext $context, int $version, st
$this->cache->set('document-save-lock-' . $document->id, true, 60);
$this->saveFromText = true;
try {
$context->save($autoSaveDocument, function () use ($document, $documentState): void {
$context->save($autoSaveDocument, function () use ($context, $document, $documentState): void {
// Store the new checksum first so a failure below cannot leave it outdated.
$context->updateDocument($document);
$this->documentMapper->update($document);
$this->writeDocumentState($document->id, $documentState);
});
$context->updateDocument($document);
$document->setLastSavedVersion($version);
$this->documentMapper->update($document);
} catch (LockedException) {
Expand Down
106 changes: 106 additions & 0 deletions tests/unit/Service/DocumentServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@
use OCA\Text\Db\DocumentMapper;
use OCA\Text\Db\SessionMapper;
use OCA\Text\Db\StepMapper;
use OCA\Text\Exception\DocumentSaveConflictException;
use OCA\Text\Service\DocumentService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\DirectEditing\IManager;
use OCP\Files\IAppData;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IConfig;
Expand Down Expand Up @@ -173,4 +176,107 @@ public function testResetsDocumentWhenFileChangedOutside(): void {
$built = $this->createBuiltDocument('changed outside');
self::assertSame($built, $this->documentService->getOrCreateDocument($built));
}

public function testNoConflictIfTextSavedInTheMeantime(): void {
$document = $this->createDocument('etag1', 1000, 'old content');
$document->setLastSavedVersion(3);
$document->resetUpdatedFields();
$stored = $this->createDocument('etag2', 1010, 'saved by text');
$stored->setLastSavedVersion(5);
$context = $this->createMock(FileContext::class);
$context->method('updateDocument')->willReturnCallback(
static fn (Document $document) => $document->setChecksum(DocumentService::computeCheckSum('saved by text'))
);
$this->documentMapper->method('find')->with($document->id)->willReturn($stored);
$this->stepMapper->method('getLatestVersion')->willReturn(5);
$context->expects(self::never())->method('save');

$result = $this->documentService->autosave($document, $context, 4, 'new content', 'doc state');
self::assertSame($stored, $result);
}

public function testConflictIfFileChangedOutside(): void {
$document = $this->createDocument('etag1', 1000, 'old content');
$document->resetUpdatedFields();
$stored = $this->createDocument('etag1', 1000, 'old content');
$context = $this->createMock(FileContext::class);
$context->method('updateDocument')->willReturnCallback(
static fn (Document $document) => $document->setChecksum(DocumentService::computeCheckSum('outside content'))
);
$context->method('loadContent')->willReturn('outside content');
$this->documentMapper->method('find')->with($document->id)->willReturn($stored);
$context->expects(self::never())->method('save');

$this->expectException(DocumentSaveConflictException::class);
$this->documentService->autosave($document, $context, 1, 'new content', 'doc state');
}

public function testNotFoundIfDocumentWasResetInTheMeantime(): void {
$document = $this->createDocument('etag1', 1000, 'old content');
$document->resetUpdatedFields();
$context = $this->createMock(FileContext::class);
$context->method('updateDocument')->willReturnCallback(
static fn (Document $document) => $document->setChecksum(DocumentService::computeCheckSum('outside content'))
);
$this->documentMapper->method('find')->with($document->id)
->willThrowException(new DoesNotExistException('Document was reset'));
$context->expects(self::never())->method('loadContent');
$context->expects(self::never())->method('save');

$this->expectException(NotFoundException::class);
$this->documentService->autosave($document, $context, 1, 'new content', 'doc state');
}

public function testUpdatesDocumentRightAfterWritingTheFile(): void {
$document = $this->createDocument('etag1', 1000, 'old content');
$document->resetUpdatedFields();
$context = $this->createMock(FileContext::class);
$saving = false;
$updatedWhileSaving = [];
$context->method('updateDocument')->willReturnCallback(
static function () use (&$saving, &$updatedWhileSaving): void {
$updatedWhileSaving[] = $saving;
}
);
$context->method('loadContent')->willReturn('old content');
$context->method('save')->willReturnCallback(
static function (string $content, callable $afterSave) use (&$saving): void {
$saving = true;
$afterSave();
$saving = false;
}
);
$this->stepMapper->method('getLatestVersion')->willReturn(1);

$this->documentService->autosave($document, $context, 1, 'new content', 'doc state');
self::assertSame([false, true], $updatedWhileSaving);
self::assertSame(1, $document->getLastSavedVersion());
}

public function testThrottledAutosaveSkipsConflictCheck(): void {
$document = $this->createDocument('etag1', time(), 'content');
$document->resetUpdatedFields();
$context = $this->createMock(FileContext::class);
$context->expects(self::never())->method('updateDocument');
$context->expects(self::never())->method('save');

$result = $this->documentService->autosave($document, $context, 1, 'new content', 'doc state');
self::assertSame($document, $result);
}

public function testManualSaveChecksForConflictsWithinAutosaveDelay(): void {
$document = $this->createDocument('etag1', time(), 'old content');
$document->resetUpdatedFields();
$stored = $this->createDocument('etag1', time(), 'old content');
$context = $this->createMock(FileContext::class);
$context->method('updateDocument')->willReturnCallback(
static fn (Document $document) => $document->setChecksum(DocumentService::computeCheckSum('outside content'))
);
$context->method('loadContent')->willReturn('outside content');
$this->documentMapper->method('find')->with($document->id)->willReturn($stored);
$context->expects(self::never())->method('save');

$this->expectException(DocumentSaveConflictException::class);
$this->documentService->autosave($document, $context, 1, 'new content', 'doc state', false, true);
}
}
Loading