@davoodmehraban89 / VELYQOR / commits / d06aa4c
Fork 0

Intelligence, Advanced Charting & Trading Platform

feat(realtime): Cloudflare Durable Object WebSocket gateway with private publisher

davoodmehraban89 committed Oct 12, 2026 at 00:19 UTC d06aa4c9c669c0b802df010dd5a3fb3ab43140be
1 file changed +117
deploy/chartnova/market-stream-worker.mjs new
+117
@@ -0,0 +1,117 @@
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 allowedSymbol(env,symbol){
19 + if(!symbolValid(symbol))return false;
20 + const approved=typeof env.STREAM_SYMBOL_ALLOWLIST==="string"?env.STREAM_SYMBOL_ALLOWLIST.split(",").map(x=>x.trim()):[];
21 + return approved.includes(symbol);
22 +}
23 +function room(env,symbol){
24 + if(!env.STREAM_ROOMS||typeof env.STREAM_ROOMS.idFromName!=="function")return null;
25 + return env.STREAM_ROOMS.get(env.STREAM_ROOMS.idFromName("symbol:"+symbol));
26 +}
27 +function parseMarketRecord(data){
28 + return data?.dataKind==="source_ohlc"?canonicalSourceCandle(data):
29 + data?.dataKind==="reference_point"?canonicalReferencePoint(data):
30 + (()=>{throw Error("unsupported record kind")})();
31 +}
32 +export async function routeStreamRequest(request,env){
33 + const url=new URL(request.url);
34 + if(url.pathname==="/health")return respond({ok:true,service:"chartnova-market-stream",livePublisherConfigured:!!(env.STREAM_INGEST_TOKEN&&env.STREAM_ROOMS),deployedPublisherVerified:false});
35 + if(url.pathname==="/stream"){
36 + if(request.method!=="GET")return respond({ok:false,error:"method_not_allowed"},405);
37 + if((request.headers.get("Upgrade")||"").toLowerCase()!=="websocket")return respond({ok:false,error:"websocket_upgrade_required"},426);
38 + if([...url.searchParams.keys()].some(k=>k!=="symbol"||url.searchParams.getAll(k).length!==1))return respond({ok:false,error:"invalid_query"},400);
39 + const symbol=url.searchParams.get("symbol");
40 + if(!allowedSymbol(env,symbol))return respond({ok:false,error:"symbol_unavailable"},404);
41 + const target=room(env,symbol);if(!target)return respond({ok:false,error:"stream_not_configured"},503);
42 + const forward=new URL("/connect",request.url);forward.searchParams.set("symbol",symbol);
43 + return target.fetch(new Request(forward,request));
44 + }
45 + if(url.pathname==="/internal/market-update"){
46 + if(request.method!=="POST")return respond({ok:false,error:"method_not_allowed"},405);
47 + const bearer=request.headers.get("authorization")||"";
48 + if(!equalSecret(bearer.startsWith("Bearer ")?bearer.slice(7):"",env.STREAM_INGEST_TOKEN))return respond({ok:false,error:"unauthorized"},401);
49 + const size=Number(request.headers.get("content-length")||0);
50 + if(size>8192)return respond({ok:false,error:"payload_too_large"},413);
51 + let item;try{item=await request.json()}catch{return respond({ok:false,error:"invalid_json"},400)}
52 + let record;
53 + try{record=parseMarketRecord(item)}catch{return respond({ok:false,error:"invalid_market_record"},422)}
54 + if(!allowedSymbol(env,record.symbol))return respond({ok:false,error:"symbol_unavailable"},404);
55 + if(!mayPublish(record))return respond({ok:false,error:"source_not_approved_for_public_stream"},403);
56 + const target=room(env,record.symbol);if(!target)return respond({ok:false,error:"stream_not_configured"},503);
57 + return target.fetch(new Request(new URL("/broadcast?symbol="+encodeURIComponent(record.symbol),request.url),{
58 + method:"POST",
59 + headers:{"content-type":"application/json","x-hub-key":env.STREAM_INGEST_TOKEN},
60 + body:JSON.stringify(record),
61 + }));
62 + }
63 + return respond({ok:false,error:"not_found"},404);
64 +}
65 +export default {fetch:routeStreamRequest};
66 +
67 +export class SymbolStreamRoom {
68 + constructor(state,env){this.state=state;this.env=env}
69 + async fetch(request){
70 + const url=new URL(request.url);
71 + const symbol=url.searchParams.get("symbol");
72 + if(!symbolValid(symbol))return respond({ok:false,error:"invalid_symbol"},400);
73 + if(url.pathname==="/connect"){
74 + if((request.headers.get("Upgrade")||"").toLowerCase()!=="websocket")return respond({ok:false,error:"upgrade_required"},426);
75 + const pair=new WebSocketPair();
76 + const [client,server]=Object.values(pair);
77 + this.state.acceptWebSocket(server,[symbol]);
78 + server.serializeAttachment({symbol,version:1});
79 + return new Response(null,{status:101,webSocket:client});
80 + }
81 + if(url.pathname==="/broadcast"&&request.method==="POST"){
82 + if(!equalSecret(request.headers.get("x-hub-key"),this.env.STREAM_INGEST_TOKEN))return respond({ok:false,error:"unauthorized"},401);
83 + let record;
84 + try{record=parseMarketRecord(await request.json())}catch{return respond({ok:false,error:"invalid_market_record"},422)}
85 + if(record.symbol!==symbol||!mayPublish(record))return respond({ok:false,error:"wrong_symbol_or_unlicensed"},403);
86 + const seq=await this.state.storage.transaction(async tx=>{
87 + const previous=await tx.get("nextSequence")??0;
88 + const next=previous+1;
89 + if(!Number.isSafeInteger(next))throw Error("stream sequence overflow");
90 + await tx.put("nextSequence",next);return next;
91 + });
92 + const envelope=transportFrame(record,seq,new Date().toISOString());
93 + const data=JSON.stringify(envelope);
94 + let delivered=0;
95 + for(const socket of this.state.getWebSockets(symbol)){
96 + if(socket.readyState!==1)continue;
97 + try{socket.send(data);delivered++}catch{try{socket.close(1011,"send error")}catch{}}
98 + }
99 + return respond({ok:true,symbol,sequence:seq,delivered});
100 + }
101 + return respond({ok:false,error:"not_found"},404);
102 + }
103 + webSocketMessage(ws,message){
104 + const attachment=ws.deserializeAttachment();
105 + if(!attachment||!symbolValid(attachment.symbol)){ws.close(1008,"invalid subscription");return}
106 + let input;try{input=parseClientMessage(message)}catch{ws.close(1008,"invalid protocol");return}
107 + if(input.type==="stream.ping"){
108 + ws.send(JSON.stringify({type:"stream.heartbeat",version:1,serverTime:new Date().toISOString()}));return;
109 + }
110 + if(input.type==="stream.subscribe"&&input.symbols.length===1&&input.symbols[0]===attachment.symbol){
111 + ws.send(JSON.stringify({type:"session.ready",version:1,symbol:attachment.symbol}));return;
112 + }
113 + ws.close(1008,"subscription mismatch");
114 + }
115 + webSocketClose(ws,code,reason){try{ws.close(code||1000,reason||"closed")}catch{}}
116 + webSocketError(ws){try{ws.close(1011,"internal error")}catch{}}
117 +}