In-browser and node.js implementations of RemoteAPI should share some code
authorrniwa@webkit.org <rniwa@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 15 Mar 2017 21:59:12 +0000 (21:59 +0000)
committerrniwa@webkit.org <rniwa@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 15 Mar 2017 21:59:12 +0000 (21:59 +0000)
https://bugs.webkit.org/show_bug.cgi?id=169695

Rubber-stamped by Antti Koivisto.

Extracted CommonRemoteAPI out of RemoteAPI implementations for node.js and browser.

* public/shared/common-remote.js: Added.
(CommonRemoteAPI): Added.
(CommonRemoteAPI.prototype.postJSON): Extracted from RemoteAPI.
(CommonRemoteAPI.prototype.postJSONWithStatus): Ditto.
(CommonRemoteAPI.prototype.getJSON): Ditto.
(CommonRemoteAPI.prototype.getJSONWithStatus): Ditto.
(CommonRemoteAPI.prototype.sendHttpRequest): Added. Needs to implemented by a subclass.
(CommonRemoteAPI.prototype._asJSON): Added.
(CommonRemoteAPI.prototype._checkStatus): Added.

* public/v3/index.html: Include common-remote.js.

* public/v3/privileged-api.js:
(PrivilegedAPI): Use class now that we don't include data.js.
(PrivilegedAPI.sendRequest): Modernized the code.
(PrivilegedAPI.requestCSRFToken): Ditto.

* public/v3/remote.js:
(BrowserRemoteAPI): Renamed from RemoteAPI. window.RemoteAPI is now an instance of this class.
(BrowserRemoteAPI.prototype.sendHttpRequest): Moved from RemoteAPI.sendHttpRequest.
(BrowserRemoteAPI.prototype.sendHttpRequest):

* server-tests/privileged-api-create-analysis-task-tests.js: Updated tests since NodeJSRemoteAPI
now throws the JSON status as an error to be consistent with BrowserRemoteAPI.
* server-tests/privileged-api-create-test-group-tests.js: Ditto.
* server-tests/privileged-api-upate-run-status.js: Ditto.

* tools/js/buildbot-triggerable.js:
(BuildbotTriggerable.prototype.syncOnce): Just use postJSONWithStatus instead of manually
checking the status.

* tools/js/remote.js:
(NodeRemoteAPI): Renamed from RemoteAPI. Still exported as RemoteAPI.
(NodeRemoteAPI.prototype.constructor):
(NodeRemoteAPI.prototype.sendHttpRequest): Modernized the code.

git-svn-id: http://svn.webkit.org/repository/webkit/trunk@214008 268f45cc-cd09-0410-ab3c-d52691b4dbfc

Websites/perf.webkit.org/ChangeLog
Websites/perf.webkit.org/public/shared/common-remote.js [new file with mode: 0644]
Websites/perf.webkit.org/public/v3/index.html
Websites/perf.webkit.org/public/v3/privileged-api.js
Websites/perf.webkit.org/public/v3/remote.js
Websites/perf.webkit.org/server-tests/privileged-api-create-analysis-task-tests.js
Websites/perf.webkit.org/server-tests/privileged-api-create-test-group-tests.js
Websites/perf.webkit.org/server-tests/privileged-api-upate-run-status.js
Websites/perf.webkit.org/tools/js/buildbot-triggerable.js
Websites/perf.webkit.org/tools/js/remote.js

index 30422d0..a12cbbe 100644 (file)
@@ -1,5 +1,50 @@
 2017-03-15  Ryosuke Niwa  <rniwa@webkit.org>
 
