Просмотр исходного кода

Merge pull request #19328 from overleaf/jdt-global-metrics

Allow for site wide metrics and counters

GitOrigin-RevId: e788488bdd673aef4ba0e45a9e39832d6203c44c
Jimmy Domagala-Tang 2 лет назад
Родитель
Сommit
168f83277b

+ 38 - 0
services/web/app/src/Features/GlobalMetrics/GlobalMetricsManager.js

@@ -0,0 +1,38 @@
+const { GlobalMetric } = require('../../models/GlobalMetric')
+/**
+ * A Generic collection used to track metrics shared across the entirety of the application
+ * examples:
+ *  - a metric to measure how many signups we have for an expensive labs experiment, so we can end stop signups
+ *  - a metric to measure how many users have been added to a test, so we can stop adding more once a cap is reached
+ *
+ */
+
+async function getMetric(key, defaultValue = 0) {
+  const metric = await GlobalMetric.findById(key)
+  if (!metric) {
+    return defaultValue
+  }
+  return metric
+}
+
+async function setMetric(key, value) {
+  return await GlobalMetric.findOneAndUpdate(
+    { _id: key },
+    { $set: { value } },
+    { new: true, upsert: true }
+  )
+}
+
+async function incrementMetric(key, value = 1) {
+  return await GlobalMetric.findOneAndUpdate(
+    { _id: key },
+    { $inc: { value } },
+    { new: true, upsert: true, setDefaultsOnInsert: true }
+  )
+}
+
+module.exports = {
+  getMetric,
+  setMetric,
+  incrementMetric,
+}

+ 1 - 0
services/web/app/src/infrastructure/mongodb.js

@@ -61,6 +61,7 @@ async function setupDb() {
   db.githubSyncUserCredentials = internalDb.collection(
     'githubSyncUserCredentials'
   )
+  db.globalMetrics = internalDb.collection('globalMetrics')
   db.grouppolicies = internalDb.collection('grouppolicies')
   db.institutions = internalDb.collection('institutions')
   db.messages = internalDb.collection('messages')

+ 19 - 0
services/web/app/src/models/GlobalMetric.js

@@ -0,0 +1,19 @@
+const mongoose = require('../infrastructure/Mongoose')
+const { Schema } = mongoose
+
+const GlobalMetricSchema = new Schema(
+  {
+    _id: { type: String, required: true },
+    value: {
+      type: Number,
+      default: 0,
+    },
+  },
+  {
+    collection: 'globalMetrics',
+    minimize: false,
+  }
+)
+
+exports.GlobalMetric = mongoose.model('GlobalMetric', GlobalMetricSchema)
+exports.GlobalMetricSchema = GlobalMetricSchema