summaryrefslogtreecommitdiffstats
path: root/services/sync/tests/unit/test_bridged_engine.js
blob: 25a81f8f690a085eaf83faa857dea59763c500c4 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

const { BridgedEngine, BridgeWrapperXPCOM } = ChromeUtils.importESModule(
  "resource://services-sync/bridged_engine.sys.mjs"
);
const { Service } = ChromeUtils.importESModule(
  "resource://services-sync/service.sys.mjs"
);

// Wraps an `object` in a proxy so that its methods are bound to it. This
// simulates how XPCOM class instances have all their methods bound.
function withBoundMethods(object) {
  return new Proxy(object, {
    get(target, key) {
      let value = target[key];
      return typeof value == "function" ? value.bind(target) : value;
    },
  });
}

add_task(async function test_interface() {
  class TestBridge {
    constructor() {
      this.storageVersion = 2;
      this.syncID = "syncID111111";
      this.clear();
    }

    clear() {
      this.lastSyncMillis = 0;
      this.wasSyncStarted = false;
      this.incomingEnvelopes = [];
      this.uploadedIDs = [];
      this.wasSyncFinished = false;
      this.wasReset = false;
      this.wasWiped = false;
    }

    // `mozIBridgedSyncEngine` methods.

    getLastSync(callback) {
      CommonUtils.nextTick(() => callback.handleSuccess(this.lastSyncMillis));
    }

    setLastSync(millis, callback) {
      this.lastSyncMillis = millis;
      CommonUtils.nextTick(() => callback.handleSuccess());
    }

    resetSyncId(callback) {
      CommonUtils.nextTick(() => callback.handleSuccess(this.syncID));
    }

    ensureCurrentSyncId(newSyncId, callback) {
      equal(newSyncId, this.syncID, "Local and new sync IDs should match");
      CommonUtils.nextTick(() => callback.handleSuccess(this.syncID));
    }

    syncStarted(callback) {
      this.wasSyncStarted = true;
      CommonUtils.nextTick(() => callback.handleSuccess());
    }

    storeIncoming(envelopes, callback) {
      this.incomingEnvelopes.push(...envelopes.map(r => JSON.parse(r)));
      CommonUtils.nextTick(() => callback.handleSuccess());
    }

    apply(callback) {
      let outgoingEnvelopes = [
        {
          id: "hanson",
          data: {
            plants: ["seed", "flower 💐", "rose"],
            canYouTell: false,
          },
        },
        {
          id: "sheryl-crow",
          data: {
            today: "winding 🛣",
            tomorrow: "winding 🛣",
          },
        },
      ].map(cleartext =>
        JSON.stringify({
          id: cleartext.id,
          payload: JSON.stringify(cleartext),
        })
      );
      CommonUtils.nextTick(() => callback.handleSuccess(outgoingEnvelopes));
    }

    setUploaded(millis, ids, callback) {
      this.uploadedIDs.push(...ids);
      CommonUtils.nextTick(() => callback.handleSuccess());
    }

    syncFinished(callback) {
      this.wasSyncFinished = true;
      CommonUtils.nextTick(() => callback.handleSuccess());
    }

    reset(callback) {
      this.clear();
      this.wasReset = true;
      CommonUtils.nextTick(() => callback.handleSuccess());
    }

    wipe(callback) {
      this.clear();
      this.wasWiped = true;
      CommonUtils.nextTick(() => callback.handleSuccess());
    }
  }

  let bridge = new TestBridge();
  let engine = new BridgedEngine("Nineties", Service);
  engine._bridge = new BridgeWrapperXPCOM(withBoundMethods(bridge));
  engine.enabled = true;

  let server = await serverForFoo(engine);
  try {
    await SyncTestingInfrastructure(server);

    info("Add server records");
    let foo = server.user("foo");
    let collection = foo.collection("nineties");
    let now = new_timestamp();
    collection.insert(
      "backstreet",
      encryptPayload({
        id: "backstreet",
        data: {
          say: "I want it that way",
          when: "never",
        },
      }),
      now
    );
    collection.insert(
      "tlc",
      encryptPayload({
        id: "tlc",
        data: {
          forbidden: ["scrubs 🚫"],
          numberAvailable: false,
        },
      }),
      now + 5
    );

    info("Sync the engine");
    // Advance the last sync time to skip the Backstreet Boys...
    bridge.lastSyncMillis = 1000 * (now + 2);
    await sync_engine_and_validate_telem(engine, false);

    let metaGlobal = foo.collection("meta").wbo("global").get();
    deepEqual(
      JSON.parse(metaGlobal.payload).engines.nineties,
      {
        version: 2,
        syncID: "syncID111111",
      },
      "Should write storage version and sync ID to m/g"
    );

    greater(bridge.lastSyncMillis, 0, "Should update last sync time");
    ok(
      bridge.wasSyncStarted,
      "Should have started sync before storing incoming"
    );
    deepEqual(
      bridge.incomingEnvelopes
        .sort((a, b) => a.id.localeCompare(b.id))
        .map(({ payload, ...envelope }) => ({
          cleartextAsObject: JSON.parse(payload),
          ...envelope,
        })),
      [
        {
          id: "tlc",
          modified: now + 5,
          cleartextAsObject: {
            id: "tlc",
            data: {
              forbidden: ["scrubs 🚫"],
              numberAvailable: false,
            },
          },
        },
      ],
      "Should stage incoming records from server"
    );
    deepEqual(
      bridge.uploadedIDs.sort(),
      ["hanson", "sheryl-crow"],
      "Should mark new local records as uploaded"
    );
    ok(bridge.wasSyncFinished, "Should have finished sync after uploading");

    deepEqual(
      collection.keys().sort(),
      ["backstreet", "hanson", "sheryl-crow", "tlc"],
      "Should have all records on server"
    );
    let expectedRecords = [
      {
        id: "sheryl-crow",
        data: {
          today: "winding 🛣",
          tomorrow: "winding 🛣",
        },
      },
      {
        id: "hanson",
        data: {
          plants: ["seed", "flower 💐", "rose"],
          canYouTell: false,
        },
      },
    ];
    for (let expected of expectedRecords) {
      let actual = collection.cleartext(expected.id);
      deepEqual(
        actual,
        expected,
        `Should upload record ${expected.id} from bridged engine`
      );
    }

    await engine.resetClient();
    ok(bridge.wasReset, "Should reset local storage for bridge");

    await engine.wipeClient();
    ok(bridge.wasWiped, "Should wipe local storage for bridge");

    await engine.resetSyncID();
    ok(
      !foo.collection("nineties"),
      "Should delete server collection after resetting sync ID"
    );
  } finally {
    await promiseStopServer(server);
    await engine.finalize();
  }
});