robdiciuccio commented on a change in pull request #11498:
URL: https://github.com/apache/superset/pull/11498#discussion_r608048513



##########
File path: superset-websocket/src/index.ts
##########
@@ -0,0 +1,465 @@
+/**
+ * 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 winston = require('winston');
+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 RedisConfig {
+  port: number;
+  host: string;
+  password?: string | null;
+  db: number;
+  ssl: boolean;
+}
+
+interface ChannelValue {
+  sockets: Array<string>;
+}
+
+const environment = process.env.NODE_ENV;
+
+// default options
+export const opts = {
+  port: 8080,
+  logLevel: 'info',
+  logToFile: false,
+  logFilename: 'app.log',
+  redis: {
+    port: 6379,
+    host: '127.0.0.1',
+    password: '',
+    db: 0,
+    ssl: false,
+  },
+  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.error('config.json not found, using defaults');
+}
+// apply config overrides
+Object.assign(opts, config);
+
+// init logger
+const logTransports = [
+  new winston.transports.Console({ handleExceptions: true }),
+];
+if (opts.logToFile && opts.logFilename) {
+  logTransports.push(
+    new winston.transports.File({
+      filename: opts.logFilename,
+      handleExceptions: true,
+    }),
+  );
+}
+const logger = winston.createLogger({
+  level: opts.logLevel,
+  transports: logTransports,
+});
+
+// enforce JWT secret length
+if (startServer && opts.jwtSecret.length < 32)
+  throw new Error('Please provide a JWT secret at least 32 bytes long');
+
+export const redisUrlFromConfig = (redisConfig: RedisConfig): string => {
+  let url = redisConfig.ssl ? 'rediss://' : 'redis://';
+  if (redisConfig.password) url += `:${redisConfig.password}@`;
+  url += `${redisConfig.host}:${redisConfig.port}/${redisConfig.db}`;
+  return url;
+};
+
+// initialize servers
+const redis = new Redis(redisUrlFromConfig(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 = '$';
+
+// initialize internal registries
+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;
+};
+
+/**
+ * Adds the passed channel and socket instance to the internal registries.
+ */
+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;
+};
+
+/**
+ * Sends a single async event payload to a single channel.
+ * A channel may have multiple connected sockets, this emits
+ * the event to all connected sockets within a channel.
+ */
+export const sendToChannel = (channel: string, value: EventValue): void => {
+  const strData = JSON.stringify(value);
+  if (!channels[channel]) {
+    logger.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) {
+      logger.debug(`Error sending to socket: ${err}`);
+      // check that the connection is still active
+      cleanChannel(channel);
+    }
+  });
+};
+
+/**
+ * Reads a range of events from a channel-specific Redis event stream.
+ * Invoked in the client re-connection flow.
+ */
+export const fetchRangeFromStream = async ({

Review comment:
       Thinking about this more, there's an argument to be made for keeping 
this consistent with the interface for `subscribeToGlobalStream`.




-- 
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]

Reply via email to