robdiciuccio commented on a change in pull request #11498: URL: https://github.com/apache/superset/pull/11498#discussion_r603543026
########## File path: superset-websocket/src/index.ts ########## @@ -0,0 +1,329 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +import * as http from 'http'; +import * as net from 'net'; +import WebSocket from 'ws'; +import { v4 as uuidv4 } from 'uuid'; + +const jwt = require('jsonwebtoken'); +const cookie = require('cookie'); +const Redis = require('ioredis'); + +export type StreamResult = [recordId: string, record: [label: 'data', data: string]]; + +// sync with superset-frontend/src/components/ErrorMessage/types +export type ErrorLevel = 'info' | 'warning' | 'error'; +export type SupersetError<ExtraType = Record<string, any> | null> = { + error_type: string; + extra: ExtraType; + level: ErrorLevel; + message: string; +}; + +type ListenerFunction = (results: StreamResult[]) => void; +interface EventValue { + id: string, + channel_id: string, + job_id: string, + user_id?: string, + status: string, + errors?: SupersetError[], + result_url?: string, +} +interface JwtPayload { channel: string } +interface FetchRangeFromStreamParams { sessionId: string, startId: string, endId: string, listener: ListenerFunction } +export interface SocketInstance { ws: WebSocket, channel: string, pongTs: number } + +interface ChannelValue { + sockets: Array<string>, +} + +const environment = process.env.NODE_ENV; +export const opts = { + port: 8080, + redis: { + port: 6379, + host: "127.0.0.1", + password: "", + db: 0 + }, + streamPrefix: "async-events-", + jwtSecret: "", + jwtCookieName: "async-token", + redisStreamReadCount: 100, + redisStreamReadBlockMs: 5000, + socketResponseTimeoutMs: 60 * 1000, + pingSocketsIntervalMs: 20 * 1000, + gcChannelsIntervalMs: 120 * 1000, +} + +const startServer = process.argv[2] === 'start'; +const configFile = environment === 'test' ? '../config.test.json' : '../config.json'; +let config = {}; +try { + config = require(configFile); +} catch(err) { + console.warn('config.json not found, using defaults'); +} + +Object.assign(opts, config); + +if(startServer && opts.jwtSecret.length < 32) + throw('Please provide a JWT secret at least 32 bytes long') + +const redis = new Redis(opts.redis); +const httpServer = http.createServer(); +export const wss = new WebSocket.Server({ noServer: true, clientTracking: false }); + +const SOCKET_ACTIVE_STATES = [WebSocket.OPEN, WebSocket.CONNECTING]; +const GLOBAL_EVENT_STREAM_NAME = `${opts.streamPrefix}full`; +const DEFAULT_STREAM_LAST_ID = '$'; + +export let channels: Record<string, ChannelValue> = {}; +export let sockets: Record<string, SocketInstance> = {}; +let lastFirehoseId: string = DEFAULT_STREAM_LAST_ID; + + +export const setLastFirehoseId = (id: string): void => { + lastFirehoseId = id; +} + +export const trackClient = (channel: string, socketInstance: SocketInstance): string => { + const socketId = uuidv4(); + sockets[socketId] = socketInstance; + + if(channel in channels) { + channels[channel].sockets.push(socketId) + } else { + channels[channel] = {sockets: [socketId]}; + } + + return socketId; +} + +export const sendToChannel = (channel: string, value: EventValue): void => { + const strData = JSON.stringify(value); + if(!channels[channel]) { + console.debug(`channel ${channel} is unknown, skipping`); + return; + } + channels[channel].sockets.forEach(socketId => { + const socketInstance: SocketInstance = sockets[socketId]; + if(!socketInstance) return cleanChannel(channel); + try { + socketInstance.ws.send(strData); + } catch(err) { + console.debug('Error sending to socket', err); + cleanChannel(channel); + } + }); +} + +export const fetchRangeFromStream = async ({sessionId, startId, endId, listener}: FetchRangeFromStreamParams) => { + const streamName = `${opts.streamPrefix}${sessionId}`; + try { + const reply = await redis.xrange(streamName, startId, endId); + if (!reply || !reply.length) return; + listener(reply); + } catch(e) { + console.error(e); + } +} + +export const subscribeToGlobalStream = async (stream: string, listener: ListenerFunction) => { + /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/ + while (true) { Review comment: When events are received, it returns immediately. More info here: https://redis.io/commands/xread#blocking-for-data > When the BLOCK command is passed, but there is data to return at least in one of the streams passed, the command is executed synchronously exactly like if the BLOCK option would be missing. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
