summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm
blob: c1f54408f24d94ba67d7740778334cded7a4f0ef (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
/* 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/. */
"use strict";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  NewTabUtils: "resource://gre/modules/NewTabUtils.sys.mjs",
  RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
  Utils: "resource://services-settings/Utils.sys.mjs",
});

const { BasePromiseWorker } = ChromeUtils.importESModule(
  "resource://gre/modules/PromiseWorker.sys.mjs"
);

const RECIPE_NAME = "personality-provider-recipe";
const MODELS_NAME = "personality-provider-models";

class PersonalityProvider {
  constructor(modelKeys) {
    this.modelKeys = modelKeys;
    this.onSync = this.onSync.bind(this);
    this.setup();
  }

  setScores(scores) {
    this.scores = scores || {};
    this.interestConfig = this.scores.interestConfig;
    this.interestVector = this.scores.interestVector;
  }

  get personalityProviderWorker() {
    if (this._personalityProviderWorker) {
      return this._personalityProviderWorker;
    }

    this._personalityProviderWorker = new BasePromiseWorker(
      "resource://activity-stream/lib/PersonalityProvider/PersonalityProviderWorker.js"
    );

    return this._personalityProviderWorker;
  }

  get baseAttachmentsURL() {
    // Returning a promise, so we can have an async getter.
    return this._getBaseAttachmentsURL();
  }

  async _getBaseAttachmentsURL() {
    if (this._baseAttachmentsURL) {
      return this._baseAttachmentsURL;
    }
    const server = lazy.Utils.SERVER_URL;
    const serverInfo = await (
      await fetch(`${server}/`, {
        credentials: "omit",
      })
    ).json();
    const {
      capabilities: {
        attachments: { base_url },
      },
    } = serverInfo;
    this._baseAttachmentsURL = base_url;
    return this._baseAttachmentsURL;
  }

  setup() {
    this.setupSyncAttachment(RECIPE_NAME);
    this.setupSyncAttachment(MODELS_NAME);
  }

  teardown() {
    this.teardownSyncAttachment(RECIPE_NAME);
    this.teardownSyncAttachment(MODELS_NAME);
    if (this._personalityProviderWorker) {
      this._personalityProviderWorker.terminate();
    }
  }

  setupSyncAttachment(collection) {
    lazy.RemoteSettings(collection).on("sync", this.onSync);
  }

  teardownSyncAttachment(collection) {
    lazy.RemoteSettings(collection).off("sync", this.onSync);
  }

  onSync(event) {
    this.personalityProviderWorker.post("onSync", [event]);
  }

  /**
   * Gets contents of the attachment if it already exists on file,
   * and if not attempts to download it.
   */
  getAttachment(record) {
    return this.personalityProviderWorker.post("getAttachment", [record]);
  }

  /**
   * Returns a Recipe from remote settings to be consumed by a RecipeExecutor.
   * A Recipe is a set of instructions on how to processes a RecipeExecutor.
   */
  async getRecipe() {
    if (!this.recipes || !this.recipes.length) {
      const result = await lazy.RemoteSettings(RECIPE_NAME).get();
      this.recipes = await Promise.all(
        result.map(async record => ({
          ...(await this.getAttachment(record)),
          recordKey: record.key,
        }))
      );
    }
    return this.recipes[0];
  }

  /**
   * Grabs a slice of browse history for building a interest vector
   */
  async fetchHistory(columns, beginTimeSecs, endTimeSecs) {
    let sql = `SELECT url, title, visit_count, frecency, last_visit_date, description
    FROM moz_places
    WHERE last_visit_date >= ${beginTimeSecs * 1000000}
    AND last_visit_date < ${endTimeSecs * 1000000}`;
    columns.forEach(requiredColumn => {
      sql += ` AND IFNULL(${requiredColumn}, '') <> ''`;
    });
    sql += " LIMIT 30000";

    const { activityStreamProvider } = lazy.NewTabUtils;
    const history = await activityStreamProvider.executePlacesQuery(sql, {
      columns,
      params: {},
    });

    return history;
  }

