Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PS-707 Databox basket - Multi Part upload files to Expose #489

Merged
merged 10 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
98 changes: 81 additions & 17 deletions databox/api/src/Integration/Phrasea/Expose/ExposeClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@

namespace App\Integration\Phrasea\Expose;

use App\Asset\Attribute\AssetTitleResolver;
use App\Asset\Attribute\AttributesResolver;
use App\Asset\FileFetcher;
use App\Attribute\AttributeInterface;
use App\Entity\Core\Asset;
use App\Entity\Core\Attribute;
use App\Entity\Integration\IntegrationToken;
use App\Storage\RenditionManager;
use App\Attribute\AttributeInterface;
use App\Integration\IntegrationConfig;
use App\Asset\Attribute\AssetTitleResolver;
use App\Asset\Attribute\AttributesResolver;
use App\Entity\Integration\IntegrationToken;
use Alchemy\StorageBundle\Upload\UploadManager;
use App\Integration\Phrasea\PhraseaClientFactory;
use App\Storage\RenditionManager;
use Symfony\Contracts\HttpClient\HttpClientInterface;

final readonly class ExposeClient
Expand All @@ -23,6 +24,7 @@ public function __construct(
private AssetTitleResolver $assetTitleResolver,
private AttributesResolver $attributesResolver,
private RenditionManager $renditionManager,
private UploadManager $uploadManager
) {
}

Expand Down Expand Up @@ -128,16 +130,68 @@ public function postAsset(IntegrationConfig $config, IntegrationToken $integrati

$fetchedFilePath = $this->fileFetcher->getFile($source);
try {
$uploadsData = [
'filename' => $source->getOriginalName(),
'type' => $source->getType(),
'size' => (int)$source->getSize(),
];

$resUploads = $this->create($config, $integrationToken)
->request('POST', '/uploads', [
'json' => $uploadsData,
])
->toArray()
;
aynsix marked this conversation as resolved.
Show resolved Hide resolved

$mUploadId = $resUploads['id'];

$parts['Parts'] = [];

// Upload the file in parts.
try {
$file = fopen($fetchedFilePath, 'r');
aynsix marked this conversation as resolved.
Show resolved Hide resolved
$partNumber = 1;

// part size is up to 5Mo https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html
$partSize = 10 * 1024 * 1024; // 10Mo

$retryCount = 3;

while (!feof($file)) {
$resUploadPart = $this->create($config, $integrationToken)
->request('POST', '/uploads/'. $mUploadId .'/part', [
'json' => ['part' => $partNumber],
])
->toArray()
;

$headerPutPart = $this->putPart($resUploadPart['url'], $file, $partSize, $retryCount);

$parts['Parts'][$partNumber] = [
'PartNumber' => $partNumber,
'ETag' => current($headerPutPart['etag']),
];

$partNumber++;
}

fclose($file);
} catch (\Throwable $e) {
$this->create($config, $integrationToken)
->request('DELETE', '/uploads/'. $mUploadId);
aynsix marked this conversation as resolved.
Show resolved Hide resolved

throw $e;
}

$data = array_merge([
'publication_id' => $publicationId,
'asset_id' => $asset->getId(),
'title' => $resolvedTitle,
'description' => $description,
'translations' => $translations,
'upload' => [
'type' => $source->getType(),
'size' => $source->getSize(),
'name' => $source->getOriginalName(),
'multipart' => [
'uploadId' => $mUploadId,
'parts' => $parts['Parts'],
],
], $extraData);

Expand All @@ -147,15 +201,8 @@ public function postAsset(IntegrationConfig $config, IntegrationToken $integrati
])
->toArray()
;
$exposeAssetId = $pubAsset['id'];

$this->uploadClient->request('PUT', $pubAsset['uploadURL'], [
'headers' => [
'Content-Type' => $source->getType(),
'Content-Length' => filesize($fetchedFilePath),
],
'body' => fopen($fetchedFilePath, 'r'),
]);
$exposeAssetId = $pubAsset['id'];

foreach ([
'preview',
Expand Down Expand Up @@ -207,4 +254,21 @@ public function deleteAsset(IntegrationConfig $config, IntegrationToken $integra
->request('DELETE', '/assets/'.$assetId)
;
}

private function putPart(string $url, mixed $handleFile, int $partSize, int $retryCount)
aynsix marked this conversation as resolved.
Show resolved Hide resolved
{
if ($retryCount > 0) {
$retryCount--;
try {
return $this->uploadClient->request('PUT', $url, [
'body' => fread($handleFile, $partSize),
])->getHeaders();
aynsix marked this conversation as resolved.
Show resolved Hide resolved
} catch (\Throwable $e) {
if ($retryCount == 0) {
throw $e; // retry unsuccess
aynsix marked this conversation as resolved.
Show resolved Hide resolved
}
$this->putPart($url, $handleFile, $partSize, $retryCount);
}
}
}
}
29 changes: 29 additions & 0 deletions lib/php/storage-bundle/Controller/MultipartUploadCancelAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Alchemy\StorageBundle\Controller;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Alchemy\StorageBundle\Upload\UploadManager;
use Alchemy\StorageBundle\Entity\MultipartUpload;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MultipartUploadCancelAction extends AbstractController
{
public function __construct(private UploadManager $uploadManager, private EntityManagerInterface $em,)
{
}

public function __invoke(MultipartUpload $data, Request $request)
{
try {
$this->uploadManager->cancelMultipartUpload($data->getPath(), $data->getUploadId());
} catch (\Throwable $e) {
// S3 storage will clean up its uncomplete uploads automatically
}

$this->em->remove($data);
}
}
23 changes: 16 additions & 7 deletions lib/php/storage-bundle/Entity/MultipartUpload.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@

namespace Alchemy\StorageBundle\Entity;

use Alchemy\StorageBundle\Controller\MultipartUploadPartAction;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use Ramsey\Uuid\Uuid;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use Doctrine\DBAL\Types\Types;
use ApiPlatform\Metadata\Delete;
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Doctrine\UuidType;
use Ramsey\Uuid\Uuid;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\GetCollection;
use Symfony\Component\Serializer\Annotation\Groups;
use Alchemy\StorageBundle\Controller\MultipartUploadPartAction;
use Alchemy\StorageBundle\Controller\MultipartUploadCancelAction;
use Alchemy\StorageBundle\Controller\MultipartUploadCompleteAction;

#[ApiResource(
shortName: 'Upload',
Expand Down Expand Up @@ -67,7 +69,14 @@
]],
],
]),
new Delete(openapiContext: ['summary' => 'Cancel an upload', 'description' => 'Cancel an upload.']),
new Delete(
controller: MultipartUploadCancelAction::class,
openapiContext: [
'summary' => 'Cancel an upload',
'description' => 'Cancel an upload.'
]
),