+        In-browser and node.js implementations of RemoteAPI should share some code
+        https://bugs.webkit.org/show_bug.cgi?id=169695
+
+        Rubber-stamped by Antti Koivisto.
+
+        Extracted CommonRemoteAPI out of RemoteAPI implementations for node.js and browser. 
+
+        * public/shared/common-remote.js: Added.
+        (CommonRemoteAPI): Added.
+        (CommonRemoteAPI.prototype.postJSON): Extracted from RemoteAPI.
+        (CommonRemoteAPI.prototype.postJSONWithStatus): Ditto.
+        (CommonRemoteAPI.prototype.getJSON): Ditto.
+        (CommonRemoteAPI.prototype.getJSONWithStatus): Ditto.
+        (CommonRemoteAPI.prototype.sendHttpRequest): Added. Needs to implemented by a subclass.
+        (CommonRemoteAPI.prototype._asJSON): Added.
+        (CommonRemoteAPI.prototype._checkStatus): Added.
+
+        * public/v3/index.html: Include common-remote.js.
+
+        * public/v3/privileged-api.js:
+        (PrivilegedAPI): Use class now that we don't include data.js.
+        (PrivilegedAPI.sendRequest): Modernized the code.
+        (PrivilegedAPI.requestCSRFToken): Ditto.
+
+        * public/v3/remote.js:
+        (BrowserRemoteAPI): Renamed from RemoteAPI. window.RemoteAPI is now an instance of this class.
+        (BrowserRemoteAPI.prototype.sendHttpRequest): Moved from RemoteAPI.sendHttpRequest.
+        (BrowserRemoteAPI.prototype.sendHttpRequest):
+
+        * server-tests/privileged-api-create-analysis-task-tests.js: Updated tests since NodeJSRemoteAPI
+        now throws the JSON status as an error to be consistent with BrowserRemoteAPI.
+        * server-tests/privileged-api-create-test-group-tests.js: Ditto.
+        * server-tests/privileged-api-upate-run-status.js: Ditto.
+
+        * tools/js/buildbot-triggerable.js:
+        (BuildbotTriggerable.prototype.syncOnce): Just use postJSONWithStatus instead of manually
+        checking the status.
+
+        * tools/js/remote.js:
+        (NodeRemoteAPI): Renamed from RemoteAPI. Still exported as RemoteAPI.
+        (NodeRemoteAPI.prototype.constructor):
+        (NodeRemoteAPI.prototype.sendHttpRequest): Modernized the code.
+
+2017-03-15  Ryosuke Niwa  <rniwa@webkit.org>
+
         Fix server tests after r213998 and r213969
         https://bugs.webkit.org/show_bug.cgi?id=169690
 
diff --git a/Websites/perf.webkit.org/public/shared/common-remote.js b/Websites/perf.webkit.org/public/shared/common-remote.js
new file mode 100644 (file)
index 0000000..a7f3024
--- /dev/null
@@ -0,0 +1,52 @@
+"use strict";
+
+class CommonRemoteAPI {
+    postJSON(path, data)
+    {
+        return this._asJSON(this.sendHttpRequest(path, 'POST', 'application/json', JSON.stringify(data || {})));
+    }
+
+    postJSONWithStatus(path, data)
+    {
+        return this._checkStatus(this.postJSON(path, data));
+    }
+
+    getJSON(path)
+    {
+        return this._asJSON(this.sendHttpRequest(path, 'GET', null, null));
+    }
+
+    getJSONWithStatus(path)
+    {
+        return this._checkStatus(this.getJSON(path));
+    }
+
+    sendHttpRequest(path, method, contentType, content)
+    {
+        throw 'NotImplemented';
+    }
+
+    _asJSON(promise)
+    {
+        return promise.then((result) => {
+            try {
+                return JSON.parse(result.responseText);
+            } catch (error) {
+                console.error(result.responseText);
+                reject(result.statusCode + ', ' + error);
+            }
+        });
+    }
+
+    _checkStatus(promise)
+    {
+        return promise.then(function (content) {
+            if (content['status'] != 'OK')
+                throw content['status'];
+            return content;
+        });
+    }
+}
+
+if (typeof module != 'undefined')
+    module.exports.CommonRemoteAPI = CommonRemoteAPI;
index 946a6ec..a078a9b 100644 (file)
@@ -38,6 +38,7 @@ Run tools/bundle-v3-scripts to speed up the load time for production.`);
 
     <template id="unbundled-scripts">
         <script src="../shared/statistics.js"></script>
+        <script src="../shared/common-remote.js"></script>
 
         <script src="instrumentation.js"></script>
         <script src="remote.js"></script>
@@ -89,6 +90,7 @@ Run tools/bundle-v3-scripts to speed up the load time for production.`);
         <script src="components/chart-pane-base.js"></script>
         <script src="components/mutable-list-view.js"></script>
         <script src="components/ratio-bar-graph.js"></script>
