parent
dc663ec8f5
commit
33a64b99ff
@ -0,0 +1,35 @@
|
|||||||
|
import {HTTPKernel} from '../HTTPKernel'
|
||||||
|
import {Request} from '../../lifecycle/Request'
|
||||||
|
import {ActivatedRoute} from '../../routing/ActivatedRoute'
|
||||||
|
import {withErrorContext} from '../../../util'
|
||||||
|
import {AbstractResolvedRouteHandlerHTTPModule} from './AbstractResolvedRouteHandlerHTTPModule'
|
||||||
|
import {ExecuteResolvedRoutePreflightHTTPModule} from './ExecuteResolvedRoutePreflightHTTPModule'
|
||||||
|
import {WebSocketBus} from '../../../support/bus'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP kernel module that runs the web socket handler for the socket connection's route.
|
||||||
|
*/
|
||||||
|
export class ExecuteResolvedWebSocketHandlerHTTPModule extends AbstractResolvedRouteHandlerHTTPModule {
|
||||||
|
public static register(kernel: HTTPKernel): void {
|
||||||
|
kernel.register(this).after(ExecuteResolvedRoutePreflightHTTPModule)
|
||||||
|
}
|
||||||
|
|
||||||
|
public async apply(request: Request): Promise<Request> {
|
||||||
|
const route = <ActivatedRoute<unknown, unknown[]>> request.make(ActivatedRoute)
|
||||||
|
const params = route.resolvedParameters
|
||||||
|
if ( !params ) {
|
||||||
|
throw new Error('Attempted to call route handler without resolved parameters.')
|
||||||
|
}
|
||||||
|
|
||||||
|
await withErrorContext(async () => {
|
||||||
|
const ws = request.make<WebSocketBus>(WebSocketBus)
|
||||||
|
await route.handler
|
||||||
|
.tap(handler => handler(ws, ...params))
|
||||||
|
.apply(request)
|
||||||
|
}, {
|
||||||
|
route,
|
||||||
|
})
|
||||||
|
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,96 @@
|
|||||||
|
import {HTTPKernelModule} from '../HTTPKernelModule'
|
||||||
|
import {HTTPKernel} from '../HTTPKernel'
|
||||||
|
import {Request} from '../../lifecycle/Request'
|
||||||
|
import {Inject, Injectable} from '../../../di'
|
||||||
|
import {Config} from '../../../service/Config'
|
||||||
|
import {setInterval} from 'timers'
|
||||||
|
import {Logging} from '../../../service/Logging'
|
||||||
|
import {WebSocketCloseEvent} from '../../lifecycle/WebSocketCloseEvent'
|
||||||
|
import Timeout = NodeJS.Timeout;
|
||||||
|
import {Bus} from '../../../support/bus'
|
||||||
|
import * as WebSockets from 'ws'
|
||||||
|
import {Maybe} from '../../../util'
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MonitorWebSocketConnectionHTTPModule extends HTTPKernelModule {
|
||||||
|
@Inject()
|
||||||
|
protected readonly config!: Config
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
protected readonly logging!: Logging
|
||||||
|
|
||||||
|
public static register(kernel: HTTPKernel): void {
|
||||||
|
kernel.register(this).core()
|
||||||
|
}
|
||||||
|
|
||||||
|
async apply(request: Request): Promise<Request> {
|
||||||
|
const ws = request.make<WebSockets.WebSocket>(WebSockets.WebSocket)
|
||||||
|
|
||||||
|
// Time to wait between pings
|
||||||
|
const pollIntervalMs = this.config.safe('server.socket.pollIntervalMs')
|
||||||
|
.or(30000)
|
||||||
|
.integer()
|
||||||
|
|
||||||
|
// Time to wait for a response
|
||||||
|
const pollResponseTimeoutMs = this.config.safe('server.socket.pollResponseTimeoutMs')
|
||||||
|
.or(3000)
|
||||||
|
.integer()
|
||||||
|
|
||||||
|
// Max # of failures before the connection is closed
|
||||||
|
const maxFailedPolls = this.config.safe('server.socket.maxFailedPolls')
|
||||||
|
.or(5)
|
||||||
|
.integer()
|
||||||
|
|
||||||
|
let failedPolls = 0
|
||||||
|
let interval: Maybe<Timeout> = undefined
|
||||||
|
|
||||||
|
await new Promise<void>(res => {
|
||||||
|
let gotResponse = false
|
||||||
|
|
||||||
|
// Listen for pong responses
|
||||||
|
ws.on('pong', () => {
|
||||||
|
this.logging.verbose('Got pong response from socket.')
|
||||||
|
gotResponse = true
|
||||||
|
})
|
||||||
|
|
||||||
|
// Listen for close event
|
||||||
|
ws.on('close', () => {
|
||||||
|
this.logging.debug('Got close event from socket.')
|
||||||
|
res()
|
||||||
|
})
|
||||||
|
|
||||||
|
interval = setInterval(async () => {
|
||||||
|
// Every interval, send a ping request and set a timeout for the response
|
||||||
|
this.logging.verbose('Sending ping request to socket...')
|
||||||
|
gotResponse = false
|
||||||
|
ws.ping()
|
||||||
|
|
||||||
|
await new Promise<void>(res2 => setTimeout(res2, pollResponseTimeoutMs))
|
||||||
|
|
||||||
|
// If no pong response is received before the timeout occurs, tick the # of failed response
|
||||||
|
if ( !gotResponse ) {
|
||||||
|
this.logging.verbose('Socket failed to respond in time.')
|
||||||
|
failedPolls += 1
|
||||||
|
} else {
|
||||||
|
// Otherwise, reset the failure counter
|
||||||
|
failedPolls = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Once the failed responses exceeds the threshold, kill the connection
|
||||||
|
if ( failedPolls > maxFailedPolls ) {
|
||||||
|
this.logging.debug('Socket exceeded maximum # of failed pings. Killing.')
|
||||||
|
res()
|
||||||
|
}
|
||||||
|
}, pollIntervalMs)
|
||||||
|
})
|
||||||
|
|
||||||
|
if ( interval ) {
|
||||||
|
clearInterval(interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tell the server to close the socket connection
|
||||||
|
const bus = request.make<Bus>(Bus)
|
||||||
|
await bus.push(new WebSocketCloseEvent())
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
import {Injectable, Inject} from '../../../di'
|
||||||
|
import {HTTPKernelModule} from '../HTTPKernelModule'
|
||||||
|
import {HTTPKernel} from '../HTTPKernel'
|
||||||
|
import {Request} from '../../lifecycle/Request'
|
||||||
|
import {Routing} from '../../../service/Routing'
|
||||||
|
import {ActivatedRoute} from '../../routing/ActivatedRoute'
|
||||||
|
import {Logging} from '../../../service/Logging'
|
||||||
|
import {apiEvent, error} from '../../response/api'
|
||||||
|
import {Bus, WebSocketBus} from '../../../support/bus'
|
||||||
|
import {WebSocketCloseEvent} from '../../lifecycle/WebSocketCloseEvent'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP kernel middleware that tries to find a registered route matching the request's
|
||||||
|
* path and creates an ActivatedRoute instance from it, limited to websocket handling
|
||||||
|
* routes.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class MountWebSocketRouteHTTPModule extends HTTPKernelModule {
|
||||||
|
public readonly executeWithBlockingWriteback = true
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
protected readonly routing!: Routing
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
protected readonly logging!: Logging
|
||||||
|
|
||||||
|
public static register(kernel: HTTPKernel): void {
|
||||||
|
kernel.register(this).before()
|
||||||
|
}
|
||||||
|
|
||||||
|
public async apply(request: Request): Promise<Request> {
|
||||||
|
const route = this.routing.match('ws', request.path)
|
||||||
|
if ( route ) {
|
||||||
|
this.logging.verbose(`Mounting activated WebSocket route: ${request.path} -> ${route}`)
|
||||||
|
const activated = <ActivatedRoute<unknown, unknown[]>> request.make(ActivatedRoute, route, request.path)
|
||||||
|
request.registerSingletonInstance<ActivatedRoute<unknown, unknown[]>>(ActivatedRoute, activated)
|
||||||
|
} else {
|
||||||
|
this.logging.debug(`No matching WebSocket route found for: ${request.method} -> ${request.path}`)
|
||||||
|
|
||||||
|
// Send an error response on the socket to the client
|
||||||
|
const ws = request.make<WebSocketBus>(WebSocketBus)
|
||||||
|
await ws.push(apiEvent(error('Endpoint is not a configured socket listener.')))
|
||||||
|
|
||||||
|
// Then, terminate the request & socket connections
|
||||||
|
await request.make<Bus>(Bus).push(new WebSocketCloseEvent())
|
||||||
|
request.response.blockingWriteback(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
import {Event} from '../../support/bus'
|
||||||
|
import {uuid4} from '../../util'
|
||||||
|
|
||||||
|
/** Event used to tell the server to close the websocket connection. */
|
||||||
|
export class WebSocketCloseEvent implements Event {
|
||||||
|
eventName = '@extollo/lib:WebSocketCloseEvent'
|
||||||
|
|
||||||
|
eventUuid = uuid4()
|
||||||
|
|
||||||
|
shouldBroadcast = false
|
||||||
|
}
|
@ -0,0 +1,123 @@
|
|||||||
|
import {AwareOfContainerLifecycle, Container, Inject, Injectable, StaticInstantiable} from '../../di'
|
||||||
|
import {
|
||||||
|
EventBus,
|
||||||
|
Event,
|
||||||
|
EventHandler,
|
||||||
|
EventHandlerSubscription,
|
||||||
|
BusSubscriber,
|
||||||
|
EventHandlerReturn,
|
||||||
|
} from './types'
|
||||||
|
import * as WebSocket from 'ws'
|
||||||
|
import {NoSerializerError, Serialization} from './serial/Serialization'
|
||||||
|
import {Logging} from '../../service/Logging'
|
||||||
|
import {Awaitable, Collection, Pipeline, uuid4} from '../../util'
|
||||||
|
import {getEventName} from './getEventName'
|
||||||
|
import {Bus} from './Bus'
|
||||||
|
import {WebSocketCloseEvent} from '../../http/lifecycle/WebSocketCloseEvent'
|
||||||
|
import {apiEvent, error} from '../../http/response/api'
|
||||||
|
import {AsyncResource, executionAsyncId} from 'async_hooks'
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class WebSocketBus implements EventBus, AwareOfContainerLifecycle {
|
||||||
|
awareOfContainerLifecycle: true = true
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
protected readonly ws!: WebSocket.WebSocket
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
protected readonly bus!: Bus
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
protected readonly serial!: Serialization
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
protected readonly logging!: Logging
|
||||||
|
|
||||||
|
public readonly uuid = uuid4()
|
||||||
|
|
||||||
|
private connected = false
|
||||||
|
|
||||||
|
/** List of local subscriptions on this bus. */
|
||||||
|
protected subscriptions: Collection<BusSubscriber<Event>> = new Collection()
|
||||||
|
|
||||||
|
/** Get a Promise that resolves then the socket closes. */
|
||||||
|
onClose(): Promise<WebSocketCloseEvent> {
|
||||||
|
return new Promise<WebSocketCloseEvent>(res => {
|
||||||
|
this.bus.subscribe(WebSocketCloseEvent, event => res(event))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pipe<T extends Event>(eventKey: StaticInstantiable<T>, line: Pipeline<T, EventHandlerReturn>): Awaitable<EventHandlerSubscription> {
|
||||||
|
return this.subscribe(eventKey, event => line.apply(event))
|
||||||
|
}
|
||||||
|
|
||||||
|
async push(event: Event): Promise<void> {
|
||||||
|
this.logging.verbose(`Pushing event to WebSocket: ${event.eventName}`)
|
||||||
|
this.logging.verbose(event)
|
||||||
|
|
||||||
|
await this.ws.send(await this.serial.encodeJSON(event))
|
||||||
|
}
|
||||||
|
|
||||||
|
async subscribe<T extends Event>(eventKey: StaticInstantiable<T>, handler: EventHandler<T>): Promise<EventHandlerSubscription> {
|
||||||
|
const uuid = uuid4()
|
||||||
|
const subscriber: BusSubscriber<Event> = {
|
||||||
|
eventName: getEventName(eventKey),
|
||||||
|
eventKey,
|
||||||
|
handler,
|
||||||
|
uuid,
|
||||||
|
} as unknown as BusSubscriber<Event>
|
||||||
|
|
||||||
|
this.logging.verbose(`Creating WebSocket subscriber ${uuid}...`)
|
||||||
|
this.logging.verbose(subscriber)
|
||||||
|
|
||||||
|
this.subscriptions.push(subscriber)
|
||||||
|
|
||||||
|
return {
|
||||||
|
unsubscribe: () => {
|
||||||
|
this.subscriptions = this.subscriptions.where('uuid', '!=', uuid)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async onMessage(message: string): Promise<void> {
|
||||||
|
const payload = await this.serial.decodeJSON<Event>(message) // FIXME validation
|
||||||
|
|
||||||
|
await this.subscriptions
|
||||||
|
.where('eventName', '=', payload.eventName)
|
||||||
|
.awaitMapCall('handler', payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
up(): void {
|
||||||
|
const resource = new AsyncResource('WebSocketBus', {
|
||||||
|
triggerAsyncId: executionAsyncId(),
|
||||||
|
requireManualDestroy: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
this.ws.on('message', async data => {
|
||||||
|
await resource.runInAsyncScope(async () => {
|
||||||
|
this.logging.verbose(`Got data from websocket: ${data}`)
|
||||||
|
try {
|
||||||
|
Container.getContainer()
|
||||||
|
await this.onMessage(`${data}`)
|
||||||
|
} catch (e: unknown) {
|
||||||
|
if ( e instanceof NoSerializerError ) {
|
||||||
|
this.logging.warn(`Discarding message as no validator could be found to deserialize it: ${data}`)
|
||||||
|
this.push(apiEvent(error('Invalid message format or serializer.')))
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
this.connected = true
|
||||||
|
}
|
||||||
|
|
||||||
|
down(): void {
|
||||||
|
this.connected = false
|
||||||
|
}
|
||||||
|
|
||||||
|
isConnected(): boolean {
|
||||||
|
return this.connected // FIXME: monitor for bad connections
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
import {BaseSerializer} from './BaseSerializer'
|
||||||
|
import {Awaitable, JSONState, uuid4} from '../../../util'
|
||||||
|
import {ObjectSerializer} from './decorators'
|
||||||
|
import {Event} from '../types'
|
||||||
|
|
||||||
|
export class JSONMessageEvent<T extends JSONState> implements Event {
|
||||||
|
constructor(
|
||||||
|
public readonly value: T,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
eventName = '@extollo/lib:JSONMessageEvent'
|
||||||
|
|
||||||
|
eventUuid = uuid4()
|
||||||
|
}
|
||||||
|
|
||||||
|
@ObjectSerializer()
|
||||||
|
export class JSONMessageEventSerializer extends BaseSerializer<JSONMessageEvent<JSONState>, { value: JSONState }> {
|
||||||
|
protected decodeSerial(serial: { value: JSONState }): Awaitable<JSONMessageEvent<JSONState>> {
|
||||||
|
return new JSONMessageEvent(serial.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
protected encodeActual(actual: JSONMessageEvent<JSONState>): Awaitable<{ value: JSONState }> {
|
||||||
|
return {
|
||||||
|
value: actual.value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getName(): string {
|
||||||
|
return '@extollo/lib:JSONMessageEventSerializer'
|
||||||
|
}
|
||||||
|
|
||||||
|
matchActual(some: JSONMessageEvent<JSONState>): boolean {
|
||||||
|
return some instanceof JSONMessageEvent
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
import {Event, SerialPayload} from '../types'
|
||||||
|
import {ObjectSerializer} from './decorators'
|
||||||
|
import {BaseSerializer} from './BaseSerializer'
|
||||||
|
import {JSONState} from '../../../util'
|
||||||
|
|
||||||
|
export class NamedEventPayload {
|
||||||
|
constructor(
|
||||||
|
public readonly eventName: string,
|
||||||
|
public readonly event: Event,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
@ObjectSerializer()
|
||||||
|
export class NamedEventPayloadSerializer extends BaseSerializer<NamedEventPayload, { eventName: string, event: SerialPayload<Event, JSONState> }> {
|
||||||
|
protected async decodeSerial(serial: { eventName: string; event: SerialPayload<Event, JSONState> }): Promise<NamedEventPayload> {
|
||||||
|
return new NamedEventPayload(
|
||||||
|
serial.eventName,
|
||||||
|
await this.getSerialization().decode(serial.event),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async encodeActual(actual: NamedEventPayload): Promise<{ eventName: string; event: SerialPayload<Event, JSONState> }> {
|
||||||
|
return {
|
||||||
|
eventName: actual.eventName,
|
||||||
|
event: await this.getSerialization().encode(actual.event),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getName(): string {
|
||||||
|
return '@extollo/lib:NamedEventPayloadSerializer'
|
||||||
|
}
|
||||||
|
|
||||||
|
matchActual(some: NamedEventPayload): boolean {
|
||||||
|
return some instanceof NamedEventPayload
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue