จัดการเหตุการณ์ในวงจรของส่วนขยาย

ส่วนขยายของคุณสามารถมีฟังก์ชัน Cloud Tasks ที่ทริกเกอร์เมื่ออินสแตนซ์ส่วนขยายผ่านเหตุการณ์วงจร ต่อไปนี้

  • มีการติดตั้งอินสแตนซ์ของส่วนขยาย
  • อัปเดตอินสแตนซ์ของส่วนขยายเป็นเวอร์ชันใหม่
  • มีการเปลี่ยนแปลงการกำหนดค่าของอินสแตนซ์ส่วนขยาย

กรณีการใช้งานที่สำคัญที่สุดอย่างหนึ่งของฟีเจอร์นี้คือการป้อนข้อมูลย้อนหลัง ตัวอย่างเช่น สมมติว่าคุณกำลังสร้างส่วนขยายที่สร้างตัวอย่างภาพขนาดย่อ ของรูปภาพที่อัปโหลดไปยังที่เก็บข้อมูล Cloud Storage งานหลักของส่วนขยาย จะดำเนินการในฟังก์ชันที่ทริกเกอร์โดยเหตุการณ์ onFinalize Cloud Storage อย่างไรก็ตาม ระบบจะประมวลผลเฉพาะรูปภาพที่อัปโหลดหลังจากติดตั้งส่วนขยายแล้วเท่านั้น การใส่ฟังก์ชันที่ทริกเกอร์โดย onInstallเหตุการณ์วงจรของแอปในส่วนขยายจะช่วยให้คุณสร้างตัวอย่างภาพปกของรูปภาพที่มีอยู่ได้เมื่อติดตั้งส่วนขยาย

กรณีการใช้งานอื่นๆ ของทริกเกอร์เหตุการณ์วงจรลูกค้ามีดังนี้

  • ตั้งค่าหลังการติดตั้งโดยอัตโนมัติ (สร้างบันทึกฐานข้อมูล จัดทำดัชนี ฯลฯ)
  • หากคุณต้องเผยแพร่การเปลี่ยนแปลงที่เข้ากันไม่ได้กับเวอร์ชันก่อนหน้า ให้ย้ายข้อมูลโดยอัตโนมัติเมื่ออัปเดต

เครื่องจัดการเหตุการณ์ในวงจรที่มีระยะเวลาสั้น

หากงานของคุณทำงานได้ภายในระยะเวลาCloud Functionsสูงสุด (9 นาทีโดยใช้ API รุ่นแรก) คุณสามารถเขียนตัวแฮนเดิลเหตุการณ์วงจรของงานเป็นฟังก์ชันเดียวที่ทริกเกอร์ในเหตุการณ์คิวงาน onDispatch ได้

export const myTaskFunction = functions.tasks.taskQueue()
  .onDispatch(async () => {
    // Complete your lifecycle event handling task.
    // ...

    // When processing is complete, report status to the user (see below).
  });

จากนั้นในไฟล์ extension.yaml ของส่วนขยาย ให้ทำดังนี้

  1. ลงทะเบียนฟังก์ชันเป็นทรัพยากรส่วนขยายด้วยชุดพร็อพเพอร์ตี้ taskQueueTrigger หากตั้งค่า taskQueueTrigger เป็นแผนที่ว่าง ({}) ส่วนขยาย จะจัดสรรคิว Cloud Tasks โดยใช้การตั้งค่าเริ่มต้น และคุณจะปรับการตั้งค่าเหล่านี้ได้หากต้องการ

    resources:
      - name: myTaskFunction
        type: firebaseextensions.v1beta.function
        description: >-
          Describe the task performed when the function is triggered by a lifecycle
          event
        properties:
          location: ${LOCATION}
          taskQueueTrigger: {}
    
  2. ลงทะเบียนฟังก์ชันเป็นตัวแฮนเดิลสำหรับเหตุการณ์วงจรอย่างน้อย 1 รายการ

    resources:
      - ...
    lifecycleEvents:
      onInstall:
        function: myTaskFunction
        processingMessage: Resizing your existing images
      onUpdate:
        function: myOtherTaskFunction
        processingMessage: Setting up your extension
      onConfigure:
        function: myOtherTaskFunction
        processingMessage: Setting up your extension
    
    

    คุณลงทะเบียนฟังก์ชันสำหรับเหตุการณ์ต่อไปนี้ได้ onInstall, onUpdate และ onConfigure กิจกรรมทั้งหมดนี้เป็นกิจกรรมที่ไม่บังคับ

  3. แนะนำ: หากไม่จำเป็นต้องมีงานประมวลผลเพื่อให้ส่วนขยายทำงาน ได้ ให้เพิ่มพารามิเตอร์ที่ผู้ใช้กำหนดค่า ซึ่งช่วยให้ผู้ใช้เลือกได้ว่าจะเปิดใช้หรือไม่

    เช่น เพิ่มพารามิเตอร์ดังนี้

    params:
      - param: DO_BACKFILL
        label: Backfill existing images
        description: >
          Should existing, unresized images in the Storage bucket be resized as well?
        type: select
        options:
          - label: Yes
            value: true
          - label: No
            value: false
    

    และในฟังก์ชัน หากตั้งค่าพารามิเตอร์เป็น false ให้ออกก่อน

    export const myTaskFunction = functions.tasks.taskQueue()
      .onDispatch(async () => {
        if (!process.env.DO_BACKFILL) {
          await runtime.setProcessingState(
            "PROCESSING_COMPLETE",
            "Existing images were not resized."
          );
          return;
        }
        // Complete your lifecycle event handling task.
        // ...
      });
    

การทำงานที่ใช้เวลานาน

หากงานไม่สามารถดำเนินการให้เสร็จภายในCloud Functionsระยะเวลา สูงสุด ให้แบ่งงานออกเป็นงานย่อย แล้วดำเนินการแต่ละงานย่อยตามลำดับโดยการจัดคิว งานด้วยเมธอด TaskQueue.enqueue() ของ Admin SDK

ตัวอย่างเช่น สมมติว่าคุณต้องการทดแทนข้อมูล Cloud Firestore คุณสามารถ แบ่งคอลเล็กชันเอกสารออกเป็นกลุ่มโดยใช้เคอร์เซอร์การค้นหา หลังจากประมวลผลก้อนข้อมูลแล้ว ให้เลื่อนออฟเซ็ตเริ่มต้นและจัดคิวการเรียกใช้ฟังก์ชันอื่น ดังที่แสดงด้านล่าง

import { getFirestore } from "firebase-admin/firestore";
import { getFunctions } from "firebase-admin/functions";

exports.backfilldata = functions.tasks.taskQueue().onDispatch(async (data) => {
  // When a lifecycle event triggers this function, it doesn't pass any data,
  // so an undefined offset indicates we're on our first invocation and should
  // start at offset 0. On subsequent invocations, we'll pass an explicit
  // offset.
  const offset = data["offset"] ?? 0;

  // Get a batch of documents, beginning at the offset.
  const snapshot = await getFirestore()
    .collection(process.env.COLLECTION_PATH)
    .startAt(offset)
    .limit(DOCS_PER_BACKFILL)
    .get();
  // Process each document in the batch.
  const processed = await Promise.allSettled(
    snapshot.docs.map(async (documentSnapshot) => {
      // Perform the processing.
    })
  );

  // If we processed a full batch, there are probably more documents to
  // process, so enqueue another invocation of this function, specifying
  // the offset to start with.
  //
  // If we processed less than a full batch, we're done.
  if (processed.length == DOCS_PER_BACKFILL) {
    const queue = getFunctions().taskQueue(
      "backfilldata",
      process.env.EXT_INSTANCE_ID
    );
    await queue.enqueue({
      offset: offset + DOCS_PER_BACKFILL,
    });
  } else {
      // Processing is complete. Report status to the user (see below).
  }
});

เพิ่มฟังก์ชันลงใน extension.yaml ตามที่อธิบายไว้ในส่วนก่อนหน้า

สถานะการรายงาน

เมื่อฟังก์ชันการประมวลผลทั้งหมดเสร็จสิ้น ไม่ว่าจะสำเร็จหรือมี ข้อผิดพลาด ให้รายงานสถานะของงานโดยใช้วิธีการรันไทม์ของส่วนขยาย Admin SDK ผู้ใช้จะดูสถานะนี้ได้ในหน้ารายละเอียดส่วนขยายใน Firebase คอนโซล

การดำเนินการเสร็จสมบูรณ์และข้อผิดพลาดที่ไม่ร้ายแรง

หากต้องการรายงานข้อผิดพลาดที่ร้ายแรงและไม่ร้ายแรง (ข้อผิดพลาดที่ไม่ได้ทำให้ส่วนขยายอยู่ในสถานะที่ใช้งานไม่ได้) และการดำเนินการที่เสร็จสมบูรณ์ ให้ใช้setProcessingState()เมธอดรันไทม์ของส่วนขยายใน Admin SDK ดังนี้

import { getExtensions } from "firebase-admin/extensions";

// ...

getExtensions().runtime().setProcessingState(processingState, message);

คุณสามารถตั้งค่าสถานะต่อไปนี้ได้

สถานะข้อผิดพลาดที่ไม่ร้ายแรง
PROCESSING_COMPLETE

ใช้เพื่อรายงานการทำงานที่สำเร็จ ตัวอย่าง

getExtensions().runtime().setProcessingState(
  "PROCESSING_COMPLETE",
  `Backfill complete. Successfully processed ${numSuccess} documents.`
);
PROCESSING_WARNING

