פלטפורמת Firebase מספקת התראות למגוון רחב של ניהול פרויקטים ואפליקציות אירועים. כמה אירועים לדוגמה שבהם המערכת של Firebase יכולה לשלוח לכם את ההודעה הזו סוג ההתראה:
- בCrashlytics, נוכל להתריע אם חלה עלייה משמעותית באפליקציה שלך קריסות.
- עבור Performance Monitoring, נוכל להתריע אם זמן ההפעלה של האפליקציה חוצה את סף מוגדר.
- ב-App Distribution, נוכל להתריע לך אם אחד מהבודקים שלך ירשום מכשיר iOS חדש במכשיר.
בהתאם להתראה ולהעדפות שהוגדרו על ידי הפרויקט חבר, התראות מהסוגים האלה מוצגות במסוף Firebase או שהן יישלחו על ידי Firebase באימייל.
בדף הזה מוסבר איך לכתוב פונקציות ב-Cloud Functions for Firebase (דור שני) שמטפלים באירועי התראות.
איך זה עובד?
אפשר להפעיל פונקציות בתגובה לאירועי התראה שנפלטים מהמקורות הבאים:
- טיפול באירוע התראה מסוג App Distribution
- טיפול באירוע התראה מסוג Crashlytics
- טיפול באירוע התראה מסוג Performance Monitoring
במחזור חיים טיפוסי, פונקציה שמופעלת על ידי אירוע התראה מבצעת הבאים:
- המערכת מאזינה או ממתינה לסוג התראה ספציפי שיופץ מ-Firebase.
- הטריגר מופעל כשמתבצעת הפעלה של ההתראה, ומקבל את עומס העבודה של האירוע שמכיל מידע ספציפי על האירוע.
- הפעלת הקוד של הפונקציה כדי לטפל בעומס העבודה של האירוע.
הפעלת פונקציה באירועי התראה
משתמשים בחבילת המשנה firebase-functions/v2/alerts
כדי לכתוב פונקציה שמטפלת באירועי התראות. הדוגמאות הבאות ספציפיות למוצרים ממחישות
תהליך עבודה שבו פונקציה משתמשת ב-webhook כדי לפרסם הודעה בערוץ Discord
כשהתראה על מוצר זה מופצת מ-Firebase.
טיפול באירוע התראה מסוג Crashlytics
בדוגמה הבאה של Crashlytics, משתמשים ב-Cloud Functions for Firebase כדי לטפל באירוע התראה על בעיה חדשה של תאונה קטלנית. הפונקציה הזו מפרסמת את פרטי ההתראה בהודעה לערוץ Discord.
הפונקציה מקשיבה לאירוע שמתאים לפרסום בעיה קריטית חדשה ב-Firebase:
Node.js
exports.postfatalissuetodiscord = onNewFatalIssuePublished(async (event) => {
Python
@crashlytics_fn.on_new_fatal_issue_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_fatal_issue_to_discord(event: crashlytics_fn.CrashlyticsNewFatalIssueEvent) -> None:
"""Publishes a message to Discord whenever a new Crashlytics fatal issue occurs."""
לאחר מכן, הפונקציה מנתחת את אובייקט האירוע שהוחזר, מנתחת מידע שימושי ממטען הנתונים של האירוע ומרכיבת הודעה שתפרסם בערוץ Discord:
Node.js
// construct a helpful message to send to Discord
const appId = event.appId;
const {id, title, subtitle, appVersion} = event.data.payload.issue;
const message = `
🚨 New fatal issue for ${appId} in version ${appVersion} 🚨
**${title}**
${subtitle}
id: \`${id}\`
`;
Python
# Construct a helpful message to send to Discord.
app_id = event.app_id
issue = event.data.payload.issue
message = f"""
🚨 New fatal issue for {app_id} in version {issue.app_version} 🚨
# {issue.title}
{issue.subtitle}
ID: `{issue.id}`
""".strip()
לבסוף, הפונקציה שולחת את ההודעה שנוצרה ל-Discord דרך בקשת HTTP:
Node.js
const response = await postMessageToDiscord("Crashlytics Bot", message);
if (response.ok) {
logger.info(
`Posted fatal Crashlytics alert ${id} for ${appId} to Discord`,
event.data.payload,
);
} else {
throw new Error(response.error);
}
Python
response = post_message_to_discord("Crashlytics Bot", message, DISCORD_WEBHOOK_URL.value)
if response.ok:
print(f"Posted fatal Crashlytics alert {issue.id} for {app_id} to Discord.")
pprint.pp(event.data.payload)
else:
response.raise_for_status()
כדי לקבל מידע על כל אירועי ההתראות של Crashlytics שאפשר לתעד, צריך לעבור אל את מאמרי העזרה של Crashlytics התראות.
טיפול באירוע התראה מסוג Performance Monitoring
בדוגמה הזו מייצאים פונקציה שמקשיבה לאירועי התראות של ערכי סף ביצועים:
Node.js
exports.postperformancealerttodiscord = onThresholdAlertPublished(
async (event) => {
Python
@performance_fn.on_threshold_alert_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_performance_alert_to_discord(event: performance_fn.PerformanceThresholdAlertEvent) -> None:
"""Publishes a message to Discord whenever a performance threshold alert is fired."""
לאחר מכן הפונקציה מנתחת את אובייקט האירוע שהוחזר ומנתחת מידע שימושי מהמטען הייעודי (payload) של האירוע ויצירה של הודעה לפרסום ב-Discord ערוץ:
Node.js
// construct a helpful message to send to Discord
const appId = event.appId;
const {
eventName,
metricType,
eventType,
numSamples,
thresholdValue,
thresholdUnit,
conditionPercentile,
appVersion,
violationValue,
violationUnit,
investigateUri,
} = event.data.payload;
const message = `
⚠️ Performance Alert for ${metricType} of ${eventType}: **${eventName}** ⚠️
App id: ${appId}
Alert condition: ${thresholdValue} ${thresholdUnit}
Percentile (if applicable): ${conditionPercentile}
App version (if applicable): ${appVersion}
Violation: ${violationValue} ${violationUnit}
Number of samples checked: ${numSamples}
**Investigate more:** ${investigateUri}
`;
Python
# Construct a helpful message to send to Discord.
app_id = event.app_id
perf = event.data.payload
message = f"""
⚠️ Performance Alert for {perf.metric_type} of {perf.event_type}: **{perf.event_name}** ⚠️
App ID: {app_id}
Alert condition: {perf.threshold_value} {perf.threshold_unit}
Percentile (if applicable): {perf.condition_percentile}
App version (if applicable): {perf.app_version}
Violation: {perf.violation_value} {perf.violation_unit}
Number of samples checked: {perf.num_samples}
**Investigate more:** {perf.investigate_uri}
""".strip()
לבסוף, הפונקציה שולחת את ההודעה שנוצרה ל-Discord דרך קוד HTTP בקשה:
Node.js
const response = await postMessageToDiscord(
"Firebase Performance Bot", message);
if (response.ok) {
logger.info(
`Posted Firebase Performance alert ${eventName} to Discord`,
event.data.payload,
);
} else {
throw new Error(response.error);
}
Python
response = post_message_to_discord("App Performance Bot", message,
DISCORD_WEBHOOK_URL.value)
if response.ok:
print(f"Posted Firebase Performance alert {perf.event_name} to Discord.")
pprint.pp(event.data.payload)
else:
response.raise_for_status()
למידע על כל אירועי ההתראות לגבי ביצועים שאפשר לתעד, אפשר לעיין במסמכי העזרה של התראות Performance Monitoring.
טיפול באירוע התראה מסוג App Distribution
בדוגמה שבקטע הזה אפשר לראות איך לכתוב פונקציה למכשירי iOS של בודקים חדשים. ההתראות של המכשיר.
בדוגמה הזו, הפונקציה מאזינה לאירועים שנשלחים בכל פעם בודק רושם מכשיר iOS חדש. כשרושמים מכשיר iOS חדש, צריך לעדכן את פרופיל ההקצאה באמצעות ה-UDID של המכשיר הזה ואז להפיץ מחדש את האפליקציה.
Node.js
exports.postnewduuidtodiscord = onNewTesterIosDevicePublished(async (event) => {
Python
@app_distribution_fn.on_new_tester_ios_device_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_new_udid_to_discord(event: app_distribution_fn.NewTesterDeviceEvent) -> None:
"""Publishes a message to Discord whenever someone registers a new iOS test device."""
לאחר מכן הפונקציה מנתחת את האובייקט שהוחזר ומנתחת מידע שימושי מהאירוע. מטען ייעודי (payload) ויצירה של הודעה לפרסום בערוץ Discord:
Node.js
// construct a helpful message to send to Discord
const appId = event.appId;
const {
testerDeviceIdentifier,
testerDeviceModelName,
testerEmail,
testerName,
} = event.data.payload;
const message = `
📱 New iOS device registered by ${testerName} <${testerEmail}> for ${appId}
UDID **${testerDeviceIdentifier}** for ${testerDeviceModelName}
`;
Python
# Construct a helpful message to send to Discord.
app_id = event.app_id
app_dist = event.data.payload
message = f"""
📱 New iOS device registered by {app_dist.tester_name} <{app_dist.tester_email}> for {app_id}
UDID **{app_dist.tester_device_identifier}** for {app_dist.tester_device_model_name}
""".strip()
לבסוף, הפונקציה שולחת את ההודעה שנוצרה ל-Discord דרך קוד HTTP בקשה:
Node.js
const response = await postMessageToDiscord("AppDistribution Bot", message);
if (response.ok) {
logger.info(
`Posted iOS device registration alert for ${testerEmail} to Discord`,
);
} else {
throw new Error(response.error);
}
Python
response = post_message_to_discord("App Distro Bot", message, DISCORD_WEBHOOK_URL.value)
if response.ok:
print(f"Posted iOS device registration alert for {app_dist.tester_email} to Discord.")
pprint.pp(event.data.payload)
else:
response.raise_for_status()
כדי לקבל מידע על כל אירועי ההתראות של App Distribution שאפשר לתעד, צריך לעבור אל את מאמרי העזרה של App Distribution התראות.
כדי ללמוד איך להשתמש בפונקציה שמופעלת על ידי התראת Firebase לגבי משוב בתוך האפליקציה מאת App Distribution, ראו שליחת משוב בתוך האפליקציה ל-Jira.