|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the 'License'); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an 'AS IS' BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""Creates API client for Bid Manager API.""" |
| 15 | + |
| 16 | +import logging |
| 17 | +import os |
| 18 | +import pathlib |
| 19 | + |
| 20 | +import smart_open |
| 21 | +import tenacity |
| 22 | +from garf_core import api_clients |
| 23 | +from google.oauth2 import service_account |
| 24 | +from google_auth_oauthlib.flow import InstalledAppFlow |
| 25 | +from googleapiclient.discovery import build |
| 26 | +from typing_extensions import override |
| 27 | + |
| 28 | +from garf_bid_manager import exceptions, query_editor |
| 29 | + |
| 30 | +_API_URL = 'https://doubleclickbidmanager.googleapis.com/' |
| 31 | +_DEFAULT_API_SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager'] |
| 32 | + |
| 33 | +_SERVICE_ACCOUNT_CREDENTIALS_FILE = str(pathlib.Path.home()) + 'dbm.json' |
| 34 | + |
| 35 | + |
| 36 | +class BidManagerApiClientError(exceptions.BidManagerApiError): |
| 37 | + """Bid Manager API client specific error.""" |
| 38 | + |
| 39 | + |
| 40 | +class BidManagerApiClient(api_clients.BaseClient): |
| 41 | + """Responsible for connecting to Bid Manager API.""" |
| 42 | + |
| 43 | + def __init__( |
| 44 | + self, |
| 45 | + api_version: str = 'v2', |
| 46 | + credentials_file: str | pathlib.Path = os.getenv( |
| 47 | + 'GARF_BID_MANAGER_CREDENTIALS_FILE', _SERVICE_ACCOUNT_CREDENTIALS_FILE |
| 48 | + ), |
| 49 | + ) -> None: |
| 50 | + """Initializes BidManagerApiClient.""" |
| 51 | + self.api_version = api_version |
| 52 | + self.credentials_file = credentials_file |
| 53 | + self._client = None |
| 54 | + self._credentials = None |
| 55 | + |
| 56 | + @property |
| 57 | + def credentials(self): |
| 58 | + if not self._credentials: |
| 59 | + self._credentials = self._get_oauth_credentials() |
| 60 | + return self._credentials |
| 61 | + |
| 62 | + @property |
| 63 | + def client(self): |
| 64 | + if self._client: |
| 65 | + return self._client |
| 66 | + return build( |
| 67 | + 'doubleclickbidmanager', |
| 68 | + self.api_version, |
| 69 | + discoveryServiceUrl=( |
| 70 | + f'{_API_URL}/$discovery/rest?version={self.api_version}' |
| 71 | + ), |
| 72 | + credentials=self.credentials, |
| 73 | + ) |
| 74 | + |
| 75 | + @override |
| 76 | + def get_response( |
| 77 | + self, request: query_editor.BidManagerApiQuery, **kwargs: str |
| 78 | + ) -> api_clients.GarfApiResponse: |
| 79 | + query = _build_request(request) |
| 80 | + query_response = self.client.queries().create(body=query).execute() |
| 81 | + report_response = ( |
| 82 | + self.client.queries() |
| 83 | + .run(queryId=query_response['queryId'], synchronous=False) |
| 84 | + .execute() |
| 85 | + ) |
| 86 | + query_id = report_response['key']['queryId'] |
| 87 | + report_id = report_response['key']['reportId'] |
| 88 | + logging.info( |
| 89 | + 'Query %s is running, report %s has been created and is ' |
| 90 | + 'currently being generated.', |
| 91 | + query_id, |
| 92 | + report_id, |
| 93 | + ) |
| 94 | + |
| 95 | + get_request = ( |
| 96 | + self.client.queries() |
| 97 | + .reports() |
| 98 | + .get( |
| 99 | + queryId=report_response['key']['queryId'], |
| 100 | + reportId=report_response['key']['reportId'], |
| 101 | + ) |
| 102 | + ) |
| 103 | + |
| 104 | + status = _check_if_report_is_done(get_request) |
| 105 | + |
| 106 | + logging.debug( |
| 107 | + 'Report %s generated successfully. Now downloading.', report_id |
| 108 | + ) |
| 109 | + with smart_open.open( |
| 110 | + status['metadata']['googleCloudStoragePath'], 'r', encoding='utf-8' |
| 111 | + ) as f: |
| 112 | + data = f.readlines() |
| 113 | + results = [] |
| 114 | + for row in data[1:]: |
| 115 | + if row := row.strip(): |
| 116 | + result = dict(zip(request.fields, row.split(','))) |
| 117 | + results.append(result) |
| 118 | + else: |
| 119 | + break |
| 120 | + return api_clients.GarfApiResponse(results=results) |
| 121 | + |
| 122 | + def _get_service_account_credentials(self): |
| 123 | + if pathlib.Path(self.credentials_file).is_file(): |
| 124 | + return service_account.Credentials.from_service_account_file( |
| 125 | + self.credentials_file, scopes=_DEFAULT_API_SCOPES |
| 126 | + ) |
| 127 | + raise BidManagerApiClientError( |
| 128 | + 'A service account key file could not be found at ' |
| 129 | + f'{self.credentials_file}.' |
| 130 | + ) |
| 131 | + |
| 132 | + def _get_oauth_credentials(self): |
| 133 | + if pathlib.Path(self.credentials_file).is_file(): |
| 134 | + return InstalledAppFlow.from_client_secrets_file( |
| 135 | + self.credentials_file, _DEFAULT_API_SCOPES |
| 136 | + ).run_local_server(port=8088) |
| 137 | + raise BidManagerApiClientError( |
| 138 | + f'Credentials file could not be found at {self.credentials_file}.' |
| 139 | + ) |
| 140 | + |
| 141 | + |
| 142 | +def _build_request(request: query_editor.BidManagerApiQuery): |
| 143 | + """Builds Bid Manager API query object from BidManagerApiQuery.""" |
| 144 | + metrics = [] |
| 145 | + group_bys = [] |
| 146 | + for field in request.fields: |
| 147 | + if field.startswith('METRIC'): |
| 148 | + metrics.append(field) |
| 149 | + elif field.startswith('FILTER'): |
| 150 | + group_bys.append(field) |
| 151 | + filters = [] |
| 152 | + data_range = None |
| 153 | + for field in request.filters: |
| 154 | + name, operator, value = field.split() |
| 155 | + if name.startswith('dataRange'): |
| 156 | + data_range = value |
| 157 | + else: |
| 158 | + filters.append({'type': name, 'value': value}) |
| 159 | + query = { |
| 160 | + 'metadata': { |
| 161 | + 'title': request.title or 'garf', |
| 162 | + 'format': 'CSV', |
| 163 | + }, |
| 164 | + 'params': { |
| 165 | + 'type': request.resource_name, |
| 166 | + 'groupBys': group_bys, |
| 167 | + 'filters': filters, |
| 168 | + }, |
| 169 | + 'schedule': {'frequency': 'ONE_TIME'}, |
| 170 | + } |
| 171 | + if metrics: |
| 172 | + query['params']['metrics'] = metrics |
| 173 | + if data_range: |
| 174 | + query['metadata']['dataRange'] = {'range': data_range} |
| 175 | + return query |
| 176 | + |
| 177 | + |
| 178 | +@tenacity.retry( |
| 179 | + stop=tenacity.stop_after_attempt(100), wait=tenacity.wait_exponential() |
| 180 | +) |
| 181 | +def _check_if_report_is_done(get_request) -> bool: |
| 182 | + status = get_request.execute() |
| 183 | + state = status.get('metadata').get('status').get('state') |
| 184 | + if state != 'DONE': |
| 185 | + logging.debug( |
| 186 | + 'Report %s it not ready, retrying...', status['key']['reportId'] |
| 187 | + ) |
| 188 | + raise Exception |
| 189 | + return status |
0 commit comments