You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Pubsub长期运行后触发16 UNAUTHENTICATED认证错误求助

Google Pubsub 长时间运行后随机出现认证失败问题求助

服务器启动时服务正常,但运行较长时间(一天及以上)后,会随机出现如下错误:

Error: 16 UNAUTHENTICATED: Failed to retrieve auth metadata with error: request to https://www.googleapis.com/oauth2/v4/token failed, reason: getaddrinfo ENOTFOUND www.googleapis.com
    at Object.callErrorFromStatus ~\<project_path>\node_modules\@grpc\grpc-js\src\call.ts:81:24)
    at Object.onReceiveStatus (~\<project_path>\node_modules\@grpc\grpc-js\src\client.ts:338:36)
    at Object.onReceiveStatus (~\<project_path>\node_modules\@grpc\grpc-js\src\client-interceptors.ts:426:34)
    at Object.onReceiveStatus (~\<project_path>\node_modules\@grpc\grpc-js\src\client-interceptors.ts:389:48)
    at ~\<project_path>\node_modules\@grpc\grpc-js\src\call-stream.ts:276:24
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
[ERROR] 08:21:29 Error: 16 UNAUTHENTICATED: Failed to retrieve auth metadata with error: request to https://www.googleapis.com/oauth2/v4/token failed, reason: getaddrinfo ENOTFOUND www.googleapis.com

如果是凭证问题,启动时就该报错,但这个错误是随机触发的,排查难度很大。有没有人遇到过类似问题?

我持有Google开发者控制台生成的OAuth凭证文件,包含以下字段:type、project_id、private_key_id、private_key、client_email、client_id、auth_uri、token_uri、auth_provider_x509_cert_url、client_x509_cert_url。目前仅使用了project_id、private_key、client_email三个字段,是否需要用到其他字段才能解决问题?我曾按照google pubsub包的文档直接链接凭证文件(未使用.env变量),但错误依旧出现。我猜测可能是OAuth刷新token的有效期问题(约几天),导致未获取到刷新token进而触发认证失败,这只是我的推测,恳请大家提供帮助。

以下是我的服务访问代码:

package.json 依赖片段

"@axelspringer/graphql-google-pubsub": "^2.1.0",
"googleapis": "^92.0.0",
"express": "^4.17.1",
"express-serve-static-core": "^0.1.1",
"cors": "^2.8.5",
"cookie-parser": "^1.4.5",
"apollo-server": "^3.5.0",
"apollo-server-core": "^3.5.0",
"apollo-server-express": "^3.5.0",
"graphql-tools": "^7.0.2",
"subscriptions-transport-ws": "^0.11.0",

src/index.ts 核心代码

import { GooglePubSub } from "@axelspringer/graphql-google-pubsub";
const express = require("express");
const cookies = require("cookie-parser");
import cors from "cors";
import { createServer } from "http";
import { makeExecutableSchema } from "@graphql-tools/schema";
import { ApolloServer } from "apollo-server-express";
import {
  ApolloServerPluginLandingPageGraphQLPlayground,
  ApolloServerPluginLandingPageDisabled,
} from "apollo-server-core";
import {
  ConnectionContext,
  ConnectionParams,
  SubscriptionServer,
} from "subscriptions-transport-ws";

const pubSubOptions = {projectId: <GOOGLE project_id>, credentials: {client_email: <GOOGLE client_email>, private_key: <GOOGLE private_key>} }

const pubsub = new GooglePubSub(pubSubOptions);

const context = async ({ req, res, connection }: MyContext) => {
  const msgHeader = connection ? connection.context : req;
  return {
    req,
    res,
    pubsub,
  };
};

(async function () {
  const app = express();
  app.use(cors());
  const httpServer = createServer(app);

  const schema = makeExecutableSchema({
    typeDefs,
    resolvers,
  });

  const server = new ApolloServer({
    schema,
    context,
    plugins: [
      process.env.NODE_ENV === "development"
        ? ApolloServerPluginLandingPageGraphQLPlayground()
        : ApolloServerPluginLandingPageDisabled(),
      {
        async serverWillStart() {
          return {
            async drainServer() {
              subscriptionServer.close();
            },
          };
        },
      },
    ],
  });

  const subscriptionServer = SubscriptionServer.create(
    {
      schema,
      execute,
      subscribe,
      onConnect: (
        connectionParams: ConnectionParams,
        webSocket: WebSocket,
        ConnectionContext: ConnectionContext
      ) => {
        const context: any = {
          pubsub,
        };

        return context;
      },
    },
    { server: httpServer, path: server.graphqlPath }
  );

  await server.start();
  app.use(cookies());
  server.applyMiddleware({ app });

  const dbUri = db_url();

  try {
    await mongoose.connect(dbUri, configs.MONGO_OPTIONS);
  } catch (err) {
    if (err instanceof Error) {
      throw new Error(err.message);
    }
    process.exit(1);
  }

  httpServer.listen(PORT, () =>
    console.log(
      `🚀 Server ready at ${configs.apiURL}:${PORT}${server.graphqlPath}`
    )
  );
})();

内容的提问来源于stack exchange,提问作者Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 02:18:19