gemercheung 3 år sedan
förälder
incheckning
dbb3b785a3
4 ändrade filer med 95 tillägg och 53 borttagningar
  1. 42 0
      src/app.controller.ts
  2. 7 7
      src/logConfig.ts
  3. 1 3
      src/meta.gateway.ts
  4. 45 43
      src/scene/scene.service.ts

+ 42 - 0
src/app.controller.ts

@@ -4,6 +4,7 @@ import { grpcClientOptions } from './scene/grpc-scene.options';
 import { ClientGrpc, Client } from '@nestjs/microservices';
 import { SceneService } from './scene/scene.service';
 import { CacheService } from './cache/cache.service';
+import { resolve } from 'path';
 
 @Controller()
 export class AppController implements OnModuleInit {
@@ -45,4 +46,45 @@ export class AppController implements OnModuleInit {
       };
     }
   }
+
+  @Get('/api/status/rooms')
+  async getOnlineRooms(): Promise<any> {
+    try {
+      const key =
+        process.env.NODE_ENV === 'development' ? 'test-room:*' : 'room:*';
+      const result = await this.cacheService.keys(key);
+      console.log('result', result);
+      interface SchemaRes {
+        roomId: string;
+        total: number;
+        userIds: string[];
+      }
+      const schemaRes: Promise<SchemaRes>[] = [];
+      const getSingleRoomStatus = (roomId: string): Promise<SchemaRes> => {
+        return new Promise(async (resolve) => {
+          const onlineRoomUsers = await this.cacheService.hGetAll(roomId);
+          const userIds = Object.keys(onlineRoomUsers);
+          const roomStatus = {
+            roomId: roomId.split(':')[1],
+            total: userIds.length,
+            userIds: userIds,
+          };
+          return resolve(roomStatus);
+        });
+      };
+      if (result.length > 0) {
+        result.forEach((room) => {
+          schemaRes.push(getSingleRoomStatus(room));
+        });
+        const roomStatus = await Promise.all(schemaRes);
+        console.log('roomStatus', roomStatus);
+        return roomStatus;
+      } else {
+        return [];
+      }
+    } catch (error) {
+      console.log('error', error);
+      return [];
+    }
+  }
 }

+ 7 - 7
src/logConfig.ts

