配置Admin凭据后Firebase函数仍无法识别Pub/Sub模拟器
问题:Firebase Functions无法识别本地运行的Pub/Sub模拟器
我遇到了和Stack Overflow帖子《Firebase functions won't see pubsub emulator running locally》相同的问题。按照帖子里的解决方案配置管理员凭据后,仍然收到错误提示:"function ignored because the pubsub emulator does not exist or is not running"。
环境变量配置日志
以下日志可证明已配置GOOGLE_APPLICATION_CREDENTIALS等环境变量:
(venv) yccheok@Yans-MacBook-Pro functions % export PUBSUB_PROJECT_ID="YYY"; export PUBSUB_EMULATOR_HOST="localhost:8085"; export GOOGLE_APPLICATION_CREDENTIALS="/Users/yccheok/yocto/ZZZ/firebase/functions/YYY.json"; firebase emulators:start (node:4337) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead. (Use `node --trace-deprecation ...` to show where the warning was created) i emulators: Starting emulators: auth, functions, firestore, pubsub, storage ⚠ emulators: It seems that you are running multiple instances of the emulator suite for project YYY. This may result in unexpected behavior. ⚠ functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: database, hosting, dataconnect ⚠ functions: Your GOOGLE_APPLICATION_CREDENTIALS environment variable points to /Users/yccheok/yocto/ZZZ/firebase/functions/YYY.json. Non-emulated services will access production using these credentials. Be careful! i firestore: Firestore Emulator logging to firestore-debug.log ✔ firestore: Firestore Emulator UI websocket is running on 9150. i pubsub: Pub/Sub Emulator logging to pubsub-debug.log i ui: Emulator UI logging to ui-debug.log i functions: Watching "/Users/yccheok/yocto/ZZZ/firebase/functions" for Cloud Functions... * Serving Flask app 'serving' * Debug mode: off WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:8081 Press CTRL+C to quit 127.0.0.1 - - [03/Sep/2024 14:50:12] "GET /__/functions.yaml HTTP/1.1" 200 - 127.0.0.1 - - [03/Sep/2024 14:50:12] "GET /__/quitquitquit HTTP/1.1" 200 - /bin/sh: line 1: 4426 Terminated: 15 python3.12 "/Users/yccheok/yocto/ZZZ/firebase/functions/venv/lib/python3.12/site-packages/firebase_functions/private/serving.py" ✔ functions: Loaded functions definitions from source: cloud_storage_trigger, on_request_example, simple_youtube_trigger, youtube_request. ✔ functions[us-central1-cloud_storage_trigger]: storage function initialized. ✔ functions[us-central1-on_request_example]: http function initialized (http://127.0.0.1:5001/YYY/us-central1/on_request_example). i functions[us-central1-simple_youtube_trigger]: function ignored because the pubsub emulator does not exist or is not running. ✔ functions[us-central1-youtube_request]: http function initialized (http://127.0.0.1:5001/YYY/us-central1/youtube_request). ┌─────────────────────────────────────────────────────────────┐ │ ✔ All emulators ready! It is now safe to connect your app. │ │ i View Emulator UI at http://127.0.0.1:4000/ │ └─────────────────────────────────────────────────────────────┘ ┌────────────────┬────────────────┬─────────────────────────────────┐ │ Emulator │ Host:Port │ View in Emulator UI │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Functions │ 127.0.0.1:5001 │ http://127.0.0.1:4000/functions │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Firestore │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Pub/Sub │ 127.0.0.1:8085 │ n/a │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Storage │ 127.0.0.1:9199 │ http://127.0.0.1:4000/storage │ └────────────────┴────────────────┴─────────────────────────────────┘ Emulator Hub running at 127.0.0.1:4400 Other reserved ports: 4500, 9150 Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.
函数代码(main.py)
@https_fn.on_request( cors = options.CorsOptions( cors_origins = ["*"], cors_methods = ["POST"], ) ) def youtube_request(req: https_fn.Request) -> https_fn.Response: # Check if the request method is POST if req.method != 'POST': return https_fn.Response(json.dumps({"error": "Only POST requests are allowed"}), status=405) # Extract data from the request request_json = req.get_json(silent=True) if request_json and 'uid' in request_json: uid = request_json['uid'] doc_id = request_json.get('doc_id') filename = request_json.get('filename') language = request_json.get('language') else: return https_fn.Response(json.dumps({"error": "Invalid request data"}), status=400) publisher = pubsub_v1.PublisherClient() # Publish message to Pub/Sub project_id = "XXX" topic_id = "youtube" topic_path = publisher.topic_path(project_id, topic_id) # List all topics in the project topics = list(publisher.list_topics(request={"project": f"projects/{project_id}"})) # Check if the test topic exists youtube_topic = next((topic for topic in topics if topic.name.endswith(f'topics/{topic_id}')), None) # If the topic doesn't exist, create it if not youtube_topic: topic = publisher.create_topic(name=topic_path) print(f"Created topic: {topic.name}") else: print(f"Topic already exists: {youtube_topic.name}") message_data = { "uid": uid, "doc_id": doc_id, "filename": filename, "language": language } data_str = json.dumps(message_data).encode("utf-8") try: future = publisher.publish(topic_path, data=data_str) message_id = future.result() return https_fn.Response(json.dumps({"message": "Message published", "message_id": message_id}), status=200) except Exception as e: return https_fn.Response(json.dumps({"error": f"An error occurred: {str(e)}"}), status=500) @pubsub_fn.on_message_published( topic = "youtube", timeout_sec = 540, memory = options.MemoryOption.GB_32 ) def youtube_trigger(event: pubsub_fn.CloudEvent[pubsub_fn.MessagePublishedData]) -> None: print("!!! youtube_trigger runs for the first-time !!!")
消息发布测试结果
已确认消息可正常发布:
curl http://127.0.0.1:5001/XXX/us-central1/youtube_request \ -X POST \ -H "Content-Type:application/json" \ -d '{ "uid": "123", "doc_id": "456", "filename": "https://youtu.be/YYY", "language": "en" }' {"message": "Message published", "message_id": "1"}
已尝试的其他步骤
猜测Firebase自带的Pub/Sub模拟器存在问题,因此尝试替换为Google Cloud Pub/Sub模拟器,步骤如下:
firebase emulators:start --only firestore,functions,auth,storage,uigcloud beta emulators pubsub start --project=XXX
但依然收到相同错误提示:
function ignored because the pubsub emulator does not exist or is not running.
可确认Pub/Sub模拟器处于运行状态,消息可正常发布,但订阅函数无法执行。似乎Pub/Sub模拟器已运行,但Functions模拟器无法发现它?
请问有什么解决建议吗?谢谢!
内容的提问来源于stack exchange,提问作者Cheok Yan Cheng
相关产品推荐
相关产品推荐