+
         <script src="pages/page.js"></script>
         <script src="pages/page-router.js"></script>
         <script src="pages/heading.js"></script>
index 768d15e..a4ca38f 100644 (file)
@@ -1,23 +1,25 @@
 "use strict";
 
-// FIXME: Use real class syntax once the dependency on data.js has been removed.
-var PrivilegedAPI = class {
+class PrivilegedAPI {
 
     static sendRequest(path, data)
     {
-        var clonedData = {};
-        for (var key in data)
+        const clonedData = {};
+        for (let key in data)
             clonedData[key] = data[key];
 
-        return this.requestCSRFToken().then(function (token) {
+        const fullPath = '/privileged-api/' + path;
+        const post = () => RemoteAPI.postJSONWithStatus(fullPath, clonedData);
+
+        return this.requestCSRFToken().then((token) => {
             clonedData['token'] = token;
-            return RemoteAPI.postJSONWithStatus('/privileged-api/' + path, clonedData).catch(function (status) {
+            return post().catch((status) => {
                 if (status != 'InvalidToken')
                     return Promise.reject(status);
-                PrivilegedAPI._token = null;
-                return PrivilegedAPI.requestCSRFToken().then(function (token) {
+                this._token = null;
+                return this.requestCSRFToken().then((token) => {
                     clonedData['token'] = token;
-                    return RemoteAPI.postJSONWithStatus('/privileged-api/' + path, clonedData);
+                    return post();
                 });
             });
         });
@@ -25,14 +27,14 @@ var PrivilegedAPI = class {
 
     static requestCSRFToken()
     {
-        var maxNetworkLatency = 3 * 60 * 1000; /* 3 minutes */
+        const maxNetworkLatency = 3 * 60 * 1000; /* 3 minutes */
         if (this._token && this._expiration > Date.now() + maxNetworkLatency)
             return Promise.resolve(this._token);
 
-        return RemoteAPI.postJSONWithStatus('/privileged-api/generate-csrf-token').then(function (result) {
-            PrivilegedAPI._token = result['token'];
-            PrivilegedAPI._expiration = new Date(result['expiration']);
-            return PrivilegedAPI._token;
+        return RemoteAPI.postJSONWithStatus('/privileged-api/generate-csrf-token').then((result) => {
+            this._token = result['token'];
+            this._expiration = new Date(result['expiration']);
+            return this._token;
         });
     }
 
index ce98fde..bfdef03 100644 (file)
@@ -1,66 +1,41 @@
 "use strict";
 
-var RemoteAPI = {};
+class BrowserRemoteAPI extends CommonRemoteAPI {
 
-RemoteAPI.postJSON = function (path, data)
-{
-    return this.getJSON(path, data || {});
-}
-
-RemoteAPI.postJSONWithStatus = function (path, data)
-{
-    return this.getJSONWithStatus(path, data || {});
-}
-
-RemoteAPI.getJSON = function(path, data)
-{
-    console.assert(!path.startsWith('http:') && !path.startsWith('https:') && !path.startsWith('file:'));
+    sendHttpRequest(path, method, contentType, content)
+    {
+        console.assert(!path.startsWith('http:') && !path.startsWith('https:') && !path.startsWith('file:'));
 
-    return new Promise(function (resolve, reject) {
-        Instrumentation.startMeasuringTime('Remote', 'getJSON');
+        return new Promise((resolve, reject) => {
+            Instrumentation.startMeasuringTime('Remote', 'sendHttpRequest');
 
-        var xhr = new XMLHttpRequest;
-        xhr.onload = function () {
-            Instrumentation.endMeasuringTime('Remote', 'getJSON');
+            function onload() {
+                Instrumentation.endMeasuringTime('Remote', 'sendHttpRequest');
+                if (xhr.status != 200)
+                    return resject(xhr.status);
+                resolve({statusCode: xhr.status, responseText: xhr.responseText});
+            };
 
-            if (xhr.status != 200) {
+            function onerror() {
+                Instrumentation.endMeasuringTime('Remote', 'sendHttpRequest');
                 reject(xhr.status);
-                return;
             }
 
-            try {
-                var parsed = JSON.parse(xhr.responseText);
-                resolve(parsed);
-            } catch (error) {
-                console.error(xhr.responseText);
-                reject(xhr.status + ', ' + error);
-            }
-        };
-
-        function onerror() {
-            Instrumentation.endMeasuringTime('Remote', 'getJSON');
-            reject(xhr.status);
-        }
+            const xhr = new XMLHttpRequest;
+            xhr.onload = onload;
+            xhr.onabort = onerror;
+            xhr.onerror = onerror;
+
+            xhr.open(method, path, true);
+            if (contentType)
+                xhr.setRequestHeader('Content-Type', contentType);
+            if (content)
+                xhr.send(content);
+            else
+                xhr.send();
+        });
+    }
 
-        xhr.onabort = onerror;
-        xhr.onerror = onerror;
-
-        if (data) {
-            xhr.open('POST', path, true);
-            xhr.setRequestHeader('Content-Type', 'application/json');
-            xhr.send(JSON.stringify(data));
-        } else {
-            xhr.open('GET', path, true);
-            xhr.send();
-        }
-    });
 }
 
-RemoteAPI.getJSONWithStatus = function(path, data)
-{
-    return this.getJSON(path, data).then(function (content) {
-        if (content['status'] != 'OK')
-            return Promise.reject(content['status']);
-        return content;
-    });
-}
+const RemoteAPI = new BrowserRemoteAPI;
index 2d1873e..8775c55 100644 (file)
@@ -63,40 +63,40 @@ describe('/privileged-api/create-analysis-task', function () {
     it('should return "MissingName" on an empty request', () => {
         return PrivilegedAPI.sendRequest('create-analysis-task', {}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'MissingName');
+        }, (error) => {
+            assert.equal(error, 'MissingName');
         });
     });
 
     it('should return "InvalidStartRun" when startRun is missing but endRun is set', () => {
         return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', endRun: 1}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidStartRun');
+        }, (error) => {
+            assert.equal(error, 'InvalidStartRun');
         });
     });
 
     it('should return "InvalidEndRun" when endRun is missing but startRun is set', () => {
         return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', startRun: 1}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidEndRun');
+        }, (error) => {
+            assert.equal(error, 'InvalidEndRun');
         });
     });
 
     it('should return "InvalidStartRun" when startRun is not a valid integer', () => {
         return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', startRun: "foo", endRun: 1}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidStartRun');
+        }, (error) => {
+            assert.equal(error, 'InvalidStartRun');
         });
     });
 
     it('should return "InvalidEndRun" when endRun is not a valid integer', () => {
         return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', startRun: 1, endRun: "foo"}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidEndRun');
+        }, (error) => {
+            assert.equal(error, 'InvalidEndRun');
         });
     });
 
@@ -106,8 +106,8 @@ describe('/privileged-api/create-analysis-task', function () {
         }).then(() => {
             return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', startRun: 100, endRun: 1}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'InvalidStartRun');
+            }, (error) => {
+                assert.equal(error, 'InvalidStartRun');
             });
         });
     });
@@ -118,8 +118,8 @@ describe('/privileged-api/create-analysis-task', function () {
         }).then(() => {
             return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', startRun: 1, endRun: 100}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'InvalidEndRun');
+            }, (error) => {
+                assert.equal(error, 'InvalidEndRun');
             });
         });
     });
@@ -130,8 +130,8 @@ describe('/privileged-api/create-analysis-task', function () {
         }).then(() => {
             return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', startRun: 1, endRun: 1}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'InvalidTimeRange');
+            }, (error) => {
+                assert.equal(error, 'InvalidTimeRange');
             });
         });
     });
@@ -142,8 +142,8 @@ describe('/privileged-api/create-analysis-task', function () {
         }).then(() => {
             return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', startRun: 1, endRun: 2}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'RunConfigMismatch');
+            }, (error) => {
+                assert.equal(error, 'RunConfigMismatch');
             });
         });
     });
@@ -204,8 +204,8 @@ describe('/privileged-api/create-analysis-task', function () {
         }).then((content) => {
             return PrivilegedAPI.sendRequest('create-analysis-task', {name: 'hi', startRun: startId, endRun: endId}).then(() => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'DuplicateAnalysisTask');
+            }, (error) => {
+                assert.equal(error, 'DuplicateAnalysisTask');
             });
         }).then(() => {
             return db.selectAll('analysis_tasks');
index a77a6e1..2c3e826 100644 (file)
@@ -116,72 +116,72 @@ describe('/privileged-api/create-test-group', function () {
     it('should return "InvalidName" on an empty request', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidName');
+        }, (error) => {
+            assert.equal(error, 'InvalidName');
         });
     });
 
     it('should return "InvalidTask" when task is not specified', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', commitSets: [[1]]}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidTask');
+        }, (error) => {
+            assert.equal(error, 'InvalidTask');
         });
     });
 
     it('should return "InvalidTask" when task is not a valid integer', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: 'foo', commitSets: [[1]]}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidTask');
+        }, (error) => {
+            assert.equal(error, 'InvalidTask');
         });
     });
 
     it('should return "InvalidCommitSets" when commit sets are not specified', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: 1, repetitionCount: 1}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidCommitSets');
+        }, (error) => {
+            assert.equal(error, 'InvalidCommitSets');
         });
     });
 
     it('should return "InvalidCommitSets" when commit sets is empty', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: 1, repetitionCount: 1, commitSets: {}}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidCommitSets');
+        }, (error) => {
+            assert.equal(error, 'InvalidCommitSets');
         });
     });
 
     it('should return "InvalidTask" when there is no matching task', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: 1, repetitionCount: 1, commitSets: {'WebKit': []}}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidTask');
+        }, (error) => {
+            assert.equal(error, 'InvalidTask');
         });
     });
 
     it('should return "InvalidRepetitionCount" when repetitionCount is not a valid integer', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: 1, repetitionCount: 'foo', commitSets: {'WebKit': []}}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidRepetitionCount');
+        }, (error) => {
+            assert.equal(error, 'InvalidRepetitionCount');
         });
     });
 
     it('should return "InvalidRepetitionCount" when repetitionCount is a negative integer', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: 1, repetitionCount: -5, commitSets: {'WebKit': []}}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidRepetitionCount');
+        }, (error) => {
+            assert.equal(error, 'InvalidRepetitionCount');
         });
     });
 
     it('should return "InvalidTask" when there is no matching task', () => {
         return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: 1, commitSets: {'WebKit': []}}).then((content) => {
             assert(false, 'should never be reached');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidTask');
+        }, (error) => {
+            assert.equal(error, 'InvalidTask');
         });
     });
 
@@ -189,8 +189,8 @@ describe('/privileged-api/create-test-group', function () {
         return createAnalysisTask('some task').then((taskId) => {
             return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: taskId, commitSets: {'WebKit': []}}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'TriggerableNotFoundForTask');
+            }, (error) => {
+                assert.equal(error, 'TriggerableNotFoundForTask');
             });
         });
     });
