Repository navigation
Expand file tree
/
Copy pathpurchase_service.py
More file actions
342 lines (296 loc) · 12.5 KB
/
Copy pathpurchase_service.py
File metadata and controls
342 lines (296 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# Core purchase link service with caching and error handling
# Orchestrates multiple link generators and provides unified interface
import json
import time
import logging
from typing import Dict, List, Optional, Any
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import asdict
from .config import config, SUPPORTED_PLATFORMS, PlatformConfig
from .link_generators import get_all_generators, PurchaseLink
# Setup logging
logger = logging.getLogger(__name__)
class PurchaseLinkCache:
"""Simple in-memory cache for purchase links."""
def __init__(self, ttl: int = 3600):
self.cache: Dict[str, Dict[str, Any]] = {}
self.ttl = ttl
def _get_cache_key(self, title: str, author: str = "", isbn: str = "") -> str:
"""Generate cache key from book identifiers."""
return f"{title.lower().strip()}|{author.lower().strip()}|{isbn.strip()}"
def get(self, title: str, author: str = "", isbn: str = "") -> Optional[Dict[str, Any]]:
"""Get cached purchase links."""
key = self._get_cache_key(title, author, isbn)
if key not in self.cache:
return None
cached_data = self.cache[key]
# Check if cache is expired
if time.time() - cached_data['timestamp'] > self.ttl:
del self.cache[key]
return None
return cached_data['data']
def set(self, title: str, author: str = "", isbn: str = "", data: Dict[str, Any] = None):
"""Cache purchase links."""
key = self._get_cache_key(title, author, isbn)
self.cache[key] = {
'data': data,
'timestamp': time.time()
}
def clear(self):
"""Clear all cached data."""
self.cache.clear()
def size(self) -> int:
"""Get cache size."""
return len(self.cache)
class PurchaseLinkService:
"""
Production-grade service for generating book purchase links.
Supports multiple platforms with caching, error handling, and concurrent processing.
"""
def __init__(self):
self.generators = get_all_generators()
self.cache = PurchaseLinkCache(ttl=config.cache_ttl)
self.logger = logging.getLogger(__name__)
# Log available generators
available_platforms = list(self.generators.keys())
self.logger.info(f"Initialized with platforms: {available_platforms}")
def get_purchase_links(
self,
title: str,
author: str = "",
isbn: str = "",
platforms: Optional[List[str]] = None,
use_cache: bool = True
) -> Dict[str, Any]:
"""
Get purchase links for a book from multiple platforms.
Args:
title: Book title (required)
author: Book author (optional)
isbn: Book ISBN (optional, but recommended)
platforms: List of platforms to check (default: all available)
use_cache: Whether to use cached results (default: True)
Returns:
Dictionary with purchase links and metadata
"""
if not title.strip():
return {
'success': False,
'error': 'Book title is required',
'links': {},
'metadata': {}
}
# Check cache first
if use_cache:
try:
cached_result = self.cache.get(title, author, isbn)
if cached_result:
self.logger.info(f"Using cached purchase links for: {title}")
return cached_result
except KeyError as e:
self.logger.warning(f"Cache key error: {e}. Using fresh lookup.")
except Exception as e:
self.logger.error(f"Cache retrieval failed: {type(e).__name__}: {e}", exc_info=True)
# Continue with fresh lookup instead of failing
# Determine which platforms to check
if platforms is None:
platforms = list(self.generators.keys())
else:
# Filter to only available platforms
platforms = [p for p in platforms if p in self.generators]
if not platforms:
return {
'success': False,
'error': 'No valid platforms specified',
'links': {},
'metadata': {}
}
# Generate links concurrently
try:
links = self._generate_links_concurrent(title, author, isbn, platforms)
except Exception as e:
self.logger.error(f"Failed to generate purchase links: {type(e).__name__}: {e}", exc_info=True)
return {
'success': False,
'error': f'Failed to generate purchase links: {str(e)}',
'links': {},
'metadata': {}
}
# Prepare result
result = {
'success': True,
'links': links,
'metadata': {
'title': title,
'author': author,
'isbn': isbn,
'platforms_checked': platforms,
'platforms_available': [p for p, data in links.items() if data.get('available', False)],
'total_links': len([p for p, data in links.items() if data.get('available', False)]),
'generated_at': time.time(),
'cache_used': False
}
}
# Cache the result
if use_cache:
try:
self.cache.set(title, author, isbn, result)
except Exception as e:
self.logger.warning(f"Failed to cache result: {type(e).__name__}: {e}. Continuing without caching.")
return result
def _generate_links_concurrent(
self,
title: str,
author: str,
isbn: str,
platforms: List[str]
) -> Dict[str, Dict[str, Any]]:
"""Generate links from multiple platforms concurrently."""
links = {}
# Use ThreadPoolExecutor for concurrent generation
with ThreadPoolExecutor(max_workers=min(len(platforms), 4)) as executor:
# Submit tasks
future_to_platform = {
executor.submit(self._generate_single_link, platform, title, author, isbn): platform
for platform in platforms
}
# Collect results
for future in as_completed(future_to_platform):
platform = future_to_platform[future]
try:
link_data = future.result(timeout=config.request_timeout)
links[platform] = link_data
except Exception as e:
self.logger.error(f"Error generating {platform} link: {e}")
links[platform] = {
'available': False,
'error': str(e),
'platform_info': SUPPORTED_PLATFORMS.get(platform, {})
}
return links
def _generate_single_link(
self,
platform: str,
title: str,
author: str,
isbn: str
) -> Dict[str, Any]:
"""Generate a single purchase link for a platform."""
try:
generator = self.generators.get(platform)
if not generator:
platform_info = SUPPORTED_PLATFORMS.get(platform, PlatformConfig(
name='Unknown', icon='', color='', priority=999, always_available=False
))
return {
'available': False,
'error': f'Generator not available for platform: {platform}',
'platform_info': {
'name': platform_info.name,
'icon': platform_info.icon,
'color': platform_info.color,
'priority': platform_info.priority,
'always_available': platform_info.always_available
}
}
# Generate the link
purchase_link = generator.generate_link(title, author, isbn)
if not purchase_link:
platform_info = SUPPORTED_PLATFORMS.get(platform, PlatformConfig(
name='Unknown', icon='', color='', priority=999, always_available=False
))
return {
'available': False,
'error': 'No link generated',
'platform_info': {
'name': platform_info.name,
'icon': platform_info.icon,
'color': platform_info.color,
'priority': platform_info.priority,
'always_available': platform_info.always_available
}
}
# Convert to dictionary and add platform info
link_data = asdict(purchase_link)
platform_info = SUPPORTED_PLATFORMS.get(platform, PlatformConfig(
name='Unknown', icon='', color='', priority=999, always_available=False
))
link_data['platform_info'] = {
'name': platform_info.name,
'icon': platform_info.icon,
'color': platform_info.color,
'priority': platform_info.priority,
'always_available': platform_info.always_available
}
return link_data
except Exception as e:
self.logger.error(f"Error in {platform} link generation: {e}")
platform_info = SUPPORTED_PLATFORMS.get(platform, PlatformConfig(
name='Unknown', icon='', color='', priority=999, always_available=False
))
return {
'available': False,
'error': str(e),
'platform_info': {
'name': platform_info.name,
'icon': platform_info.icon,
'color': platform_info.color,
'priority': platform_info.priority,
'always_available': platform_info.always_available
}
}
def get_platform_status(self) -> Dict[str, Any]:
"""Get status of all supported platforms."""
status = {
'total_platforms': len(SUPPORTED_PLATFORMS),
'available_platforms': len(self.generators),
'platforms': {}
}
for platform_id, platform_info in SUPPORTED_PLATFORMS.items():
generator_available = platform_id in self.generators
status['platforms'][platform_id] = {
'name': platform_info.name,
'generator_available': generator_available,
'always_available': platform_info.always_available,
'priority': platform_info.priority,
'icon': platform_info.icon,
'color': platform_info.color
}
return status
def clear_cache(self):
"""Clear the purchase links cache."""
self.cache.clear()
self.logger.info("Purchase links cache cleared")
def get_cache_stats(self) -> Dict[str, Any]:
"""Get cache statistics."""
return {
'size': self.cache.size(),
'ttl': self.cache.ttl,
'hit_rate': 'Not implemented' # Could be added with counters
}
def health_check(self) -> Dict[str, Any]:
"""Perform health check on the service."""
try:
# Test with a known book
test_result = self.get_purchase_links(
title="The Great Gatsby",
author="F. Scott Fitzgerald",
platforms=['google_books'], # Use most reliable platform
use_cache=False
)
return {
'status': 'healthy',
'service': 'Purchase Links Service',
'version': '1.0.0',
'platforms_available': len(self.generators),
'cache_size': self.cache.size(),
'test_successful': test_result.get('success', False),
'timestamp': time.time()
}
except Exception as e:
self.logger.error(f"Health check failed: {e}")
return {
'status': 'unhealthy',
'error': str(e),
'timestamp': time.time()
}