ใช้เพื่อรายงานความสำเร็จบางส่วน ตัวอย่าง

getExtensions().runtime().setProcessingState(
  "PROCESSING_WARNING",
  `Backfill complete. ${numSuccess} documents processed successfully.`
    + ` ${numFailed} documents failed to process. ${listOfErrors}.`
    + ` ${instructionsToFixTheProblem}`
);
PROCESSING_FAILED

ใช้เพื่อรายงานข้อผิดพลาดที่ทำให้งานไม่สำเร็จ แต่ไม่ได้ ทำให้ส่วนขยายใช้งานไม่ได้ ตัวอย่าง

getExtensions().runtime().setProcessingState(
  "PROCESSING_FAILED",
  `Backfill failed. ${errorMsg} ${optionalInstructionsToFixTheProblem}.`
);

หากต้องการรายงานข้อผิดพลาดที่ทำให้ส่วนขยายใช้งานไม่ได้ โปรดโทรหา setFatalError()

NONE

ใช้เพื่อล้างสถานะของงาน คุณสามารถใช้พารามิเตอร์นี้เพื่อล้าง ข้อความสถานะจากคอนโซลได้ (เช่น หลังจากผ่านไประยะหนึ่ง นับตั้งแต่ตั้งค่า PROCESSING_COMPLETE) ตัวอย่าง

getExtensions().runtime().setProcessingState("NONE");

ข้อผิดพลาดร้ายแรง

หากเกิดข้อผิดพลาดที่ทำให้ส่วนขยายทำงานไม่ได้ เช่น งานการตั้งค่าที่จำเป็นล้มเหลว ให้รายงานข้อผิดพลาดร้ายแรงโดยทำดังนี้ setFatalError()

import { getExtensions } from "firebase-admin/extensions";

// ...

getExtensions().runtime().setFatalError(`Post-installation setup failed. ${errorMessage}`);

การปรับแต่งคิวงาน

หากตั้งค่าพร็อพเพอร์ตี้ taskQueueTrigger เป็น {} ส่วนขยายจะ จัดสรรคิว Cloud Tasks ด้วยการตั้งค่าเริ่มต้นเมื่อมีการติดตั้งอินสแตนซ์ ส่วนขยาย หรือคุณจะปรับขีดจํากัดการทํางานพร้อมกันของคิวงานและลักษณะการทํางานของการลองใหม่ได้โดยระบุค่าต่อไปนี้

resources:
  - name: myTaskFunction
    type: firebaseextensions.v1beta.function
    description: >-
      Perform a task when triggered by a lifecycle event
    properties:
      location: ${LOCATION}
      taskQueueTrigger:
        rateLimits:
          maxConcurrentDispatches: 1000
          maxDispatchesPerSecond: 500
        retryConfig:
          maxAttempts: 100  # Warning: setting this too low can prevent the function from running
          minBackoffSeconds: 0.1
          maxBackoffSeconds: 3600
          maxDoublings: 16
lifecycleEvents:
  onInstall: 
    function: myTaskFunction
    processingMessage: Resizing your existing images
  onUpdate:
    function: myTaskFunction
    processingMessage: Setting up your extension
  onConfigure:
    function: myOtherTaskFunction
    processingMessage: Setting up your extension

โปรดดูรายละเอียดเกี่ยวกับพารามิเตอร์เหล่านี้ในเอกสารประกอบของ Google Cloud ที่หัวข้อกำหนดค่าคิว Cloud Tasks

อย่าพยายามระบุพารามิเตอร์คิวของงานโดยส่งไปยัง taskQueue() ระบบจะไม่สนใจการตั้งค่าเหล่านี้และจะใช้การกำหนดค่าใน extension.yaml และ ค่าเริ่มต้นของการกำหนดค่าแทน

เช่น การดำเนินการต่อไปนี้จะไม่ได้ผล

export const myBrokenTaskFunction = functions.tasks
  // DON'T DO THIS IN AN EXTENSION! THESE SETTINGS ARE IGNORED.
  .taskQueue({
    retryConfig: {
      maxAttempts: 5,
      minBackoffSeconds: 60,
    },
    rateLimits: {
      maxConcurrentDispatches: 1000,
      maxDispatchesPerSecond: 10,
    },
  })
  .onDispatch(
    // ...
  );

พร็อพเพอร์ตี้ taskQueueTrigger ใน extension.yaml เป็นวิธีเดียวในการกำหนดค่าคิวงานของส่วนขยาย

ตัวอย่าง

ส่วนขยาย storage-resize-images, firestore-bigquery-export และ firestore-translate-text อย่างเป็นทางการทั้งหมดใช้ตัวแฮนเดิลเหตุการณ์วงจรเพื่อเติมข้อมูลย้อนหลัง