Prechádzať zdrojové kódy

Refactor code to change installApk endpoint to sendMessage endpoint

x1ongzhu 1 rok pred
rodič
commit
6e4bfb59bf

+ 4 - 9
src/device/device.controller.ts

@@ -4,6 +4,7 @@ import { PageRequest } from 'src/common/dto/page-request'
 import { Device } from './entities/device.entity'
 import { Device } from './entities/device.entity'
 import { Public } from 'src/auth/public.decorator'
 import { Public } from 'src/auth/public.decorator'
 import { HasRoles } from 'src/auth/roles.decorator'
 import { HasRoles } from 'src/auth/roles.decorator'
+import { SendMessageDto } from './dtos/send-message.dto'
 
 
 @Controller('device')
 @Controller('device')
 export class DeviceController {
 export class DeviceController {
@@ -32,15 +33,9 @@ export class DeviceController {
         return await this.deviceService.updateDevice(id, data)
         return await this.deviceService.updateDevice(id, data)
     }
     }
 
 
-    @Post('/:id/installApk')
+    @Post('/:id/sendMessage')
     @HasRoles('admin')
     @HasRoles('admin')
-    async installApk(@Param('id') id: string, @Body() { apkUrl }: { apkUrl: string }) {
-        return await this.deviceService.installApk(id, apkUrl)
-    }
-
-    @Post('/:id/runScript')
-    @HasRoles('admin')
-    async runScript(@Param('id') id: string, @Body() { script }: { script: string }) {
-        return await this.deviceService.runScript(id, script)
+    async installApk(@Param('id') id: string, @Body() message: SendMessageDto) {
+        return await this.deviceService.sendMessage(id, message)
     }
     }
 }
 }

+ 6 - 15
src/device/device.service.ts

@@ -18,12 +18,13 @@ import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity
 import { TaskService } from '../task/task.service'
 import { TaskService } from '../task/task.service'
 import { OperatorConfigService } from '../operator_config/operator_config.service'
 import { OperatorConfigService } from '../operator_config/operator_config.service'
 import { Interval } from '@nestjs/schedule'
 import { Interval } from '@nestjs/schedule'
-import { EventsGateway } from 'src/events/events.gateway'
+import { EventsGateway } from '../events/events.gateway'
 import { DeviceTask, DeviceTaskStatus } from './entities/device-task.entity'
 import { DeviceTask, DeviceTaskStatus } from './entities/device-task.entity'
 import { DeviceTaskItem, DeviceTaskItemStatus } from './entities/device-task-item.entity'
 import { DeviceTaskItem, DeviceTaskItemStatus } from './entities/device-task-item.entity'
 import PQueue from 'p-queue'
 import PQueue from 'p-queue'
 import { randomUUID } from 'crypto'
 import { randomUUID } from 'crypto'
 import { setTimeout } from 'timers/promises'
 import { setTimeout } from 'timers/promises'
+import { SendMessageDto } from './dtos/send-message.dto'
 
 
 @Injectable()
 @Injectable()
 export class DeviceService implements OnModuleInit {
 export class DeviceService implements OnModuleInit {
@@ -332,24 +333,14 @@ export class DeviceService implements OnModuleInit {
         return device
         return device
     }
     }
 
 
-    async sendToDeviceWithAck(socketId: string, action: string, data: any) {
+    async sendMessage(deviceId: string, message: SendMessageDto) {
+        const device = await this.findOnelineDevice(deviceId)
         return await this.eventsGateway.sendForResult(
         return await this.eventsGateway.sendForResult(
             {
             {
                 id: randomUUID(),
                 id: randomUUID(),
-                action,
-                data
+                ...message
             },
             },
-            socketId
+            device.socketId
         )
         )
     }
     }
-
-    async installApk(deviceId: string, apkUrl: string) {
-        const device = await this.findOnelineDevice(deviceId)
-        return await this.sendToDeviceWithAck(device.socketId, 'installApk', { apkUrl })
-    }
-
-    async runScript(deviceId: string, script: string) {
-        const device = await this.findOnelineDevice(deviceId)
-        return await this.sendToDeviceWithAck(device.socketId, 'runScript', { script })
-    }
 }
 }

+ 9 - 0
src/device/dtos/send-message.dto.ts

@@ -0,0 +1,9 @@
+import { IsObject, IsString } from 'class-validator'
+
+export class SendMessageDto {
+    @IsString()
+    action: string
+
+    @IsObject()
+    data: any
+}

+ 13 - 5
src/events/events.gateway.ts

@@ -102,10 +102,18 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
         this.server.emit(event, data)
         this.server.emit(event, data)
     }
     }
 
 
-    public sendForResult(message: Message, to: string) {
-        return new Promise((resolve, reject) => {
-            this.callbacks[message.id] = [resolve, reject]
-            this.server.to(to).emit('message', message)
-        })
+    public sendForResult(message: Message, to: string, timeout = 2 * 60 * 1000) {
+        return Promise.race([
+            new Promise((resolve, reject) => {
+                this.callbacks[message.id] = [resolve, reject]
+                this.server.to(to).emit('message', message)
+            }),
+            new Promise((resolve, reject) => {
+                setTimeout(() => {
+                    delete this.callbacks[message.id]
+                    reject(new Error('Timeout'))
+                }, timeout)
+            })
+        ])
     }
     }
 }
 }

+ 13 - 17
src/task/task.service.ts

@@ -1079,23 +1079,19 @@ export class TaskService implements OnModuleInit {
                     .map((item) => ({ ...item, message: this.getMessage(task) }))
                     .map((item) => ({ ...item, message: this.getMessage(task) }))
                 if (items.length === 0) return
                 if (items.length === 0) return
                 try {
                 try {
-                    const res: any = await Promise.race([
-                        this.eventsGateway.sendForResult(
-                            {
-                                id: randomUUID(),
-                                action: 'task',
-                                data: {
-                                    config: { ...taskConfig, ...(device.configOverrides || {}) },
-                                    tasks: items,
-                                    taskId: task.id
-                                }
-                            },
-                            device.socketId
-                        ),
-                        setTimeout(120000).then(() => {
-                            return Promise.reject(new Error('timeout waiting for response'))
-                        })
-                    ])
+                    const res: any = this.eventsGateway.sendForResult(
+                        {
+                            id: randomUUID(),
+                            action: 'task',
+                            data: {
+                                config: { ...taskConfig, ...(device.configOverrides || {}) },
+                                tasks: items,
+                                taskId: task.id
+                            }
+                        },
+                        device.socketId
+                    )
+
                     Logger.log(
                     Logger.log(
                         `Task completed: ${res.success.length} success, ${res.fail.length} fail, ${
                         `Task completed: ${res.success.length} success, ${res.fail.length} fail, ${
                             res.retry?.length || 0
                             res.retry?.length || 0