2021-08-03 22:02:59 +03:00
|
|
|
//
|
2022-04-14 08:30:30 +03:00
|
|
|
// Copyright © 2022 Hardcore Engineering Inc.
|
2021-08-03 22:02:59 +03:00
|
|
|
//
|
|
|
|
// Licensed under the Eclipse Public 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 https://www.eclipse.org/legal/epl-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.
|
|
|
|
//
|
|
|
|
|
2023-01-04 20:58:54 +03:00
|
|
|
import core, {
|
|
|
|
generateId,
|
|
|
|
MeasureContext,
|
|
|
|
Ref,
|
|
|
|
Space,
|
|
|
|
toWorkspaceString,
|
|
|
|
TxFactory,
|
|
|
|
WorkspaceId
|
|
|
|
} from '@hcengineering/core'
|
2022-09-21 11:08:25 +03:00
|
|
|
import { readRequest, Response, serialize, UNAUTHORIZED, unknownError } from '@hcengineering/platform'
|
|
|
|
import type { Pipeline } from '@hcengineering/server-core'
|
|
|
|
import { decodeToken, Token } from '@hcengineering/server-token'
|
2021-08-03 22:02:59 +03:00
|
|
|
import { createServer, IncomingMessage } from 'http'
|
2022-11-02 11:50:14 +03:00
|
|
|
import WebSocket, { WebSocketServer } from 'ws'
|
2022-05-23 18:53:33 +03:00
|
|
|
import { BroadcastCall, Session } from './types'
|
2021-08-03 22:02:59 +03:00
|
|
|
|
2022-01-27 11:53:09 +03:00
|
|
|
let LOGGING_ENABLED = true
|
2021-08-11 12:35:56 +03:00
|
|
|
|
2022-04-23 06:45:55 +03:00
|
|
|
export function disableLogging (): void {
|
|
|
|
LOGGING_ENABLED = false
|
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
|
|
|
|
interface Workspace {
|
2023-01-04 20:58:54 +03:00
|
|
|
id: string
|
|
|
|
pipeline: Promise<Pipeline>
|
2021-08-11 12:35:56 +03:00
|
|
|
sessions: [Session, WebSocket][]
|
2022-05-23 18:53:33 +03:00
|
|
|
upgrade: boolean
|
2023-01-04 20:58:54 +03:00
|
|
|
closing?: Promise<void>
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
class SessionManager {
|
|
|
|
private readonly workspaces = new Map<string, Workspace>()
|
|
|
|
|
2022-05-23 18:53:33 +03:00
|
|
|
constructor (readonly sessionFactory: (token: Token, pipeline: Pipeline, broadcast: BroadcastCall) => Session) {}
|
|
|
|
|
|
|
|
createSession (token: Token, pipeline: Pipeline): Session {
|
|
|
|
return this.sessionFactory(token, pipeline, this.broadcast.bind(this))
|
|
|
|
}
|
|
|
|
|
2022-04-23 06:45:55 +03:00
|
|
|
async addSession (
|
|
|
|
ctx: MeasureContext,
|
|
|
|
ws: WebSocket,
|
|
|
|
token: Token,
|
2023-01-04 20:58:54 +03:00
|
|
|
pipelineFactory: (ws: WorkspaceId, upgrade: boolean) => Promise<Pipeline>,
|
2022-11-16 18:03:03 +03:00
|
|
|
productId: string
|
2022-04-23 06:45:55 +03:00
|
|
|
): Promise<Session> {
|
2022-11-16 18:03:03 +03:00
|
|
|
const wsString = toWorkspaceString(token.workspace, '@')
|
2023-01-04 20:58:54 +03:00
|
|
|
|
|
|
|
let workspace = this.workspaces.get(wsString)
|
|
|
|
await workspace?.closing
|
|
|
|
workspace = this.workspaces.get(wsString)
|
|
|
|
|
2021-08-11 12:35:56 +03:00
|
|
|
if (workspace === undefined) {
|
2023-01-04 20:58:54 +03:00
|
|
|
workspace = this.createWorkspace(pipelineFactory, token)
|
|
|
|
}
|
2022-01-27 11:53:09 +03:00
|
|
|
|
2023-01-04 20:58:54 +03:00
|
|
|
if (token.extra?.model === 'upgrade') {
|
|
|
|
console.log('reloading workspace', JSON.stringify(token))
|
|
|
|
// If upgrade client is used.
|
|
|
|
// Drop all existing clients
|
|
|
|
await this.closeAll(ctx, wsString, workspace, 0, 'upgrade')
|
|
|
|
// Wipe workspace and update values.
|
|
|
|
if (!workspace.upgrade) {
|
|
|
|
// This is previous workspace, intended to be closed.
|
|
|
|
workspace.id = generateId()
|
|
|
|
workspace.sessions = []
|
|
|
|
workspace.upgrade = token.extra?.model === 'upgrade'
|
2022-05-23 18:53:33 +03:00
|
|
|
}
|
2023-01-04 20:58:54 +03:00
|
|
|
if (LOGGING_ENABLED) console.log('no sessions for workspace', wsString)
|
|
|
|
// Re-create pipeline.
|
|
|
|
workspace.pipeline = pipelineFactory(token.workspace, true)
|
2022-05-23 18:53:33 +03:00
|
|
|
|
2023-01-04 20:58:54 +03:00
|
|
|
const pipeline = await workspace.pipeline
|
|
|
|
const session = this.createSession(token, pipeline)
|
2021-08-11 12:35:56 +03:00
|
|
|
workspace.sessions.push([session, ws])
|
|
|
|
return session
|
|
|
|
}
|
2023-01-04 20:58:54 +03:00
|
|
|
|
|
|
|
if (workspace.upgrade) {
|
|
|
|
ws.close()
|
|
|
|
throw new Error('Upgrade in progress....')
|
|
|
|
}
|
|
|
|
|
|
|
|
const pipeline = await workspace.pipeline
|
|
|
|
const session = this.createSession(token, pipeline)
|
|
|
|
workspace.sessions.push([session, ws])
|
|
|
|
await this.setStatus(ctx, session, true)
|
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
private createWorkspace (
|
|
|
|
pipelineFactory: (ws: WorkspaceId, upgrade: boolean) => Promise<Pipeline>,
|
|
|
|
token: Token
|
|
|
|
): Workspace {
|
|
|
|
const upgrade = token.extra?.model === 'upgrade'
|
|
|
|
const workspace = {
|
|
|
|
id: generateId(),
|
|
|
|
pipeline: pipelineFactory(token.workspace, upgrade),
|
|
|
|
sessions: [],
|
|
|
|
upgrade
|
|
|
|
}
|
|
|
|
console.log('Creating Workspace:', workspace.id)
|
|
|
|
this.workspaces.set(toWorkspaceString(token.workspace), workspace)
|
|
|
|
return workspace
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
|
|
|
|
2022-04-23 06:45:55 +03:00
|
|
|
private async setStatus (ctx: MeasureContext, session: Session, online: boolean): Promise<void> {
|
|
|
|
try {
|
|
|
|
const user = (
|
2022-05-23 18:53:33 +03:00
|
|
|
await session.pipeline().modelDb.findAll(
|
2022-04-23 06:45:55 +03:00
|
|
|
core.class.Account,
|
|
|
|
{
|
|
|
|
email: session.getUser()
|
|
|
|
},
|
|
|
|
{ limit: 1 }
|
|
|
|
)
|
|
|
|
)[0]
|
|
|
|
if (user === undefined) return
|
|
|
|
const status = (await session.findAll(ctx, core.class.UserStatus, { modifiedBy: user._id }, { limit: 1 }))[0]
|
|
|
|
const txFactory = new TxFactory(user._id)
|
|
|
|
if (status === undefined) {
|
|
|
|
const tx = txFactory.createTxCreateDoc(core.class.UserStatus, user._id as string as Ref<Space>, {
|
|
|
|
online
|
|
|
|
})
|
|
|
|
tx.space = core.space.DerivedTx
|
|
|
|
await session.tx(ctx, tx)
|
|
|
|
} else if (status.online !== online) {
|
|
|
|
const tx = txFactory.createTxUpdateDoc(status._class, status.space, status._id, {
|
|
|
|
online
|
|
|
|
})
|
|
|
|
tx.space = core.space.DerivedTx
|
|
|
|
await session.tx(ctx, tx)
|
|
|
|
}
|
2022-04-29 08:27:17 +03:00
|
|
|
} catch {}
|
2022-04-23 06:45:55 +03:00
|
|
|
}
|
|
|
|
|
2022-11-16 18:03:03 +03:00
|
|
|
async close (
|
|
|
|
ctx: MeasureContext,
|
|
|
|
ws: WebSocket,
|
|
|
|
workspaceId: WorkspaceId,
|
|
|
|
code: number,
|
|
|
|
reason: string
|
|
|
|
): Promise<void> {
|
2021-08-11 12:35:56 +03:00
|
|
|
if (LOGGING_ENABLED) console.log(`closing websocket, code: ${code}, reason: ${reason}`)
|
2022-11-16 18:03:03 +03:00
|
|
|
const wsid = toWorkspaceString(workspaceId)
|
|
|
|
const workspace = this.workspaces.get(wsid)
|
2021-08-11 12:35:56 +03:00
|
|
|
if (workspace === undefined) {
|
2022-01-27 11:53:09 +03:00
|
|
|
console.error(new Error('internal: cannot find sessions'))
|
|
|
|
return
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
2022-04-23 06:45:55 +03:00
|
|
|
const index = workspace.sessions.findIndex((p) => p[1] === ws)
|
|
|
|
if (index !== -1) {
|
|
|
|
const session = workspace.sessions[index]
|
|
|
|
workspace.sessions.splice(index, 1)
|
2022-06-01 15:05:07 +03:00
|
|
|
session[1].close()
|
2022-04-23 06:45:55 +03:00
|
|
|
const user = session[0].getUser()
|
|
|
|
const another = workspace.sessions.findIndex((p) => p[0].getUser() === user)
|
|
|
|
if (another === -1) {
|
|
|
|
await this.setStatus(ctx, session[0], false)
|
|
|
|
}
|
|
|
|
if (workspace.sessions.length === 0) {
|
2023-01-04 20:58:54 +03:00
|
|
|
const workspaceId = workspace.id
|
|
|
|
if (LOGGING_ENABLED) console.log('no sessions for workspace', wsid, workspaceId)
|
|
|
|
|
|
|
|
async function waitAndClose (workspace: Workspace): Promise<void> {
|
|
|
|
const pipeline = await workspace.pipeline
|
|
|
|
await pipeline.close()
|
|
|
|
}
|
|
|
|
workspace.closing = waitAndClose(workspace).then(() => {
|
|
|
|
if (this.workspaces.get(wsid)?.id === workspaceId) {
|
|
|
|
this.workspaces.delete(wsid)
|
|
|
|
}
|
|
|
|
console.log('Closed workspace', workspaceId)
|
|
|
|
})
|
|
|
|
workspace.closing.catch((err) => {
|
|
|
|
this.workspaces.delete(wsid)
|
|
|
|
console.error(err)
|
|
|
|
})
|
|
|
|
await workspace.closing
|
2022-04-23 06:45:55 +03:00
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-04 20:58:54 +03:00
|
|
|
async closeAll (ctx: MeasureContext, wsId: string, workspace: Workspace, code: number, reason: string): Promise<void> {
|
|
|
|
console.log(`closing workspace ${wsId} - ${workspace.id}, code: ${code}, reason: ${reason}`)
|
|
|
|
|
|
|
|
const sessions = Array.from(workspace.sessions)
|
|
|
|
workspace.sessions = []
|
|
|
|
|
2023-01-26 16:53:00 +03:00
|
|
|
const closeS = async (s: Session, webSocket: WebSocket): Promise<void> => {
|
2023-01-04 20:58:54 +03:00
|
|
|
// await for message to go to client.
|
|
|
|
await new Promise((resolve) => {
|
|
|
|
// Override message handler, to wait for upgrading response from clients.
|
2023-01-26 16:53:00 +03:00
|
|
|
webSocket.on('close', () => {
|
2023-01-04 20:58:54 +03:00
|
|
|
resolve(null)
|
|
|
|
})
|
2023-01-26 16:53:00 +03:00
|
|
|
webSocket.send(
|
2023-01-04 20:58:54 +03:00
|
|
|
serialize({
|
|
|
|
result: {
|
|
|
|
_class: core.class.TxModelUpgrade
|
|
|
|
}
|
|
|
|
})
|
|
|
|
)
|
2023-01-26 16:53:00 +03:00
|
|
|
setTimeout(resolve, 1000)
|
2023-01-04 20:58:54 +03:00
|
|
|
})
|
2023-01-26 16:53:00 +03:00
|
|
|
webSocket.close()
|
|
|
|
await this.setStatus(ctx, s, false)
|
2023-01-04 20:58:54 +03:00
|
|
|
}
|
2023-01-26 16:53:00 +03:00
|
|
|
|
|
|
|
console.log(workspace.id, 'Clients disconnected. Closing Workspace...')
|
|
|
|
await Promise.all(sessions.map((s) => closeS(s[0], s[1])))
|
|
|
|
|
|
|
|
const closePipeline = async (): Promise<void> => {
|
|
|
|
try {
|
|
|
|
await (await workspace.pipeline).close()
|
|
|
|
} catch (err: any) {
|
|
|
|
console.error(err)
|
|
|
|
}
|
2023-01-04 20:58:54 +03:00
|
|
|
}
|
2023-01-26 16:53:00 +03:00
|
|
|
await Promise.race([
|
2023-01-31 08:48:40 +03:00
|
|
|
closePipeline(),
|
2023-01-26 16:53:00 +03:00
|
|
|
new Promise((resolve) => {
|
|
|
|
setTimeout(resolve, 15000)
|
|
|
|
})
|
|
|
|
])
|
|
|
|
console.log(workspace.id, 'Workspace closed...')
|
2023-01-04 20:58:54 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
async closeWorkspaces (ctx: MeasureContext): Promise<void> {
|
|
|
|
for (const w of this.workspaces) {
|
|
|
|
await this.closeAll(ctx, w[0], w[1], 1, 'shutdown')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-16 18:03:03 +03:00
|
|
|
broadcast (from: Session | null, workspaceId: WorkspaceId, resp: Response<any>, target?: string): void {
|
|
|
|
const workspace = this.workspaces.get(toWorkspaceString(workspaceId))
|
2021-08-11 12:35:56 +03:00
|
|
|
if (workspace === undefined) {
|
2022-01-27 11:53:09 +03:00
|
|
|
console.error(new Error('internal: cannot find sessions'))
|
|
|
|
return
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
|
|
|
if (LOGGING_ENABLED) console.log(`server broadcasting to ${workspace.sessions.length} clients...`)
|
|
|
|
const msg = serialize(resp)
|
|
|
|
for (const session of workspace.sessions) {
|
2022-04-14 08:30:30 +03:00
|
|
|
if (session[0] !== from) {
|
|
|
|
if (target === undefined) {
|
|
|
|
session[1].send(msg)
|
|
|
|
} else if (session[0].getUser() === target) {
|
|
|
|
session[1].send(msg)
|
|
|
|
}
|
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-23 06:45:55 +03:00
|
|
|
async function handleRequest<S extends Session> (
|
|
|
|
ctx: MeasureContext,
|
|
|
|
service: S,
|
|
|
|
ws: WebSocket,
|
|
|
|
msg: string
|
|
|
|
): Promise<void> {
|
2021-08-03 22:02:59 +03:00
|
|
|
const request = readRequest(msg)
|
2022-06-01 15:05:07 +03:00
|
|
|
if (request.id === -1 && request.method === 'hello') {
|
|
|
|
ws.send(serialize({ id: -1, result: 'hello' }))
|
|
|
|
return
|
|
|
|
}
|
2023-01-04 20:58:54 +03:00
|
|
|
if (request.id === -1 && request.method === '#upgrade') {
|
|
|
|
ws.close(0, 'upgrade')
|
|
|
|
return
|
|
|
|
}
|
2021-08-03 22:02:59 +03:00
|
|
|
const f = (service as any)[request.method]
|
2021-12-06 18:16:38 +03:00
|
|
|
try {
|
2021-12-22 12:02:51 +03:00
|
|
|
const params = [ctx, ...request.params]
|
|
|
|
const result = await f.apply(service, params)
|
|
|
|
const resp: Response<any> = { id: request.id, result }
|
2021-12-06 18:16:38 +03:00
|
|
|
ws.send(serialize(resp))
|
|
|
|
} catch (err: any) {
|
2021-12-22 12:02:51 +03:00
|
|
|
const resp: Response<any> = {
|
|
|
|
id: request.id,
|
|
|
|
error: unknownError(err)
|
|
|
|
}
|
2021-12-06 18:16:38 +03:00
|
|
|
ws.send(serialize(resp))
|
|
|
|
}
|
2021-08-03 22:02:59 +03:00
|
|
|
}
|
|
|
|
|
2021-08-04 19:17:01 +03:00
|
|
|
/**
|
|
|
|
* @public
|
|
|
|
* @param sessionFactory -
|
2021-08-04 12:10:22 +03:00
|
|
|
* @param port -
|
|
|
|
* @param host -
|
2021-08-03 22:02:59 +03:00
|
|
|
*/
|
2022-04-23 06:45:55 +03:00
|
|
|
export function start (
|
|
|
|
ctx: MeasureContext,
|
2023-01-04 20:58:54 +03:00
|
|
|
pipelineFactory: (workspace: WorkspaceId, upgrade: boolean) => Promise<Pipeline>,
|
2022-05-23 18:53:33 +03:00
|
|
|
sessionFactory: (token: Token, pipeline: Pipeline, broadcast: BroadcastCall) => Session,
|
2022-04-23 06:45:55 +03:00
|
|
|
port: number,
|
2022-11-16 18:03:03 +03:00
|
|
|
productId: string,
|
2022-04-23 06:45:55 +03:00
|
|
|
host?: string
|
2023-01-04 20:58:54 +03:00
|
|
|
): () => Promise<void> {
|
2021-08-04 23:47:15 +03:00
|
|
|
console.log(`starting server on port ${port} ...`)
|
2021-08-03 22:02:59 +03:00
|
|
|
|
2022-05-23 18:53:33 +03:00
|
|
|
const sessions = new SessionManager(sessionFactory)
|
|
|
|
|
2022-11-02 11:50:14 +03:00
|
|
|
const wss = new WebSocketServer({
|
2022-05-23 18:53:33 +03:00
|
|
|
noServer: true,
|
|
|
|
perMessageDeflate: {
|
|
|
|
zlibDeflateOptions: {
|
|
|
|
// See zlib defaults.
|
2023-01-12 22:56:35 +03:00
|
|
|
chunkSize: 10 * 1024,
|
2022-05-23 18:53:33 +03:00
|
|
|
memLevel: 7,
|
|
|
|
level: 3
|
|
|
|
},
|
|
|
|
zlibInflateOptions: {
|
|
|
|
chunkSize: 10 * 1024
|
2023-01-12 22:56:35 +03:00
|
|
|
}
|
2022-05-23 18:53:33 +03:00
|
|
|
}
|
|
|
|
})
|
2021-08-03 22:02:59 +03:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
2021-08-28 10:08:41 +03:00
|
|
|
wss.on('connection', async (ws: WebSocket, request: any, token: Token) => {
|
2023-01-04 20:58:54 +03:00
|
|
|
let buffer: string[] | undefined = []
|
2021-08-19 20:34:58 +03:00
|
|
|
|
2022-04-23 06:45:55 +03:00
|
|
|
ws.on('message', (msg: string) => {
|
2023-01-04 20:58:54 +03:00
|
|
|
buffer?.push(msg)
|
2022-04-23 06:45:55 +03:00
|
|
|
})
|
2022-11-16 18:03:03 +03:00
|
|
|
const session = await sessions.addSession(ctx, ws, token, pipelineFactory, productId)
|
2021-08-03 22:02:59 +03:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
2021-12-22 12:02:51 +03:00
|
|
|
ws.on('message', async (msg: string) => await handleRequest(ctx, session, ws, msg))
|
2022-04-23 06:45:55 +03:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
2022-11-16 18:03:03 +03:00
|
|
|
ws.on('close', (code: number, reason: string) => {
|
|
|
|
void sessions.close(ctx, ws, token.workspace, code, reason)
|
|
|
|
})
|
2023-01-04 20:58:54 +03:00
|
|
|
const b = buffer
|
|
|
|
buffer = undefined
|
|
|
|
for (const msg of b) {
|
2021-12-22 12:02:51 +03:00
|
|
|
await handleRequest(ctx, session, ws, msg)
|
2021-08-19 20:34:58 +03:00
|
|
|
}
|
2021-08-03 22:02:59 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
const server = createServer()
|
2021-08-07 08:58:28 +03:00
|
|
|
server.on('upgrade', (request: IncomingMessage, socket: any, head: Buffer) => {
|
2021-08-03 22:02:59 +03:00
|
|
|
const token = request.url?.substring(1) // remove leading '/'
|
2021-08-04 10:56:34 +03:00
|
|
|
try {
|
2022-01-27 11:53:09 +03:00
|
|
|
const payload = decodeToken(token ?? '')
|
2021-08-09 00:04:39 +03:00
|
|
|
console.log('client connected with payload', payload)
|
2022-11-16 18:03:03 +03:00
|
|
|
|
2022-11-22 21:13:26 +03:00
|
|
|
if (payload.workspace.productId !== productId) {
|
2022-11-16 18:03:03 +03:00
|
|
|
throw new Error('Invalid workspace product')
|
|
|
|
}
|
|
|
|
|
2022-04-23 06:45:55 +03:00
|
|
|
wss.handleUpgrade(request, socket, head, (ws) => wss.emit('connection', ws, request, payload))
|
2021-08-04 10:56:34 +03:00
|
|
|
} catch (err) {
|
2022-11-22 21:13:26 +03:00
|
|
|
console.error('invalid token', err)
|
2022-07-05 08:43:17 +03:00
|
|
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
|
|
const resp: Response<any> = {
|
|
|
|
id: -1,
|
|
|
|
error: UNAUTHORIZED,
|
|
|
|
result: 'hello'
|
|
|
|
}
|
|
|
|
ws.send(serialize(resp))
|
|
|
|
ws.onmessage = (msg) => {
|
|
|
|
const resp: Response<any> = {
|
|
|
|
error: UNAUTHORIZED
|
|
|
|
}
|
|
|
|
ws.send(serialize(resp))
|
|
|
|
}
|
|
|
|
})
|
2021-08-03 22:02:59 +03:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
server.listen(port, host)
|
2023-01-04 20:58:54 +03:00
|
|
|
return async () => {
|
2021-11-22 14:17:10 +03:00
|
|
|
server.close()
|
2023-01-04 20:58:54 +03:00
|
|
|
await sessions.closeWorkspaces(ctx)
|
2021-11-22 14:17:10 +03:00
|
|
|
}
|
2021-08-03 22:02:59 +03:00
|
|
|
}
|