Răsfoiți Sursa

Merge pull request #6017 from weseek/feat/97185-create-ttl-index-for-activity-collection-at-server-startup

feat: Create TTL index for Activity collection at ActivityService initialize
Shun Miyazawa 3 ani în urmă
părinte
comite
718cf10511

+ 1 - 0
packages/app/.env.development

@@ -29,3 +29,4 @@ OGP_URI="http://ogp:8088"
 # SLACKBOT_WITHOUT_PROXY_BOT_TOKEN=''
 # GROWI_CLOUD_URI='http://growi.cloud'
 # GROWI_APP_ID_FOR_GROWI_CLOUD=012345
+# ACTIVITY_EXPIRATION_SECONDS=2592000

+ 1 - 0
packages/app/src/server/crowi/index.js

@@ -704,6 +704,7 @@ Crowi.prototype.setupActivityService = async function() {
   const ActivityService = require('../service/activity');
   if (this.activityService == null) {
     this.activityService = new ActivityService(this);
+    await this.activityService.createTtlIndex();
   }
 };
 

+ 30 - 0
packages/app/src/server/service/activity.ts

@@ -1,4 +1,5 @@
 import { getModelSafely } from '@growi/core';
+import mongoose from 'mongoose';
 
 import { IActivity } from '~/interfaces/activity';
 import { IPage } from '~/interfaces/page';
@@ -44,6 +45,35 @@ class ActivityService {
     });
   }
 
+  createTtlIndex = async function() {
+    const configManager = this.crowi.configManager;
+    const activityExpirationSeconds = configManager != null ? configManager.getConfig('crowi', 'app:activityExpirationSeconds') : 2592000;
+    const collection = mongoose.connection.collection('activities');
+
+    try {
+      const targetField = 'createdAt_1';
+
+      const indexes = await collection.indexes();
+      const foundCreatedAt = indexes.find(i => i.name === targetField);
+
+      const isNotSpec = foundCreatedAt?.expireAfterSeconds == null || foundCreatedAt?.expireAfterSeconds !== activityExpirationSeconds;
+      const shoudDropIndex = foundCreatedAt != null && isNotSpec;
+      const shoudCreateIndex = foundCreatedAt == null || shoudDropIndex;
+
+      if (shoudDropIndex) {
+        await collection.dropIndex(targetField);
+      }
+
+      if (shoudCreateIndex) {
+        await collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: activityExpirationSeconds });
+      }
+    }
+    catch (err) {
+      logger.error('Failed to create TTL Index', err);
+      throw err;
+    }
+  };
+
 
   /**
      * @param {object} parameters

+ 6 - 0
packages/app/src/server/service/config-loader.ts

@@ -622,6 +622,12 @@ const ENV_VAR_NAME_TO_CONFIG_INFO = {
     type: ValueType.NUMBER,
     default: 8,
   },
+  ACTIVITY_EXPIRATION_SECONDS: {
+    ns: 'crowi',
+    key: 'app:activityExpirationSeconds',
+    type: ValueType.NUMBER,
+    default: 2592000,
+  },
 };