Merge pull request #452 from shikorism/fix/451-atomic-metadata-resolve

Metadata解決処理をトランザクション内で実行する
This commit is contained in:
shibafu 2020-08-01 18:48:13 +09:00 committed by GitHub
commit a63c39a56f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,6 +8,7 @@ use App\MetadataResolver\MetadataResolver;
use App\Tag; use App\Tag;
use App\Utilities\Formatter; use App\Utilities\Formatter;
use GuzzleHttp\Exception\TransferException; use GuzzleHttp\Exception\TransferException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
class MetadataResolveService class MetadataResolveService
@ -33,32 +34,34 @@ class MetadataResolveService
throw new DeniedHostException($url); throw new DeniedHostException($url);
} }
// 無かったら取得 return DB::transaction(function () use ($url) {
// TODO: ある程度古かったら再取得とかありだと思う // 無かったら取得
$metadata = Metadata::find($url); // TODO: ある程度古かったら再取得とかありだと思う
if ($metadata == null || ($metadata->expires_at !== null && $metadata->expires_at < now())) { $metadata = Metadata::find($url);
try { if ($metadata == null || ($metadata->expires_at !== null && $metadata->expires_at < now())) {
$resolved = $this->resolver->resolve($url); try {
$metadata = Metadata::updateOrCreate(['url' => $url], [ $resolved = $this->resolver->resolve($url);
'title' => $resolved->title, $metadata = Metadata::updateOrCreate(['url' => $url], [
'description' => $resolved->description, 'title' => $resolved->title,
'image' => $resolved->image, 'description' => $resolved->description,
'expires_at' => $resolved->expires_at 'image' => $resolved->image,
]); 'expires_at' => $resolved->expires_at
]);
$tagIds = []; $tagIds = [];
foreach ($resolved->normalizedTags() as $tagName) { foreach ($resolved->normalizedTags() as $tagName) {
$tag = Tag::firstOrCreate(['name' => $tagName]); $tag = Tag::firstOrCreate(['name' => $tagName]);
$tagIds[] = $tag->id; $tagIds[] = $tag->id;
}
$metadata->tags()->sync($tagIds);
} catch (TransferException $e) {
// 何らかの通信エラーによってメタデータの取得に失敗した時、とりあえずエラーログにURLを残す
Log::error(self::class . ': メタデータの取得に失敗 URL=' . $url);
throw $e;
} }
$metadata->tags()->sync($tagIds);
} catch (TransferException $e) {
// 何らかの通信エラーによってメタデータの取得に失敗した時、とりあえずエラーログにURLを残す
Log::error(self::class . ': メタデータの取得に失敗 URL=' . $url);
throw $e;
} }
}
return $metadata; return $metadata;
});
} }
} }