@@ -35,7 +35,7 @@ export const LoggerConfig = {
     winston.format.json(),
     winston.format.printf(
       (info) =>
-        `${info.timestamp} [${info.level}] ${info.context || ''}: ${ info.message
+        `${info.timestamp} [${info.level}] ${info.context || ''}: ${info.message
         }`,
     ),
     // nestWinstonModuleUtilities.format.nestLike('Meta-server', {
@@ -65,15 +65,15 @@ export const LoggerConfig = {
       filename: 'combine.log',
       level: 'error',
     }),
-    // new winston.transports.File({
-    //   dirname: logDir,
-    //   filename: 'combine.log',
-    //   level: 'info',
-    // }),
+    new winston.transports.File({
+      dirname: logDir,
+      filename: 'combine.log',
+      level: 'verbose',
+    }),
     new winston.transports.File({
       dirname: logDir,
       filename: 'bootsrap.log',
-      level: 'http',
+      level: 'warn',
     }),
   ],
 };

+ 1 - 3
src/meta.gateway.ts

@@ -19,11 +19,9 @@ import {
 
 import { Buffer } from 'buffer';
 import { Inject } from '@nestjs/common';
-import * as path from 'path';
-import { createReadStream } from 'fs';
+
 import { SceneService } from './scene/scene.service';
 import { ConfigService } from '@nestjs/config';
-import { stringify } from 'querystring';
 import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
 import { Logger } from 'winston';
 // 'Verbose' | 'Debug' | 'Info' | 'Warning' | 'Error' | 'Fatal';

+ 45 - 43
src/scene/scene.service.ts

@@ -1,7 +1,7 @@
 import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
 import { ClientGrpc, Client } from '@nestjs/microservices';
 import { grpcClientOptions } from './grpc-scene.options';
-import { Logger } from '@nestjs/common';
+import { Inject } from '@nestjs/common';
 import { DataChannel, PeerConnection } from 'node-datachannel';
 import { BehaviorSubject } from 'rxjs';
 // import * as streamBuffers from 'stream-buffers';
@@ -16,7 +16,8 @@ import { DelayQueue, RxQueue, DebounceQueue } from '../queue/mod';
 import { MoveService } from 'src/move/move.service';
 import { GetRouterService } from 'src/get-router/get-router.service';
 import { ConfigService } from '@nestjs/config';
-
+import { Logger } from 'winston';
+import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
 // interface UserInfo {
 //   userId: string;
 //   roomId: string;
@@ -42,7 +43,8 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
     private streamService: StreamService,
     private rotateService: RotateService,
     private moveService: MoveService,
-    private getRouterService: GetRouterService, // @InjectQueue('rotate') private rotateQueue: Queue, // @InjectQueue('walking') private walkingQueue: Queue,
+    private getRouterService: GetRouterService,
+    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
   ) { }
   @Client(grpcClientOptions) private readonly client: ClientGrpc;
 
@@ -66,7 +68,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
 
   private channel: DataChannel;
   private peer: PeerConnection;
-  private logger: Logger = new Logger('SceneService');
+  // private logger: Logger = new Logger('SceneService');
   private frameCntInterval = 1000;
   private user_id: string;
   private roomId: string;
@@ -135,8 +137,8 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
     Number.prototype.padLeft = function (n, str) {
       return Array(n - String(this).length + 1).join(str || '0') + this;
     };
-    // this.logger.log('roQueue-period :' + Number(this.roQueue.period));
-    this.logger.log('moveQueue-period :' + Number(this.moveQueue.period));
+    // this.logger.info('roQueue-period :' + Number(this.roQueue.period));
+    this.logger.info('moveQueue-period :' + Number(this.moveQueue.period));
   }
 
   public isHeaderOrLast(index: number, length: number): boolean {
@@ -307,7 +309,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
             const stop = performance.now();
             const inMillSeconds = stop - start;
             const rounded = Number(inMillSeconds).toFixed(3);
-            this.logger.log(
+            this.logger.info(
               `[timer]-rotate-入队列前: ${rounded}ms -->` +
               JSON.stringify(stream),
             );
@@ -381,7 +383,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
 
       clearTimeout(this._rotateTimeout);
       this._rotateTimeout = setTimeout(() => {
-        this.logger.log('rotate end', Date.now());
+        this.logger.info('rotate end', Date.now());
         this.rotateframeCnt = -1;
         this._rotateCountFame = -1;
         this._rotateCount = 0;
@@ -413,7 +415,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
   //         this._rotateCountFame += 1;
 
   //         const IDRflag = this._rotateCountFame % 5 === 0 ? 1 : 3;
-  //         this.logger.log(
+  //         this.logger.info(
   //           `当前rotate ,mainframeCnt:${this.frameCnt.getValue()}, _rotateCountFame:${this._rotateCountFame
   //           } IDRflag:${IDRflag}`,
   //         );
@@ -422,7 +424,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
   //           this.rotateFirstIDR = false;
   //         }
 
-  //         this.logger.log(
+  //         this.logger.info(
   //           '[media-rotate]: ' +
   //           ', frame: ' +
   //           stream.frame +
@@ -432,7 +434,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
   //           stream.clipPath,
   //           // stream.metaData,
   //         );
-  //         // this.logger.log(
+  //         // this.logger.info(
   //         //   `roQueueSubscription:frame:${this.rotateframeCnt}  ` +
   //         //   JSON.stringify(stream.metaData),
   //         // );
@@ -441,7 +443,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
   //         if (res.done) {
   //           clearTimeout(this._rotateTimeout);
   //           this._rotateTimeout = setTimeout(() => {
-  //             this.logger.log('rotate end', Date.now());
+  //             this.logger.info('rotate end', Date.now());
   //             this.frameCnt.next(res.frame);
   //             this.rotateframeCnt = -1;
   //             this._rotateCountFame = -1;
@@ -477,7 +479,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
     this.rotateStopThrottle = true;
     this.isStopJointing = true;
     const lastStreamFrame = this.lastMoveStreamFrame.getValue();
-    this.logger.log(
+    this.logger.info(
       'handleRotateOrWalkingStop-frame',
       JSON.stringify(lastStreamFrame),
     );
@@ -504,7 +506,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
     const breakPointId = metaData.endBreakPointId || metaData.breakPointId;
     const cameraAngle = newUserStates.playerState.camera.angle;
     const playerAngle = newUserStates.playerState.player.angle;
-    this.logger.log(
+    this.logger.info(
       'stop-data-0' +
       'trace_id: ' +
       trace_id +
@@ -527,7 +529,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
       cameraAngle,
       playerAngle,
     );
-    this.logger.log('stop-redisMeta-frame', JSON.stringify(redisMeta));
+    this.logger.info('stop-redisMeta-frame', JSON.stringify(redisMeta));
     if (redisMeta) {
       const src = redisMeta.mediaSrc.split('?')[0];
       const mediaSrc = this.configService.get('app.prefix') + src;
@@ -582,7 +584,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
    */
   async walking(request: MoveRequest) {
     this.latestWalkingRequest = request;
-    this.logger.log('walking-trace_id', request.trace_id);
+    this.logger.info('walking-trace_id', request.trace_id);
 
     // if (this.isHasWalkingJoints()) {
     //   console.log('lock-锁-walking', this.latestWalkingRequest);
@@ -612,7 +614,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
           //TODO 正在行走时,有新的reqest
           if (frame) {
             // console.log('unlock-Joints', JSON.stringify(frame));
-            this.logger.log('Joints', JSON.stringify(frame));
+            this.logger.info('Joints', JSON.stringify(frame));
             this.resumeRotate();
             let isRotateStop = false;
             let isWalkingStop = false;
@@ -693,13 +695,13 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
       this._rotateCount = 0;
       const user = this.moveService.users[this.user_id];
       console.log('进入1 - searchRoad');
-      this.logger.log(
+      this.logger.info(
         'handleWalking-users' +
         JSON.stringify(this.moveService.users) +
         ' this.user_id: ' +
         this.user_id,
       );
-      this.logger.log(
+      this.logger.info(
         'handleWalking-currentUser' +
         JSON.stringify(user) +
         ' this.user_id: ' +
@@ -712,7 +714,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
         user.breakPointId,
         request.clicking_action.clicking_point,
       );
-      this.logger.log('walking-path', path);
+      this.logger.info('walking-path', path);
       if (!path) {
         console.log('不存在--path', path);
         this.cleanMoveSteam();
@@ -760,7 +762,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
         const seqs = Array.from(walkingRes).flat() as any as StreamReplyType[];
 
         if (seqs?.length) {
-          this.logger.log(
+          this.logger.info(
             'walking --队列总览:' +
             ' 总段数: ' +
             walkingRes.length +
@@ -776,7 +778,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
           const stop = performance.now();
           const inMillSeconds = stop - start;
           const rounded = Number(inMillSeconds).toFixed(3);
-          this.logger.log(`[timer]-move-入队列前:-->${rounded}ms`);
+          this.logger.info(`[timer]-move-入队列前:-->${rounded}ms`);
 
           this.handleSeqMoving(seqs);
         } else {
@@ -810,7 +812,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
    */
   async joystick(request: JoystickRequest) {
     // TODO hasJoystickMoveRequest中断
-    this.logger.log('this.hasJoystickMoveRequest', this.hasJoystickMoveRequest);
+    this.logger.info('this.hasJoystickMoveRequest', this.hasJoystickMoveRequest);
     if (!this.hasJoystickMoveRequest) {
       this.handlejoystick(request);
     }
@@ -967,8 +969,8 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
         console.log(`complementFrame调用时间---->${rounded}`);
       } else {
         console.log('complementFrame-空1');
-        this.logger.log('joystick opt done');
-        this.logger.log('joystick 交权给空流,当前pts', hasPush.frame);
+        this.logger.info('joystick opt done');
+        this.logger.info('joystick 交权给空流,当前pts', hasPush.frame);
         this.hasJoystickFocusRepeat = false;
         this.onJoysticking.next(false);
         this.resumeStream();
@@ -987,12 +989,12 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
       //const joystickRes = await this.moveService.joystick(request);
       this._rotateCount = 0;
       const joystickRes = await this.moveService.seqExeJoystick(request);
-      this.logger.log(
+      this.logger.info(
         'joystick-breakPointId:' +
         this.moveService.users[this.user_id].breakPointId,
       );
       // 有数据 [0]是rotate数据,[1-infinity]是walking数据
-      //this.logger.log('joystickRes', JSON.stringify(joystickRes));
+      //this.logger.info('joystickRes', JSON.stringify(joystickRes));
 
       if (joystickRes) {
         this.onJoysticking.next(true);
@@ -1027,7 +1029,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
     // if (!this.moveQueueSubscription) {
     //   this.handleMoveSteam();
     // }
-    // this.logger.log('moving-seqs', seqs.length);
+    // this.logger.info('moving-seqs', seqs.length);
     this.onMoving.next(true);
     this.holdSteam();
     // 保证每一段都是序列动作的前面队列是空的
@@ -1072,7 +1074,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
           serverTime: this.mockserverTime,
           DIR: stream.DIR,
         };
-        this.logger.log(
+        this.logger.info(
           '[media-move]: ' +
           ', moveframeCnt: ' +
           this.moveframeCnt +
@@ -1084,7 +1086,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
           stream.DIR,
           // stream.metaData,
         );
-        this.logger.log(
+        this.logger.info(
           '[media-move-lastMovingPointArray]',
           this.lastMovingPointArray?.length,
         );
@@ -1100,7 +1102,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
         const isLastFrameIndex = this.lastMovingPointArray.findIndex(
           (item) => item.mediaSrc === metaData.mediaSrc,
         );
-        // this.logger.log('path-update-index', isLastFrameIndex);
+        // this.logger.info('path-update-index', isLastFrameIndex);
 
         if (res.done) {
           const frameTimeEnd = performance.now();
@@ -1110,7 +1112,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
           this.frameCnt.next(res.frame);
           //关节点入库
           if (isLastFrameIndex > -1) {
-            //this.logger.log('path-update-array', this.lastMovingPointArray);
+            //this.logger.info('path-update-array', this.lastMovingPointArray);
             const currentMeta = this.lastMovingPointArray[isLastFrameIndex];
             const userId = this.user_id;
             const breakPointId = currentMeta.metaData.endBreakPointId;
@@ -1123,7 +1125,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
           clearTimeout(this._moveTimeout);
 
           this._moveTimeout = setTimeout(() => {
-            this.logger.log('move 交权给空流,当前pts', res.frame);
+            this.logger.info('move 交权给空流,当前pts', res.frame);
             this.rewalking = false;
             this.frameCnt.next(res.frame);
             this.rotateframeCnt = -1;
@@ -1134,7 +1136,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
             this.cleanMoveSteam();
             this.globalOptLock = false;
             this.resumeStream();
-            this.logger.log('move end');
+            this.logger.info('move end');
           }, 200);
         } else {
           console.error('流地址有误::', res.frame, JSON.stringify(res));
@@ -1271,7 +1273,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
           if (frameData) {
             this.globalOptLock = true;
             const nextFrame = this.frameCnt.getValue() + 1;
-            this.logger.warn('lostIframe', nextFrame);
+            this.logger.warn('lostIframe:' + nextFrame);
             frameData.frame = nextFrame;
             frameData.DIR = 1;
             const res = await this.streamService.pushFrameToSteam(frameData);
@@ -1296,7 +1298,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
 
   handleBreath(request) {
     const npsRes = this.moveService.getBreakPoints(request);
-    //this.logger.log('npsRes', npsRes.nps);
+    //this.logger.info('npsRes', npsRes.nps);
     this.streamService.pushNormalDataToStream(npsRes);
   }
 
@@ -1312,7 +1314,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
       const usersData = this.rotateService.getNewUserStateRequest(request);
       if (usersData) {
         usersData.actionType = 1024;
-        //this.logger.log(
+        //this.logger.info(
         //   'joystick:->updateUserStatus' +
         //   'playerPosition:' +
         //   JSON.stringify(
@@ -1346,12 +1348,12 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
     });
   }
   handleStream() {
-    this.logger.log('this.frameCntSubscription', this.frameCntSubscription);
+    this.logger.info('this.frameCntSubscription', this.frameCntSubscription);
     let redisData;
     if (!this.frameCntSubscription) {
       this.frameCntSubscription = this.frameCnt.subscribe(async (frame) => {
         try {
-          this.logger.log('frame', frame);
+          this.logger.info('frame: ' + frame);
           console.log(
             'networkState:::--->' +
             ' maxMessageSize: ' +
@@ -1373,7 +1375,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
               app_id,
               this.user_id,
             );
-            this.logger.log('获取-首屏', redisData);
+            this.logger.info('获取-首屏', redisData);
             this.onSteaming = true;
             this.holdSteam();
             if (redisData && 'mediaSrc' in redisData) {
@@ -1382,7 +1384,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
                 const src = mediaSrc.split('?')[0];
                 const clipPath = this.configService.get('app.prefix') + src;
                 delete redisData.mediaSrc;
-                this.logger.log(
+                this.logger.info(
                   `user:${this.user_id}:first render stream` +
                   JSON.stringify({ path: clipPath, meta: redisData }),
                 );
@@ -1441,7 +1443,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
               false,
             );
             if (redisDataAuto) {
-              this.logger.log(`空白流::有数据:${frame}`);
+              this.logger.info(`空白流::有数据:${frame}`);
               'mediaSrc' in redisDataAuto && delete redisDataAuto.mediaSrc;
               const streamMeta: StreamMetaType = {
                 frame: frame,
@@ -1450,7 +1452,7 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
               this.streamService.pushMetaDataToSteam(streamMeta);
             } else {
               this.stopStream();
-              this.logger.log('空流无Redis数据');
+              this.logger.info('空流无Redis数据');
             }
           }
         } catch (error) {