new GetCollection(security: 'is_granted(\'ROLE_ADMIN\')'),
],
normalizationContext: ['groups' => ['upload:read']],
Expand Down
4 changes: 4 additions & 0 deletions lib/php/storage-bundle/Resources/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ services:
tags:
- { name: controller.service_arguments }

Alchemy\StorageBundle\Controller\MultipartUploadCancelAction:
tags:
- { name: controller.service_arguments }

Alchemy\StorageBundle\Doctrine\MultipartUploadListener: ~

Alchemy\StorageBundle\Storage\PathGenerator: ~
Expand Down
12 changes: 6 additions & 6 deletions lib/php/storage-bundle/Upload/UploadManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@

namespace Alchemy\StorageBundle\Upload;

use Alchemy\StorageBundle\Entity\MultipartUpload;
use Aws\Api\DateTimeResult;
use Aws\S3\S3Client;
use Doctrine\ORM\EntityManagerInterface;
use Aws\Api\DateTimeResult;
use Psr\Log\LoggerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Alchemy\StorageBundle\Entity\MultipartUpload;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

final readonly class UploadManager
{
Expand Down Expand Up @@ -62,7 +62,7 @@ public function getSignedUrl(string $uploadId, string $path, int $partNumber): s
return (string) $request->getUri();
}

public function markComplete(string $uploadId, string $filename, array $parts): void
public function markComplete(string $uploadId, string $filename, array $parts)
{
$params = [
'Bucket' => $this->uploadBucket,
Expand All @@ -73,7 +73,7 @@ public function markComplete(string $uploadId, string $filename, array $parts):
'UploadId' => $uploadId,
];

$this->client->completeMultipartUpload($params);
return $this->client->completeMultipartUpload($params);
}

public function createPutObjectSignedURL(string $path, string $contentType): string
Expand Down
Loading