Cloud Storage 트리거


Cloud Storage에 있는 파일과 폴더의 업로드, 업데이트 또는 삭제에 대한 응답으로 함수를 트리거할 수 있습니다.

이 페이지의 예시는 Cloud Storage에 이미지 파일이 업로드되면 트리거되는 샘플 함수를 기반으로 한 것입니다. 이 샘플 함수는 이벤트 속성 액세스 방법, Cloud Functions 인스턴스로 파일을 다운로드하는 방법을 비롯하여 Cloud Storage 이벤트 처리와 관련된 그 밖의 기본사항을 보여줍니다.

필수 모듈 가져오기

시작하려면 Cloud Storage 이벤트 처리에 필요한 모듈을 가져옵니다.

Node.js

 const {onObjectFinalized} = require("firebase-functions/v2/storage");

Python(미리보기)

 from firebase_functions import storage_fn

전체 샘플을 빌드하려면 Firebase Admin SDK 및 이미지 처리 도구의 종속 항목도 추가합니다.

Node.js

 const {initializeApp} = require("firebase-admin/app");
const {getStorage} = require("firebase-admin/storage");
const logger = require("firebase-functions/logger");
const path = require("path");

// library for image resizing
const sharp = require("sharp");

initializeApp();

Python(미리보기)

 import io
import pathlib

from PIL import Image

from firebase_admin import initialize_app

initialize_app()
from firebase_admin import storage

Cloud Storage 함수 범위 지정

다음 패턴을 사용하여 함수의 범위를 특정 Cloud Storage 버킷으로 지정하고 원하는 옵션을 설정합니다.

Node.js

// scope handler to a specific bucket, using storage options parameter
export archivedopts = onObjectArchived({ bucket: "myBucket" }, (event) => {
  //…
});

Python(미리보기)

# Scope handler to a specific bucket using storage options parameter
@storage_fn.on_object_archived(bucket="myBucket")
def archived_bucket(event: storage_fn.CloudEvent[storage_fn.StorageObjectData]):
    # ...

반면에 썸네일 생성기 함수 예시는 프로젝트의 기본 버킷으로 범위가 지정되어 있습니다.

Node.js

exports.generateThumbnail = onObjectFinalized({cpu: 2}, async (event) => {
// ...
});

Python(미리보기)

@storage_fn.on_object_archived()
def generatethumbnail(event: storage_fn.CloudEvent[storage_fn.StorageObjectData]):
    # ...

함수 위치 설정

위치가 일치하지 않으면 배포가 실패할 수 있습니다. 또한 Cloud Storage 버킷 위치와 함수 위치 사이의 거리로 인해 상당한 네트워크 지연 시간이 발생할 수 있습니다. 이러한 상황을 방지하려면 다음 중 한 가지 방식으로 버킷/트리거 위치와 일치하도록 함수 위치를 지정합니다.

  • 함수 위치가 트리거 위치와 동일합니다.
  • 함수 위치가 트리거 위치 내에 있습니다(트리거 리전이 이중/멀티 리전인 경우).
  • 트리거 리전이 us-central1로 설정되어 있으면 함수가 모든 위치에 있을 수 있습니다.

Cloud Storage 이벤트 처리

Cloud Storage 이벤트에 응답하는 다음 핸들러를 사용할 수 있습니다.

Node.js

  • onObjectArchived: 버킷에서 객체 버전 관리를 사용 설정한 경우에만 전송됩니다. 이 이벤트는 객체를 보관처리했거나 이름이 동일한 객체를 업로드하여 덮어씀으로써 객체의 서비스 중인 버전이 보관처리 버전이 되었음을 나타냅니다.
  • onObjectDeleted: 객체가 영구 삭제되면 전송됩니다. 여기에는 덮어썼거나 버킷 수명 주기 구성에 따라 삭제된 객체가 포함됩니다. 객체 버전 관리를 사용 설정한 버킷에서는 객체를 보관처리(onArchive 참조)할 때 storage.objects.delete 메서드를 통해 보관처리했더라도 이 이벤트가 전송되지 않습니다.
  • onObjectFinalized: 버킷에서 새 객체나 기존 객체의 새 세대를 만들면 전송됩니다. 여기에는 기존 객체 복사나 재작성이 포함됩니다. 실패한 업로드는 이 이벤트를 트리거하지 않습니다.
  • onMetadataUpdated: 기존 객체의 메타데이터가 변경되면 전송됩니다.

Python(미리보기)

  • on_object_archived: 버킷에서 객체 버전 관리를 사용 설정한 경우에만 전송됩니다. 이 이벤트는 객체를 보관처리했거나 이름이 동일한 객체를 업로드하여 덮어씀으로써 객체의 서비스 중인 버전이 보관처리 버전이 되었음을 나타냅니다.
  • on_object_deleted: 객체가 영구 삭제되면 전송됩니다. 여기에는 덮어썼거나 버킷 수명 주기 구성에 따라 삭제된 객체가 포함됩니다. 객체 버전 관리를 사용 설정한 버킷에서는 객체를 보관처리(onArchive 참조)할 때 storage.objects.delete 메서드를 통해 보관처리했더라도 이 이벤트가 전송되지 않습니다.
  • on_object_finalized: 버킷에서 새 객체나 기존 객체의 새 세대를 만들면 전송됩니다. 여기에는 기존 객체 복사나 재작성이 포함됩니다. 실패한 업로드는 이 이벤트를 트리거하지 않습니다.
  • on_metadata_updated: 기존 객체의 메타데이터가 변경되면 전송됩니다.

