Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid passing messages multiple times #331

Merged
merged 4 commits into from
Feb 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 6 additions & 20 deletions packages/nest-electron/src/electron.decorators.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { Inject, applyDecorators } from '@nestjs/common'
import { MessagePattern } from '@nestjs/microservices'
import { app, ipcMain } from 'electron'
import { EventPattern, MessagePattern } from '@nestjs/microservices'
import { ELECTRON_WINDOW, ELECTRON_WINDOW_DEFAULT_NAME, IPC_HANDLE, IPC_ON } from './electron.constants'
import { ChannelMaps, ipcMessageDispatcher } from './transport'
import { generateRandomString, linkPathAndChannel } from './utils'
import { ChannelMaps } from './transport'
import { generateRandomString } from './utils'

function createIpcDecorator(type: typeof IPC_HANDLE | typeof IPC_ON) {
return (channel: string) => {
Expand All @@ -13,27 +12,14 @@ function createIpcDecorator(type: typeof IPC_HANDLE | typeof IPC_ON) {
const channelId = `${channel}-${generateRandomString()}`

function ipcDecorator() {
return (target: any, _key: string, _descriptor: PropertyDescriptor) => {
app.on('ready', () => {
const path = Reflect.getMetadata('path', target.constructor)
const channelNames = linkPathAndChannel(channel, path)
const mainChannelName = channelNames[0]
for (const channel of channelNames) {
// These four channel names eventually converge into mainChannelName
if (type === IPC_ON)
ipcMain.on(channel, (...args) => ipcMessageDispatcher.emit(mainChannelName, IPC_ON, ...args))
else if (type === IPC_HANDLE)
ipcMain.handle(channel, (...args) => ipcMessageDispatcher.emit(mainChannelName, IPC_HANDLE, ...args))
}

ChannelMaps.set(mainChannelName, channelId)
})
return (target: any, key: string, _descriptor: PropertyDescriptor) => {
ChannelMaps.set(channelId, { target, key, channel })
}
}

return applyDecorators(
ipcDecorator(),
MessagePattern(channelId),
type === IPC_HANDLE ? MessagePattern(channelId) : EventPattern(channelId),
)
}
}
Expand Down
80 changes: 45 additions & 35 deletions packages/nest-electron/src/electron.transport.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,65 @@
import { Logger } from '@nestjs/common'
import type { CustomTransportStrategy, MessageHandler } from '@nestjs/microservices'
import { Server } from '@nestjs/microservices'
import { isObservable, lastValueFrom } from 'rxjs'
import './nest.hacker'
import { IPC_HANDLE, IPC_ON } from './electron.constants'
import { ChannelMaps, ipcMessageDispatcher } from './transport'
import type { IpcMainEvent, IpcMainInvokeEvent } from 'electron'
import { ipcMain } from 'electron'
import { ChannelMaps } from './transport'
import { linkPathAndChannel } from './utils'

export class ElectronIpcTransport extends Server implements CustomTransportStrategy {
protected readonly logger: Logger
export interface IpcContext {
ipcEvt: IpcMainEvent | IpcMainInvokeEvent
}

constructor(name: string = ElectronIpcTransport.name) {
super()
this.logger = new Logger(name)
export class ElectronIpcTransport extends Server implements CustomTransportStrategy {
close(): any {
}

async onMessage(messageChannel: string, type: string, ...args: any[]): Promise<any | void> {
try {
const noHandlerError = () => {
const errMsg = `No handler for message channel "${messageChannel}"`
listen(callback: () => void): any {
ChannelMaps.forEach(({ target, channel }, channelId) => {
const path = Reflect.getMetadata('path', target.constructor)
const channelNames = linkPathAndChannel(channel, path)

const handler = this.getHandlers().get(channelId)
if (!handler) {
const errMsg = `No handler for message channel "${channelNames[0]}"`
this.logger.error(errMsg)
throw new Error(errMsg)
}

const channelId = ChannelMaps.get(messageChannel)
if (!channelId)
noHandlerError()
for (const ch of channelNames) {
if (handler.isEventHandler)
ipcMain.on(ch, this.applyHandler(handler, ch))
else
ipcMain.handle(ch, this.applyHandler(handler, ch))
}
})

const handler: MessageHandler | undefined = this.messageHandlers.get(channelId)
if (!handler)
noHandlerError()
callback()
}

this.logger.log(`[${type === IPC_HANDLE ? 'ipcMain.handle' : 'ipcMain.on'}] Process message ${messageChannel}`)
const [ipcEventObject, ...payload] = args
private applyHandler(handler: MessageHandler, channel: string) {
return async (...args) => {
try {
if (!handler.isEventHandler)
this.logger.log(`[IPC] Process message ${channel}`)
else
this.logger.log(`[IPC] Process event ${channel}`)

const data = payload.length === 0 ? undefined : payload.length === 1 ? payload[0] : payload
const [ipcMainEventObject, ...payload] = args

const result = await handler(data, { ipcEvt: ipcEventObject })
const data = payload.length === 0 ? undefined : payload.length === 1 ? payload[0] : payload
const ctx: IpcContext = { ipcEvt: ipcMainEventObject }

if (type !== IPC_ON)
return isObservable(result) ? await lastValueFrom(result) : result
}
catch (error) {
throw new Error(error.message ?? error)
return await handler(data, ctx).then(async (res) => {
return isObservable(res)
? await lastValueFrom(res)
: res
})
}
catch (error) {
throw new Error(error.message ?? error)
}
}
}

close(): any {
}

listen(callback: () => void): any {
ipcMessageDispatcher.on('ipc-message', this.onMessage.bind(this))
callback()
}
}
2 changes: 1 addition & 1 deletion packages/nest-electron/src/transport/channels.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const ChannelMaps = new Map<string, string>()
export const ChannelMaps = new Map<string, { target: Object; key: string | symbol; channel: string }>()
12 changes: 0 additions & 12 deletions packages/nest-electron/src/transport/dispatcher.ts

This file was deleted.

1 change: 0 additions & 1 deletion packages/nest-electron/src/transport/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from './dispatcher'
export * from './filter'
export * from './channels'