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.
|
|
|
|
//
|
|
|
|
|
2022-11-16 18:03:03 +03:00
|
|
|
import core, { 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 {
|
2022-04-14 08:30:30 +03:00
|
|
|
pipeline: Pipeline
|
2021-08-11 12:35:56 +03:00
|
|
|
sessions: [Session, WebSocket][]
|
2022-05-23 18:53:33 +03:00
|
|
|
upgrade: boolean
|
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,
|
2022-11-16 18:03:03 +03:00
|
|
|
pipelineFactory: (ws: WorkspaceId) => Promise<Pipeline>,
|
|
|
|
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, '@')
|
|
|
|
const workspace = this.workspaces.get(wsString)
|
2021-08-11 12:35:56 +03:00
|
|
|
if (workspace === undefined) {
|
2022-04-23 06:45:55 +03:00
|
|
|
return await this.createWorkspace(ctx, pipelineFactory, token, ws)
|
2021-08-11 12:35:56 +03:00
|
|
|
} else {
|
2022-05-23 18:53:33 +03:00
|
|
|
if (token.extra?.model === 'upgrade') {
|
2022-01-27 11:53:09 +03:00
|
|
|
console.log('reloading workspace', JSON.stringify(token))
|
|
|
|
// If upgrade client is used.
|
|
|
|
// Drop all existing clients
|
|
|
|
if (workspace.sessions.length > 0) {
|
|
|
|
for (const s of workspace.sessions) {
|
2022-06-01 15:05:07 +03:00
|
|
|
s[1].send(
|
|
|
|
serialize({
|
|
|
|
result: {
|
|
|
|
_class: core.class.TxModelUpgrade
|
|
|
|
}
|
|
|
|
})
|
|
|
|
)
|
2022-04-23 06:45:55 +03:00
|
|
|
await this.close(ctx, s[1], token.workspace, 0, 'upgrade')
|
2022-01-27 11:53:09 +03:00
|
|
|
}
|
|
|
|
}
|
2022-04-23 06:45:55 +03:00
|
|
|
return await this.createWorkspace(ctx, pipelineFactory, token, ws)
|
2022-01-27 11:53:09 +03:00
|
|
|
}
|
|
|
|
|
2022-05-23 18:53:33 +03:00
|
|
|
if (workspace.upgrade) {
|
2022-06-01 15:05:07 +03:00
|
|
|
ws.close()
|
2022-05-23 18:53:33 +03:00
|
|
|
throw new Error('Upgrade in progress....')
|
|
|
|
}
|
|
|
|
|
|
|
|
const session = this.createSession(token, workspace.pipeline)
|
2021-08-11 12:35:56 +03:00
|
|
|
workspace.sessions.push([session, ws])
|
2022-04-23 06:45:55 +03:00
|
|
|
await this.setStatus(ctx, session, true)
|
2021-08-11 12:35:56 +03:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
private async createWorkspace (
|
|
|
|
ctx: MeasureContext,
|
2022-11-16 18:03:03 +03:00
|
|
|
pipelineFactory: (ws: WorkspaceId) => Promise<Pipeline>,
|
2022-04-23 06:45:55 +03:00
|
|
|
token: Token,
|
|
|
|
ws: WebSocket
|
|
|
|
): Promise<Session> {
|
2022-04-14 08:30:30 +03:00
|
|
|
const pipeline = await pipelineFactory(token.workspace)
|
2022-05-23 18:53:33 +03:00
|
|
|
const session = this.createSession(token, pipeline)
|
2022-01-27 11:53:09 +03:00
|
|
|
const workspace: Workspace = {
|
2022-04-14 08:30:30 +03:00
|
|
|
pipeline,
|
2022-05-23 18:53:33 +03:00
|
|
|
sessions: [[session, ws]],
|
|
|
|
upgrade: token.extra?.model === 'upgrade'
|
2022-01-27 11:53:09 +03:00
|
|
|
}
|
2022-11-16 18:03:03 +03:00
|
|
|
this.workspaces.set(toWorkspaceString(token.workspace), workspace)
|
2022-04-23 06:45:55 +03:00
|
|
|
await this.setStatus(ctx, session, true)
|
2022-01-27 11:53:09 +03:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
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) {
|
2022-11-16 18:03:03 +03:00
|
|
|
if (LOGGING_ENABLED) console.log('no sessions for workspace', wsid)
|
|
|
|
this.workspaces.delete(wsid)
|
2022-06-01 15:05:07 +03:00
|
|
|
await workspace.pipeline.close().catch((err) => console.error(err))
|
2022-04-23 06:45:55 +03:00
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
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,
|
2022-11-16 18:03:03 +03:00
|
|
|
pipelineFactory: (workspace: WorkspaceId) => 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
|
|
|
|
): () => 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.
|
|
|
|
chunkSize: 1024,
|
|
|
|
memLevel: 7,
|
|
|
|
level: 3
|
|
|
|
},
|
|
|
|
zlibInflateOptions: {
|
|
|
|
chunkSize: 10 * 1024
|
|
|
|
},
|
|
|
|
// Below options specified as default values.
|
|
|
|
concurrencyLimit: 10, // Limits zlib concurrency for perf.
|
|
|
|
threshold: 1024 // Size (in bytes) below which messages
|
|
|
|
// should not be compressed if context takeover is disabled.
|
|
|
|
}
|
|
|
|
})
|
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) => {
|
2021-08-19 20:34:58 +03:00
|
|
|
const buffer: string[] = []
|
|
|
|
|
2022-04-23 06:45:55 +03:00
|
|
|
ws.on('message', (msg: string) => {
|
|
|
|
buffer.push(msg)
|
|
|
|
})
|
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)
|
|
|
|
})
|
2021-08-19 20:34:58 +03:00
|
|
|
for (const msg of buffer) {
|
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)
|
2021-11-22 14:17:10 +03:00
|
|
|
return () => {
|
|
|
|
server.close()
|
|
|
|
}
|
2021-08-03 22:02:59 +03:00
|
|
|
}
|