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
23 changes: 21 additions & 2 deletions src/Vocab/Loader/DefaultVocabLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@
use function is_resource;
use function is_writable;
use function mkdir;
use function rename;
use function sha1;
use function sprintf;
use function stream_copy_to_stream;
use function uniqid;
use function unlink;

use const DIRECTORY_SEPARATOR;

Expand Down Expand Up @@ -68,10 +71,11 @@ public function loadFile(string $uri, string|null $checksum = null): string
}

try {
$cacheStream = fopen($cacheFile, 'w+');
$tmpFile = $cacheFile . '_' . uniqid('tmp', more_entropy: true);
$cacheStream = fopen($tmpFile, 'w+');

if ($cacheStream === false) {
throw new IOError(sprintf('Could not open file for write: %s', $cacheFile));
throw new IOError(sprintf('Could not open file for write: %s', $tmpFile));
}

try {
Expand All @@ -86,6 +90,17 @@ public function loadFile(string $uri, string|null $checksum = null): string
throw new IOError($message);
}

if (rename($tmpFile, $cacheFile) === false) {
$message = 'Could not rename file';
$lastError = error_get_last();

if ($lastError !== null) {
$message .= ': ' . $lastError['message'];
}

throw new IOError($message);
}

if ($checksum !== null) {
if (! $this->checkHash($cacheFile, $checksum)) {
throw new IOError(sprintf(
Expand All @@ -96,6 +111,10 @@ public function loadFile(string $uri, string|null $checksum = null): string
}
} finally {
fclose($cacheStream);

if (file_exists($tmpFile)) {
unlink($tmpFile);
}
}
} finally {
fclose($stream);
Expand Down
6 changes: 5 additions & 1 deletion tests/EncoderProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Yethee\Tiktoken\Tests;

use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamFile;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Yethee\Tiktoken\EncoderProvider;
Expand Down Expand Up @@ -46,7 +47,7 @@ public function testUseHashWhenLoadVocab(): void
$cache = vfsStream::setup('cache');
$vocabCacheFilename = hash('sha1', EncoderProvider::ENCODINGS['p50k_base']['vocab']);

$cacheFile = vfsStream::newFile($vocabCacheFilename)
vfsStream::newFile($vocabCacheFilename)
->withContent('broken cache')
->at($cache);

Expand All @@ -56,6 +57,9 @@ public function testUseHashWhenLoadVocab(): void

$provider->get('p50k_base');

$cacheFile = $cache->getChild($vocabCacheFilename);

self::assertInstanceOf(vfsStreamFile::class, $cacheFile);
self::assertNotEquals('broken cache', $cacheFile->getContent());
}

Expand Down