  /**
   * Handles setup and metrics of history fetch.
   */
  async getHistory() {
    let endTimeSecs = new Date().getTime() / 1000;
    let beginTimeSecs = endTimeSecs - this.interestConfig.history_limit_secs;
    if (
      !this.interestConfig ||
      !this.interestConfig.history_required_fields ||
      !this.interestConfig.history_required_fields.length
    ) {
      return [];
    }
    let history = await this.fetchHistory(
      this.interestConfig.history_required_fields,
      beginTimeSecs,
      endTimeSecs
    );

    return history;
  }

  async setBaseAttachmentsURL() {
    await this.personalityProviderWorker.post("setBaseAttachmentsURL", [
      await this.baseAttachmentsURL,
    ]);
  }

  async setInterestConfig() {
    this.interestConfig = this.interestConfig || (await this.getRecipe());
    await this.personalityProviderWorker.post("setInterestConfig", [
      this.interestConfig,
    ]);
  }

  async setInterestVector() {
    await this.personalityProviderWorker.post("setInterestVector", [
      this.interestVector,
    ]);
  }

  async fetchModels() {
    const models = await lazy.RemoteSettings(MODELS_NAME).get();
    return this.personalityProviderWorker.post("fetchModels", [models]);
  }

  async generateTaggers() {
    await this.personalityProviderWorker.post("generateTaggers", [
      this.modelKeys,
    ]);
  }

  async generateRecipeExecutor() {
    await this.personalityProviderWorker.post("generateRecipeExecutor");
  }

  async createInterestVector() {
    const history = await this.getHistory();

    const interestVectorResult = await this.personalityProviderWorker.post(
      "createInterestVector",
      [history]
    );

    return interestVectorResult;
  }

  async init(callback) {
    await this.setBaseAttachmentsURL();
    await this.setInterestConfig();
    if (!this.interestConfig) {
      return;
    }

    // We always generate a recipe executor, no cache used here.
    // This is because the result of this is an object with
    // functions (taggers) so storing it in cache is not possible.
    // Thus we cannot use it to rehydrate anything.
    const fetchModelsResult = await this.fetchModels();
    // If this fails, log an error and return.
    if (!fetchModelsResult.ok) {
      return;
    }
    await this.generateTaggers();
    await this.generateRecipeExecutor();

    // If we don't have a cached vector, create a new one.
    if (!this.interestVector) {
      const interestVectorResult = await this.createInterestVector();
      // If that failed, log an error and return.
      if (!interestVectorResult.ok) {
        return;
      }
      this.interestVector = interestVectorResult.interestVector;
    }

    // This happens outside the createInterestVector call above,
    // because create can be skipped if rehydrating from cache.
    // In that case, the interest vector is provided and not created, so we just set it.
    await this.setInterestVector();

    this.initialized = true;
    if (callback) {
      callback();
    }
  }

  async calculateItemRelevanceScore(pocketItem) {
    if (!this.initialized) {
      return pocketItem.item_score || 1;
    }
    const itemRelevanceScore = await this.personalityProviderWorker.post(
      "calculateItemRelevanceScore",
      [pocketItem]
    );
    if (!itemRelevanceScore) {
      return -1;
    }
    const { scorableItem, rankingVector } = itemRelevanceScore;
    // Put the results on the item for debugging purposes.
    pocketItem.scorableItem = scorableItem;
    pocketItem.rankingVector = rankingVector;
    return rankingVector.score;
  }

  /**
   * Returns an object holding the personalization scores of this provider instance.
   */
  getScores() {
    return {
      // We cannot return taggers here.
      // What we return here goes into persistent cache, and taggers have functions on it.
      // If we attempted to save taggers into persistent cache, it would store it to disk,
      // and the next time we load it, it would start thowing function is not defined.
      interestConfig: this.interestConfig,
      interestVector: this.interestVector,
    };
  }
}

const EXPORTED_SYMBOLS = ["PersonalityProvider"];