summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/lib/RecommendationProvider.sys.mjs
blob: 875c90492beff0cc0855227fd973c6a4ece5f3ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  PersistentCache: "resource://activity-stream/lib/PersistentCache.sys.mjs",
  PersonalityProvider:
    "resource://activity-stream/lib/PersonalityProvider/PersonalityProvider.sys.mjs",
});

import {
  actionTypes as at,
  actionCreators as ac,
} from "resource://activity-stream/common/Actions.sys.mjs";

const CACHE_KEY = "personalization";
const PREF_PERSONALIZATION_MODEL_KEYS =
  "discoverystream.personalization.modelKeys";
const PREF_USER_TOPSTORIES = "feeds.section.topstories";
const PREF_SYSTEM_TOPSTORIES = "feeds.system.topstories";
const PREF_PERSONALIZATION = "discoverystream.personalization.enabled";
const MIN_PERSONALIZATION_UPDATE_TIME = 12 * 60 * 60 * 1000; // 12 hours
const PREF_PERSONALIZATION_OVERRIDE =
  "discoverystream.personalization.override";

// The main purpose of this class is to handle interactions with the recommendation provider.
// A recommendation provider scores a list of stories, currently this is a personality provider.
// So all calls to the provider, anything involved with the setup of the provider,
// accessing prefs for the provider, or updaing devtools with provider state, is contained in here.
export class RecommendationProvider {
  constructor() {
    // Persistent cache for remote endpoint data.
    this.cache = new lazy.PersistentCache(CACHE_KEY, true);
  }

  async setProvider(isStartup = false, scores) {
    // A provider is already set. This can happen when new stories come in
    // and we need to update their scores.
    // We can use the existing one, a fresh one is created after startup.
    // Using the existing one might be a bit out of date,
    // but it's fine for now. We can rely on restarts for updates.
    // See bug 1629931 for improvements to this.
    if (!this.provider) {
      this.provider = new lazy.PersonalityProvider(this.modelKeys);
      this.provider.setScores(scores);
    }

    if (this.provider && this.provider.init) {
      await this.provider.init();
      this.store.dispatch(
        ac.BroadcastToContent({
          type: at.DISCOVERY_STREAM_PERSONALIZATION_INIT,
          meta: {
            isStartup,
          },
        })
      );
    }
  }

  async enable(isStartup) {
    await this.loadPersonalizationScoresCache(isStartup);
    Services.obs.addObserver(this, "idle-daily");
    this.loaded = true;
    this.store.dispatch(
      ac.BroadcastToContent({
        type: at.DISCOVERY_STREAM_PERSONALIZATION_UPDATED,
        meta: {
          isStartup,
        },
      })
    );
  }

  get showStories() {
    // Combine user-set stories opt-out with Mozilla-set config
    return (
      this.store.getState().Prefs.values[PREF_SYSTEM_TOPSTORIES] &&
      this.store.getState().Prefs.values[PREF_USER_TOPSTORIES]
    );
  }

  get personalized() {
    // If stories are not displayed, no point in trying to personalize them.
    if (!this.showStories) {
      return false;
    }
    const spocsPersonalized =
      this.store.getState().Prefs.values?.pocketConfig?.spocsPersonalized;
    const recsPersonalized =
      this.store.getState().Prefs.values?.pocketConfig?.recsPersonalized;
    const personalization =
      this.store.getState().Prefs.values[PREF_PERSONALIZATION];

    // There is a server sent flag to keep personalization on.
    // If the server stops sending this, we turn personalization off,
    // until the server starts returning the signal.
    const overrideState =
      this.store.getState().Prefs.values[PREF_PERSONALIZATION_OVERRIDE];

    return (
      personalization &&
      !overrideState &&
      (spocsPersonalized || recsPersonalized)
    );
  }

  get modelKeys() {
    if (!this._modelKeys) {
      this._modelKeys =
        this.store.getState().Prefs.values[PREF_PERSONALIZATION_MODEL_KEYS];
    }

    return this._modelKeys;
  }

  /*
   * This creates a new recommendationProvider using fresh data,
   * It's run on a last updated timer. This is the opposite of loadPersonalizationScoresCache.
   * This is also much slower so we only trigger this in the background on idle-daily.
   * It causes new profiles to pick up personalization slowly because the first time
   * a new profile is run you don't have any old cache to use, so it needs to wait for the first
   * idle-daily. Older profiles can rely on cache during the idle-daily gap. Idle-daily is
   * usually run once every 24 hours.
   */
  async updatePersonalizationScores() {
    if (
      !this.personalized ||
      Date.now() - this.personalizationLastUpdated <
        MIN_PERSONALIZATION_UPDATE_TIME
    ) {
      return;
    }

    await this.setProvider();

    const personalization = { scores: this.provider.getScores() };
    this.personalizationLastUpdated = Date.now();

    this.store.dispatch(
      ac.BroadcastToContent({
        type: at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED,
        data: {
          lastUpdated: this.personalizationLastUpdated,
        },
      })
    );
    personalization._timestamp = this.personalizationLastUpdated;
    this.cache.set("personalization", personalization);
  }

  /*
   * This just re hydrates the provider from cache.
   * We can call this on startup because it's generally fast.
   * It reports to devtools the last time the data in the cache was updated.
   */
  async loadPersonalizationScoresCache(isStartup = false) {
    const cachedData = (await this.cache.get()) || {};
    const { personalization } = cachedData;

    if (this.personalized && personalization?.scores) {
      await this.setProvider(isStartup, personalization.scores);

      this.personalizationLastUpdated = personalization._timestamp;

      this.store.dispatch(
        ac.BroadcastToContent({
          type: at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED,
          data: {
            lastUpdated: this.personalizationLastUpdated,
          },
          meta: {
            isStartup,
          },
        })
      );
    }
  }

  // This turns personalization on/off if the server sends the override command.
  // The server sends a true signal to keep personalization on. So a malfunctioning
  // server would more likely mistakenly turn off personalization, and not turn it on.
  // This is safer, because the override is for cases where personalization is causing issues.
  // So having it mistakenly go off is safe, but it mistakenly going on could be bad.
  personalizationOverride(overrideCommand) {
    // Are we currently in an override state.
    // This is useful to know if we want to do a cleanup.
    const overrideState =
      this.store.getState().Prefs.values[PREF_PERSONALIZATION_OVERRIDE];

    // Is this profile currently set to be personalized.
    const personalization =
      this.store.getState().Prefs.values[PREF_PERSONALIZATION];

    // If we have an override command, profile is currently personalized,
    // and is not currently being overridden, we can set the override pref.
    if (overrideCommand && personalization && !overrideState) {
      this.store.dispatch(ac.SetPref(PREF_PERSONALIZATION_OVERRIDE, true));
    }

    // This is if we need to revert an override and do cleanup.
    // We do this if we are in an override state,
    // but not currently receiving the override signal.
    if (!overrideCommand && overrideState) {
      this.store.dispatch({
        type: at.CLEAR_PREF,
        data: { name: PREF_PERSONALIZATION_OVERRIDE },
      });
    }
  }

  async calculateItemRelevanceScore(item) {
    if (this.provider) {
      const scoreResult = await this.provider.calculateItemRelevanceScore(item);
      if (scoreResult === 0 || scoreResult) {
        item.score = scoreResult;
      }
    }
  }

  teardown() {
    if (this.provider && this.provider.teardown) {
      // This removes any in memory listeners if available.
      this.provider.teardown();
    }
    if (this.loaded) {
      Services.obs.removeObserver(this, "idle-daily");
    }
    this.loaded = false;
  }

  async resetState() {
    this._modelKeys = null;
    this.personalizationLastUpdated = null;
    this.provider = null;
    await this.cache.set("personalization", {});
    this.store.dispatch(
      ac.OnlyToMain({
        type: at.DISCOVERY_STREAM_PERSONALIZATION_RESET,
      })
    );
  }

  async observe(subject, topic) {
    switch (topic) {
      case "idle-daily":
        await this.updatePersonalizationScores();
        this.store.dispatch(
          ac.BroadcastToContent({
            type: at.DISCOVERY_STREAM_PERSONALIZATION_UPDATED,
          })
        );
        break;
    }
  }

  async onAction(action) {
    switch (action.type) {
      case at.INIT:
        await this.enable(true /* isStartup */);
        break;
      case at.DISCOVERY_STREAM_CONFIG_CHANGE:
        this.teardown();
        await this.resetState();
        await this.enable();
        break;
      case at.DISCOVERY_STREAM_DEV_IDLE_DAILY:
        Services.obs.notifyObservers(null, "idle-daily");
        break;
      case at.PREF_CHANGED:
        switch (action.data.name) {
          case PREF_PERSONALIZATION_MODEL_KEYS:
            this.store.dispatch(
              ac.BroadcastToContent({
                type: at.DISCOVERY_STREAM_CONFIG_RESET,
              })
            );
            break;
        }
        break;
      case at.DISCOVERY_STREAM_PERSONALIZATION_TOGGLE:
        let enabled = this.store.getState().Prefs.values[PREF_PERSONALIZATION];
        this.store.dispatch(ac.SetPref(PREF_PERSONALIZATION, !enabled));
        break;
      case at.DISCOVERY_STREAM_PERSONALIZATION_OVERRIDE:
        this.personalizationOverride(action.data.override);
        break;
    }
  }
}