@@ -199,8 +199,8 @@ describe('/privileged-api/create-test-group', function () {
         return addTriggerableAndCreateTask('some task').then((taskId) => {
             return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: taskId, commitSets: {'WebKit': []}}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'InvalidCommitSets');
+            }, (error) => {
+                assert.equal(error, 'InvalidCommitSets');
             });
         });
     });
@@ -209,8 +209,8 @@ describe('/privileged-api/create-test-group', function () {
         return addTriggerableAndCreateTask('some task').then((taskId) => {
             return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: taskId, commitSets: {'Foo': []}}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'RepositoryNotFound');
+            }, (error) => {
+                assert.equal(error, 'RepositoryNotFound');
             });
         });
     });
@@ -219,8 +219,8 @@ describe('/privileged-api/create-test-group', function () {
         return addTriggerableAndCreateTask('some task').then((taskId) => {
             return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: taskId, commitSets: {'WebKit': ['1']}}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'RevisionNotFound');
+            }, (error) => {
+                assert.equal(error, 'RevisionNotFound');
             });
         });
     });
@@ -229,8 +229,8 @@ describe('/privileged-api/create-test-group', function () {
         return addTriggerableAndCreateTask('some task').then((taskId) => {
             return PrivilegedAPI.sendRequest('create-test-group', {name: 'test', task: taskId, commitSets: {'WebKit': ['191622', '191623'], 'macOS': ['15A284']}}).then((content) => {
                 assert(false, 'should never be reached');
-            }, (response) => {
-                assert.equal(response['status'], 'InvalidCommitSets');
+            }, (error) => {
+                assert.equal(error, 'InvalidCommitSets');
             });
         });
     });
index e2f6b76..698a60b 100644 (file)
@@ -75,9 +75,9 @@ describe("/privileged-api/update-run-status", function () {
             RemoteAPI.clearCookies();
             return RemoteAPI.postJSONWithStatus('/privileged-api/update-run-status', {token: PrivilegedAPI._token});
         }).then(() => {
-            assert(false, 'PrivilegedAPI.sendRequest should reject');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidToken');
+            assert(false, 'should never be reached');
+        }, (error) => {
+            assert.equal(error, 'InvalidToken');
         });
     });
 
@@ -94,9 +94,9 @@ describe("/privileged-api/update-run-status", function () {
         }).then(() => {
             return RemoteAPI.postJSONWithStatus('/privileged-api/update-run-status', {token: 'bad'});
         }).then(() => {
-            assert(false, 'PrivilegedAPI.sendRequest should reject');
-        }, (response) => {
-            assert.equal(response['status'], 'InvalidToken');
+            assert(false, 'should never be reached');
+        }, (error) => {
+            assert.equal(error, 'InvalidToken');
         });
     });
 
index aaf5b2a..45b22c1 100644 (file)
@@ -69,14 +69,11 @@ class BuildbotTriggerable {
             return self._pullBuildbotOnAllSyncers(buildReqeustsByGroup);
         }).then(function (updates) {
             // FIXME: Add a new API that just updates the requests.
-            return self._remote.postJSON(`/api/build-requests/${self._name}`, {
+            return self._remote.postJSONWithStatus(`/api/build-requests/${self._name}`, {
                 'slaveName': self._slaveInfo.name,
                 'slavePassword': self._slaveInfo.password,
                 'buildRequestUpdates': updates});
-        }).then(function (response) {
-            if (response['status'] != 'OK')
-                self._logger.log('Failed to update the build requests status: ' + response['status']);
-        })
+        });
     }
 
     _validateRequests(buildRequests)
index db26ae6..2ee38b4 100644 (file)
@@ -4,10 +4,12 @@ let assert = require('assert');
 let http = require('http');
 let https = require('https');
 let querystring = require('querystring');
+let CommonRemoteAPI = require('../../public/shared/common-remote.js').CommonRemoteAPI;
 
