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, {
|
|
|
|
MeasureContext,
|
|
|
|
Ref,
|
|
|
|
Space,
|
2023-02-15 06:14:20 +03:00
|
|
|
Tx,
|
2023-01-04 20:58:54 +03:00
|
|
|
TxFactory,
|
2023-05-19 14:46:05 +03:00
|
|
|
TxWorkspaceEvent,
|
|
|
|
WorkspaceEvent,
|
2023-05-03 17:09:48 +03:00
|
|
|
WorkspaceId,
|
|
|
|
generateId,
|
|
|
|
toWorkspaceString
|
2023-01-04 20:58:54 +03:00
|
|
|
} from '@hcengineering/core'
|
2023-05-10 20:16:13 +03:00
|
|
|
import { unknownError } from '@hcengineering/platform'
|
|
|
|
import { HelloRequest, HelloResponse, Response, readRequest } from '@hcengineering/rpc'
|
2023-03-24 07:53:12 +03:00
|
|
|
import type { Pipeline, SessionContext } from '@hcengineering/server-core'
|
2023-05-03 17:09:48 +03:00
|
|
|
import { Token } from '@hcengineering/server-token'
|
|
|
|
// import WebSocket, { RawData } from 'ws'
|
|
|
|
|
|
|
|
import {
|
|
|
|
BroadcastCall,
|
|
|
|
ConnectionSocket,
|
|
|
|
LOGGING_ENABLED,
|
|
|
|
PipelineFactory,
|
|
|
|
ServerFactory,
|
|
|
|
Session,
|
2023-05-10 20:16:13 +03:00
|
|
|
SessionManager,
|
|
|
|
Workspace
|
2023-05-03 17:09:48 +03:00
|
|
|
} from './types'
|
2021-08-11 12:35:56 +03:00
|
|
|
|
2023-03-15 19:36:50 +03:00
|
|
|
function timeoutPromise (time: number): Promise<void> {
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
setTimeout(resolve, time)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
class TSessionManager implements SessionManager {
|
2023-04-20 13:11:22 +03:00
|
|
|
readonly workspaces = new Map<string, Workspace>()
|
2023-05-03 17:09:48 +03:00
|
|
|
checkInterval: any
|
|
|
|
|
2023-05-10 20:16:13 +03:00
|
|
|
sessions: Map<string, { session: Session, socket: ConnectionSocket }> = new Map()
|
|
|
|
|
2023-05-19 14:46:05 +03:00
|
|
|
maintenanceTimer: any
|
|
|
|
timeMinutes = 0
|
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
constructor (
|
|
|
|
readonly ctx: MeasureContext,
|
|
|
|
readonly sessionFactory: (token: Token, pipeline: Pipeline, broadcast: BroadcastCall) => Session
|
|
|
|
) {
|
|
|
|
this.checkInterval = setInterval(() => this.handleInterval(), 1000)
|
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
|
2023-05-19 14:46:05 +03:00
|
|
|
scheduleMaintenance (timeMinutes: number): void {
|
|
|
|
this.timeMinutes = timeMinutes
|
|
|
|
|
|
|
|
this.sendMaintenanceWarning()
|
|
|
|
|
|
|
|
const nextTime = (): number => (this.timeMinutes > 1 ? 60 * 1000 : this.timeMinutes * 60 * 1000)
|
|
|
|
|
|
|
|
const showMaintenance = (): void => {
|
|
|
|
if (this.timeMinutes > 1) {
|
|
|
|
this.timeMinutes -= 1
|
|
|
|
clearTimeout(this.maintenanceTimer)
|
|
|
|
this.maintenanceTimer = setTimeout(showMaintenance, nextTime())
|
|
|
|
} else {
|
|
|
|
this.timeMinutes = 0
|
|
|
|
}
|
|
|
|
|
|
|
|
this.sendMaintenanceWarning()
|
|
|
|
}
|
|
|
|
|
|
|
|
clearTimeout(this.maintenanceTimer)
|
|
|
|
this.maintenanceTimer = setTimeout(showMaintenance, nextTime())
|
|
|
|
}
|
|
|
|
|
|
|
|
private sendMaintenanceWarning (): void {
|
|
|
|
if (this.timeMinutes === 0) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
const event: TxWorkspaceEvent = this.createMaintenanceWarning()
|
|
|
|
for (const ws of this.workspaces.values()) {
|
|
|
|
this.broadcastAll(ws, [event])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private createMaintenanceWarning (): TxWorkspaceEvent {
|
|
|
|
return {
|
|
|
|
_id: generateId(),
|
|
|
|
_class: core.class.TxWorkspaceEvent,
|
|
|
|
event: WorkspaceEvent.MaintenanceNotification,
|
|
|
|
modifiedBy: core.account.System,
|
|
|
|
modifiedOn: Date.now(),
|
|
|
|
objectSpace: core.space.DerivedTx,
|
|
|
|
space: core.space.DerivedTx,
|
|
|
|
createdBy: core.account.System,
|
|
|
|
params: {
|
|
|
|
timeMinutes: this.timeMinutes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ticks = 0
|
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
handleInterval (): void {
|
|
|
|
for (const h of this.workspaces.entries()) {
|
|
|
|
for (const s of h[1].sessions) {
|
2023-05-19 14:46:05 +03:00
|
|
|
if (this.ticks % (5 * 60) === 0) {
|
|
|
|
s[1].session.mins5.find = s[1].session.current.find
|
|
|
|
s[1].session.mins5.tx = s[1].session.current.tx
|
|
|
|
|
|
|
|
s[1].session.current = { find: 0, tx: 0 }
|
|
|
|
}
|
2023-05-10 20:16:13 +03:00
|
|
|
for (const r of s[1].session.requests.values()) {
|
2023-05-03 17:09:48 +03:00
|
|
|
const ed = Date.now()
|
|
|
|
|
|
|
|
if (ed - r.start > 30000) {
|
2023-05-10 20:16:13 +03:00
|
|
|
console.log(h[0], 'request hang found, 30sec', h[0], s[1].session.getUser(), r.params)
|
2023-05-03 17:09:48 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-05-19 14:46:05 +03:00
|
|
|
this.ticks++
|
2023-05-03 17:09:48 +03:00
|
|
|
}
|
2022-05-23 18:53:33 +03:00
|
|
|
|
|
|
|
createSession (token: Token, pipeline: Pipeline): Session {
|
|
|
|
return this.sessionFactory(token, pipeline, this.broadcast.bind(this))
|
|
|
|
}
|
|
|
|
|
2023-03-24 07:53:12 +03:00
|
|
|
upgradeId: string | undefined
|
|
|
|
|
2022-04-23 06:45:55 +03:00
|
|
|
async addSession (
|
|
|
|
ctx: MeasureContext,
|
2023-05-03 17:09:48 +03:00
|
|
|
ws: ConnectionSocket,
|
2022-04-23 06:45:55 +03:00
|
|
|
token: Token,
|
2023-02-15 06:14:20 +03:00
|
|
|
pipelineFactory: PipelineFactory,
|
2023-02-28 10:02:15 +03:00
|
|
|
productId: string,
|
|
|
|
sessionId?: string
|
2022-04-23 06:45:55 +03:00
|
|
|
): Promise<Session> {
|
2023-05-03 17:09:48 +03:00
|
|
|
return await ctx.with('add-session', {}, async (ctx) => {
|
|
|
|
const wsString = toWorkspaceString(token.workspace, '@')
|
2023-01-04 20:58:54 +03:00
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
let workspace = this.workspaces.get(wsString)
|
|
|
|
await workspace?.closing
|
|
|
|
workspace = this.workspaces.get(wsString)
|
2023-01-04 20:58:54 +03:00
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
if (workspace === undefined) {
|
|
|
|
workspace = this.createWorkspace(ctx, pipelineFactory, token)
|
|
|
|
}
|
|
|
|
|
2023-05-10 20:16:13 +03:00
|
|
|
let pipeline: Pipeline
|
2023-05-03 17:09:48 +03:00
|
|
|
if (token.extra?.model === 'upgrade') {
|
2023-05-10 20:16:13 +03:00
|
|
|
if (this.upgradeId !== undefined && sessionId !== this.upgradeId) {
|
|
|
|
ws.close()
|
|
|
|
throw new Error('Another Upgrade in progress....')
|
|
|
|
}
|
|
|
|
this.upgradeId = sessionId
|
|
|
|
pipeline = await this.createUpgradeSession(token, sessionId, ctx, wsString, workspace, pipelineFactory, ws)
|
|
|
|
} else {
|
|
|
|
if (workspace.upgrade && sessionId !== this.upgradeId) {
|
|
|
|
ws.close()
|
|
|
|
throw new Error('Upgrade in progress....')
|
|
|
|
}
|
|
|
|
pipeline = await ctx.with('pipeline', {}, async () => await (workspace as Workspace).pipeline)
|
2022-05-23 18:53:33 +03:00
|
|
|
}
|
|
|
|
|
2023-01-04 20:58:54 +03:00
|
|
|
const session = this.createSession(token, pipeline)
|
2023-05-10 20:16:13 +03:00
|
|
|
session.sessionId = sessionId !== undefined && (sessionId ?? '').trim().length > 0 ? sessionId : generateId()
|
2023-05-03 17:09:48 +03:00
|
|
|
session.sessionInstanceId = generateId()
|
2023-05-10 20:16:13 +03:00
|
|
|
this.sessions.set(ws.id, { session, socket: ws })
|
|
|
|
// We need to delete previous session with Id if found.
|
|
|
|
workspace.sessions.set(session.sessionId, { session, socket: ws })
|
2023-05-03 17:09:48 +03:00
|
|
|
await ctx.with('set-status', {}, () => this.setStatus(ctx, session, true))
|
2023-05-19 14:46:05 +03:00
|
|
|
|
|
|
|
if (this.timeMinutes > 0) {
|
|
|
|
void ws.send(
|
|
|
|
ctx,
|
|
|
|
{ result: this.createMaintenanceWarning() },
|
|
|
|
session.binaryResponseMode,
|
|
|
|
session.useCompression
|
|
|
|
)
|
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
return session
|
2023-05-03 17:09:48 +03:00
|
|
|
})
|
|
|
|
}
|
2023-01-04 20:58:54 +03:00
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
private async createUpgradeSession (
|
|
|
|
token: Token,
|
|
|
|
sessionId: string | undefined,
|
|
|
|
ctx: MeasureContext,
|
|
|
|
wsString: string,
|
|
|
|
workspace: Workspace,
|
|
|
|
pipelineFactory: PipelineFactory,
|
|
|
|
ws: ConnectionSocket
|
2023-05-10 20:16:13 +03:00
|
|
|
): Promise<Pipeline> {
|
2023-05-03 17:09:48 +03:00
|
|
|
if (LOGGING_ENABLED) {
|
|
|
|
console.log(token.workspace.name, 'reloading workspace', JSON.stringify(token))
|
2023-01-04 20:58:54 +03:00
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
// 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()
|
2023-05-10 20:16:13 +03:00
|
|
|
workspace.sessions = new Map()
|
2023-05-03 17:09:48 +03:00
|
|
|
workspace.upgrade = token.extra?.model === 'upgrade'
|
2023-02-28 10:02:15 +03:00
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
if (LOGGING_ENABLED) {
|
|
|
|
console.log(token.workspace.name, 'no sessions for workspace', wsString)
|
|
|
|
}
|
|
|
|
// Re-create pipeline.
|
2023-05-16 10:05:47 +03:00
|
|
|
workspace.pipeline = pipelineFactory(ctx, token.workspace, true, (tx, targets) =>
|
|
|
|
this.broadcastAll(workspace, tx, targets)
|
|
|
|
)
|
2023-05-10 20:16:13 +03:00
|
|
|
return await workspace.pipeline
|
2023-01-04 20:58:54 +03:00
|
|
|
}
|
|
|
|
|
2023-05-16 10:05:47 +03:00
|
|
|
broadcastAll (workspace: Workspace, tx: Tx[], targets?: string[]): void {
|
2023-05-03 17:09:48 +03:00
|
|
|
if (workspace?.upgrade ?? false) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
const ctx = this.ctx.newChild('broadcast-all', {})
|
2023-05-10 20:16:13 +03:00
|
|
|
const sessions = [...workspace.sessions.values()]
|
2023-05-03 17:09:48 +03:00
|
|
|
function send (): void {
|
|
|
|
for (const session of sessions.splice(0, 1)) {
|
2023-05-16 10:05:47 +03:00
|
|
|
if (targets !== undefined && !targets.includes(session.session.getUser())) continue
|
2023-05-03 17:09:48 +03:00
|
|
|
for (const _tx of tx) {
|
2023-05-10 20:16:13 +03:00
|
|
|
void session.socket.send(ctx, { result: _tx }, session.session.binaryResponseMode, false)
|
2023-05-03 17:09:48 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if (sessions.length > 0) {
|
|
|
|
setImmediate(send)
|
|
|
|
} else {
|
|
|
|
ctx.end()
|
2023-02-15 06:14:20 +03:00
|
|
|
}
|
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
send()
|
2023-02-15 06:14:20 +03:00
|
|
|
}
|
|
|
|
|
2023-03-02 06:31:47 +03:00
|
|
|
private createWorkspace (ctx: MeasureContext, pipelineFactory: PipelineFactory, token: Token): Workspace {
|
2023-01-04 20:58:54 +03:00
|
|
|
const upgrade = token.extra?.model === 'upgrade'
|
2023-02-15 06:14:20 +03:00
|
|
|
const workspace: Workspace = {
|
2023-01-04 20:58:54 +03:00
|
|
|
id: generateId(),
|
2023-05-16 10:05:47 +03:00
|
|
|
pipeline: pipelineFactory(ctx, token.workspace, upgrade, (tx, targets) =>
|
|
|
|
this.broadcastAll(workspace, tx, targets)
|
|
|
|
),
|
2023-05-10 20:16:13 +03:00
|
|
|
sessions: new Map(),
|
2023-01-04 20:58:54 +03:00
|
|
|
upgrade
|
|
|
|
}
|
2023-04-13 20:39:20 +03:00
|
|
|
if (LOGGING_ENABLED) console.time(token.workspace.name)
|
|
|
|
if (LOGGING_ENABLED) console.timeLog(token.workspace.name, 'Creating Workspace:', workspace.id)
|
2023-01-04 20:58:54 +03:00
|
|
|
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 = (
|
2023-03-01 19:46:36 +03:00
|
|
|
await session.findAll(
|
|
|
|
ctx,
|
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]
|
2023-04-05 10:12:06 +03:00
|
|
|
const txFactory = new TxFactory(user._id, true)
|
2022-04-23 06:45:55 +03:00
|
|
|
if (status === undefined) {
|
|
|
|
const tx = txFactory.createTxCreateDoc(core.class.UserStatus, user._id as string as Ref<Space>, {
|
|
|
|
online
|
|
|
|
})
|
|
|
|
await session.tx(ctx, tx)
|
|
|
|
} else if (status.online !== online) {
|
|
|
|
const tx = txFactory.createTxUpdateDoc(status._class, status.space, status._id, {
|
|
|
|
online
|
|
|
|
})
|
|
|
|
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,
|
2023-05-03 17:09:48 +03:00
|
|
|
ws: ConnectionSocket,
|
2022-11-16 18:03:03 +03:00
|
|
|
workspaceId: WorkspaceId,
|
|
|
|
code: number,
|
|
|
|
reason: string
|
|
|
|
): Promise<void> {
|
2023-10-07 13:38:21 +03:00
|
|
|
if (this.checkInterval !== undefined) {
|
|
|
|
clearInterval(this.checkInterval)
|
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
// if (LOGGING_ENABLED) console.log(workspaceId.name, `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) {
|
2023-04-13 20:39:20 +03:00
|
|
|
if (LOGGING_ENABLED) console.error(new Error('internal: cannot find sessions'))
|
2022-01-27 11:53:09 +03:00
|
|
|
return
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
2023-05-10 20:16:13 +03:00
|
|
|
const sessionRef = this.sessions.get(ws.id)
|
|
|
|
if (sessionRef !== undefined) {
|
|
|
|
if (this.upgradeId === sessionRef.session.sessionId) {
|
|
|
|
this.upgradeId = undefined
|
|
|
|
}
|
|
|
|
this.sessions.delete(ws.id)
|
|
|
|
workspace.sessions.delete(sessionRef.session.sessionId)
|
2023-05-03 17:09:48 +03:00
|
|
|
try {
|
2023-05-10 20:16:13 +03:00
|
|
|
sessionRef.socket.close()
|
2023-05-03 17:09:48 +03:00
|
|
|
} catch (err) {
|
|
|
|
// Ignore if closed
|
|
|
|
}
|
2023-05-10 20:16:13 +03:00
|
|
|
const user = sessionRef.session.getUser()
|
|
|
|
const another = Array.from(workspace.sessions.values()).findIndex((p) => p.session.getUser() === user)
|
2022-04-23 06:45:55 +03:00
|
|
|
if (another === -1) {
|
2023-05-10 20:16:13 +03:00
|
|
|
await this.setStatus(ctx, sessionRef.session, false)
|
2022-04-23 06:45:55 +03:00
|
|
|
}
|
2023-05-10 20:16:13 +03:00
|
|
|
if (!workspace.upgrade) {
|
|
|
|
// Wait 10 second for new client to appear before closing workspace.
|
|
|
|
if (workspace.sessions.size === 0) {
|
|
|
|
setTimeout(() => {
|
|
|
|
void this.performWorkspaceCloseCheck(workspace, workspaceId, wsid)
|
|
|
|
}, 5000)
|
2023-03-15 19:36:50 +03:00
|
|
|
}
|
2023-05-10 20:16:13 +03:00
|
|
|
} else {
|
|
|
|
await this.performWorkspaceCloseCheck(workspace, workspaceId, wsid)
|
2022-04-23 06:45:55 +03:00
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-24 07:53:12 +03:00
|
|
|
async closeAll (
|
|
|
|
ctx: MeasureContext,
|
|
|
|
wsId: string,
|
|
|
|
workspace: Workspace,
|
|
|
|
code: number,
|
|
|
|
reason: 'upgrade' | 'shutdown'
|
|
|
|
): Promise<void> {
|
2023-04-13 20:39:20 +03:00
|
|
|
if (LOGGING_ENABLED) console.timeLog(wsId, `closing workspace ${workspace.id}, code: ${code}, reason: ${reason}`)
|
2023-01-04 20:58:54 +03:00
|
|
|
|
|
|
|
const sessions = Array.from(workspace.sessions)
|
2023-05-10 20:16:13 +03:00
|
|
|
workspace.sessions = new Map()
|
2023-01-04 20:58:54 +03:00
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
const closeS = async (s: Session, webSocket: ConnectionSocket): Promise<void> => {
|
2023-03-24 07:53:12 +03:00
|
|
|
s.workspaceClosed = true
|
|
|
|
if (reason === 'upgrade') {
|
2023-05-03 17:09:48 +03:00
|
|
|
// Override message handler, to wait for upgrading response from clients.
|
2023-05-10 20:16:13 +03:00
|
|
|
await webSocket.send(
|
|
|
|
ctx,
|
|
|
|
{
|
|
|
|
result: {
|
|
|
|
_class: core.class.TxModelUpgrade
|
|
|
|
}
|
|
|
|
},
|
|
|
|
s.binaryResponseMode,
|
|
|
|
false
|
|
|
|
)
|
2023-03-24 07:53:12 +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
|
|
|
|
2023-04-13 20:39:20 +03:00
|
|
|
if (LOGGING_ENABLED) console.timeLog(wsId, workspace.id, 'Clients disconnected. Closing Workspace...')
|
2023-05-10 20:16:13 +03:00
|
|
|
await Promise.all(sessions.map((s) => closeS(s[1].session, s[1].socket)))
|
2023-01-26 16:53:00 +03:00
|
|
|
|
|
|
|
const closePipeline = async (): Promise<void> => {
|
|
|
|
try {
|
2023-04-13 20:39:20 +03:00
|
|
|
if (LOGGING_ENABLED) console.timeLog(wsId, 'closing pipeline')
|
2023-01-26 16:53:00 +03:00
|
|
|
await (await workspace.pipeline).close()
|
2023-04-13 20:39:20 +03:00
|
|
|
if (LOGGING_ENABLED) console.timeLog(wsId, 'closing pipeline done')
|
2023-01-26 16:53:00 +03:00
|
|
|
} catch (err: any) {
|
|
|
|
console.error(err)
|
|
|
|
}
|
2023-01-04 20:58:54 +03:00
|
|
|
}
|
2023-03-15 19:36:50 +03:00
|
|
|
await Promise.race([closePipeline(), timeoutPromise(15000)])
|
2023-04-13 20:39:20 +03:00
|
|
|
if (LOGGING_ENABLED) console.timeLog(wsId, 'Workspace closed...')
|
|
|
|
console.timeEnd(wsId)
|
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')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-10 20:16:13 +03:00
|
|
|
private async performWorkspaceCloseCheck (
|
|
|
|
workspace: Workspace,
|
|
|
|
workspaceId: WorkspaceId,
|
|
|
|
wsid: string
|
|
|
|
): Promise<void> {
|
|
|
|
if (workspace.sessions.size === 0) {
|
|
|
|
const wsUID = workspace.id
|
|
|
|
if (LOGGING_ENABLED) {
|
|
|
|
console.log(workspaceId.name, 'no sessions for workspace', wsid, wsUID)
|
|
|
|
}
|
|
|
|
|
|
|
|
const waitAndClose = async (workspace: Workspace): Promise<void> => {
|
|
|
|
try {
|
|
|
|
const pl = await workspace.pipeline
|
|
|
|
await Promise.race([pl, timeoutPromise(60000)])
|
|
|
|
await Promise.race([pl.close(), timeoutPromise(60000)])
|
|
|
|
|
|
|
|
if (this.workspaces.get(wsid)?.id === wsUID) {
|
|
|
|
this.workspaces.delete(wsid)
|
|
|
|
}
|
|
|
|
if (LOGGING_ENABLED) {
|
|
|
|
console.timeLog(workspaceId.name, 'Closed workspace', wsUID)
|
|
|
|
}
|
|
|
|
} catch (err: any) {
|
|
|
|
this.workspaces.delete(wsid)
|
|
|
|
if (LOGGING_ENABLED) {
|
|
|
|
console.error(workspaceId.name, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
workspace.closing = waitAndClose(workspace)
|
|
|
|
await workspace.closing
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-02 06:31:47 +03:00
|
|
|
broadcast (from: Session | null, workspaceId: WorkspaceId, resp: Response<any>, target?: string[]): void {
|
2022-11-16 18:03:03 +03:00
|
|
|
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
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
if (workspace?.upgrade ?? false) {
|
|
|
|
return
|
|
|
|
}
|
2023-05-10 20:16:13 +03:00
|
|
|
if (LOGGING_ENABLED) console.log(workspaceId.name, `server broadcasting to ${workspace.sessions.size} clients...`)
|
2023-05-03 17:09:48 +03:00
|
|
|
|
2023-05-10 20:16:13 +03:00
|
|
|
const sessions = [...workspace.sessions.values()]
|
2023-05-03 17:09:48 +03:00
|
|
|
const ctx = this.ctx.newChild('broadcast', {})
|
|
|
|
function send (): void {
|
2023-05-10 20:16:13 +03:00
|
|
|
for (const sessionRef of sessions.splice(0, 1)) {
|
|
|
|
if (sessionRef.session.sessionId !== from?.sessionId) {
|
2023-05-03 17:09:48 +03:00
|
|
|
if (target === undefined) {
|
2023-05-10 20:16:13 +03:00
|
|
|
void sessionRef.socket.send(ctx, resp, sessionRef.session.binaryResponseMode, false)
|
|
|
|
} else if (target.includes(sessionRef.session.getUser())) {
|
|
|
|
void sessionRef.socket.send(ctx, resp, sessionRef.session.binaryResponseMode, false)
|
2023-05-03 17:09:48 +03:00
|
|
|
}
|
2022-04-14 08:30:30 +03:00
|
|
|
}
|
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
if (sessions.length > 0) {
|
|
|
|
setImmediate(send)
|
|
|
|
} else {
|
|
|
|
ctx.end()
|
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
send()
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
2023-05-10 20:16:13 +03:00
|
|
|
|
|
|
|
async handleRequest<S extends Session>(
|
|
|
|
requestCtx: MeasureContext,
|
|
|
|
service: S,
|
|
|
|
ws: ConnectionSocket,
|
|
|
|
msg: any,
|
|
|
|
workspace: string
|
|
|
|
): Promise<void> {
|
|
|
|
const userCtx = requestCtx.newChild('client', { workspace }) as SessionContext
|
|
|
|
userCtx.sessionId = service.sessionInstanceId ?? ''
|
|
|
|
|
|
|
|
// Calculate total number of clients
|
|
|
|
const reqId = generateId()
|
|
|
|
|
|
|
|
const st = Date.now()
|
|
|
|
try {
|
|
|
|
await userCtx.with('handleRequest', {}, async (ctx) => {
|
|
|
|
const request = await ctx.with('read', {}, async () => readRequest(msg, false))
|
|
|
|
if (request.id === -1 && request.method === 'hello') {
|
|
|
|
const hello = request as HelloRequest
|
|
|
|
service.binaryResponseMode = hello.binary ?? false
|
|
|
|
service.useCompression = hello.compression ?? false
|
|
|
|
|
|
|
|
if (LOGGING_ENABLED) {
|
|
|
|
console.timeLog(
|
|
|
|
workspace,
|
|
|
|
'hello happen',
|
|
|
|
service.getUser(),
|
2023-05-12 14:53:38 +03:00
|
|
|
'binary:',
|
2023-05-10 20:16:13 +03:00
|
|
|
service.binaryResponseMode,
|
2023-05-12 14:53:38 +03:00
|
|
|
'compression:',
|
2023-05-10 20:16:13 +03:00
|
|
|
service.useCompression,
|
2023-05-12 14:53:38 +03:00
|
|
|
'workspace users:',
|
|
|
|
this.workspaces.get(workspace)?.sessions?.size,
|
|
|
|
'total users:',
|
|
|
|
this.sessions.size
|
2023-05-10 20:16:13 +03:00
|
|
|
)
|
|
|
|
}
|
|
|
|
const helloResponse: HelloResponse = { id: -1, result: 'hello', binary: service.binaryResponseMode }
|
|
|
|
await ws.send(ctx, helloResponse, false, false)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
service.requests.set(reqId, {
|
|
|
|
id: reqId,
|
|
|
|
params: request,
|
|
|
|
start: st
|
|
|
|
})
|
|
|
|
if (request.id === -1 && request.method === '#upgrade') {
|
|
|
|
ws.close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
const f = (service as any)[request.method]
|
|
|
|
try {
|
|
|
|
const params = [...request.params]
|
|
|
|
|
|
|
|
const result = await ctx.with('call', {}, async (callTx) => f.apply(service, [callTx, ...params]))
|
|
|
|
|
|
|
|
const resp: Response<any> = { id: request.id, result }
|
|
|
|
|
|
|
|
await handleSend(
|
|
|
|
ctx,
|
|
|
|
ws,
|
|
|
|
resp,
|
2023-05-12 14:53:38 +03:00
|
|
|
this.sessions.size < 100 ? 10000 : 1001,
|
2023-05-10 20:16:13 +03:00
|
|
|
service.binaryResponseMode,
|
|
|
|
service.useCompression
|
|
|
|
)
|
|
|
|
} catch (err: any) {
|
|
|
|
if (LOGGING_ENABLED) console.error(err)
|
|
|
|
const resp: Response<any> = {
|
|
|
|
id: request.id,
|
|
|
|
error: unknownError(err)
|
|
|
|
}
|
2023-05-19 14:46:05 +03:00
|
|
|
await ws.send(ctx, resp, service.binaryResponseMode, service.useCompression)
|
2023-05-10 20:16:13 +03:00
|
|
|
}
|
|
|
|
})
|
|
|
|
} finally {
|
|
|
|
userCtx.end()
|
|
|
|
service.requests.delete(reqId)
|
|
|
|
}
|
|
|
|
}
|
2021-08-11 12:35:56 +03:00
|
|
|
}
|
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
async function handleSend (
|
2022-04-23 06:45:55 +03:00
|
|
|
ctx: MeasureContext,
|
2023-05-03 17:09:48 +03:00
|
|
|
ws: ConnectionSocket,
|
|
|
|
msg: Response<any>,
|
2023-05-10 20:16:13 +03:00
|
|
|
chunkLimit: number,
|
|
|
|
useBinary: boolean,
|
|
|
|
useCompression: boolean
|
2022-04-23 06:45:55 +03:00
|
|
|
): Promise<void> {
|
2023-05-03 17:09:48 +03:00
|
|
|
// ws.send(msg)
|
|
|
|
if (Array.isArray(msg.result) && chunkLimit > 0 && msg.result.length > chunkLimit) {
|
|
|
|
// Split and send by chunks
|
|
|
|
const data = [...msg.result]
|
|
|
|
|
|
|
|
let cid = 1
|
|
|
|
while (data.length > 0) {
|
|
|
|
const chunk = data.splice(0, chunkLimit)
|
|
|
|
if (chunk !== undefined) {
|
2023-05-10 20:16:13 +03:00
|
|
|
await ws.send(
|
|
|
|
ctx,
|
|
|
|
{ ...msg, result: chunk, chunk: { index: cid, final: data.length === 0 } },
|
|
|
|
useBinary,
|
|
|
|
useCompression
|
|
|
|
)
|
2023-04-13 20:39:20 +03:00
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
cid++
|
2021-12-22 12:02:51 +03:00
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
} else {
|
2023-05-10 20:16:13 +03:00
|
|
|
await ws.send(ctx, msg, useBinary, useCompression)
|
2023-05-03 17:09:48 +03:00
|
|
|
}
|
|
|
|
}
|
2021-08-03 22:02:59 +03:00
|
|
|
|
2023-05-03 17:09:48 +03:00
|
|
|
/**
|
|
|
|
* @public
|
|
|
|
*/
|
|
|
|
export function start (
|
|
|
|
ctx: MeasureContext,
|
|
|
|
opt: {
|
|
|
|
port: number
|
|
|
|
pipelineFactory: PipelineFactory
|
|
|
|
sessionFactory: (token: Token, pipeline: Pipeline, broadcast: BroadcastCall) => Session
|
|
|
|
productId: string
|
|
|
|
serverFactory: ServerFactory
|
2023-05-15 07:41:33 +03:00
|
|
|
enableCompression?: boolean
|
2021-11-22 14:17:10 +03:00
|
|
|
}
|
2023-05-03 17:09:48 +03:00
|
|
|
): () => Promise<void> {
|
|
|
|
const sessions = new TSessionManager(ctx, opt.sessionFactory)
|
|
|
|
return opt.serverFactory(
|
|
|
|
sessions,
|
2023-05-10 20:16:13 +03:00
|
|
|
(rctx, service, ws, msg, workspace) => sessions.handleRequest(rctx, service, ws, msg, workspace),
|
2023-05-03 17:09:48 +03:00
|
|
|
ctx,
|
|
|
|
opt.pipelineFactory,
|
|
|
|
opt.port,
|
2023-05-15 07:41:33 +03:00
|
|
|
opt.productId,
|
|
|
|
opt.enableCompression ?? true
|
2023-05-03 17:09:48 +03:00
|
|
|
)
|
2021-08-03 22:02:59 +03:00
|
|
|
}
|