Intelligence, Advanced Charting & Trading Platform
feature/chartnova-multimarket-chart-ws-foundation
diagnostics/chartnova-blank-screen-2026-10-15
diagnostics/chartnova-stage2-v27-preview-2026-10-15
docs/chartnova-stage1-reconcile-manifest-2026-10-15
feature/chartnova-ios-widget
feature/chartnova-light-catalog-lazy-series-2026-10-15
feature/chartnova-market-terminal
feature/chartnova-multimarket-chart-ws-foundation
feature/chartnova-neon-direct-history
feature/chartnova-neon-history
feature/paper-trading-risk-controls-2026-10-14
fix/alpha-vantage-live-payload
fix/chartnova-progressive-loading-2026-10-15
fix/live-proof-runner-cwd-2026-10-14
foundation/phase-0
foundation/postgres-core
main
ops/chartnova-emergency-rollback-2026-10-15
phase-1/candle-builder
phase-1/data-proof-artifact
phase-1/data-proof-metrics
phase-1/data-proof-report
phase-1/external-gates-state
phase-1/gold-api-fallback
phase-1/ingestion-pipeline
phase-1/live-proof-runner
phase-1/market-calendar
phase-1/market-domain
phase-1/neon-live-proof
phase-1/persistence-contract
phase-1/postgres-ci
phase-1/provider-adapters
phase-1/provider-recovery
phase-1/quality-propagation
phase-1/spike-detection
phase-1/xau-provider-adapter
risk/chartnova-alert-runtime-atomic-2026-10-22
risk/chartnova-atomic-outbox-2026-10-22
risk/chartnova-seven-track-safety-2026-10-21
safety/p0-triage-2026-10-13
| 1 | // Separate, UNDEPLOYED Cloudflare Worker + Durable Object WebSocket gateway. |
| 2 | // Hibernation keeps inbound subscriptions alive without a permanent Worker process. |
| 3 | // To activate: configure STREAM_ROOMS DO binding, STREAM_INGEST_TOKEN secret, |
| 4 | // route /stream and /internal/market-update, and review provider/public licensing. |
| 5 | import { |
| 6 | canonicalReferencePoint, canonicalSourceCandle, mayPublish, transportFrame, |
| 7 | } from "../../packages/market-feed/src/contracts.mjs"; |
| 8 | import {parseSubscriptions,parseClientMessage} from "../../packages/market-feed/src/stream-protocol.mjs"; |
| 9 | |
| 10 | const JSON_HEADERS={"content-type":"application/json; charset=utf-8","cache-control":"no-store","x-content-type-options":"nosniff"}; |
| 11 | const respond=(data,status=200)=>Response.json(data,{status,headers:JSON_HEADERS}); |
| 12 | const symbolValid=s=>typeof s==="string"&&/^[A-Z0-9_]{3,48}$/.test(s); |
| 13 | function equalSecret(a,b){ |
| 14 | if(typeof a!=="string"||typeof b!=="string"||b.length<32||a.length!==b.length)return false; |
| 15 | let mismatch=0;for(let i=0;i<a.length;i++)mismatch|=a.charCodeAt(i)^b.charCodeAt(i); |
| 16 | return mismatch===0; |
| 17 | } |
| 18 | function allowedOrigin(env,origin){ |
| 19 | if(!origin)return true; // non-browser subscribers still require independent edge rate limits |
| 20 | const list=typeof env.STREAM_ALLOWED_ORIGINS==="string"?env.STREAM_ALLOWED_ORIGINS.split(",").map(x=>x.trim()):[]; |
| 21 | return list.includes(origin); |
| 22 | } |
| 23 | async function readLimitedJson(request,maxBytes=8192){ |
| 24 | if(!request.body)return null; |
| 25 | const reader=request.body.getReader();let bytes=0;const decoder=new TextDecoder();let data=""; |
| 26 | try{ |
| 27 | while(true){const {done,value}=await reader.read();if(done)break; |
| 28 | bytes+=value.byteLength;if(bytes>maxBytes)throw Error("payload_too_large"); |
| 29 | data+=decoder.decode(value,{stream:true}); |
| 30 | } |
| 31 | data+=decoder.decode();return JSON.parse(data); |
| 32 | }finally{reader.releaseLock()} |
| 33 | } |
| 34 | function allowedSymbol(env,symbol){ |
| 35 | if(!symbolValid(symbol))return false; |
| 36 | const approved=typeof env.STREAM_SYMBOL_ALLOWLIST==="string"?env.STREAM_SYMBOL_ALLOWLIST.split(",").map(x=>x.trim()):[]; |
| 37 | return approved.includes(symbol); |
| 38 | } |
| 39 | function room(env,symbol){ |
| 40 | if(!env.STREAM_ROOMS||typeof env.STREAM_ROOMS.idFromName!=="function")return null; |
| 41 | return env.STREAM_ROOMS.get(env.STREAM_ROOMS.idFromName("symbol:"+symbol)); |
| 42 | } |
| 43 | function parseMarketRecord(data){ |
| 44 | return data?.dataKind==="source_ohlc"?canonicalSourceCandle(data): |
| 45 | data?.dataKind==="reference_point"?canonicalReferencePoint(data): |
| 46 | (()=>{throw Error("unsupported record kind")})(); |
| 47 | } |
| 48 | export async function routeStreamRequest(request,env){ |
| 49 | const url=new URL(request.url); |
| 50 | if(url.pathname==="/health")return respond({ok:true,service:"chartnova-market-stream",livePublisherConfigured:!!(env.STREAM_INGEST_TOKEN&&env.STREAM_ROOMS),deployedPublisherVerified:false}); |
| 51 | if(url.pathname==="/stream"){ |
| 52 | if(request.method!=="GET")return respond({ok:false,error:"method_not_allowed"},405); |
| 53 | if((request.headers.get("Upgrade")||"").toLowerCase()!=="websocket")return respond({ok:false,error:"websocket_upgrade_required"},426); |
| 54 | if(!allowedOrigin(env,request.headers.get("Origin")))return respond({ok:false,error:"origin_not_allowed"},403); |
| 55 | if([...url.searchParams.keys()].some(k=>k!=="symbol"||url.searchParams.getAll(k).length!==1))return respond({ok:false,error:"invalid_query"},400); |
| 56 | const symbol=url.searchParams.get("symbol"); |
| 57 | if(!allowedSymbol(env,symbol))return respond({ok:false,error:"symbol_unavailable"},404); |
| 58 | const target=room(env,symbol);if(!target)return respond({ok:false,error:"stream_not_configured"},503); |
| 59 | const forward=new URL("/connect",request.url);forward.searchParams.set("symbol",symbol); |
| 60 | return target.fetch(new Request(forward,request)); |
| 61 | } |
| 62 | if(url.pathname==="/internal/market-update"){ |
| 63 | if(request.method!=="POST")return respond({ok:false,error:"method_not_allowed"},405); |
| 64 | const bearer=request.headers.get("authorization")||""; |
| 65 | if(!equalSecret(bearer.startsWith("Bearer ")?bearer.slice(7):"",env.STREAM_INGEST_TOKEN))return respond({ok:false,error:"unauthorized"},401); |
| 66 | const size=Number(request.headers.get("content-length")||0); |
| 67 | if(size>8192)return respond({ok:false,error:"payload_too_large"},413); |
| 68 | let item;try{item=await readLimitedJson(request)}catch{return respond({ok:false,error:"invalid_json_or_oversized"},400)} |
| 69 | let record; |
| 70 | try{record=parseMarketRecord(item)}catch{return respond({ok:false,error:"invalid_market_record"},422)} |
| 71 | if(!allowedSymbol(env,record.symbol))return respond({ok:false,error:"symbol_unavailable"},404); |
| 72 | if(!mayPublish(record))return respond({ok:false,error:"source_not_approved_for_public_stream"},403); |
| 73 | const target=room(env,record.symbol);if(!target)return respond({ok:false,error:"stream_not_configured"},503); |
| 74 | return target.fetch(new Request(new URL("/broadcast?symbol="+encodeURIComponent(record.symbol),request.url),{ |
| 75 | method:"POST", |
| 76 | headers:{"content-type":"application/json","x-hub-key":env.STREAM_INGEST_TOKEN}, |
| 77 | body:JSON.stringify(record), |
| 78 | })); |
| 79 | } |
| 80 | return respond({ok:false,error:"not_found"},404); |
| 81 | } |
| 82 | export default {fetch:routeStreamRequest}; |
| 83 | |
| 84 | export class SymbolStreamRoom { |
| 85 | constructor(state,env){this.state=state;this.env=env} |
| 86 | async fetch(request){ |
| 87 | const url=new URL(request.url); |
| 88 | const symbol=url.searchParams.get("symbol"); |
| 89 | if(!symbolValid(symbol))return respond({ok:false,error:"invalid_symbol"},400); |
| 90 | if(url.pathname==="/connect"){ |
| 91 | if((request.headers.get("Upgrade")||"").toLowerCase()!=="websocket")return respond({ok:false,error:"upgrade_required"},426); |
| 92 | if(this.state.getWebSockets(symbol).length>=256)return respond({ok:false,error:"room_connection_limit"},429); |
| 93 | const pair=new WebSocketPair(); |
| 94 | const [client,server]=Object.values(pair); |
| 95 | this.state.acceptWebSocket(server,[symbol]); |
| 96 | server.serializeAttachment({symbol,version:1}); |
| 97 | return new Response(null,{status:101,webSocket:client}); |
| 98 | } |
| 99 | if(url.pathname==="/broadcast"&&request.method==="POST"){ |
| 100 | if(!equalSecret(request.headers.get("x-hub-key"),this.env.STREAM_INGEST_TOKEN))return respond({ok:false,error:"unauthorized"},401); |
| 101 | let record; |
| 102 | try{record=parseMarketRecord(await readLimitedJson(request))}catch{return respond({ok:false,error:"invalid_market_record"},422)} |
| 103 | if(record.symbol!==symbol||!mayPublish(record))return respond({ok:false,error:"wrong_symbol_or_unlicensed"},403); |
| 104 | const seq=await this.state.storage.transaction(async tx=>{ |
| 105 | const previous=await tx.get("nextSequence")??0; |
| 106 | const next=previous+1; |
| 107 | if(!Number.isSafeInteger(next))throw Error("stream sequence overflow"); |
| 108 | await tx.put("nextSequence",next);return next; |
| 109 | }); |
| 110 | const envelope=transportFrame(record,seq,new Date().toISOString()); |
| 111 | const data=JSON.stringify(envelope); |
| 112 | let delivered=0; |
| 113 | for(const socket of this.state.getWebSockets(symbol)){ |
| 114 | if(socket.readyState!==1)continue; |
| 115 | // Do not let a slow consumer hold an ever-growing outbound queue. |
| 116 | // An affected client must reconnect and reconcile from REST. |
| 117 | if(typeof socket.bufferedAmount==="number"&&socket.bufferedAmount>1_048_576){ |
| 118 | try{socket.close(1013,"slow consumer; REST recovery required")}catch{} |
| 119 | continue; |
| 120 | } |
| 121 | try{socket.send(data);delivered++}catch{try{socket.close(1011,"send error")}catch{}} |
| 122 | } |
| 123 | return respond({ok:true,symbol,sequence:seq,delivered}); |
| 124 | } |
| 125 | return respond({ok:false,error:"not_found"},404); |
| 126 | } |
| 127 | webSocketMessage(ws,message){ |
| 128 | const attachment=ws.deserializeAttachment(); |
| 129 | if(!attachment||!symbolValid(attachment.symbol)){ws.close(1008,"invalid subscription");return} |
| 130 | let input;try{input=parseClientMessage(message)}catch{ws.close(1008,"invalid protocol");return} |
| 131 | if(input.type==="stream.ping"){ |
| 132 | ws.send(JSON.stringify({type:"stream.heartbeat",version:1,serverTime:new Date().toISOString()}));return; |
| 133 | } |
| 134 | if(input.type==="stream.subscribe"&&input.symbols.length===1&&input.symbols[0]===attachment.symbol){ |
| 135 | ws.send(JSON.stringify({type:"session.ready",version:1,symbol:attachment.symbol}));return; |
| 136 | } |
| 137 | ws.close(1008,"subscription mismatch"); |
| 138 | } |
| 139 | webSocketClose(ws,code,reason){try{ws.close(code||1000,reason||"closed")}catch{}} |
| 140 | webSocketError(ws){try{ws.close(1011,"internal error")}catch{}} |
| 141 | } |