aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/tensorboard/components/tf_backend/test/requestManagerTests.ts
blob: 23a4e8f6111b115875ec6d38a69d1f454acff7d3 (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
292
293
294
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

import {RequestManager, RequestNetworkError} from '../requestManager';

interface MockRequest {
  resolve: Function;
  reject: Function;
  id: number;
  url: string;
}

class MockedRequestManager extends RequestManager {
  private resolvers: Function[];
  private rejectors: Function[];
  public requestsDispatched: number;
  constructor(maxRequests = 10, maxRetries = 3) {
    super(maxRequests, maxRetries);
    this.resolvers = [];
    this.rejectors = [];
    this.requestsDispatched = 0;
  }
  protected _promiseFromUrl(url) {
    return new Promise((resolve, reject) => {
      const mockJSON = {
        ok: true,
        json() {
          return url;
        },
        url,
        status: 200,
      };
      const mockFailedRequest: any = {
        ok: false,
        url,
        status: 502,
      };
      const mockFailure = new RequestNetworkError(mockFailedRequest, url);
      this.resolvers.push(() => {
        resolve(mockJSON);
      });
      this.rejectors.push(() => {
        reject(mockFailure);
      });
      this.requestsDispatched++;
    });
  }
  public resolveFakeRequest() {
    this.resolvers.pop()();
  }
  public rejectFakeRequest() {
    this.rejectors.pop()();
  }
  public dispatchAndResolve() {
    // Wait for at least one request to be dispatched, then resolve it.
    this.waitForDispatch(1).then(() => this.resolveFakeRequest());
  }
  public waitForDispatch(num) {
    return waitForCondition(() => {
      return this.requestsDispatched >= num;
    });
  }
}

/** Create a promise that returns when *check* returns true.
 * May cause a test timeout if check never becomes true.
 */

function waitForCondition(check: () => boolean): Promise<any> {
  return new Promise((resolve, reject) => {
    const go = () => {
      if (check()) {
        resolve();
      }
      setTimeout(go, 2);
    };
    go();
  });
}

describe('backend', () => {
  describe('request manager', () => {
    it('request loads JSON properly', (done) => {
      const rm = new RequestManager();
      const promise = rm.request('data/example.json');
      promise.then(
          (response) => {
            chai.assert.deepEqual(response, {foo: 3, bar: 'zoidberg'});
            done();
          },
          (reject) => {
            throw new Error(reject);
          });
    });

    it('rejects on bad url', (done) => {
      const rm = new RequestManager(5, 0);
      const badUrl = '_bad_url_which_doesnt_exist.json';
      const promise = rm.request(badUrl);
      promise.then(
          (success) => {
            done(new Error('the promise should have rejected'));
          },
          (reject: RequestNetworkError) => {
            chai.assert.include(reject.message, '404');
            chai.assert.include(reject.message, badUrl);
            chai.assert.equal(reject.req.status, 404);
            done();
          });
    });

    it('can retry if requests fail', (done) => {
      const rm = new MockedRequestManager(3, 5);
      const r = rm.request('foo');
      rm.waitForDispatch(1)
          .then(() => {
            rm.rejectFakeRequest();
            return rm.waitForDispatch(2);
          })
          .then(() => rm.resolveFakeRequest());
      r.then((success) => done());
    });

    it('retries at most maxRetries times', (done) => {
      const MAX_RETRIES = 2;
      const rm = new MockedRequestManager(3, MAX_RETRIES);
      const r = rm.request('foo');
      rm.waitForDispatch(1)
          .then(() => {
            rm.rejectFakeRequest();
            return rm.waitForDispatch(2);
          })
          .then(() => {
            rm.rejectFakeRequest();
            return rm.waitForDispatch(3);
          })
          .then(() => {
            rm.rejectFakeRequest();
          });

      r.then(
          (success) => done(new Error('The reqest should have failed')),
          (failure) => done());
    });

    it('requestManager only sends maxRequests requests at a time', (done) => {
      const rm = new MockedRequestManager(3);
      const r0 = rm.request('1');
      const r1 = rm.request('2');
      const r2 = rm.request('3');
      const r3 = rm.request('4');
      chai.assert.equal(rm.activeRequests(), 3, 'three requests are active');
      chai.assert.equal(
          rm.outstandingRequests(), 4, 'four requests are pending');
      rm.waitForDispatch(3)
          .then(() => {
            chai.assert.equal(
                rm.activeRequests(), 3, 'three requests are still active (1)');
            chai.assert.equal(
                rm.requestsDispatched, 3, 'three requests were dispatched');
            rm.resolveFakeRequest();
            return rm.waitForDispatch(4);
          })
          .then(() => {
            chai.assert.equal(
                rm.activeRequests(), 3, 'three requests are still active (2)');
            chai.assert.equal(
                rm.requestsDispatched, 4, 'four requests were dispatched');
            chai.assert.equal(
                rm.outstandingRequests(), 3, 'three requests are pending');
            rm.resolveFakeRequest();
            rm.resolveFakeRequest();
            rm.resolveFakeRequest();
            return r3;
          })
          .then(() => {
            chai.assert.equal(rm.activeRequests(), 0, 'all requests finished');
            chai.assert.equal(
                rm.outstandingRequests(), 0, 'no requests pending');
            done();
          });
    });

    it('queue continues after failures', (done) => {
      const rm = new MockedRequestManager(1, 0);
      const r0 = rm.request('1');
      const r1 = rm.request('2');
      rm.waitForDispatch(1).then(() => {
        rm.rejectFakeRequest();
      });

      r0.then(
            (success) => done(new Error('r0 should have failed')),
            (failure) => 'unused_argument')
          .then(() => rm.resolveFakeRequest());

      // When the first request rejects, it should decrement nActiveRequests
      // and then launch remaining requests in queue (i.e. this one)
      r1.then((success) => done(), (failure) => done(new Error(failure)));
    });

    it('queue is LIFO', (done) => {
      /* This test is a bit tricky.
       * We want to verify that the RequestManager queue has LIFO semantics.
       * So we construct three requests off the bat: A, B, C.
       * So LIFO semantics ensure these will resolve in order A, C, B.
       * (Because the A request launches immediately when we create it, it's
       * not in queue)
       * Then after resolving A, C moves out of queue, and we create X.
       * So expected final order is A, C, X, B.
       * We verify this with an external var that counts how many requests were
       * resolved.
       */
      const rm = new MockedRequestManager(1);
      let nResolved = 0;
      function assertResolutionOrder(expectedSpotInSequence) {
        return () => {
          nResolved++;
          chai.assert.equal(expectedSpotInSequence, nResolved);
        };
      }

      function launchThirdRequest() {
        rm.request('started late but goes third')
            .then(assertResolutionOrder(3))
            .then(() => rm.dispatchAndResolve());
      }

      rm.request('first')
          .then(
              assertResolutionOrder(1))  // Assert that this one resolved first
          .then(launchThirdRequest)
          .then(() => rm.dispatchAndResolve());  // then trigger the next one

      rm.request('this one goes fourth')  // created second, will go last
          .then(assertResolutionOrder(
              4))       // assert it was the fourth to get resolved
          .then(done);  // finish the test

      rm.request('second')
          .then(assertResolutionOrder(2))
          .then(() => rm.dispatchAndResolve());

      rm.dispatchAndResolve();
    });

    it('requestManager can clear queue', (done) => {
      const rm = new MockedRequestManager(1);
      let requestsResolved = 0;
      let requestsRejected = 0;
      const success = () => requestsResolved++;
      const failure = (err) => {
        chai.assert.equal(err.name, 'RequestCancellationError');
        requestsRejected++;
      };
      const finishTheTest = () => {
        chai.assert.equal(rm.activeRequests(), 0, 'no requests still active');
        chai.assert.equal(
            rm.requestsDispatched, 1, 'only one req was ever dispatched');
        chai.assert.equal(rm.outstandingRequests(), 0, 'no pending requests');
        chai.assert.equal(requestsResolved, 1, 'one request got resolved');
        chai.assert.equal(
            requestsRejected, 4, 'four were cancelled and threw errors');
        done();
      };
      rm.request('0').then(success, failure).then(finishTheTest);
      rm.request('1').then(success, failure);
      rm.request('2').then(success, failure);
      rm.request('3').then(success, failure);
      rm.request('4').then(success, failure);
      chai.assert.equal(rm.activeRequests(), 1, 'one req is active');
      rm.waitForDispatch(1).then(() => {
        chai.assert.equal(rm.activeRequests(), 1, 'one req is active');
        chai.assert.equal(rm.requestsDispatched, 1, 'one req was dispatched');
        chai.assert.equal(rm.outstandingRequests(), 5, 'five reqs outstanding');
        rm.clearQueue();
        rm.resolveFakeRequest();
        // resolving the first request triggers finishTheTest
      });
    });
  });
});