// posts_on_publish — docs TRIGGER on the `posts` collection (create|update). // When a post transitions INTO "published", enqueue batched reader-notification // jobs onto the `post-notifications` queue (decoupling the burst from delivery, // and staying well under the per-execution emission ceiling via chunking). let ev = ctx.event.docs; if ev == () { return; } let data = ev.data; if data == () { return; } let was = if ev.prev_data == () { () } else { ev.prev_data.status }; let became_published = data.status == "published" && was != "published"; if !became_published { return; } // collect reader emails in chunks of 50 let res = users::list(#{ "$limit": 500 }); let batch = []; let total = 0; for u in res.users { if users::has_role(u.id, "reader") { batch.push(u.email); total += 1; if batch.len() >= 50 { queue::enqueue("post-notifications", #{ post_id: ev.id, title: data.title, slug: data.slug, emails: batch }); batch = []; } } } if batch.len() > 0 { queue::enqueue("post-notifications", #{ post_id: ev.id, title: data.title, slug: data.slug, emails: batch }); } log::info("queued post notifications", #{ post: ev.id, title: data.title, readers: total });