javascript - 使用 Firebase admin sdk 和云功能的 FCM 错误

标签 javascript firebase firebase-cloud-messaging google-cloud-functions firebase-admin

反复出现这个错误。错误#1

    { Error: fcm.googleapis.com network timeout. Please try again.
    at FirebaseAppError.Error (native)
    at FirebaseAppError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28)
    at new FirebaseAppError (/user_code/node_modules/firebase-admin/lib/utils/error.js:70:23)
    at TLSSocket.<anonymous> (/user_code/node_modules/firebase-admin/lib/utils/api-request.js:106:51)
    at emitNone (events.js:86:13)
    at TLSSocket.emit (events.js:185:7)
    at TLSSocket.Socket._onTimeout (net.js:339:8)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)
  errorInfo: 
   { code: 'app/network-timeout',
     message: 'fcm.googleapis.com network timeout. Please try again.' } }

我有时会遇到另一个错误。错误 #2

 { Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "read ECONNRESET".
    at FirebaseAppError.Error (native)
    at FirebaseAppError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28)
    at new FirebaseAppError (/user_code/node_modules/firebase-admin/lib/utils/error.js:70:23)
    at /user_code/node_modules/firebase-admin/lib/firebase-app.js:106:23
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)
  errorInfo: 
   { code: 'app/invalid-credential',
     message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "read ECONNRESET".' } }

另一种类型。错误 #3

Error sending message: { Error: A network request error has occurred: read ECONNRESET
    at FirebaseAppError.Error (native)
    at FirebaseAppError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28)
    at new FirebaseAppError (/user_code/node_modules/firebase-admin/lib/utils/error.js:70:23)
    at ClientRequest.<anonymous> (/user_code/node_modules/firebase-admin/lib/utils/api-request.js:115:43)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at emitErrorNT (net.js:1276:8)
  errorInfo: 
   { code: 'app/network-error',
     message: 'A network request error has occurred: read ECONNRESET' } }

我尝试用我的云功能做的是检查用户详细信息,基于价格匹配发送 FCM 消息。云函数是一个数据库触发器。这是我的云功能的代码。我在代码中没有看到任何问题,因为我正在使用 promises。

// Checks price alerts for users
exports.priceAlertCheck = functions.database.ref('/crons/alerts/price').onWrite(event => {
  const promises = [];
  admin.database().ref(`/alerts/price`).once('value', function(alertSnapshot) {
    alertSnapshot.forEach(function(dataSnapshot) {
      promises.push(createPriceAlertPromise(dataSnapshot));
    });
  });
  return Promise.all(promises);
});

function createPriceUrl(fromCurrency, toCurrency, exchange) {
  return 'https://zzzz.com/data/price?fsym='
          +fromCurrency+'&tsyms='+toCurrency+(exchange ? '&e='+exchange : '');
}

function createPriceAlertPromise(snapshot) {
  const comboKeyArray = snapshot.key.split('-');
  const fromCurrency = comboKeyArray[0];
  const toCurrency = comboKeyArray[1];
  const exchange = comboKeyArray[2];
  return request(createPriceUrl(fromCurrency, toCurrency, exchange), function (error, response, body) {
      if (!error && response.statusCode == 200) {
        const jsonobj = JSON.parse(response.body);
        const currentPrice = jsonobj[toCurrency];
        const promises = [];

        snapshot.forEach(function(data) {
            promises.push(sendAlertNotifications(snapshot.key, data.key, currentPrice));
        });
        return Promise.all(promises);
      } else {
        console.log('Error fetching price', snapshot.key);
      }
  });
}

function sendAlertNotifications(comboKey, userId, currentPrice) {
  const getUserPromise = admin.database()
                          .ref(`/users/${userId}`)
                          .once('value');
  const getUserPriceAlertsPromise = admin.database()
                          .ref(`/user_alerts/price/${userId}`)
                          .once('value');
  return Promise.all([getUserPromise, getUserPriceAlertsPromise]).then(results => {
    const userSnapshot = results[0];
    if(!userSnapshot.val()){
      return console.log('Not user details', userId)
    }
    const instanceId = userSnapshot.val().instanceId;
    const subscriptionStatus = userSnapshot.val().subscriptionStatus;
    const priceAlertSnapshot = results[1];
    if(subscriptionStatus != 1){
      return console.log('Not Sending alerts. Subscription Expired', userId);
    }
    // Check if there are any device tokens.
    if (!priceAlertSnapshot.hasChildren()) {
      return console.log('There are no alerts to send for', comboKey, ", userId:", userId);
    }
    console.log("Alerts of users fetched for ", comboKey, " : ", priceAlertSnapshot.numChildren(), ", userId:", userId);
    const promises = [];
    priceAlertSnapshot.forEach(function(dataSnapshot) {
        promises.push(sendAlertNotification(userId, instanceId, currentPrice, dataSnapshot));
    });
    return Promise.all(promises);
  })
  .catch(error => {
    console.log("Error getting user alert details:", error, ", userId:", userId);
  });
}

function sendAlertNotification(userId, instanceId, currentPrice, dataSnapshot) {
  const comboKey = dataSnapshot.val().name;
  const comboKeyArray = comboKey.split('-');
  const fromCurrency = comboKeyArray[0];
  const toCurrency = comboKeyArray[1];
  const exchange = comboKeyArray[2];
  const alertPrice = dataSnapshot.val().value;
  if(priceAlertConditionCheck(currentPrice, dataSnapshot)) {
    // Notification details.
    const payload = {
      notification: {
        title: `${fromCurrency} Price Alert`,
        body: "You have been notified",
        sound: 'default',
        tag: comboKey
      },
      data: {
        title: `${fromCurrency} Price Alert`,
        body: "You have been notified",
        name: comboKey,
        sound: 'default',
        type: "alert"
      }
    };
    // Set the message as high priority and have it expire after 24 hours.
    var options = {
      priority: "high",
      timeToLive: 60 * 10
    };

    return admin.messaging().sendToDevice(instanceId, payload, options).then(response => {
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error("Failure sending message:", error, " userId:", userId, " token:", instanceId);
        }
        console.log("Successfully sent message:", response, ", userId:", userId);
      });
    })
    .catch(error => {
      console.log("Error sending message:", error, " userId:", userId, " token:", instanceId);
    });
  }
  return;
}

目前数据很小,我仍然在 firebase 数据库中遇到 30% 的失败(10 到 15 条记录)。当有 10k 条记录时,这将如何工作?我怎样才能防止这些错误?此外,没有针对这些错误代码“app/”的文档,但仅针对“message/”错误。

更新#1:更新函数:

function createPriceAlertPromise(snapshot) {
  const comboKeyArray = snapshot.key.split('-');
  const fromCurrency = comboKeyArray[0];
  const toCurrency = comboKeyArray[1];
  const exchange = comboKeyArray[2];
  return rp(createPriceUrl(fromCurrency, toCurrency, exchange),
  {resolveWithFullResponse: true}).then(response => {
    if (response.statusCode === 200) {
      const jsonobj = JSON.parse(response.body);
      const currentPrice = jsonobj[toCurrency];
      const promises = [];

      snapshot.forEach(function(data) {
          promises.push(sendAlertNotifications(snapshot.key, data.key, currentPrice));
      });
      return Promise.all(promises);
    }
    throw response.body;
  }).catch(error => {
    console.log('Error fetching price', error);
  });
}

更新#2:将函数的超时时间增加到 540 秒,但仍然出现错误#1

更新#3:更新的功能:错误#1 现在消失了,但错误#3 仍然存在并且发生得更频繁

// Checks price alerts for users
exports.priceAlertCheck = functions.database.ref('/crons/alerts/price').onWrite(event => {
  return admin.database().ref(`/alerts/price`).once('value').then(alertSnapshot => {
    const promises = [];
    alertSnapshot.forEach(function(dataSnapshot) {
      promises.push(createPriceAlertPromise(dataSnapshot));
    });
    return Promise.all(promises).then(response => {
      return deleteFirebaseApp();
    })
    .catch(function(error) {
      return logError(error);
    });
  });
});
function createPriceAlertPromise(snapshot) {
  const comboKeyArray = snapshot.key.split('-');
  const fromCurrency = comboKeyArray[0];
  const toCurrency = comboKeyArray[1];
  const exchange = comboKeyArray[2];
  return rp(createPriceUrl(fromCurrency, toCurrency, exchange),
  {resolveWithFullResponse: true}).then(response => {
    if (response.statusCode === 200) {
      const jsonobj = JSON.parse(response.body);
      const currentPrice = jsonobj[toCurrency];

      const forEachPromise =  new Promise(function(resolve) {
        const promises = [];
        snapshot.forEach(function(data) {
          promises.push(sendAlertNotifications(snapshot.key, data.key, currentPrice));
        });
        resolve(promises);
      });

      forEachPromise.then(promises => {
        return Promise.all(promises);
      })
      .catch(error => {
        return reportError(error, { type: 'database_query', context: 'forEach'});
      });
    } else {
      throw response.body;
    }
  }).catch(error => {
    return reportError(error, { type: 'http_request', context: 'price fetching'});
  });
}

最佳答案

您的代码正在使用不处理 promise 的节点模块 request。在处理 Cloud Functions 时,通常更容易使用名为 request-promise 的模块包装器它会返回一个 promise,这样您就可以以一种更有用的方式对 HTTP 请求的结果使用react,以便在 Cloud Functions 中运行代码。

一旦您开始从您的函数返回有效 promise ,Cloud Functions 将等待这些请求完全完成,然后再进行清理。 ECONNRESET 错误是它在您的请求完成之前过早清理的症状。我在 Firebase blog post 中写了一点点最近。

关于javascript - 使用 Firebase admin sdk 和云功能的 FCM 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45004564/

相关文章:

javascript - 使具有圆边响应的 svg 路径

javascript - 在 Firebase 实时数据库中,signOut() 是否会自动调用 ref.off() ?

node.js - (..).then 不是函数,firebase 云函数

iOS - Firebase 过滤器查询

javascript - 如何将项目添加到 promise 之外的数组中

ios - 如何将 FCM token 发送到服务器?

javascript - 选项卡未处于焦点时的 Firebase 通知

javascript - 使用javascript/css将另一个div拖到它上面时如何使div的特定部分变灰

javascript - 将服务内的变量绑定(bind)到 Angular 应用程序中的 html 模板

javascript - 滑动到固定位置标题的内容