ב-Firebase אפשר לקבל התראות על מגוון רחב של אירועים שקשורים לניהול פרויקטים ואפליקציות. הנה כמה דוגמאות לאירועים שבהם Firebase יכולה לשלוח לכם התראה מהסוג הזה:
- ב-Crashlytics, אנחנו יכולים להתריע אם יש עלייה דרמטית במספר הקריסות באפליקציה.
- ב-Performance Monitoring, אנחנו יכולים להתריע אם זמן ההפעלה של האפליקציה חורג מהסף שהגדרתם.
- ב-App Distribution, אנחנו יכולים להודיע לך אם אחד מהבודקים שלך רושם מכשיר iOS חדש.
בהתאם להתראה ולהעדפות שהגדירו חברי הפרויקט, Firebase מציג את סוגי ההתראות האלה בFirebaseמסוף או שולח אותן באימייל.
בדף הזה מוסבר איך לכתוב פונקציות ב-Cloud Functions for Firebase (דור שני) שמטפלות באירועי התראות.
איך זה עובד?
אפשר להפעיל פונקציות בתגובה לאירועי התראות שנוצרו על ידי המקורות הבאים:
- טיפול באירוע התראה של App Distribution
- טיפול באירוע התראה של Crashlytics
- טיפול באירוע התראה של Performance Monitoring
במחזור חיים אופייני, פונקציה שמופעלת על ידי אירוע התראה מבצעת את הפעולות הבאות:
- האזנה/המתנה לסוג ספציפי של התראה שתישלח מ-Firebase.
- מופעל כשההתראה נשלחת, ומקבל את המטען הייעודי (payload) של האירוע שמכיל מידע ספציפי על האירוע.
- מפעיל את קוד הפונקציה כדי לטפל במטען הייעודי (payload) של האירוע.
הפעלת פונקציה באירועי התראה
משתמשים בחבילת המשנה 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."""
לאחר מכן הפונקציה מנתחת את אובייקט האירוע שהוחזר, מנתחת מידע שימושי מהמטען הייעודי (payload) של האירוע ויוצרת הודעה לפרסום בערוץ 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(`Discord returned status code ${response.status}`);
}
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(`Discord returned status code ${response.status}`);
}
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(`Discord returned status code ${response.status}`);
}
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.
במאמר שליחת משוב מתוך האפליקציה ל-Jira מוסבר איך להשתמש בפונקציה שמופעלת על ידי התראה של Firebase על משוב מתוך האפליקציה מ-App Distribution.