h7-shared 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- h7_shared/__init__.py +28 -0
- h7_shared/price_protocol.py +441 -0
- h7_shared/wallet_protocol.py +520 -0
- h7_shared/wallet_transport.py +392 -0
- h7_shared-0.1.0.dist-info/METADATA +103 -0
- h7_shared-0.1.0.dist-info/RECORD +8 -0
- h7_shared-0.1.0.dist-info/WHEEL +5 -0
- h7_shared-0.1.0.dist-info/top_level.txt +1 -0
h7_shared/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Shared protocols for Hash7: wallet, transport, price."""
|
|
2
|
+
|
|
3
|
+
from .wallet_protocol import (
|
|
4
|
+
WalletKey, WalletCache, Config, GatewayError,
|
|
5
|
+
SNAPSHOT_VERSION, namespace, proxy_routes, number, normalize_bybit, BybitWallet,
|
|
6
|
+
)
|
|
7
|
+
from .wallet_transport import (
|
|
8
|
+
ExchangeWallet, wallet_type, amount, empty, put, normalize,
|
|
9
|
+
SPOT_EXCHANGES, FUTURES_EXCHANGES,
|
|
10
|
+
)
|
|
11
|
+
from .price_protocol import (
|
|
12
|
+
PriceCache, PriceKey, PriceType, MarketKind, Config as PriceConfig,
|
|
13
|
+
transport_for_exchange, PublicPriceTransport, BybitPublicTransport, BinancePublicTransport,
|
|
14
|
+
namespace as price_namespace, proxy_routes as price_proxy_routes,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
# wallet_protocol
|
|
19
|
+
'WalletKey', 'WalletCache', 'Config', 'GatewayError',
|
|
20
|
+
'SNAPSHOT_VERSION', 'namespace', 'proxy_routes', 'number', 'normalize_bybit', 'BybitWallet',
|
|
21
|
+
# wallet_transport
|
|
22
|
+
'ExchangeWallet', 'wallet_type', 'amount', 'empty', 'put', 'normalize',
|
|
23
|
+
'SPOT_EXCHANGES', 'FUTURES_EXCHANGES',
|
|
24
|
+
# price_protocol
|
|
25
|
+
'PriceCache', 'PriceKey', 'PriceType', 'MarketKind', 'PriceConfig',
|
|
26
|
+
'transport_for_exchange', 'PublicPriceTransport', 'BybitPublicTransport', 'BinancePublicTransport',
|
|
27
|
+
'price_namespace', 'price_proxy_routes',
|
|
28
|
+
]
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
"""Public quote observations and admission shared by the API and engine."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from decimal import Decimal, InvalidOperation
|
|
12
|
+
from enum import Enum
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
import aiohttp
|
|
16
|
+
from yarl import URL
|
|
17
|
+
|
|
18
|
+
from .wallet_protocol import _ADMIT, _PAUSE, _UNQUEUE
|
|
19
|
+
|
|
20
|
+
SNAPSHOT_VERSION = 2
|
|
21
|
+
SUPPORTED_EXCHANGES = frozenset(('bybit', 'binance'))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PriceType(str, Enum):
|
|
25
|
+
LAST = 'last'
|
|
26
|
+
MARK = 'mark'
|
|
27
|
+
INDEX = 'index'
|
|
28
|
+
BID = 'bid'
|
|
29
|
+
ASK = 'ask'
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MarketKind(str, Enum):
|
|
33
|
+
SPOT = 'spot'
|
|
34
|
+
LINEAR = 'linear'
|
|
35
|
+
INVERSE = 'inverse'
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class GatewayError(Exception):
|
|
39
|
+
def __init__(self, status=503, code='DETAILS_EXCHANGE_UNAVAILABLE', retry_after=None, scope='exchange'):
|
|
40
|
+
self.status, self.code, self.retry_after, self.scope = status, code, retry_after, scope
|
|
41
|
+
super().__init__(code)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def number(value):
|
|
45
|
+
result = Decimal(str(value))
|
|
46
|
+
if not result.is_finite() or result <= 0:
|
|
47
|
+
raise ValueError('Price must be positive and finite')
|
|
48
|
+
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class PriceKey:
|
|
53
|
+
exchange_code: str
|
|
54
|
+
market_kind: MarketKind
|
|
55
|
+
settlement: str
|
|
56
|
+
symbol: str
|
|
57
|
+
price_type: PriceType = PriceType.LAST
|
|
58
|
+
source_kind: str = 'public_rest'
|
|
59
|
+
is_testnet: bool = False
|
|
60
|
+
|
|
61
|
+
def __post_init__(self):
|
|
62
|
+
object.__setattr__(self, 'exchange_code', self.exchange_code.lower())
|
|
63
|
+
object.__setattr__(self, 'market_kind', MarketKind(self.market_kind))
|
|
64
|
+
object.__setattr__(self, 'price_type', PriceType(self.price_type))
|
|
65
|
+
object.__setattr__(self, 'settlement', self.settlement.upper())
|
|
66
|
+
symbol = self.symbol.upper()
|
|
67
|
+
if '/' in symbol:
|
|
68
|
+
base, quote = symbol.split('/', 1)
|
|
69
|
+
quote = quote.split(':', 1)[0]
|
|
70
|
+
# USDC perpetual IDs on Bybit must come from the instrument registry.
|
|
71
|
+
if self.exchange_code == 'bybit' and quote == 'USDC' and self.market_kind != MarketKind.SPOT:
|
|
72
|
+
raise ValueError('Native Bybit USDC instrument ID is required')
|
|
73
|
+
symbol = base + quote
|
|
74
|
+
if not re.fullmatch(r'[A-Z0-9._-]{1,100}', symbol):
|
|
75
|
+
raise ValueError('Invalid instrument ID')
|
|
76
|
+
if self.source_kind != 'public_rest':
|
|
77
|
+
raise ValueError('Only confirmed public REST observations are enabled')
|
|
78
|
+
if self.market_kind == MarketKind.SPOT and self.price_type in (PriceType.MARK, PriceType.INDEX):
|
|
79
|
+
raise ValueError('Spot does not provide this price type')
|
|
80
|
+
object.__setattr__(self, 'symbol', symbol)
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def identity(self):
|
|
84
|
+
parts = [SNAPSHOT_VERSION, self.exchange_code, self.market_kind.value,
|
|
85
|
+
self.settlement, self.symbol, self.price_type.value, self.is_testnet]
|
|
86
|
+
return hashlib.sha256(json.dumps(parts, separators=(',', ':')).encode()).hexdigest()
|
|
87
|
+
|
|
88
|
+
def short_id(self):
|
|
89
|
+
return f'{self.exchange_code}:{self.market_kind.value}:{self.symbol}:{self.price_type.value}'
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def namespace(environment):
|
|
93
|
+
return f'h7:price:v2:{environment}'
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True)
|
|
97
|
+
class Config:
|
|
98
|
+
fresh_seconds: float = 10
|
|
99
|
+
retention_seconds: int = 3600
|
|
100
|
+
cooldown_ms: int = 500
|
|
101
|
+
operation_seconds: float = 5
|
|
102
|
+
lease_ms: int = 10000
|
|
103
|
+
max_operations: int = 16
|
|
104
|
+
max_per_proxy: int = 2
|
|
105
|
+
proxy_interval_ms: int = 100
|
|
106
|
+
max_requests: int = 128
|
|
107
|
+
strict_max_age: float = 2
|
|
108
|
+
|
|
109
|
+
def __post_init__(self):
|
|
110
|
+
values = (self.fresh_seconds, self.retention_seconds, self.cooldown_ms,
|
|
111
|
+
self.operation_seconds, self.lease_ms, self.max_operations,
|
|
112
|
+
self.max_per_proxy, self.proxy_interval_ms, self.max_requests, self.strict_max_age)
|
|
113
|
+
if any(not math.isfinite(v) or v <= 0 for v in values):
|
|
114
|
+
raise ValueError('Price limits must be positive and finite')
|
|
115
|
+
if self.lease_ms <= self.operation_seconds * 1000:
|
|
116
|
+
raise ValueError('Price lease must outlive the operation')
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def proxy_routes(pool):
|
|
120
|
+
from .wallet_protocol import proxy_routes as build
|
|
121
|
+
return build(pool)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class PublicPriceTransport:
|
|
125
|
+
def __init__(self, session, redis=None, prefix='', operation_seconds=5):
|
|
126
|
+
self.session, self.operation_seconds = session, operation_seconds
|
|
127
|
+
|
|
128
|
+
def endpoint(self, key):
|
|
129
|
+
raise NotImplementedError
|
|
130
|
+
|
|
131
|
+
async def request(self, key, route, *, batch=False):
|
|
132
|
+
host, path, params = self.endpoint(key)
|
|
133
|
+
if batch:
|
|
134
|
+
params.pop('symbol', None)
|
|
135
|
+
url = URL(host + path).with_query(params)
|
|
136
|
+
try:
|
|
137
|
+
async with self.session.get(url, proxy=None if route == 'direct' else route,
|
|
138
|
+
timeout=aiohttp.ClientTimeout(total=self.operation_seconds),
|
|
139
|
+
allow_redirects=False) as reply:
|
|
140
|
+
if reply.status in (403, 418, 429):
|
|
141
|
+
pause = 600 if reply.status == 403 else 60
|
|
142
|
+
try:
|
|
143
|
+
pause = max(pause, int(reply.headers.get('Retry-After', pause)))
|
|
144
|
+
except (ValueError, TypeError):
|
|
145
|
+
pass
|
|
146
|
+
raise GatewayError(429, 'DETAILS_EXCHANGE_RATE_LIMITED', pause, scope='proxy')
|
|
147
|
+
if reply.status != 200:
|
|
148
|
+
raise GatewayError()
|
|
149
|
+
data = await reply.json(content_type=None)
|
|
150
|
+
observed = time.time()
|
|
151
|
+
except (aiohttp.ClientError, TimeoutError, ValueError):
|
|
152
|
+
raise GatewayError() from None
|
|
153
|
+
if key.exchange_code == 'bybit':
|
|
154
|
+
if not isinstance(data, dict):
|
|
155
|
+
raise GatewayError()
|
|
156
|
+
code = data.get('retCode')
|
|
157
|
+
if code in (10006, 10429, 20003):
|
|
158
|
+
raise GatewayError(429, 'DETAILS_EXCHANGE_RATE_LIMITED', 60)
|
|
159
|
+
if code == 10009:
|
|
160
|
+
raise GatewayError(429, 'DETAILS_EXCHANGE_RATE_LIMITED', 600, scope='proxy')
|
|
161
|
+
if code != 0:
|
|
162
|
+
raise GatewayError()
|
|
163
|
+
rows = data.get('result', {}).get('list')
|
|
164
|
+
server_time = data.get('time')
|
|
165
|
+
else:
|
|
166
|
+
rows = data if isinstance(data, list) else [data]
|
|
167
|
+
server_time = None
|
|
168
|
+
if not isinstance(rows, list):
|
|
169
|
+
raise GatewayError()
|
|
170
|
+
return rows, observed, server_time
|
|
171
|
+
|
|
172
|
+
def observation(self, key, row, observed, server_time):
|
|
173
|
+
if not isinstance(row, dict) or row.get('symbol') != key.symbol:
|
|
174
|
+
raise GatewayError(503, 'DETAILS_PRICE_NOT_FOUND')
|
|
175
|
+
fields = ({PriceType.LAST: 'lastPrice', PriceType.MARK: 'markPrice', PriceType.INDEX: 'indexPrice',
|
|
176
|
+
PriceType.BID: 'bid1Price', PriceType.ASK: 'ask1Price'} if key.exchange_code == 'bybit' else
|
|
177
|
+
{PriceType.LAST: 'lastPrice', PriceType.MARK: 'markPrice', PriceType.INDEX: 'indexPrice',
|
|
178
|
+
PriceType.BID: 'bidPrice', PriceType.ASK: 'askPrice'})
|
|
179
|
+
try:
|
|
180
|
+
value = str(number(row.get(fields[key.price_type])))
|
|
181
|
+
stamp = server_time if server_time is not None else row.get('time', row.get('closeTime'))
|
|
182
|
+
stamp = float(stamp) / 1000 if stamp not in (None, '') else None
|
|
183
|
+
if stamp is not None and not math.isfinite(stamp):
|
|
184
|
+
raise ValueError
|
|
185
|
+
except (ValueError, InvalidOperation, TypeError):
|
|
186
|
+
raise GatewayError(503, 'DETAILS_PRICE_TYPE_UNAVAILABLE') from None
|
|
187
|
+
return dict(price=value, observed_at=observed, exchange_timestamp=stamp)
|
|
188
|
+
|
|
189
|
+
async def fetch(self, key, route):
|
|
190
|
+
rows, observed, server_time = await self.request(key, route)
|
|
191
|
+
row = next((row for row in rows if isinstance(row, dict) and row.get('symbol') == key.symbol), None)
|
|
192
|
+
return self.observation(key, row, observed, server_time)
|
|
193
|
+
|
|
194
|
+
async def fetch_batch(self, keys, route):
|
|
195
|
+
first = keys[0]
|
|
196
|
+
if any((key.exchange_code, key.market_kind, key.is_testnet, key.price_type) !=
|
|
197
|
+
(first.exchange_code, first.market_kind, first.is_testnet, first.price_type) or
|
|
198
|
+
self.endpoint(key)[:2] != self.endpoint(first)[:2] for key in keys):
|
|
199
|
+
raise ValueError('Batch instruments must share one endpoint and price type')
|
|
200
|
+
rows, observed, server_time = await self.request(first, route, batch=True)
|
|
201
|
+
indexed = {row['symbol']: row for row in rows if isinstance(row, dict) and 'symbol' in row}
|
|
202
|
+
observations = {}
|
|
203
|
+
for key in keys:
|
|
204
|
+
try:
|
|
205
|
+
observations[key.identity] = self.observation(key, indexed.get(key.symbol), observed, server_time)
|
|
206
|
+
except GatewayError:
|
|
207
|
+
continue
|
|
208
|
+
return observations
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class BybitPublicTransport(PublicPriceTransport):
|
|
212
|
+
ENDPOINT_MAINNET = 'https://api.bybit.com'
|
|
213
|
+
ENDPOINT_TESTNET = 'https://api-testnet.bybit.com'
|
|
214
|
+
|
|
215
|
+
def endpoint(self, key):
|
|
216
|
+
host = self.ENDPOINT_TESTNET if key.is_testnet else self.ENDPOINT_MAINNET
|
|
217
|
+
return host, '/v5/market/tickers', {'category': key.market_kind.value, 'symbol': key.symbol}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class BinancePublicTransport(PublicPriceTransport):
|
|
221
|
+
def endpoint(self, key):
|
|
222
|
+
if key.market_kind == MarketKind.SPOT:
|
|
223
|
+
host = 'https://testnet.binance.vision' if key.is_testnet else 'https://api.binance.com'
|
|
224
|
+
path = '/api/v3/ticker/24hr'
|
|
225
|
+
else:
|
|
226
|
+
linear = key.market_kind == MarketKind.LINEAR
|
|
227
|
+
host = ('https://demo-fapi.binance.com' if linear else 'https://demo-dapi.binance.com') if key.is_testnet else (
|
|
228
|
+
'https://fapi.binance.com' if linear else 'https://dapi.binance.com')
|
|
229
|
+
prefix = '/fapi/v1' if linear else '/dapi/v1'
|
|
230
|
+
path = prefix + ('/premiumIndex' if key.price_type in (PriceType.MARK, PriceType.INDEX) else
|
|
231
|
+
'/ticker/bookTicker' if key.price_type in (PriceType.BID, PriceType.ASK) else '/ticker/24hr')
|
|
232
|
+
return host, path, {'symbol': key.symbol}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def transport_for_exchange(exchange_code, session, redis=None, prefix='', operation_seconds=5):
|
|
236
|
+
cls = {'bybit': BybitPublicTransport, 'binance': BinancePublicTransport}.get(exchange_code.lower())
|
|
237
|
+
if cls is None:
|
|
238
|
+
raise ValueError('Unsupported public price exchange')
|
|
239
|
+
return cls(session, redis, prefix, operation_seconds)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
_PUBLISH = '''
|
|
243
|
+
if redis.call('GET', KEYS[2]) ~= ARGV[3] then return 0 end
|
|
244
|
+
local candidate = cjson.decode(ARGV[1])
|
|
245
|
+
local old = redis.call('GET', KEYS[1])
|
|
246
|
+
if old then
|
|
247
|
+
old = cjson.decode(old)
|
|
248
|
+
if old.version == candidate.version and tonumber(old.generation or 0) > tonumber(candidate.generation) then return 0 end
|
|
249
|
+
end
|
|
250
|
+
redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
|
|
251
|
+
return 1
|
|
252
|
+
'''
|
|
253
|
+
_FINISH = '''
|
|
254
|
+
if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
|
|
255
|
+
if ARGV[2] ~= '' then
|
|
256
|
+
local candidate = cjson.decode(ARGV[2])
|
|
257
|
+
local old = redis.call('GET', KEYS[4])
|
|
258
|
+
if not old or tonumber(cjson.decode(old).generation or 0) <= tonumber(candidate.generation) then
|
|
259
|
+
redis.call('SET', KEYS[4], ARGV[2], 'EX', ARGV[3])
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
if ARGV[4] ~= '' then redis.call('SET', KEYS[5], ARGV[4], 'PX', ARGV[5]) end
|
|
263
|
+
redis.call('DEL', KEYS[1])
|
|
264
|
+
redis.call('ZREM', KEYS[2], ARGV[1])
|
|
265
|
+
redis.call('ZREM', KEYS[3], ARGV[1])
|
|
266
|
+
return 1
|
|
267
|
+
'''
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class PriceCache:
|
|
271
|
+
def __init__(self, redis, transport, routes, config, prefix, source='api'):
|
|
272
|
+
if not routes:
|
|
273
|
+
raise ValueError('Explicit direct or proxy routes are required')
|
|
274
|
+
self.redis, self.transport, self.routes = redis, transport, routes
|
|
275
|
+
self.config, self.prefix, self.source = config, prefix, source
|
|
276
|
+
|
|
277
|
+
def snapshot_key(self, key):
|
|
278
|
+
return f'{self.prefix}:{key.identity}:snapshot'
|
|
279
|
+
|
|
280
|
+
def valid(self, snapshot, key):
|
|
281
|
+
try:
|
|
282
|
+
return (snapshot['version'] == SNAPSHOT_VERSION and snapshot['identity'] == key.identity
|
|
283
|
+
and snapshot['observation_kind'] == 'rest' and number(snapshot['price']) > 0
|
|
284
|
+
and 0 <= time.time() - snapshot['received_at'] <= self.config.retention_seconds)
|
|
285
|
+
except (ValueError, InvalidOperation, KeyError, TypeError):
|
|
286
|
+
return False
|
|
287
|
+
|
|
288
|
+
async def read(self, key):
|
|
289
|
+
raw = await self.redis.get(self.snapshot_key(key))
|
|
290
|
+
try:
|
|
291
|
+
snapshot = json.loads(raw) if raw else None
|
|
292
|
+
except (ValueError, TypeError):
|
|
293
|
+
return None
|
|
294
|
+
return snapshot if snapshot and self.valid(snapshot, key) else None
|
|
295
|
+
|
|
296
|
+
async def get(self, key, fresh=False, max_age=None, *, wait_seconds=0, allow_stale=False):
|
|
297
|
+
try:
|
|
298
|
+
return await self._get(key, fresh, max_age, wait_seconds)
|
|
299
|
+
except GatewayError as error:
|
|
300
|
+
if allow_stale and not fresh and error.status >= 429 and error.code != 'DETAILS_PRICE_CONFIG_MISMATCH':
|
|
301
|
+
snapshot = await self.read(key)
|
|
302
|
+
if snapshot:
|
|
303
|
+
return snapshot, 'stale'
|
|
304
|
+
raise
|
|
305
|
+
|
|
306
|
+
async def _get(self, key, fresh, max_age, wait_seconds):
|
|
307
|
+
cfg = self.config
|
|
308
|
+
max_age = cfg.fresh_seconds if max_age is None else max_age
|
|
309
|
+
if not math.isfinite(max_age) or max_age < 0 or not math.isfinite(wait_seconds):
|
|
310
|
+
raise ValueError('Invalid price age or wait')
|
|
311
|
+
wait_seconds = min(30, max(0, wait_seconds))
|
|
312
|
+
scope = f'{self.prefix}:{key.exchange_code}:{int(key.is_testnet)}'
|
|
313
|
+
signature = hashlib.sha256(json.dumps([cfg.max_operations, cfg.max_per_proxy, cfg.proxy_interval_ms,
|
|
314
|
+
cfg.cooldown_ms, cfg.operation_seconds, cfg.lease_ms,
|
|
315
|
+
self.routes], separators=(',', ':')).encode()).hexdigest()
|
|
316
|
+
await self.redis.set(scope + ':config', signature, nx=True)
|
|
317
|
+
if await self.redis.get(scope + ':config') != signature:
|
|
318
|
+
raise GatewayError(503, 'DETAILS_PRICE_CONFIG_MISMATCH')
|
|
319
|
+
base = f'{self.prefix}:{key.identity}'
|
|
320
|
+
lock, cooldown, error_key = base + ':lock', base + ':cooldown', base + ':error'
|
|
321
|
+
global_slots, pause, queue = scope + ':slots', scope + ':pause', scope + ':queue'
|
|
322
|
+
route = self.routes[int(key.identity[:16], 16) % len(self.routes)]
|
|
323
|
+
route_base = scope + ':route:' + self.route_id(route)
|
|
324
|
+
slots, route_pause = route_base + ':slots', route_base + ':pause'
|
|
325
|
+
token = uuid.uuid4().hex
|
|
326
|
+
started, loop = time.time(), asyncio.get_running_loop()
|
|
327
|
+
deadline = loop.time() + cfg.operation_seconds + wait_seconds + 1
|
|
328
|
+
queue_until = started + wait_seconds
|
|
329
|
+
try:
|
|
330
|
+
while True:
|
|
331
|
+
snapshot = await self.read(key)
|
|
332
|
+
if snapshot:
|
|
333
|
+
age = time.time() - snapshot['received_at']
|
|
334
|
+
if (not fresh and age <= max_age) or (fresh and snapshot['received_at'] >= started and age <= cfg.strict_max_age):
|
|
335
|
+
return snapshot, 'cache'
|
|
336
|
+
state = await self.redis.eval(
|
|
337
|
+
_ADMIT, 13, lock, cooldown, global_slots, slots, pause, slots + ':interval', error_key,
|
|
338
|
+
pause, route_pause, queue, queue + ':expires', queue + ':sequence', queue + ':routes',
|
|
339
|
+
int(time.time() * 1000), token, cfg.lease_ms, cfg.max_operations, cfg.max_per_proxy,
|
|
340
|
+
cfg.cooldown_ms, cfg.proxy_interval_ms, int(queue_until * 1000))
|
|
341
|
+
if state != 'ok':
|
|
342
|
+
if state == 'paused':
|
|
343
|
+
ttl = max(await self.redis.pttl(pause), await self.redis.pttl(route_pause))
|
|
344
|
+
raise GatewayError(429, 'DETAILS_EXCHANGE_RATE_LIMITED', max(1, (ttl + 999) // 1000))
|
|
345
|
+
if state == 'cooldown':
|
|
346
|
+
completed = await self.read(key)
|
|
347
|
+
if completed and ((not fresh and time.time() - completed['received_at'] <= max_age) or
|
|
348
|
+
(completed['received_at'] >= started and time.time() - completed['received_at'] <= cfg.strict_max_age)):
|
|
349
|
+
return completed, 'cache'
|
|
350
|
+
failure = await self.redis.get(error_key)
|
|
351
|
+
if failure:
|
|
352
|
+
raise GatewayError(**json.loads(failure))
|
|
353
|
+
if (state == 'wait' and loop.time() < deadline) or (wait_seconds and time.time() < queue_until):
|
|
354
|
+
await asyncio.sleep(0.02)
|
|
355
|
+
continue
|
|
356
|
+
raise GatewayError(504 if state == 'wait' else 429,
|
|
357
|
+
'DETAILS_EXCHANGE_TIMEOUT' if state == 'wait' else 'DETAILS_EXCHANGE_BUSY', 1)
|
|
358
|
+
encoded, failure = '', ''
|
|
359
|
+
try:
|
|
360
|
+
generation = await self.redis.incr(self.prefix + ':generation')
|
|
361
|
+
async with asyncio.timeout(cfg.operation_seconds):
|
|
362
|
+
if hasattr(self.transport, 'fetch_admitted'):
|
|
363
|
+
data = await self.transport.fetch_admitted(key, route, token, lock)
|
|
364
|
+
else:
|
|
365
|
+
data = await self.transport.fetch(key, route)
|
|
366
|
+
snapshot = self.build(key, data, generation)
|
|
367
|
+
if time.time() - snapshot['received_at'] > cfg.strict_max_age and fresh:
|
|
368
|
+
raise GatewayError(503, 'DETAILS_PRICE_STALE')
|
|
369
|
+
encoded = json.dumps(snapshot)
|
|
370
|
+
except (GatewayError, TimeoutError, ValueError, InvalidOperation, TypeError, KeyError) as error:
|
|
371
|
+
if not isinstance(error, GatewayError):
|
|
372
|
+
error = GatewayError(504 if isinstance(error, TimeoutError) else 503)
|
|
373
|
+
failure = json.dumps(dict(status=error.status, code=error.code, retry_after=error.retry_after, scope=error.scope))
|
|
374
|
+
if error.code == 'DETAILS_EXCHANGE_RATE_LIMITED':
|
|
375
|
+
await self.redis.eval(_PAUSE, 1, route_pause if error.scope == 'proxy' else pause,
|
|
376
|
+
(error.retry_after or 1) * 1000)
|
|
377
|
+
raise error
|
|
378
|
+
finally:
|
|
379
|
+
committed = await asyncio.shield(self.redis.eval(
|
|
380
|
+
_FINISH, 5, lock, global_slots, slots, self.snapshot_key(key), error_key,
|
|
381
|
+
token, encoded, cfg.retention_seconds, failure, cfg.cooldown_ms))
|
|
382
|
+
if not committed:
|
|
383
|
+
raise GatewayError(503, 'DETAILS_PRICE_LEASE_EXPIRED')
|
|
384
|
+
latest = await self.read(key)
|
|
385
|
+
if latest and (not fresh or (latest['received_at'] >= started
|
|
386
|
+
and time.time() - latest['received_at'] <= cfg.strict_max_age)):
|
|
387
|
+
return latest, 'exchange'
|
|
388
|
+
raise GatewayError(503, 'DETAILS_PRICE_STALE')
|
|
389
|
+
finally:
|
|
390
|
+
await asyncio.shield(self.redis.eval(_UNQUEUE, 3, queue, queue + ':expires', queue + ':routes', token))
|
|
391
|
+
|
|
392
|
+
def build(self, key, data, generation):
|
|
393
|
+
observed = float(data['observed_at'])
|
|
394
|
+
if not math.isfinite(observed) or observed > time.time() or observed < time.time() - self.config.retention_seconds:
|
|
395
|
+
raise ValueError('Invalid observation time')
|
|
396
|
+
return dict(version=SNAPSHOT_VERSION, identity=key.identity, price=str(number(data['price'])),
|
|
397
|
+
received_at=observed, fetched_at=datetime.fromtimestamp(observed, timezone.utc).isoformat(),
|
|
398
|
+
exchange_timestamp=data.get('exchange_timestamp'), generation=generation, observation_kind='rest',
|
|
399
|
+
source=self.source, exchange_code=key.exchange_code, market_kind=key.market_kind.value,
|
|
400
|
+
settlement=key.settlement, symbol=key.symbol, price_type=key.price_type.value, is_testnet=key.is_testnet)
|
|
401
|
+
|
|
402
|
+
async def refresh_batch(self, keys, wait_seconds=3):
|
|
403
|
+
if not keys:
|
|
404
|
+
return
|
|
405
|
+
first = keys[0]
|
|
406
|
+
if any((item.exchange_code, item.market_kind, item.is_testnet, item.price_type) !=
|
|
407
|
+
(first.exchange_code, first.market_kind, first.is_testnet, first.price_type) for item in keys):
|
|
408
|
+
raise ValueError('Mixed batch market or contour')
|
|
409
|
+
batch_key = PriceKey(first.exchange_code, first.market_kind, first.settlement,
|
|
410
|
+
'__BATCH__', first.price_type, is_testnet=first.is_testnet)
|
|
411
|
+
cache = self
|
|
412
|
+
class Batch:
|
|
413
|
+
async def fetch_admitted(self, key, route, token, lock):
|
|
414
|
+
# Reserve order before HTTP; publishing a late batch cannot replace a newer request.
|
|
415
|
+
generation = await cache.redis.incr(cache.prefix + ':generation')
|
|
416
|
+
data = await cache.transport.fetch_batch(keys, route)
|
|
417
|
+
if not data:
|
|
418
|
+
raise GatewayError(503, 'DETAILS_PRICE_NOT_FOUND')
|
|
419
|
+
for item in keys:
|
|
420
|
+
if item.identity in data:
|
|
421
|
+
snapshot = cache.build(item, data[item.identity], generation)
|
|
422
|
+
published = await cache.redis.eval(_PUBLISH, 2, cache.snapshot_key(item), lock,
|
|
423
|
+
json.dumps(snapshot), cache.config.retention_seconds, token)
|
|
424
|
+
if not published and await cache.redis.get(lock) != token:
|
|
425
|
+
raise GatewayError(503, 'DETAILS_PRICE_LEASE_EXPIRED')
|
|
426
|
+
return dict(price='1', observed_at=time.time())
|
|
427
|
+
batch = PriceCache(self.redis, Batch(), self.routes, self.config, self.prefix, self.source)
|
|
428
|
+
await batch.get(batch_key, fresh=True, wait_seconds=wait_seconds)
|
|
429
|
+
|
|
430
|
+
@staticmethod
|
|
431
|
+
def route_id(route):
|
|
432
|
+
return hashlib.sha256(('direct' if route == 'direct' else urlsplit(route).netloc.rsplit('@', 1)[-1]).encode()).hexdigest()
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def key_from_market(code, market, price_type=PriceType.LAST, *, is_testnet=False):
|
|
436
|
+
kind = MarketKind.SPOT if market.get('spot') or market.get('type') == 'spot' else (
|
|
437
|
+
MarketKind.INVERSE if market.get('inverse') else MarketKind.LINEAR)
|
|
438
|
+
settlement = market.get('settle') or (market.get('base') if kind == MarketKind.INVERSE else market.get('quote'))
|
|
439
|
+
if not settlement or not market.get('id'):
|
|
440
|
+
raise ValueError('Registered market ID and settlement are required')
|
|
441
|
+
return PriceKey(code, kind, settlement, market['id'], price_type, is_testnet=is_testnet)
|