מדריך קלאודפלייר בעברית

תיעוד 51

רישום אירועי העלאה ב-R2 באמצעות Event Notifications

בדוגמה הזאת משתמשים ב-Event Notifications של R2 כדי לקלוט אירועי העלאה, להעביר אותם דרך Queue, ולשמור את יומן האירועים בדלי R2 נפרד.

התהליך כולל שני דליים, Queue אחד ו-Worker צרכן. הדלי הראשון מקבל את הקבצים שמעלים, והדלי השני שומר את רשומות האירועים שה-Worker יוצר.

#1. התקנת Wrangler

לפני שמתחילים, מתקינים או מעדכנים את Wrangler, כלי שורת הפקודה של Cloudflare Developer Platform. ההוראות הרשמיות נמצאות בעמוד Install/Update Wrangler.

#2. יצירת דליי R2

צריך ליצור שני דליים:

  • example-upload-bucket: לדלי הזה מעלים אובייקטים חדשים. כל העלאה תיצור התראה שה-Worker הצרכן יקבל.
  • example-log-sink-bucket: בדלי הזה יישמרו רשומות ההעלאה שה-Worker יכתוב.

יוצרים את שני הדליים באמצעות Wrangler:

npx wrangler r2 bucket create example-upload-bucket
npx wrangler r2 bucket create example-log-sink-bucket

#3. יצירת Queue

Event Notifications קולטות שינויים בנתונים של example-upload-bucket. יוצרים Queue חדש שיקבל את ההתראות:

npx wrangler queues create example-event-notification-queue

#4. יצירת Worker צרכן

לפני שמפעילים Event Notifications עבור example-upload-bucket, צריך ליצור Worker צרכן שיקבל את ההודעות מה-Queue.

יוצרים Worker חדש באמצעות C3, כלי שורת הפקודה create-cloudflare. אפשר להשתמש במנהל החבילות המועדף:

#npm

npm create cloudflare@latest -- consumer-worker

#Yarn

yarn create cloudflare consumer-worker

#pnpm

pnpm create cloudflare@latest consumer-worker

במהלך ההגדרה בוחרים באפשרויות הבאות:

  • בשאלה What would you like to start with? בוחרים Hello World example.
  • בשאלה Which template would you like to use? בוחרים Worker only.
  • בשאלה Which language do you want to use? בוחרים TypeScript.
  • בשאלה Do you want to use git for version control? בוחרים Yes.
  • בשאלה Do you want to deploy your application? בוחרים No, מפני שצריך לבצע שינויים לפני הפריסה.

עוברים לתיקייה החדשה:

cd consumer-worker

#5. הגדרת ה-Worker

בקובץ ההגדרות של Wrangler מוסיפים צרכן Queue ו-binding לדלי R2. הגדרת הצרכן רושמת את ה-Worker כצרכן של ההתראות. ה-binding נותן ל-Worker גישה לדלי שבו יישמרו היומנים.

אם הפרויקט משתמש ב-wrangler.jsonc, מוסיפים הגדרה כזאת:

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "event-notification-writer",
  "main": "src/index.ts",
  // Set this to today's date
  "compatibility_date": "2026-08-18",
  "compatibility_flags": [
    "nodejs_compat"
  ],
  "queues": {
    "consumers": [
      {
        "queue": "example-event-notification-queue",
        "max_batch_size": 100,
        "max_batch_timeout": 5
      }
    ]
  },
  "r2_buckets": [
    {
      "binding": "LOG_SINK",
      "bucket_name": "example-log-sink-bucket"
    }
  ]
}

אם הפרויקט משתמש ב-wrangler.toml, ההגדרה המקבילה היא:

"$schema" = "./node_modules/wrangler/config-schema.json"
name = "event-notification-writer"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-08-18"
compatibility_flags = [ "nodejs_compat" ]

[[queues.consumers]]
queue = "example-event-notification-queue"
max_batch_size = 100
max_batch_timeout = 5

[[r2_buckets]]
binding = "LOG_SINK"
bucket_name = "example-log-sink-bucket"

השם LOG_SINK הוא ה-binding שבו הקוד ישתמש כדי לגשת אל example-log-sink-bucket.

#6. כתיבת הודעות Event Notification ל-R2

מוסיפים handler מסוג queue לקובץ src/index.ts. ה-handler מקבל קבוצת הודעות, הופך אותה ל-JSON, ושומר אותה כאובייקט חדש בדלי היומנים. בדוגמה הזאת אין צורך ב-handler מסוג fetch.

export interface Env {
  LOG_SINK: R2Bucket;
}

export default {
  async queue(batch, env): Promise<void> {
    const batchId = new Date().toISOString().replace(/[:.]/g, "-");
    const fileName = `upload-logs-${batchId}.json`;

    // Serialize the entire batch of messages to JSON
    const fileContent = new TextEncoder().encode(
      JSON.stringify(batch.messages),
    );

    // Write the batch of messages to R2
    await env.LOG_SINK.put(fileName, fileContent, {
      httpMetadata: {
        contentType: "application/json",
      },
    });
  },
} satisfies ExportedHandler<Env>;

שם הקובץ כולל חותמת זמן, לדוגמה upload-logs-2026-08-18T12-34-56-789Z.json. תוכן הקובץ הוא מערך הודעות ה-Queue שהתקבלו באותה קבוצה.

#7. פריסת ה-Worker

פורסים את ה-Worker הצרכן באמצעות הפקודה:

npx wrangler deploy

#8. הפעלת Event Notifications

אחרי שה-Worker מוכן לקבל הודעות, מחברים את example-upload-bucket אל ה-Queue. הפקודה הבאה יוצרת התראה עבור אירועים מסוג object-create ושולחת אותם אל example-event-notification-queue:

npx wrangler r2 bucket notification create example-upload-bucket --event-type object-create --queue example-event-notification-queue

#9. בדיקת התהליך המלא

מעלים אובייקט אל example-upload-bucket דרך לוח הבקרה של Cloudflare. בתוך כמה שניות אמור להופיע ב-example-log-sink-bucket קובץ JSON חדש שמכיל את הודעות ההעלאה.

אם לא מופיע קובץ, בודקים שה-Worker נפרס בהצלחה, שה-Queue מוגדר כצרכן בקובץ Wrangler, שה-binding בשם LOG_SINK מצביע אל example-log-sink-bucket, ושפקודת יצירת ההתראה הסתיימה ללא שגיאה.