-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
179 lines (144 loc) · 6.37 KB
/
server.py
File metadata and controls
179 lines (144 loc) · 6.37 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
# mypy: ignore-errors
from __future__ import annotations
import asyncio
import time
from typing import TYPE_CHECKING
import grpc
import structlog
from grpc_reflection.v1alpha import reflection
from .protos import price_feed_pb2, price_feed_pb2_grpc # type: ignore
if TYPE_CHECKING:
from collections.abc import AsyncGenerator
from redis.asyncio import Redis
logger = structlog.get_logger()
class PriceFeedServicer(price_feed_pb2_grpc.PriceFeedServicer):
def __init__(self, redis_client: Redis) -> None:
self.redis = redis_client
async def GetPrice(
self, request: price_feed_pb2.PriceRequest, context: grpc.aio.ServicerContext
) -> price_feed_pb2.PriceResponse:
pair = request.pair.upper()
if not pair:
await context.abort(grpc.StatusCode.INVALID_ARGUMENT, "Pair cannot be empty")
key = f"price:{pair}"
price_str = await self.redis.get(key)
if not price_str:
await context.abort(grpc.StatusCode.NOT_FOUND, f"Price not found for {pair}")
try:
price = float(price_str)
timestamp = int(time.time() * 1000)
return price_feed_pb2.PriceResponse(pair=pair, price=price, timestamp=timestamp)
except ValueError:
logger.error("Invalid price data in redis", pair=pair, value=price_str)
await context.abort(grpc.StatusCode.INTERNAL, "Invalid price data")
async def GetPrices(
self, request: price_feed_pb2.PricesRequest, _context: grpc.aio.ServicerContext
) -> price_feed_pb2.PricesResponse:
pairs = [p.upper() for p in request.pairs if p.strip()]
if not pairs:
return price_feed_pb2.PricesResponse(prices=[])
keys = [f"price:{p}" for p in pairs]
values = await self.redis.mget(keys)
responses = []
now = int(time.time() * 1000)
for i, val in enumerate(values):
if val is not None:
try:
price = float(val)
responses.append(
price_feed_pb2.PriceResponse(pair=pairs[i], price=price, timestamp=now)
)
except ValueError:
logger.warning("Skipping invalid price data", pair=pairs[i], value=val)
continue
return price_feed_pb2.PricesResponse(prices=responses)
async def SubscribePrice(
self, request: price_feed_pb2.SubscribeRequest, _context: grpc.aio.ServicerContext
) -> AsyncGenerator[price_feed_pb2.PriceUpdate, None]:
pair = request.pair.upper()
key = f"price:{pair}"
last_price = None
while True:
price_str = await self.redis.get(key)
if price_str:
try:
price = float(price_str)
if price != last_price:
last_price = price
yield price_feed_pb2.PriceUpdate(
pair=pair, price=price, timestamp=int(time.time() * 1000)
)
except ValueError:
logger.warning("Invalid price data in stream", pair=pair, value=price_str)
await asyncio.sleep(0.1)
async def SubscribeAll(
self, _request: price_feed_pb2.Empty, _context: grpc.aio.ServicerContext
) -> AsyncGenerator[price_feed_pb2.PriceUpdate, None]:
last_prices: dict[str, float] = {}
while True:
keys: list[str] = []
async for key in self.redis.scan_iter(match="price:*", count=100):
keys.append(key)
if keys:
values = await self.redis.mget(keys)
now = int(time.time() * 1000)
for i, key in enumerate(keys):
pair = key.split(":", 1)[1]
val = values[i]
if val is not None:
try:
price = float(val)
if last_prices.get(pair) != price:
last_prices[pair] = price
yield price_feed_pb2.PriceUpdate(
pair=pair, price=price, timestamp=now
)
except ValueError:
logger.warning("Invalid price data in stream", pair=pair, value=val)
await asyncio.sleep(1.0)
async def HealthCheck(
self, _request: price_feed_pb2.Empty, _context: grpc.aio.ServicerContext
) -> price_feed_pb2.HealthResponse:
try:
await self.redis.ping()
return price_feed_pb2.HealthResponse(
status=price_feed_pb2.HealthResponse.SERVING, message="Redis connection active"
)
except Exception as e:
logger.error("Health check failed", error=str(e))
return price_feed_pb2.HealthResponse(
status=price_feed_pb2.HealthResponse.NOT_SERVING,
message="Service dependency unavailable",
)
async def serve_grpc(
redis_client: Redis,
port: int,
ssl_key_path: str | None = None,
ssl_cert_path: str | None = None,
) -> grpc.aio.Server:
server = grpc.aio.server()
price_feed_pb2_grpc.add_PriceFeedServicer_to_server(PriceFeedServicer(redis_client), server)
service_names = (
price_feed_pb2.DESCRIPTOR.services_by_name["PriceFeed"].full_name,
reflection.SERVICE_NAME,
)
reflection.enable_server_reflection(service_names, server)
listen_addr = f"[::]:{port}"
if bool(ssl_key_path) != bool(ssl_cert_path):
missing = "ssl_cert_path" if ssl_key_path else "ssl_key_path"
raise ValueError(
f"Both ssl_key_path and ssl_cert_path must be provided for TLS, "
f"or neither. Missing: {missing}"
)
if ssl_key_path and ssl_cert_path:
with open(ssl_key_path, "rb") as key_file, open(ssl_cert_path, "rb") as cert_file:
private_key = key_file.read()
certificate = cert_file.read()
credentials = grpc.ssl_server_credentials([(private_key, certificate)])
server.add_secure_port(listen_addr, credentials)
logger.info("Starting gRPC server with TLS", address=listen_addr)
else:
server.add_insecure_port(listen_addr)
logger.info("Starting gRPC server (insecure)", address=listen_addr)
await server.start()
return server