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