absl::StatusOr GenerateAgentConnectionId()

in cpp/acs_agent_helper.cc [195:231]


absl::StatusOr<AgentConnectionId> GenerateAgentConnectionId(
    std::string channel_id, bool regional) {
  absl::StatusOr<AcsToken> AcsToken = ParseAcsToken(kAcsTokenEndpointGce);
  if (!AcsToken.ok()) {
    // If the token is not available from the GCE endpoint, try the GKE
    // endpoint.
    AcsToken = ParseAcsToken(kAcsTokenEndpointGke);
    if (!AcsToken.ok()) {
      return AcsToken.status();
    }
  }
  const std::string& zone = AcsToken->zone;
  // Deduce the location from the zone.
  // If regional is true, the location is the zone without the last two
  // characters. Otherwise, the location is the zone itself.
  // Example: zone: us-central1-a -> region: us-central1
  size_t last_hyphen_index = zone.find_last_of('-');
  if (last_hyphen_index == std::string::npos) {
    return absl::InternalError(
        absl::StrCat("Wrong format of zone from metadata service: ", zone));
  }
  std::string location = regional ? zone.substr(0, last_hyphen_index) : zone;
  std::string endpoint =
      absl::StrContainsIgnoreCase(location, "staging")
          ? absl::StrCat(location,
                         "-agentcommunication.sandbox.googleapis.com:443")
          : absl::StrCat(location, "-agentcommunication.googleapis.com:443");

  std::string resource_id =
      absl::StrFormat("projects/%s/zones/%s/instances/%s",
                      AcsToken->project_number, zone, AcsToken->instance_id);
  return AgentConnectionId{.token = std::move(AcsToken->token),
                           .resource_id = std::move(resource_id),
                           .channel_id = std::move(channel_id),
                           .endpoint = std::move(endpoint),
                           .regional = regional};
}