From 4ddb1fbe583b7d9d4271b8474545fad3c6b45b1e Mon Sep 17 00:00:00 2001 From: Grant Limberg Date: Tue, 2 Sep 2025 07:49:41 -0700 Subject: [PATCH] Create the pubsub topic if it doesn't exist --- nonfree/controller/PubSubListener.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/nonfree/controller/PubSubListener.cpp b/nonfree/controller/PubSubListener.cpp index 72905a77a..8c6b48e4a 100644 --- a/nonfree/controller/PubSubListener.cpp +++ b/nonfree/controller/PubSubListener.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -34,6 +35,29 @@ PubSubListener::PubSubListener(std::string controller_id, std::string project, s { GOOGLE_PROTOBUF_VERIFY_VERSION; + // Create Topic if it doesn't exist + // this is only really needed for testing with the emulator + // in production the topic should be created via terraform or gcloud + // before starting the controller + auto topicAdminClient = pubsub_admin::TopicAdminClient(pubsub_admin::MakeTopicAdminConnection()); + auto topicName = pubsub::Topic(project, topic).FullName(); + auto topicResult = topicAdminClient.GetTopic(topicName); + if (! topicResult.ok()) { + // Only create if not found + if (topicResult.status().code() == google::cloud::StatusCode::kNotFound) { + auto createResult = topicAdminClient.CreateTopic(topicName); + if (! createResult.ok()) { + fprintf(stderr, "Failed to create topic: %s\n", createResult.status().message().c_str()); + throw std::runtime_error("Failed to create topic"); + } + fprintf(stderr, "Created topic: %s\n", topicName.c_str()); + } + else { + fprintf(stderr, "Failed to get topic: %s\n", topicResult.status().message().c_str()); + throw std::runtime_error("Failed to get topic"); + } + } + google::pubsub::v1::Subscription request; request.set_name(_subscription.FullName()); request.set_topic(pubsub::Topic(project, topic).FullName());