Cloud Storage 객체 속성 액세스

Cloud Functions는 업데이트된 파일의 객체 크기 및 콘텐츠 유형과 같은 다양한 Cloud Storage 객체 속성을 노출합니다. 객체의 메타데이터가 변경될 때마다 metageneration 속성이 증가합니다. 새 객체의 경우 metageneration 값이 1입니다.

Node.js

const fileBucket = event.data.bucket; // Storage bucket containing the file.
const filePath = event.data.name; // File path in the bucket.
const contentType = event.data.contentType; // File content type.

Python(미리보기)

bucket_name = event.data.bucket
file_path = pathlib.PurePath(event.data.name)
content_type = event.data.content_type

썸네일 이미지 생성 샘플에서는 이러한 속성 중 일부를 사용하여 함수가 다음과 같은 값을 반환하는 종료 사례를 감지합니다.

Node.js

// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith("image/")) {
  return logger.log("This is not an image.");
}
// Exit if the image is already a thumbnail.
const fileName = path.basename(filePath);
if (fileName.startsWith("thumb_")) {
  return logger.log("Already a Thumbnail.");
}

Python(미리보기)

# Exit if this is triggered on a file that is not an image.
if not content_type or not content_type.startswith("image/"):
    print(f"This is not an image. ({content_type})")
    return

# Exit if the image is already a thumbnail.
if file_path.name.startswith("thumb_"):
    print("Already a thumbnail.")
    return

파일 다운로드, 변환, 업로드

간혹 Cloud Storage에서 파일을 다운로드할 필요가 없는 경우도 있습니다. 하지만 Cloud Storage에 저장된 파일로 썸네일 이미지를 생성하는 것과 같은 집중적인 작업을 수행하려면 함수 인스턴스(즉, 코드를 실행하는 가상 머신)에 파일을 다운로드해야 합니다.

Cloud Functions를 Node.js용 sharp, Python용 Pillow와 같은 이미지 처리 프로그램과 함께 사용하면 그래픽 이미지 파일을 조작할 수 있습니다. 다음은 업로드된 이미지 파일의 썸네일 이미지를 만드는 방법의 예시입니다.

Node.js

/**
 * When an image is uploaded in the Storage bucket,
 * generate a thumbnail automatically using sharp.
 */
exports.generateThumbnail = onObjectFinalized({cpu: 2}, async (event) => {

  const fileBucket = event.data.bucket; // Storage bucket containing the file.
  const filePath = event.data.name; // File path in the bucket.
  const contentType = event.data.contentType; // File content type.

  // Exit if this is triggered on a file that is not an image.
  if (!contentType.startsWith("image/")) {
    return logger.log("This is not an image.");
  }
  // Exit if the image is already a thumbnail.
  const fileName = path.basename(filePath);
  if (fileName.startsWith("thumb_")) {
    return logger.log("Already a Thumbnail.");
  }

  // Download file into memory from bucket.
  const bucket = getStorage().bucket(fileBucket);
  const downloadResponse = await bucket.file(filePath).download();
  const imageBuffer = downloadResponse[0];
  logger.log("Image downloaded!");

  // Generate a thumbnail using sharp.
  const thumbnailBuffer = await sharp(imageBuffer).resize({
    width: 200,
    height: 200,
    withoutEnlargement: true,
  }).toBuffer();
  logger.log("Thumbnail created");

  // Prefix 'thumb_' to file name.
  const thumbFileName = `thumb_${fileName}`;
  const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);

  // Upload the thumbnail.
  const metadata = {contentType: contentType};
  await bucket.file(thumbFilePath).save(thumbnailBuffer, {
    metadata: metadata,
  });
  return logger.log("Thumbnail uploaded!");
});

Cloud Functions 인스턴스의 임시 디렉터리에 파일을 다운로드합니다. 이 위치에서 필요에 따라 파일을 처리한 다음 Cloud Storage에 업로드할 수 있습니다. 비동기 작업을 수행하는 경우 콜백에서 JavaScript 프로미스를 반환해야 합니다.

Python(미리보기)

@storage_fn.on_object_finalized()
def generatethumbnail(
    event: storage_fn.CloudEvent[storage_fn.StorageObjectData],
):
    """When an image is uploaded in the Storage bucket, generate a thumbnail
    automatically using Pillow."""

    bucket_name = event.data.bucket
    file_path = pathlib.PurePath(event.data.name)
    content_type = event.data.content_type

    # Exit if this is triggered on a file that is not an image.
    if not content_type or not content_type.startswith("image/"):
        print(f"This is not an image. ({content_type})")
        return

    # Exit if the image is already a thumbnail.
    if file_path.name.startswith("thumb_"):
        print("Already a thumbnail.")
        return

    bucket = storage.bucket(bucket_name)

    image_blob = bucket.blob(str(file_path))
    image_bytes = image_blob.download_as_bytes()
    image = Image.open(io.BytesIO(image_bytes))

    image.thumbnail((200, 200))
    thumbnail_io = io.BytesIO()
    image.save(thumbnail_io, format="png")
    thumbnail_path = file_path.parent / pathlib.PurePath(
        f"thumb_{file_path.stem}.png"
    )
    thumbnail_blob = bucket.blob(str(thumbnail_path))
    thumbnail_blob.upload_from_string(
        thumbnail_io.getvalue(), content_type="image/png"
    )


이 코드는 임시 디렉터리에 저장된 이미지의 200x200 썸네일을 만든 후 다시 Cloud Storage에 업로드합니다.