-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path123.py
More file actions
4272 lines (3791 loc) · 165 KB
/
Copy path123.py
File metadata and controls
4272 lines (3791 loc) · 165 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, request, jsonify, make_response, g, has_request_context
from flask_compress import Compress
import yfinance as yf
from flask_cors import CORS
import pandas as pd
import os
import firebase_admin
from firebase_admin import credentials, auth, firestore
import datetime
import requests
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
from contextlib import contextmanager
from copy import deepcopy
from functools import wraps
from pathlib import Path
from threading import BoundedSemaphore, Event, Lock, Thread
import time
import json
import base64
import hashlib
import math
import re
import redis
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from limits.errors import StorageError as RateLimitStorageError
from earnings_calendar import register_earnings_calendar_routes
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 256 * 1024
PROCESS_STARTED_AT = time.time()
def _environment_flag(name, default=False):
value = os.environ.get(name)
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
def _bounded_env_int(name, default, minimum, maximum):
try:
value = int(os.environ.get(name, default))
except (TypeError, ValueError):
value = default
return max(minimum, min(maximum, value))
PRODUCTION_MODE = (
_environment_flag("PRODUCTION")
or _environment_flag("RENDER")
or os.environ.get("ENVIRONMENT", "").strip().lower() in {"prod", "production"}
)
SHARED_CACHE_URL = os.environ.get("REDIS_URL", "").strip()
SHARED_CACHE_PREFIX = "dcf-cache:v1"
SHARED_CACHE_RETRY_SECONDS = 30
SHARED_CACHE_PROBE_INTERVAL_SECONDS = 30
_shared_cache = redis.Redis.from_url(
SHARED_CACHE_URL,
socket_connect_timeout=0.25,
socket_timeout=0.25,
decode_responses=True,
) if SHARED_CACHE_URL else None
_shared_cache_state_lock = Lock()
_shared_cache_disabled_until = 0.0
_shared_cache_probe_stop = Event()
def _shared_cache_mark_failure():
global _shared_cache_disabled_until, RATE_LIMIT_STORAGE_READY
with _shared_cache_state_lock:
_shared_cache_disabled_until = max(
_shared_cache_disabled_until,
time.monotonic() + SHARED_CACHE_RETRY_SECONDS,
)
RATE_LIMIT_STORAGE_READY = False
def _shared_cache_mark_success():
global _shared_cache_disabled_until, RATE_LIMIT_STORAGE_READY
with _shared_cache_state_lock:
_shared_cache_disabled_until = 0.0
if _shared_cache:
RATE_LIMIT_STORAGE_READY = True
def _shared_cache_available():
if not _shared_cache:
return False
with _shared_cache_state_lock:
return time.monotonic() >= _shared_cache_disabled_until
if _shared_cache:
try:
_shared_cache.ping()
_shared_cache_mark_success()
print(json.dumps({"event": "shared_quote_cache", "status": "enabled"}, separators=(",", ":")))
except Exception as exc:
_shared_cache_mark_failure()
print(json.dumps({
"event": "shared_quote_cache", "status": "unavailable",
"fallback": "process_memory", "error": type(exc).__name__,
}, separators=(",", ":")))
else:
print(json.dumps({
"event": "shared_quote_cache",
"status": "disabled",
"fallback": "process_memory",
}, separators=(",", ":")))
def _probe_shared_cache():
"""Probe Redis on a timer so request paths do not pay outage timeouts."""
while not _shared_cache_probe_stop.wait(SHARED_CACHE_PROBE_INTERVAL_SECONDS):
if not _shared_cache:
return
try:
_shared_cache.ping()
except Exception as exc:
_shared_cache_mark_failure()
print(f"Shared cache probe failed: {type(exc).__name__}")
else:
_shared_cache_mark_success()
if _shared_cache:
Thread(target=_probe_shared_cache, name="shared-cache-probe", daemon=True).start()
# Negotiate Brotli or gzip for JSON responses. Brotli support is supplied by
# the explicit Brotli dependency in requirements.txt; gzip remains available
# for clients and proxies that do not advertise `br`.
app.config["COMPRESS_ALGORITHM"] = ["br", "gzip"]
app.config["COMPRESS_MIN_SIZE"] = 500
Compress(app)
DEFAULT_CORS_ORIGINS = [
"https://adamulek123.github.io",
"http://localhost:8000",
"http://127.0.0.1:8000",
]
allowed_origins = [
origin.strip()
for origin in os.environ.get(
"CORS_ALLOWED_ORIGINS", ",".join(DEFAULT_CORS_ORIGINS)
).split(",")
if origin.strip()
]
CORS(
app,
resources={r"/*": {"origins": allowed_origins}},
methods=["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "If-None-Match"],
expose_headers=["ETag", "Retry-After"],
supports_credentials=False,
)
@app.before_request
def start_request_metrics():
g.request_started_at = time.perf_counter()
g.firestore_deadline = (
g.request_started_at + FIRESTORE_REQUEST_BUDGET_SECONDS
)
@app.before_request
def enforce_production_dependencies():
if (
PRODUCTION_MODE
and request.endpoint not in {"health_check", "live_check", "ready_check"}
and not RATE_LIMIT_STORAGE_READY
):
return jsonify({
"message": "Shared rate-limit storage is unavailable.",
"code": "RATE_LIMIT_STORAGE_UNAVAILABLE",
}), 503
@app.after_request
def log_request_metrics(response):
started_at = getattr(g, "request_started_at", None)
if started_at is not None:
payload = {
"event": "http_request",
"route": request.path,
"method": request.method,
"status": response.status_code,
"durationMs": round((time.perf_counter() - started_at) * 1000, 1),
"bytes": response.calculate_content_length() or 0,
"cacheControl": response.headers.get("Cache-Control"),
"coldStart": time.time() - PROCESS_STARTED_AT < 60,
}
print(json.dumps(payload, separators=(",", ":")))
return response
@app.after_request
def apply_response_cache_policy(response):
"""Prevent shared caches from retaining authenticated or failed responses."""
if "Cache-Control" in response.headers:
return response
if request.path == "/" and request.method == "GET" and response.status_code < 400:
response.headers["Cache-Control"] = "public, max-age=60"
elif request.method != "GET" or response.status_code >= 400:
response.headers["Cache-Control"] = "no-store"
else:
# Every API read currently requires a Firebase bearer token. Keep it
# revalidatable by the browser, but never eligible for a shared cache.
response.headers["Cache-Control"] = "private, max-age=0, must-revalidate"
return response
def _rate_limit_key():
"""Prefer a verified UID, while never putting bearer material in a key."""
verified_uid = getattr(g, "firebase_uid", None)
if isinstance(verified_uid, str) and verified_uid:
return "uid:" + hashlib.sha256(verified_uid.encode("utf-8")).hexdigest()
remote = get_remote_address() or "unknown"
return "ip:" + str(remote)
# Production must have a shared limiter backend. Local development retains the
# documented in-memory behavior, but a Redis outage is not silently treated as
# a safe aggregate limit in production.
RATE_LIMIT_STORAGE_READY = bool(_shared_cache and _shared_cache_available())
limiter = Limiter(
_rate_limit_key,
app=app,
default_limits=["200 per day", "50 per hour"],
storage_uri=SHARED_CACHE_URL or "memory://",
storage_options={
"socket_connect_timeout": 0.25,
"socket_timeout": 0.25,
# Normalize Redis failures so the application can turn them into a
# controlled fail-closed response instead of leaking a 500.
"wrap_exceptions": True,
} if SHARED_CACHE_URL else None,
in_memory_fallback_enabled=bool(SHARED_CACHE_URL) and not PRODUCTION_MODE,
)
def _rate_limit_storage_failure_response(error):
"""Fail closed when a production limiter storage operation fails.
Flask-Limiter performs its storage operation inside the decorated view
wrapper, after the readiness guard has run. A Redis outage can therefore
happen while the process still reports ready. Mark the shared circuit
unhealthy before responding so subsequent application requests are also
rejected until the probe recovers it. Development's in-memory fallback
remains owned by Flask-Limiter and is not disabled here.
"""
if PRODUCTION_MODE:
_shared_cache_mark_failure()
g.rate_limit_storage_failed = True
print(json.dumps({
"event": "rate_limit_storage_unavailable",
"error": type(error).__name__,
}, separators=(",", ":")))
return jsonify({
"message": "Shared rate-limit storage is unavailable.",
"code": "RATE_LIMIT_STORAGE_UNAVAILABLE",
}), 503
@app.errorhandler(RateLimitStorageError)
def handle_rate_limit_storage_error(error):
return _rate_limit_storage_failure_response(error)
@app.errorhandler(redis.exceptions.RedisError)
def handle_raw_rate_limit_redis_error(error):
# RedisStorage wraps normal fixed-window operations, but keep the handler
# defensive for storage strategies/providers that surface the native
# exception directly.
return _rate_limit_storage_failure_response(error)
# Emulator use is an explicit local-development choice. In particular, do not
# let inherited SDK host variables change production's Firebase transport.
use_firebase_emulators = _environment_flag("USE_FIREBASE_EMULATORS", default=False)
inherited_emulator_hosts = {
name: os.environ.get(name, "").strip()
for name in ("FIREBASE_AUTH_EMULATOR_HOST", "FIRESTORE_EMULATOR_HOST")
if os.environ.get(name, "").strip()
}
if PRODUCTION_MODE and (use_firebase_emulators or inherited_emulator_hosts):
raise RuntimeError("Firebase emulator configuration is forbidden in production.")
if not use_firebase_emulators:
for emulator_variable in ("FIREBASE_AUTH_EMULATOR_HOST", "FIRESTORE_EMULATOR_HOST"):
os.environ.pop(emulator_variable, None)
if use_firebase_emulators:
os.environ.setdefault("FIREBASE_AUTH_EMULATOR_HOST", "127.0.0.1:9099")
os.environ.setdefault("FIRESTORE_EMULATOR_HOST", "127.0.0.1:8080")
os.environ.setdefault("FIREBASE_PROJECT_ID", "dcf123-b6cb1")
print(
"Local Firebase emulator mode enabled "
f"(Auth: {os.environ['FIREBASE_AUTH_EMULATOR_HOST']}, "
f"Firestore: {os.environ['FIRESTORE_EMULATOR_HOST']})."
)
encoded_key = os.environ.get('FIREBASE_SERVICE_ACCOUNT_KEY_BASE64')
db = None
if encoded_key:
try:
decoded_key_str = base64.b64decode(encoded_key).decode('utf-8')
service_account_info = json.loads(decoded_key_str)
cred = credentials.Certificate(service_account_info)
firebase_admin.initialize_app(cred)
db = firestore.client()
print("Firebase Admin SDK initialized successfully from secret.")
except Exception as e:
print(json.dumps({
"event": "firebase_init_failed",
"mode": "service_account",
"errorType": type(e).__name__,
}, separators=(",", ":")))
elif os.environ.get("FIREBASE_AUTH_EMULATOR_HOST"):
try:
firebase_admin.initialize_app(options={
"projectId": os.environ.get("FIREBASE_PROJECT_ID", "dcf123-b6cb1")
})
if os.environ.get("FIRESTORE_EMULATOR_HOST"):
db = firestore.client()
print("Firebase Admin SDK initialized for the local emulator.")
except Exception as e:
print(json.dumps({
"event": "firebase_init_failed",
"mode": "emulator",
"errorType": type(e).__name__,
}, separators=(",", ":")))
else:
print("FIREBASE_SERVICE_ACCOUNT_KEY_BASE64 environment variable not found. Firebase features will be limited.")
register_earnings_calendar_routes(app, limiter, lambda: db)
_ticker_cache = []
_ticker_by_symbol = {}
_ticker_cache_ready = False
_ticker_cache_error = None
_fx_cache = {}
_price_cache = {}
_price_failure_cache = {}
_history_cache = {}
_yahoo_info_cache = {}
_financial_document_cache = {}
_price_cache_lock = Lock()
_price_fetch_lock = Lock()
_history_cache_lock = Lock()
_yahoo_info_cache_lock = Lock()
_financial_document_cache_lock = Lock()
_provider_executor = ThreadPoolExecutor(
max_workers=_bounded_env_int("YAHOO_MAX_WORKERS", 8, 2, 16)
)
_yahoo_provider_semaphore = BoundedSemaphore(
_bounded_env_int("YAHOO_MAX_IN_FLIGHT", 4, 1, 16)
)
_auth_provider_semaphore = BoundedSemaphore(4)
_yahoo_info_inflight = {}
_history_inflight = {}
_financial_document_inflight = {}
_provider_registry_lock = Lock()
FX_CACHE_TTL_SECONDS = 6 * 60 * 60
PRICE_FRESH_TTL_SECONDS = 5 * 60
PRICE_STALE_TTL_SECONDS = 24 * 60 * 60
PRICE_LAST_KNOWN_TTL_SECONDS = 7 * 24 * 60 * 60
PRICE_FAILURE_CACHE_TTL_SECONDS = 15
YAHOO_INFO_CACHE_TTL_SECONDS = 5 * 60
YAHOO_INFO_FAILURE_CACHE_TTL_SECONDS = 15
FINANCIAL_DOCUMENT_CACHE_TTL_SECONDS = 24 * 60 * 60
FINANCIAL_DOCUMENT_CACHE_MAX_ENTRIES = 200
FINANCIAL_DOCUMENT_NEGATIVE_CACHE_TTL_SECONDS = 30
FIRESTORE_DOCUMENT_TIMEOUT_SECONDS = 4
FIRESTORE_STREAM_TIMEOUT_SECONDS = 6
FIRESTORE_REQUEST_BUDGET_SECONDS = 8
FIRESTORE_SINGLE_FLIGHT_WAIT_SECONDS = 1
YAHOO_INFO_TIMEOUT_SECONDS = 8
YAHOO_HISTORY_TIMEOUT_SECONDS = 10
YAHOO_PROVIDER_QUEUE_TIMEOUT_SECONDS = 0.25
AUTH_VERIFY_TIMEOUT_SECONDS = 6
MAX_PROVIDER_BATCH_TICKERS = 50
MAX_SERVER_NUMBER_ABS = 1e18
MAX_FINANCIAL_JSON_DEPTH = 12
MAX_FINANCIAL_JSON_ITEMS = 5000
TICKER_PATTERN = re.compile(r"^[A-Z0-9][A-Z0-9.^=-]{0,19}$")
def _shared_cache_key(resource, key):
return f"{SHARED_CACHE_PREFIX}:{resource}:{key}"
def _shared_cache_get(resource, key):
if not _shared_cache_available():
return None
try:
value = _shared_cache.get(_shared_cache_key(resource, key))
parsed = json.loads(value) if value else None
_shared_cache_mark_success()
return parsed
except Exception as exc:
_shared_cache_mark_failure()
print(f"Shared cache read failed for {resource}: {type(exc).__name__}")
return None
def _shared_cache_get_many(resource, keys):
"""Read a set of cache keys in one Redis operation, outside provider locks."""
if not keys or not _shared_cache_available():
return {}
cache_keys = [_shared_cache_key(resource, key) for key in keys]
try:
mget = getattr(_shared_cache, "mget", None)
if not callable(mget):
return {}
values = mget(cache_keys)
parsed = {}
for key, value in zip(keys, values or []):
if value:
try:
parsed[key] = json.loads(value)
except (TypeError, ValueError):
print(f"Shared cache value invalid for {resource}")
_shared_cache_mark_success()
return parsed
except Exception as exc:
_shared_cache_mark_failure()
print(f"Shared cache batch read failed for {resource}: {type(exc).__name__}")
return {}
def _shared_cache_set(resource, key, value, ttl_seconds):
_shared_cache_set_many(resource, {key: value}, ttl_seconds)
def _shared_cache_set_many(resource, values, ttl_seconds):
"""Write cache values with one pipelined Redis operation."""
if not values or not _shared_cache_available():
return
try:
pipeline_factory = getattr(_shared_cache, "pipeline", None)
if not callable(pipeline_factory):
return
pipeline = pipeline_factory(transaction=False)
ttl = max(1, int(ttl_seconds))
for key, value in values.items():
pipeline.setex(
_shared_cache_key(resource, key),
ttl,
json.dumps(value, default=str, separators=(",", ":")),
)
pipeline.execute()
_shared_cache_mark_success()
except Exception as exc:
_shared_cache_mark_failure()
print(f"Shared cache write failed for {resource}: {type(exc).__name__}")
def _log_cache_event(resource, outcome):
print(json.dumps({"event": "cache", "resource": resource, "outcome": outcome}, separators=(",", ":")))
class ProviderInputError(ValueError):
pass
class ProviderBusyError(RuntimeError):
pass
class ProviderTimeoutError(TimeoutError):
pass
class FirestoreUnavailableError(RuntimeError):
pass
class FirestoreBusyError(RuntimeError):
pass
class StoredFinancialShapeError(ValueError):
pass
def _normalize_ticker(value):
if not isinstance(value, str):
return None
normalized = value.strip().upper()
return normalized if TICKER_PATTERN.fullmatch(normalized) else None
def _safe_log_symbol(value):
return _normalize_ticker(value) or "INVALID"
def _ticker_query_value():
raw_value = request.args.get("ticker")
if raw_value is None or not str(raw_value).strip():
return None, (jsonify({"error": "Ticker symbol is required"}), 400)
normalized = _normalize_ticker(raw_value)
if not normalized or not is_valid_ticker(normalized):
return None, (jsonify({"error": "Invalid ticker symbol"}), 400)
return normalized, None
def _provider_error_response(operation, error):
_log_provider_failure(
"provider_request_failed",
error=error,
operation=str(operation).replace("\n", " ")[:80],
)
if isinstance(error, ProviderInputError):
return jsonify({"error": "Invalid provider request."}), 400
if isinstance(error, ProviderTimeoutError):
return jsonify({
"error": "Market data provider timed out. Please try again later.",
"code": "PROVIDER_TIMEOUT",
}), 504
if isinstance(error, ProviderBusyError):
return jsonify({
"error": "Market data provider is busy. Please try again shortly.",
"code": "PROVIDER_BUSY",
}), 503
return jsonify({
"error": "Market data provider is temporarily unavailable.",
"code": "PROVIDER_UNAVAILABLE",
}), 503
def _log_provider_failure(event, ticker=None, error=None, **fields):
payload = {"event": event}
if ticker is not None:
payload["ticker"] = _safe_log_symbol(ticker)
if error is not None:
payload["errorType"] = type(error).__name__
payload.update(fields)
print(json.dumps(payload, separators=(",", ":")))
def _run_bounded_provider(operation, callback, timeout, semaphore=None):
"""Run a blocking SDK call with a bounded queue and execution deadline."""
semaphore = semaphore or _yahoo_provider_semaphore
if not semaphore.acquire(timeout=YAHOO_PROVIDER_QUEUE_TIMEOUT_SECONDS):
raise ProviderBusyError(f"{operation} provider capacity is busy")
try:
future = _provider_executor.submit(callback)
except Exception:
semaphore.release()
raise
# A timed-out worker may still be unwinding inside the SDK. Keep the
# semaphore occupied until that worker actually exits.
future.add_done_callback(lambda _: semaphore.release())
try:
return future.result(timeout=max(0.1, float(timeout)))
except FutureTimeoutError as error:
future.cancel()
raise ProviderTimeoutError(f"{operation} provider timed out") from error
def _singleflight_lock(registry, key, busy_error):
with _provider_registry_lock:
lock = registry.setdefault(key, Lock())
if not lock.acquire(timeout=FIRESTORE_SINGLE_FLIGHT_WAIT_SECONDS):
raise busy_error
return lock
def _release_singleflight_lock(registry, key, lock):
lock.release()
with _provider_registry_lock:
if registry.get(key) is lock:
registry.pop(key, None)
def _get_yahoo_info(symbol):
key = _normalize_ticker(symbol)
if not key:
raise ProviderInputError("Invalid ticker symbol")
lock = _singleflight_lock(
_yahoo_info_inflight,
key,
ProviderBusyError("Yahoo info provider capacity is busy"),
)
try:
now = time.time()
with _yahoo_info_cache_lock:
cached = _yahoo_info_cache.get(key)
if cached:
ttl = (
YAHOO_INFO_FAILURE_CACHE_TTL_SECONDS
if cached.get("error")
else YAHOO_INFO_CACHE_TTL_SECONDS
)
if now - cached.get("timestamp", 0) < ttl:
if cached.get("error"):
_log_cache_event("yahoo_info", "negative_hit")
raise RuntimeError("Yahoo provider recently failed; retry shortly.")
_log_cache_event("yahoo_info", "hit")
return deepcopy(cached.get("data", {}))
shared = _shared_cache_get("yahoo-info", key)
if isinstance(shared, dict):
if shared.get("error"):
_log_cache_event("yahoo_info", "shared_negative_hit")
raise RuntimeError("Yahoo provider recently failed; retry shortly.")
data = shared.get("data")
if isinstance(data, dict):
with _yahoo_info_cache_lock:
_yahoo_info_cache[key] = {
"data": deepcopy(data),
"error": False,
"timestamp": now,
}
_log_cache_event("yahoo_info", "shared_hit")
return deepcopy(data)
_log_cache_event("yahoo_info", "miss")
try:
info = _run_bounded_provider(
"Yahoo info",
lambda: yf.Ticker(key).info,
YAHOO_INFO_TIMEOUT_SECONDS,
)
if not isinstance(info, dict):
info = {}
except Exception as error:
_log_cache_event("yahoo_info", "negative_set")
with _yahoo_info_cache_lock:
_yahoo_info_cache[key] = {"error": True, "timestamp": now}
_shared_cache_set(
"yahoo-info",
key,
{"error": True},
YAHOO_INFO_FAILURE_CACHE_TTL_SECONDS,
)
raise
with _yahoo_info_cache_lock:
_yahoo_info_cache[key] = {
"data": deepcopy(info),
"error": False,
"timestamp": now,
}
_shared_cache_set(
"yahoo-info",
key,
{"data": info, "error": False},
YAHOO_INFO_CACHE_TTL_SECONDS,
)
return deepcopy(info)
finally:
_release_singleflight_lock(_yahoo_info_inflight, key, lock)
MAX_PORTFOLIO_TICKERS = 50
MAX_PORTFOLIO_POSITIONS = 200
MAX_PORTFOLIO_ENTRY_PRICE_USD = 1e12
MAX_PORTFOLIO_SIZE_VALUE = 1e15
MAX_PORTFOLIO_LEVERAGE = 1e3
MAX_PORTFOLIOS = 20
MAX_PORTFOLIO_NAME_LENGTH = 60
MAX_PORTFOLIO_POSITION_ID_LENGTH = 128
MAX_PORTFOLIO_POSITION_CREATED_AT_LENGTH = 128
MAX_WATCHLISTS = 20
MAX_WATCHLIST_TICKERS = 50
MAX_WATCHLIST_NAME_LENGTH = 60
MAX_SAVED_CALCULATIONS = 50
PORTFOLIO_PRICE_FETCH_TIMEOUT_SECONDS = 10
PORTFOLIO_LOAD_TIMEOUT_SECONDS = 15
HISTORY_CACHE_TTL_SECONDS = 5 * 60
HISTORY_FAILURE_CACHE_TTL_SECONDS = 60
PRICE_CACHE_MAX_ENTRIES = 500
HISTORY_CACHE_MAX_ENTRIES = 200
WATCHLIST_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
PORTFOLIO_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_-]{8,128}$")
CALCULATION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.^=-]{0,127}$")
CALCULATION_TICKER_PATTERN = re.compile(r"^[A-Z0-9][A-Z0-9.^=-]{0,19}$")
CALCULATION_SCHEMA_VERSION = 1
MAX_CALCULATION_RESULT_LENGTH = 64
PORTFOLIO_SETTINGS_DOC = "_settings"
CURRENCY_PATTERN = re.compile(r"^[A-Z]{3}$")
WATCHLIST_META_COLLECTION = "_watchlist_meta"
WATCHLIST_GUARD_DOC = "_guard"
_watchlist_process_guards_lock = Lock()
_watchlist_process_guards = {}
@contextmanager
def _watchlist_user_guard(uid):
"""Serialize same-user name/count mutations within this worker.
Firestore's per-user guard document below provides the cross-worker
transaction conflict. This short-lived process guard keeps local fakes
and same-process requests from observing one another between transaction
retries, and its reference-counted cleanup prevents unbounded UID growth.
"""
with _watchlist_process_guards_lock:
entry = _watchlist_process_guards.get(uid)
if entry is None:
entry = {"lock": Lock(), "users": 0}
_watchlist_process_guards[uid] = entry
entry["users"] += 1
lock = entry["lock"]
lock.acquire()
try:
yield
finally:
lock.release()
with _watchlist_process_guards_lock:
entry["users"] -= 1
if entry["users"] == 0 and _watchlist_process_guards.get(uid) is entry:
_watchlist_process_guards.pop(uid, None)
def load_tickers_to_cache():
global _ticker_cache, _ticker_by_symbol, _ticker_cache_ready, _ticker_cache_error
try:
ticker_path = Path(__file__).resolve().parent / "all_exchanges_clean.json"
with ticker_path.open("r", encoding="utf-8") as f:
raw_tickers = json.load(f)
if not isinstance(raw_tickers, list):
raise ValueError("ticker data must be a JSON array")
_ticker_cache = [item for item in raw_tickers if isinstance(item, dict)]
_ticker_by_symbol = {
str(item.get("symbol", "")).upper(): item
for item in _ticker_cache if item.get("symbol")
}
_ticker_cache_ready = bool(_ticker_cache)
_ticker_cache_error = None if _ticker_cache_ready else "ticker data is empty"
print(json.dumps({
"event": "ticker_cache",
"status": "ready" if _ticker_cache_ready else "empty",
"count": len(_ticker_cache),
}, separators=(",", ":")))
except FileNotFoundError:
print(json.dumps({
"event": "ticker_cache",
"status": "missing",
}, separators=(",", ":")))
_ticker_cache = []
_ticker_by_symbol = {}
_ticker_cache_ready = False
_ticker_cache_error = "ticker data file is missing"
except Exception as error:
print(json.dumps({
"event": "ticker_cache",
"status": "invalid",
"errorType": type(error).__name__,
}, separators=(",", ":")))
_ticker_cache = []
_ticker_by_symbol = {}
_ticker_cache_ready = False
_ticker_cache_error = type(error).__name__
load_tickers_to_cache()
def is_valid_ticker(ticker_symbol):
normalized = _normalize_ticker(ticker_symbol)
if not normalized or not _ticker_cache_ready:
return False
return normalized in _ticker_by_symbol
def _safe_float(value):
try:
if value is None or isinstance(value, bool):
return None
normalized = float(value)
if not math.isfinite(normalized) or abs(normalized) > MAX_SERVER_NUMBER_ABS:
return None
return normalized
except (OverflowError, TypeError, ValueError):
return None
def _prune_cache(cache, limit):
while len(cache) > limit:
oldest = min(cache, key=lambda key: cache[key].get("timestamp", 0))
cache.pop(oldest, None)
def _normalize_tickers(ticker_symbols, deduplicate=False):
normalized = []
seen = set()
if not isinstance(ticker_symbols, (list, tuple)):
return normalized
for symbol in ticker_symbols:
symbol_clean = _normalize_ticker(symbol) or ""
if deduplicate and (not symbol_clean or symbol_clean in seen):
continue
seen.add(symbol_clean)
normalized.append(symbol_clean)
return normalized
def _extract_batch_price(downloaded, symbol, allow_single_column_fallback=False):
if downloaded is None or getattr(downloaded, "empty", True):
return None
series = None
for field in ("Close", "Adj Close"):
try:
candidate = downloaded[field]
except (KeyError, TypeError):
continue
if isinstance(candidate, pd.DataFrame):
if symbol in candidate.columns:
series = candidate[symbol]
elif allow_single_column_fallback and len(candidate.columns) == 1:
series = candidate.iloc[:, 0]
else:
# A Series has no reliable symbol identity in a multi-symbol
# response. Only use it when the original request was single-
# symbol, or when Yahoo explicitly labels the series for us.
series_name = getattr(candidate, "name", None)
if allow_single_column_fallback or series_name == symbol:
series = candidate
if series is not None:
break
if series is None:
return None
values = pd.to_numeric(series, errors="coerce").dropna()
return _safe_float(values.iloc[-1]) if not values.empty else None
def _fetch_current_prices(symbols):
if not symbols:
return {}
if len(symbols) > MAX_PROVIDER_BATCH_TICKERS:
raise ProviderInputError(
f"At most {MAX_PROVIDER_BATCH_TICKERS} provider tickers may be requested."
)
end = (_utc_now() + datetime.timedelta(days=1)).date().isoformat()
start = (_utc_now() - datetime.timedelta(days=7)).date().isoformat()
downloaded = _run_bounded_provider(
"Yahoo quote batch",
lambda: yf.download(
tickers=symbols,
start=start,
end=end,
interval="1d",
auto_adjust=True,
progress=False,
group_by="column",
threads=False,
timeout=PORTFOLIO_PRICE_FETCH_TIMEOUT_SECONDS,
),
PORTFOLIO_PRICE_FETCH_TIMEOUT_SECONDS,
)
allow_single_column_fallback = len(symbols) == 1
return {
symbol: _extract_batch_price(
downloaded,
symbol,
allow_single_column_fallback=allow_single_column_fallback,
)
for symbol in symbols
}
def _quote_age(quote, now):
if not isinstance(quote, dict):
return float("inf")
try:
timestamp = quote.get("timestamp", 0)
if isinstance(timestamp, bool):
return float("inf")
timestamp = float(timestamp)
if not math.isfinite(timestamp):
return float("inf")
return max(0, now - timestamp)
except (OverflowError, TypeError, ValueError):
return float("inf")
def _quote_freshness(quote, now):
if not isinstance(quote, dict) or _safe_float(quote.get("price")) is None:
return "unavailable"
age = _quote_age(quote, now)
if age < PRICE_FRESH_TTL_SECONDS:
return "fresh"
if age < PRICE_STALE_TTL_SECONDS:
return "stale"
if age < PRICE_LAST_KNOWN_TTL_SECONDS:
return "last_known"
return "unavailable"
def list_current_price(ticker_symbols):
normalized = _normalize_tickers(ticker_symbols)
symbols = list(dict.fromkeys(symbol for symbol in normalized if symbol))
now = time.time()
results = {}
cache_statuses = {}
freshnesses = {}
fallback_candidates = {}
missing = []
# Redis reads are batched before the provider lock. If Redis is down, the
# circuit returns an empty mapping immediately and process-local state is
# used without paying a timeout per symbol.
shared_quotes = _shared_cache_get_many("portfolio-quote", symbols)
shared_failures = _shared_cache_get_many("portfolio-quote-failure", symbols)
for symbol in symbols:
with _price_cache_lock:
cached = _price_cache.get(symbol)
local_failure = _price_failure_cache.get(symbol)
cached_freshness = _quote_freshness(cached, now)
if cached_freshness == "fresh":
results[symbol] = cached
cache_statuses[symbol] = "hit"
freshnesses[symbol] = "fresh"
_log_cache_event("portfolio_quote", "fresh")
continue
if cached_freshness in {"stale", "last_known"}:
fallback_candidates[symbol] = cached
elif isinstance(cached, dict) and cached.get("price") is not None:
_log_cache_event("portfolio_quote", "expired")
shared = shared_quotes.get(symbol)
shared_freshness = _quote_freshness(shared, now)
if shared_freshness == "fresh":
with _price_cache_lock:
_price_cache[symbol] = shared
_prune_cache(_price_cache, PRICE_CACHE_MAX_ENTRIES)
results[symbol] = shared
cache_statuses[symbol] = "shared"
freshnesses[symbol] = "fresh"
_log_cache_event("portfolio_quote", "fresh")
continue
if shared_freshness in {"stale", "last_known"}:
current_fallback = fallback_candidates.get(symbol)
if not current_fallback or _quote_age(shared, now) < _quote_age(current_fallback, now):
fallback_candidates[symbol] = shared
with _price_cache_lock:
_price_cache[symbol] = fallback_candidates[symbol]
_prune_cache(_price_cache, PRICE_CACHE_MAX_ENTRIES)
elif isinstance(shared, dict) and shared.get("price") is not None:
_log_cache_event("portfolio_quote", "expired")
shared_failure = shared_failures.get(symbol)
recent_failure = shared_failure or local_failure
if (
symbol not in fallback_candidates
and recent_failure
and _quote_age(recent_failure, now) < PRICE_FAILURE_CACHE_TTL_SECONDS
):
results[symbol] = {"price": None, "timestamp": recent_failure.get("timestamp")}
cache_statuses[symbol] = "error"
freshnesses[symbol] = "unavailable"
_log_cache_event("portfolio_quote", "negative_hit")
continue
missing.append(symbol)
_log_cache_event("portfolio_quote", "miss")
shared_quote_writes = {}
shared_failure_writes = {}
if missing:
with _price_fetch_lock:
refresh_symbols = []
refresh_now = time.time()
for symbol in missing:
with _price_cache_lock:
cached = _price_cache.get(symbol)
if _quote_freshness(cached, refresh_now) == "fresh":
results[symbol] = cached
cache_statuses[symbol] = "hit"
freshnesses[symbol] = "fresh"
_log_cache_event("portfolio_quote", "fresh")
else:
refresh_symbols.append(symbol)
fetched = {}
fetch_failed = False
if refresh_symbols:
try:
fetched = _fetch_current_prices(refresh_symbols)
except Exception as exc:
fetch_failed = True
_log_provider_failure(
"portfolio_quote_batch_failed",
error=exc,
count=len(refresh_symbols),
)
for symbol in refresh_symbols:
price = fetched.get(symbol)
if price is not None:
quote = {"price": price, "timestamp": time.time()}
results[symbol] = quote
cache_statuses[symbol] = "miss"
freshnesses[symbol] = "fresh"
with _price_cache_lock: