Explorar documentação
Guias
Baixe um MP4 para o armazenamento privado S3, retome depois de reiniciar e dê acesso ao arquivo verificado.
Nesta página
O que você vai construir
Um item durável se move de um vídeo ID para um arquivo pronto para aplicação. Mantenha cada estágio no disco para que um novo processo possa continuar do último resultado confirmado.
item.json
→ enviar uma vez → executar salvo + trabalho ID
→ Recuperar o trabalho → delivery.json
→ verificar bytes S3 → media.mp4 + ready.json
→ autorize o usuário do aplicativo → download de curta duração URLAntes de começar
Escolha um caminho de exemplo para os seis passos. Ambos usam FlashData instalado CLI com um perfil de proprietário salvo e permissão youtube_download, S3 privado storage.json para uploads, e uma identidade AWS que pode ler o objeto entregue.
Use Python 3.10+ em seu ambiente Python. Os scripts chamam o CLI para preservar seu diário de execução, e Boto3 para ler S3 e assinar links. Bash, jq, Node.js e AWS CLI não são necessários. Execute os comandos abaixo com python, ou python3 se esse é o seu nome de intérprete.
python --version
flashdata --version
python -m pip install boto3Instale Bash, jq, Node.js 22+ e AWS CLI v2. Em Windows, execute comandos Bash em Git Bash. Instale os pacotes de assinatura do Node S3 no passo 6.
Salve as configurações de execução
Crie uma pasta de itens privados fora do controle de fonte. Guarde as configurações para o seu caminho escolhido e edite os caminhos absolutos e o nome do perfil. Cada processo usa essa conta salva e executa o diário. Credenciais de armazenamento ficam em storage.json privado. Faça um processo por item de cada vez.
Salve pipeline.json. Em Windows, caminhos avançados como C:/private/flashdata-state trabalham em JSON.
{
"stateDir": "/absolute/path/to/flashdata-state",
"storageConfig": "/absolute/path/to/private/storage.json",
"profile": "default"
}# pipeline.env — edit these paths for your existing installation.
export FLASHDATA_STATE_DIR='/absolute/path/to/flashdata-state'
export FLASHDATA_STORAGE_CONFIG='/absolute/path/to/private/storage.json'
export FLASHDATA_PROFILE='default'
# Use the saved profile for every process.
unset FLASHDATA_API_KEY1. Salve um item persistente
Salve item.json nessa pasta. Substitua o vídeo e o destino S3, este exemplo pede um MP4 a até 720p. Fique com o runId para refazer. Uma saída planejada diferente precisa de um novo runId e prefixo de objeto.
{
"runId": "media:clip-001:720p:v1",
"request": {
"source": "youtube_download",
"video_id": "jNQXAC9IVRw",
"params": {
"download_type": "audio_video",
"video_quality": "<=720",
"output_format": "mp4"
}
},
"destination": {
"bucket": "your-media-bucket",
"region": "us-east-1",
"prefix": "media/clip-001-v1"
}
}2. Salve o script e verifique o acesso
Crie o arquivo abaixo antes de verificar. Valida o destino S3 e mantém um recibo para cada tentativa de submissão.
Crie o roteiro do oleoduto
Crie pipeline.py na mesma pasta que pipeline.json e item.json. Copie o código completo abaixo para o arquivo e salve-o. Você vai reutilizá-lo para verificações, submissão e recuperação nas etapas 2–4.
# pipeline.py — Python 3.10+ and the FlashData CLI on PATH.
import argparse
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent
def read_json(path):
return json.loads(Path(path).read_text(encoding='utf-8-sig'))
def delivery_directory():
# Recovery updates this pointer only after the delivery is saved successfully.
return ROOT / (ROOT / 'delivery-dir.txt').read_text(encoding='utf-8').strip()
def main(action):
os.umask(0o077)
settings = read_json(ROOT / 'pipeline.json')
for name in ['stateDir', 'storageConfig']:
if not Path(settings[name]).is_absolute():
raise ValueError('Set an absolute path for ' + name)
item = read_json(ROOT / 'item.json')
run_id = item['runId']
env = dict(os.environ)
env.pop('FLASHDATA_API_KEY', None) # Reuse the saved owner profile.
flags = ['--profile', settings['profile'], '--state-dir', settings['stateDir'],
'--json', '--non-interactive']
def cli(*args, payload=None, attempt=None):
result = subprocess.run(['flashdata', *args, *flags], cwd=ROOT, env=env,
input=json.dumps(payload) if payload is not None else None,
capture_output=True, text=True, encoding='utf-8')
if attempt:
(attempt / 'receipt.json').write_text(result.stdout, encoding='utf-8')
(attempt / 'error.json').write_text(result.stderr, encoding='utf-8')
if result.returncode:
if attempt:
raise RuntimeError('Keep ' + str(attempt) + '; inspect its error and saved run.')
raise RuntimeError(result.stderr.strip() or 'FlashData command failed.')
response = json.loads(result.stdout)
if not response.get('ok'):
raise RuntimeError('Inspect the CLI response before continuing.')
return response
def new_attempt(stage):
attempts = ROOT / 'attempts'
attempts.mkdir(exist_ok=True)
return Path(tempfile.mkdtemp(prefix=stage + '.', dir=attempts))
if action == 'check':
access = cli('auth', 'status')['data']
identity = access['identity']
if (not access.get('accessVerified')
or identity['identity'].get('recurringAllowed') is not True
or 'youtube_download' not in identity.get('permittedSources', [])):
raise ValueError('Owner access with youtube_download is required.')
print(json.dumps({'accountId': identity['identity']['accountId'],
'permittedSources': identity['permittedSources']}, indent=2))
for args in [('account', 'balance'),
('account', 'pricing', '--source', 'youtube_download', '--request-count', '1'),
('account', 'limits')]:
print(json.dumps(cli(*args)['data'], indent=2))
elif action in ['dry-run', 'submit']:
storage = read_json(settings['storageConfig'])
destination = item['destination']
if (item['request']['source'] != 'youtube_download'
or storage.get('storage_type') != 's3'
or storage.get('storage_url') != destination['bucket']
or storage.get('region') != destination['region']):
raise ValueError('Check item.json and the S3 destination in storage.json.')
request = item['request']
request['params']['storage'] = {**storage, 'object_prefix': destination['prefix']}
args = ['query', '--input', '-', '--mode', 'async', '--run-id', run_id]
if action == 'dry-run':
response = cli(*args, '--dry-run', payload=request)
if response['data'].get('dryRun') is not True:
raise ValueError('Expected a dry-run result.')
print(json.dumps({'ok': True, 'dryRun': True}))
else:
attempt = new_attempt('submit')
response = cli(*args, '--output', str(attempt / 'submission.json'),
payload=request, attempt=attempt)
print(json.dumps({'runId': run_id, 'cached': response.get('cached'),
'receipt': str(attempt / 'submission.json')}, indent=2))
elif action == 'inspect':
run = cli('runs', 'show', run_id)['data']
print(json.dumps({'runId': run_id, 'status': run['status'], 'jobId': run.get('remoteId'),
'errorCode': run.get('errorCode'),
'candidateJobIds': run.get('candidateRemoteIds')}, indent=2))
elif action == 'recover':
attempt = new_attempt('recover')
cli('runs', 'recover', run_id, '--timeout', '10m',
'--output', str(attempt / 'delivery.json'), attempt=attempt)
run = cli('runs', 'show', run_id)
(attempt / 'run.json').write_text(json.dumps(run, indent=2), encoding='utf-8')
delivery = read_json(attempt / 'delivery.json')
if delivery.get('source') != 'youtube_download' or delivery.get('status') != 'done':
raise ValueError('Inspect the saved delivery before verifying.')
pointer = ROOT / 'delivery-dir.next'
pointer.write_text(attempt.relative_to(ROOT).as_posix(), encoding='utf-8')
pointer.replace(ROOT / 'delivery-dir.txt')
print('Delivery files:', attempt)
elif action == 'delivery':
delivery = read_json(delivery_directory() / 'delivery.json')
print(json.dumps({'status': delivery['status'], 'file': delivery['results'][0],
'usage': delivery.get('usage')}, indent=2))
if __name__ == '__main__':
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
parser = argparse.ArgumentParser()
parser.add_argument('action', choices=['check', 'dry-run', 'submit', 'inspect', 'recover', 'delivery'])
try:
main(parser.parse_args().action)
except (OSError, ValueError, KeyError, RuntimeError) as error:
print(str(error), file=sys.stderr)
sys.exit(1)Crie request-media.sh na mesma pasta que pipeline.env e item.json. Copie o código completo abaixo para o arquivo e salve-o.
#!/usr/bin/env bash
set -euo pipefail
umask 077
cd -- "$(dirname -- "$0")"
. ./pipeline.env
: "${FLASHDATA_STATE_DIR:?Set your existing absolute CLI state directory}"
: "${FLASHDATA_STORAGE_CONFIG:?Set the absolute path to private storage.json}"
action=${1:-dry-run}
[[ "$action" == dry-run || "$action" == submit ]] || exit 2
run_id=$(jq -er '.runId | select(type == "string" and length > 0)' item.json)
request() {
jq -en --slurpfile item item.json --slurpfile storage "$FLASHDATA_STORAGE_CONFIG" '
$item[0] as $i | $storage[0] as $s
| if $i.request.source != "youtube_download"
or $s.storage_type != "s3" or $s.storage_url != $i.destination.bucket
or $s.region != $i.destination.region
then error("Check item.json and the S3 destination in storage.json")
else $i.request | .params.storage = ($s + {object_prefix: $i.destination.prefix}) end'
}
args=(query --input - --mode async --run-id "$run_id"
--profile "${FLASHDATA_PROFILE:-default}" --state-dir "$FLASHDATA_STATE_DIR"
--json --non-interactive)
if [[ "$action" == dry-run ]]; then
request | flashdata "${args[@]}" --dry-run
else
mkdir -p attempts
attempt=$(mktemp -d attempts/submit.XXXXXX)
if ! request | flashdata "${args[@]}" --output "$attempt/submission.json" \
> "$attempt/receipt.json" 2> "$attempt/error.json"; then
cat "$attempt/error.json" >&2
printf 'Keep %s; inspect the saved run before retrying.\n' "$attempt" >&2
exit 1
fi
jq '{runId, cached, data}' "$attempt/receipt.json"
printf 'Saved receipt: %s/submission.json\n' "$attempt"
fiVerifique sua conta salva
Execute esta verificação gratuita da pasta de itens após salvar o script. Acesso do proprietário desaparecido ou permissão youtube_download para a verificação. Confirme a conta ID, saldo, taxa por TB e limites. A carga final depende dos bytes enviados.
python pipeline.py checkset -euo pipefail
. ./pipeline.env
: "${FLASHDATA_STATE_DIR:?Set your existing absolute CLI state directory}"
: "${FLASHDATA_STORAGE_CONFIG:?Set the absolute path to private storage.json}"
flashdata --version
jq --version
node --version
aws --version
flashdata auth status --profile "${FLASHDATA_PROFILE:-default}" \
--state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive |
jq -e 'if .ok and .data.accessVerified
and (.data.identity.identity.recurringAllowed == true)
and (.data.identity.permittedSources | index("youtube_download") != null)
then {accountId: .data.identity.identity.accountId,
permittedSources: .data.identity.permittedSources}
else error("Owner access with youtube_download is required.") end'
flashdata account balance --profile "${FLASHDATA_PROFILE:-default}" \
--state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive
flashdata account pricing --source youtube_download --request-count 1 \
--profile "${FLASHDATA_PROFILE:-default}" --state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive
flashdata account limits --profile "${FLASHDATA_PROFILE:-default}" \
--state-dir "$FLASHDATA_STATE_DIR" --json --non-interactiveValidar sem download
Depois de salvar o script auxiliar, execute a simulação. Python exibe ok: true e dryRun: true; Bash exibe true. Isso valida a entrada e o acesso sem enviar trabalhos de mídia nem reservar créditos.
python pipeline.py dry-runset -euo pipefail
bash request-media.sh dry-run | jq -e '.ok and .data.dryRun'3. Submeta e retenha o trabalho ID
Isso envia um download pago de antecedentes. Espere status: accepted e um jobId na corrida local. Mantenha o perfil, diretório estatal e item.json para recuperação. A mídia só está pronta após o passo 5.
python pipeline.py submitpython pipeline.py inspectbash request-media.sh submitset -euo pipefail
. ./pipeline.env
RUN_ID=$(jq -er '.runId' item.json)
flashdata runs show "$RUN_ID" --profile "${FLASHDATA_PROFILE:-default}" \
--state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive |
jq '{runId, status: .data.status, jobId: .data.remoteId,
errorCode: .data.errorCode, candidateJobIds: .data.candidateRemoteIds}'Se a corrida já está salva ou incerta
| CLI | Ação |
|---|---|
| accepted + jobId | Recupere esta corrida no passo 4. Mantenha o trabalho ID se o processo parar. |
| succeeded | Recover/export sua resposta salva, então verifique o armazenamento. Não submeta um novo item. |
| Resultado desconhecido / nenhum trabalho confirmado ID | Mantenha o controle, recibo e erro. Inspecione History ou o candidato IDs antes de decidir sobre outra submissão. |
4. Recupere o registro de entrega
Corra da pasta de itens em qualquer novo terminal. A recuperação espera pelo trabalho original e imprime um diretório contendo delivery.json, run.json e recibos. Um intervalo de tempo de 10 para a espera local, repetição da recuperação para retomar o mesmo trabalho.
Retomar o trabalho salvo
Reutilize pipeline.py salvo no passo 2. Nenhum roteiro adicional é necessário.
python pipeline.py recoverPrimeiro crie recover-media.sh ao lado de item.json e cole no código abaixo. Salve o arquivo e execute o comando de recuperação abaixo dele.
#!/usr/bin/env bash
set -euo pipefail
umask 077
cd -- "$(dirname -- "$0")"
. ./pipeline.env
: "${FLASHDATA_STATE_DIR:?Set your existing absolute CLI state directory}"
RUN_ID=$(jq -er '.runId' item.json)
mkdir -p attempts
DELIVERY_DIR=$(mktemp -d attempts/recover.XXXXXX)
if ! flashdata runs recover "$RUN_ID" --timeout 10m \
--profile "${FLASHDATA_PROFILE:-default}" --state-dir "$FLASHDATA_STATE_DIR" \
--output "$DELIVERY_DIR/delivery.json" --json --non-interactive \
> "$DELIVERY_DIR/receipt.json" 2> "$DELIVERY_DIR/error.json"; then
cat "$DELIVERY_DIR/error.json" >&2
printf 'Keep %s; recover the same run after resolving the error.\n' "$DELIVERY_DIR" >&2
exit 1
fi
flashdata runs show "$RUN_ID" --profile "${FLASHDATA_PROFILE:-default}" \
--state-dir "$FLASHDATA_STATE_DIR" --json --non-interactive > "$DELIVERY_DIR/run.json"
jq -e '.source == "youtube_download" and .status == "done"' \
"$DELIVERY_DIR/delivery.json" >/dev/null
printf '%s\n' "$DELIVERY_DIR"set -euo pipefail
DELIVERY_DIR=$(bash recover-media.sh)
printf 'Delivery files: %s\n' "$DELIVERY_DIR"Inspecione o objeto entregue
Espere um objeto S3 URL, um tamanho de arquivo positivo e um MD5. Objetos particulares precisam da sua identidade AWS. Python salva o diretório de sucesso em delivery-dir.txt para scripts posteriores. Bash mantém DELIVERY_DIR; em um novo terminal, defina-o para o diretório impresso.
python pipeline.py deliveryjq '{status, file: .results[0], usage}' "$DELIVERY_DIR/delivery.json"5. Verifique bytes antes de marcar pronto
O verificador verifica a entrada original, o balde S3 e prefixo, transmite o objeto privado para o disco, e compara sua contagem de bytes e MD5. Apenas arquivos correspondentes produzem verified/ready.json.. Python lê delivery-dir.txt; Node usa DELIVERY_DIR. Nem submete uma consulta FlashData.
Guarde o script de verificação
Este verificador lida com o objeto padrão Amazon S3 URLs. Para terminais personalizados ou outro provedor, use seu objeto autenticado lido e mantenha o mesmo destino, bytes e verificações de soma.
Crie verify-media.py ao lado de pipeline.py e copie o código completo abaixo. Guarde os dois arquivos na pasta de itens.
# verify-media.py — uses Boto3's configured AWS read identity.
import hashlib
import json
import os
import re
import sys
from contextlib import closing
from datetime import datetime, timezone
from urllib.parse import unquote, urlsplit
import boto3
from pipeline import ROOT, delivery_directory, read_json
def main():
os.umask(0o077)
directory = delivery_directory()
item = read_json(ROOT / 'item.json')
saved = read_json(directory / 'run.json')
raw = (directory / 'delivery.json').read_bytes()
delivery = json.loads(raw)
run = saved.get('data', {})
if (not saved.get('ok') or run.get('id') != item['runId']
or run.get('status') != 'succeeded' or not run.get('remoteId')
or delivery.get('source') != 'youtube_download' or delivery.get('status') != 'done'
or not isinstance(delivery.get('results'), list) or len(delivery['results']) != 1):
raise ValueError('Inspect the saved run and completed delivery before verifying.')
file = delivery['results'][0]
bucket, region, prefix = (item['destination'][key] for key in ['bucket', 'region', 'prefix'])
original = run.get('input', {})
storage = original.get('params', {}).get('storage', {})
if (original.get('source') != 'youtube_download' or original.get('video_id') != item['request']['video_id']
or any(original.get('params', {}).get(key) != item['request']['params'][key]
for key in ['download_type', 'video_quality', 'output_format'])
or storage.get('storage_url') != bucket or storage.get('region') != region
or storage.get('object_prefix') != prefix):
raise ValueError('item.json changed after submission. Inspect the original run.')
url = urlsplit(file['file_url'])
hosts = [bucket + '.s3.' + region + '.amazonaws.com', bucket + '.s3.amazonaws.com']
key = unquote(url.path[1:], errors='strict')
if (url.scheme != 'https' or url.netloc not in hosts or url.query or url.fragment
or not prefix or not key.startswith(prefix + '/')):
raise ValueError('The delivery does not match the planned Amazon S3 destination.')
if (type(file.get('file_size')) is not int or file['file_size'] <= 0
or not re.fullmatch(r'[a-fA-F0-9]{32}', file.get('md5', ''))):
raise ValueError('A positive file_size and MD5 are required. Keep the manifest.')
verification = directory / 'verified'
verification.mkdir(mode=0o700) # Stop if an earlier verification already exists.
local_file = verification / 'media.mp4'
s3 = boto3.client('s3', region_name=region)
response = s3.get_object(Bucket=bucket, Key=key)
size, digest = 0, hashlib.md5(usedforsecurity=False)
with closing(response['Body']) as stream, local_file.open('xb') as output:
while chunk := stream.read(1024 * 1024):
output.write(chunk)
size += len(chunk)
digest.update(chunk)
md5 = digest.hexdigest()
if size != file['file_size'] or md5 != file['md5'].lower():
raise ValueError('Byte count or MD5 mismatch. Keep the file; do not mark it ready.')
ready = {'runId': item['runId'], 'jobId': run['remoteId'], 'videoId': item['request']['video_id'],
'bucket': bucket, 'region': region, 'objectKey': key,
'storageVersionId': response.get('VersionId'), 'bytes': size, 'md5': md5,
'verifiedAt': datetime.now(timezone.utc).isoformat(), 'localFile': str(local_file.resolve()),
'deliverySha256': hashlib.sha256(raw).hexdigest(), 'usage': delivery.get('usage')}
with (verification / 'ready.json').open('x', encoding='utf-8') as output:
json.dump(ready, output, indent=2)
print('Delivery verified:', verification / 'ready.json')
print(json.dumps(ready, indent=2))
if __name__ == '__main__':
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
try:
main()
except Exception as error:
print(str(error), file=sys.stderr)
sys.exit(1)Crie verify-media.mjs ao lado de item.json e copie o código completo abaixo.
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { resolve, join } from 'node:path';
try {
const directory = process.argv[2];
if (!directory) throw new Error('Pass the directory printed by the recovery step.');
const readJson = async path => JSON.parse(await readFile(path, 'utf8'));
const item = await readJson('item.json');
const run = await readJson(join(directory, 'run.json'));
const raw = await readFile(join(directory, 'delivery.json'));
const delivery = JSON.parse(raw);
if (!run.ok || run.data?.id !== item.runId || run.data?.status !== 'succeeded'
|| !run.data?.remoteId || delivery.source !== 'youtube_download'
|| delivery.status !== 'done' || delivery.results?.length !== 1) {
throw new Error('Inspect the saved run and completed delivery before verifying.');
}
const file = delivery.results[0];
const { bucket, region, prefix } = item.destination;
const input = run.data.input;
const storage = input?.params?.storage;
if (input?.source !== 'youtube_download' || input.video_id !== item.request.video_id
|| ['download_type', 'video_quality', 'output_format'].some(
key => input.params?.[key] !== item.request.params[key])
|| storage?.storage_url !== bucket || storage.region !== region
|| storage.object_prefix !== prefix) {
throw new Error('item.json changed after submission. Inspect the original run.');
}
const url = new URL(file.file_url);
const hosts = [bucket + '.s3.' + region + '.amazonaws.com', bucket + '.s3.amazonaws.com'];
const objectKey = decodeURIComponent(url.pathname.slice(1));
if (url.protocol !== 'https:' || !hosts.includes(url.host) || url.username
|| url.password || url.search || url.hash || !prefix
|| !objectKey.startsWith(prefix + '/')) {
throw new Error('The delivery does not match the planned Amazon S3 destination.');
}
if (!Number.isSafeInteger(file.file_size) || file.file_size <= 0
|| !/^[a-f0-9]{32}$/i.test(file.md5 ?? '')) {
throw new Error('A positive file_size and MD5 are required. Keep the manifest.');
}
const verification = join(directory, 'verified');
await mkdir(verification, { mode: 0o700 }); // Existing attempt: stop without overwriting.
const localFile = join(verification, 'media.mp4');
let metadata;
try {
metadata = JSON.parse(execFileSync('aws', ['s3api', 'get-object',
'--bucket', bucket, '--key', objectKey, '--region', region,
'--output', 'json', '--no-cli-pager', '--no-cli-auto-prompt', localFile],
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }));
} catch {
throw new Error('S3 read failed. Keep this attempt and check the AWS read identity.');
}
let bytes = 0;
const hash = createHash('md5');
for await (const chunk of createReadStream(localFile)) {
bytes += chunk.length;
hash.update(chunk);
}
const md5 = hash.digest('hex');
if (bytes !== file.file_size || md5 !== file.md5.toLowerCase()) {
throw new Error('Byte count or MD5 mismatch. Keep the file; do not mark it ready.');
}
const ready = { runId: item.runId, jobId: run.data.remoteId,
videoId: item.request.video_id, bucket, region, objectKey, storageVersionId: metadata.VersionId ?? null,
bytes, md5, verifiedAt: new Date().toISOString(), localFile: resolve(localFile),
deliverySha256: createHash('sha256').update(raw).digest('hex'), usage: delivery.usage };
const readyFile = join(verification, 'ready.json');
await writeFile(readyFile, JSON.stringify(ready, null, 2), { flag: 'wx', mode: 0o600 });
console.log('Delivery verified:', readyFile);
} catch (error) {
console.error(error instanceof Error ? error.message : 'Inspect the saved attempt.');
process.exitCode = 1;
}Faça a verificação
Depois de salvar o script, execute-o na pasta de itens.
python verify-media.pyset -euo pipefail
: "${DELIVERY_DIR:?Set the directory printed by recovery}"
node verify-media.mjs "$DELIVERY_DIR"
jq '{runId, jobId, bucket, region, objectKey, bytes, md5, storageVersionId}' \
"$DELIVERY_DIR/verified/ready.json"Entregue ready.json para sua aplicação
Esperar entrega verificada e um registro contendo o run/job IDs, balde, região, chave de objeto, tamanho verificado e MD5. Este é o registro da sua aplicação, criado pelo roteiro. Arquive-o com delivery.json e o item original, sobrevive à janela de retenção do resultado API.
Para transcrição, indexação ou outro processamento, passe o localFile verificado para seu trabalhador. Para um download voltado para o usuário, continue com o passo 6.
6. Dê a sua aplicação de acesso controlado
Em sua infraestrutura, autorize o usuário e procure o registro pronto do usuário em sua própria loja. Então crie um S3 de curta duração, baixe URL. Use o destino salvo; não aceite um balde ou chave de objeto fornecido pelo navegador.
Salve o script de download-link
O SDK usa a identidade da AWS. Nenhuma consulta FlashData é enviada.
O URL nomeia a versão de objeto verificada quando o S3 fornece uma versão. Sem uma versão ID, mantenha cada chave de saída imutável após verificação. Uma leitura de identidade de uma versão específica precisa de s3:GetObjectVersion; uma leitura não-versionada precisa de s3:GetObject.
Crie create-download-link.py ao lado de pipeline.py e copie o código completo abaixo. Ele usa o pacote Boto3 instalado no início.
# create-download-link.py — run in your backend after authorizing the user.
import json
import os
import sys
import boto3
from botocore.config import Config
from pipeline import delivery_directory, read_json
def main():
os.umask(0o077)
# In an app, load this user's verified ready record from your own store.
directory = delivery_directory() / 'verified'
ready = read_json(directory / 'ready.json')
if any(not isinstance(ready.get(key), str) or not ready[key]
for key in ['bucket', 'region', 'objectKey', 'verifiedAt']):
raise ValueError('Use the ready.json produced by the verification step.')
destination = directory / 'access.json'
if destination.exists():
raise FileExistsError('Keep the existing access.json or choose a new output filename.')
params = {'Bucket': ready['bucket'], 'Key': ready['objectKey']}
version = ready.get('storageVersionId')
if version and version != 'null':
params['VersionId'] = version
s3 = boto3.client('s3', region_name=ready['region'], config=Config(signature_version='s3v4'))
url = s3.generate_presigned_url('get_object', Params=params, ExpiresIn=300, HttpMethod='GET')
with destination.open('x', encoding='utf-8') as output:
json.dump({'url': url, 'expiresInSeconds': 300}, output, indent=2)
# Do not log the signed URL; return it only to the authorized user.
print('Access record saved:', destination)
if __name__ == '__main__':
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
try:
main()
except Exception as error:
print(str(error), file=sys.stderr)
sys.exit(1)Instale os pacotes de assinatura na pasta de itens e salve a fonte abaixo como create-download-link.mjs nessa pasta.
test -f package.json || npm init -y
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner// create-download-link.mjs — run in your backend with its AWS read identity.
import { readFile } from 'node:fs/promises';
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
try {
const path = process.argv[2];
if (!path) throw new Error('Pass the verified ready.json file.');
const ready = JSON.parse(await readFile(path, 'utf8'));
if (['bucket', 'region', 'objectKey', 'verifiedAt'].some(
key => typeof ready[key] !== 'string' || !ready[key])) {
throw new Error('Use the ready.json produced by the verification step.');
}
// Load this record from your own store after authorizing the requesting user.
const version = ready.storageVersionId;
const command = new GetObjectCommand({
Bucket: ready.bucket, Key: ready.objectKey,
...(version && version !== 'null' ? { VersionId: version } : {}),
});
const client = new S3Client({ region: ready.region });
const url = await getSignedUrl(client, command, { expiresIn: 300 });
console.log(JSON.stringify({ url, expiresInSeconds: 300 }, null, 2));
} catch (error) {
console.error(error instanceof Error ? error.message : 'Could not create a download link.');
process.exitCode = 1;
}Devolva o link para o usuário autorizado
Espere um access.json privado contendo url e expiresInSeconds: 300. Sua infraestrutura devolve apenas o URL ao usuário autorizado. Qualquer um pode baixar o arquivo por até cinco minutos, pode expirar mais cedo com as credenciais de assinatura.
Criar um novo link do registro pronto salvo quando o usuário pedir acesso. Mantenha a chave do objeto e a versão em seu banco de dados, ao invés de armazenar o URL expirante como o endereço do ativo. Este exemplo local para se access.json já existir.
python create-download-link.py(
set -euo pipefail
umask 077
: "${DELIVERY_DIR:?Set the directory printed by recovery}"
# Keep the signed link in a private file; do not log it or paste it into chat.
set -C
node create-download-link.mjs "$DELIVERY_DIR/verified/ready.json" \
> "$DELIVERY_DIR/verified/access.json"
)Recomeçar da última etapa confirmada
| Situação | Próxima ação |
|---|---|
| Trabalho aceito / espera local cronometrado | Repita runs recover com o mesmo runId em um novo diretório de tentativas. |
| S3 acesso negado ou interrompido leitura | Conserte a identidade ou conexão da AWS. Recupere-se em um novo diretório e verifique novamente, mantenha o arquivo anterior parcial. |
| Contagem de bytes / MD5 / Desvio de destino | Pare. Compare o manifesto, a versão do objeto e o destino planejado antes de usar a mídia. |
| verificado/ já existe | Leia seu ready.json, ou inspecione sua verificação incompleta. O roteiro não vai sobrescrevê-lo. |
| O download do aplicativo URL expirou | Autorize o acesso novamente e assine o object/version. salvo. Não envie outro download do FlashData. |
| run_id_input_conflict | O pedido mudou. Recupere a corrida original, use um novo runId apenas para uma saída intencional. |
| 401 / 403 / 402 / 429 | Conserte acesso, permissões ou equilíbrio, siga Retry-After. Inspecione o trabalho salvo antes de tentar novamente uma submissão. |
Aplique os mesmos estágios em uma fila
- Comece com um item em voo. Leia os limites atuais antes de aumentar a concordância de aplicação.
- Mantenha um runId durável para cada versão video/output, com um prefixo de destino distinto. Guarde a conta, o trabalho ID e o resultado final em seu banco de dados de aplicações.
- Persista no diretório de estado CLI através do processo reiniciado. Máquinas separadas precisam de coordenação de aplicativos compartilhados, um diário local não desduplica diretórios estatais independentes.
- Use ready.json como transferência para processamento a jusante. Reter itens fracassados individualmente para que as entregas bem sucedidas sejam reutilizadas.