blob: 86bd3bae5f04352b9907132ba70516be9988e758 [file] [log] [blame]
Copybara854996b2021-09-07 19:36:02 +00001# Copyright 2019 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style
3# license that can be found in the LICENSE file or at
4# https://developers.google.com/open-source/licenses/bsd
5
6"""Task handlers for publishing issue updates onto a pub/sub topic.
7
8The pub/sub topic name is: `projects/{project-id}/topics/issue-updates`.
9"""
10from __future__ import print_function
11from __future__ import division
12from __future__ import absolute_import
13
14import httplib2
15import logging
16import sys
17
18import settings
19
20from googleapiclient.discovery import build
21from apiclient.errors import Error as ApiClientError
22from oauth2client.client import GoogleCredentials
23from oauth2client.client import Error as Oauth2ClientError
24
25from framework import exceptions
26from framework import jsonfeed
27
28
Adrià Vilanova Martínezde942802022-07-15 14:06:55 +020029# TODO: change to FlaskInternalTask when convert to flask
Copybara854996b2021-09-07 19:36:02 +000030class PublishPubsubIssueChangeTask(jsonfeed.InternalTask):
31 """JSON servlet that pushes issue update messages onto a pub/sub topic."""
32
33 def HandleRequest(self, mr):
34 """Push a message onto a pub/sub queue.
35
36 Args:
37 mr: common information parsed from the HTTP request.
38 Returns:
39 A dictionary. If an error occurred, the 'error' field will be a string
40 containing the error message.
41 """
42 pubsub_client = set_up_pubsub_api()
43 if not pubsub_client:
44 return {
45 'error': 'Pub/Sub API init failure.',
46 }
47
48 issue_id = mr.GetPositiveIntParam('issue_id')
49 if not issue_id:
50 return {
51 'error': 'Cannot proceed without a valid issue ID.',
52 }
53 try:
54 issue = self.services.issue.GetIssue(mr.cnxn, issue_id, use_cache=False)
55 except exceptions.NoSuchIssueException:
56 return {
57 'error': 'Could not find issue with ID %s' % issue_id,
58 }
59
60 pubsub_client.projects().topics().publish(
61 topic=settings.pubsub_topic_id,
62 body={
63 'messages': [{
64 'attributes': {
65 'local_id': str(issue.local_id),
66 'project_name': str(issue.project_name),
67 },
68 }],
69 },
70 ).execute()
71
72 return {}
73
Adrià Vilanova Martínezde942802022-07-15 14:06:55 +020074 # def GetPublishPubsubIssueChangeTask(self, **kwargs):
75 # return self.handler(**kwargs)
76
77 # def PostPublishPubsubIssueChangeTask(self, **kwargs):
78 # return self.handler(**kwargs)
79
Copybara854996b2021-09-07 19:36:02 +000080
81def set_up_pubsub_api():
82 """Attempts to build and return a pub/sub API client."""
83 try:
84 return build('pubsub', 'v1', http=httplib2.Http(),
85 credentials=GoogleCredentials.get_application_default())
86 except (Oauth2ClientError, ApiClientError):
87 logging.error("Error setting up Pub/Sub API: %s" % sys.exc_info()[0])
88 return None