-class RemoteAPI {
+class NodeRemoteAPI extends CommonRemoteAPI {
     constructor(server)
     {
+        super();
         this._server = null;
         this._cookies = new Map;
         if (server)
@@ -53,50 +55,6 @@ class RemoteAPI {
 
     clearCookies() { this._cookies = new Map; }
 
-    getJSON(path)
-    {
-        return this.sendHttpRequest(path, 'GET', null, null).then(function (result) {
-            try {
-                return JSON.parse(result.responseText);
-            } catch (error) {
-                console.error(result.responseText);
-                throw error;
-            }
-        });
-    }
-
-    getJSONWithStatus(path)
-    {
-        return this.getJSON(path).then(function (result) {
-            if (result['status'] != 'OK')
-                return Promise.reject(result);
-            return result;
-        });
-    }
-
-    postJSON(path, data)
-    {
-        const contentType = 'application/json';
-        const payload = JSON.stringify(data || {});
-        return this.sendHttpRequest(path, 'POST', 'application/json', payload).then(function (result) {
-            try {
-                return JSON.parse(result.responseText);
-            } catch (error) {
-                console.error(result.responseText);
-                throw error;
-            }
-        });
-    }
-
-    postJSONWithStatus(path, data)
-    {
-        return this.postJSON(path, data).then(function (result) {
-            if (result['status'] != 'OK')
-                return Promise.reject(result);
-            return result;
-        });
-    }
-
     postFormUrlencodedData(path, data)
     {
         const contentType = 'application/x-www-form-urlencoded';
@@ -109,8 +67,7 @@ class RemoteAPI {
     sendHttpRequest(path, method, contentType, content)
     {
         let server = this._server;
-        const self = this;
-        return new Promise(function (resolve, reject) {
+        return new Promise((resolve, reject) => {
             let options = {
                 hostname: server.host,
                 port: server.port,
@@ -119,20 +76,18 @@ class RemoteAPI {
                 path: path,
             };
 
-            let request = (server.scheme == 'http' ? http : https).request(options, function (response) {
+            let request = (server.scheme == 'http' ? http : https).request(options, (response) => {
                 let responseText = '';
                 response.setEncoding('utf8');
-                response.on('data', function (chunk) { responseText += chunk; });
-                response.on('end', function () {
-                    if (response.statusCode != 200) {
-                        reject(response.statusCode);
-                        return;
-                    }
+                response.on('data', (chunk) => { responseText += chunk; });
+                response.on('end', () => {
+                    if (response.statusCode != 200)
+                        return reject(response.statusCode);
 
                     if ('set-cookie' in response.headers) {
-                        for (const cookie of response.headers['set-cookie']) {
-                            var nameValue = cookie.split('=')
-                            self._cookies.set(nameValue[0], nameValue[1]);
+                        for (let cookie of response.headers['set-cookie']) {
+                            const nameValue = cookie.split('=');
+                            this._cookies.set(nameValue[0], nameValue[1]);
                         }
                     }
                     resolve({statusCode: response.statusCode, responseText: responseText});
@@ -144,11 +99,8 @@ class RemoteAPI {
             if (contentType)
                 request.setHeader('Content-Type', contentType);
 
-            if (self._cookies.size) {
-                request.setHeader('Cookie', Array.from(self._cookies.keys()).map(function (key) {
-                    return `${key}=${self._cookies.get(key)}`;
-                }).join('; '));
-            }
+            if (this._cookies.size)
+                request.setHeader('Cookie', Array.from(this._cookies.keys()).map((key) => `${key}=${this._cookies.get(key)}`).join('; '));
 
             if (content)
                 request.write(content);
@@ -159,4 +111,4 @@ class RemoteAPI {
 };
 
 if (typeof module != 'undefined')
-    module.exports.RemoteAPI = RemoteAPI;
+    module.exports.RemoteAPI = NodeRemoteAPI;