-
Notifications
You must be signed in to change notification settings - Fork 33
/
docker-json-client.js
221 lines (187 loc) · 7.28 KB
/
docker-json-client.js
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
/*
* Copyright 2012 Mark Cavage, Inc. All rights reserved.
* Copyright (c) 2015, Joyent, Inc.
*/
/*
* Adapted from
* <github.com/mcavage/node-restify/blob/master/lib/clients/string_client.js>
* now at <https://github.com/restify/clients/blob/master/lib/StringClient.js>
*
* This subclasses the Restify StringClient to add the following features:
*
* 1. Extend the callback from
* callback(err, req, res, <JSON-parsed-body>);
* to:
* callback(err, req, res, <JSON-parsed-body>, <raw-body (Buffer)>);
* This allows one to work on the raw body for special case handling, if
* wanted. I wouldn't propose this for restify core because it shouldn't
* add features that make it harder to go all streaming.
*
* 2. In restify.JsonClient, if the body is not parseable JSON, it log.trace's
* an error, and returns `{}` (see mcavage/restify#388). I don't particularly
* like that because it is ambiguous (and also disallows returning a JSON
* body that is false-y: `false`, `0`, `null`).
*
* Instead this client will do the following:
* (a) If the response is an error status (>=400), then return `undefined`
* for the body. This allows the caller to know if the body was parsed
* because `undefined` is not representable in JSON.
* (b) If the response is a success (<400), then return an InvalidContent
* restify error.
*
* (TODO: I'd support this for restify code, but it *is* backward
* incompatible.)
*
* 3. `.write()` doesn't default a null `body` to `{}`.
* This change isn't because I came across the need for it, but because that
* just seems wrong.
*
* 4. Doesn't set `res.body` which restify's StringClient.parse seems to do
* ... as an accident of history I'm guessing?
*/
/* jsl:ignore */
'use strict';
/* jsl:end */
var assert = require('assert-plus');
var crypto = require('crypto');
var restify = require('restify');
var strsplit = require('strsplit').strsplit;
var util = require('util');
var zlib = require('zlib');
var codeToHttpError = require('restify/lib/errors/http_error').codeToHttpError;
var RestError = require('restify/lib/errors').RestError;
var StringClient = require('restify/lib/clients/string_client');
// --- API
function DockerJsonClient(options) {
assert.object(options, 'options');
options.accept = 'application/json';
options.name = options.name || 'DockerJsonClient';
options.contentType = 'application/json';
StringClient.call(this, options);
this._super = StringClient.prototype;
}
util.inherits(DockerJsonClient, StringClient);
DockerJsonClient.prototype.write = function write(options, body, callback) {
assert.object(body, 'body');
// This is change #3.
var resBody = JSON.stringify(body);
return (this._super.write.call(this, options, resBody, callback));
};
DockerJsonClient.prototype.parse = function parse(req, callback) {
function parseResponse(err, res) {
var chunks = []; // gunzipped response chunks (Buffer objects)
var len = 0; // accumulated count of chunk lengths
var contentMd5;
var contentMd5Hash;
var gz;
var resErr = err;
function finish() {
var body = Buffer.concat(chunks, len);
if (res.log.trace()) {
res.log.trace({body: body.toString(), len: len},
'body received');
}
// Content-Length check
var contentLength = Number(res.headers['content-length']);
if (!isNaN(contentLength) && len !== contentLength) {
resErr = new restify.InvalidContent(util.format(
'Incomplete content: Content-Length:%s but got %s bytes',
contentLength, len));
callback(resErr, req, res);
return;
}
// Content-MD5 check.
if (contentMd5Hash &&
contentMd5 !== contentMd5Hash.digest('base64'))
{
resErr = new restify.BadDigestError('Content-MD5');
callback(resErr, req, res);
return;
}
// Parse the body as JSON, if we can.
// Note: This regex-based trim works on a buffer. `trim()` doesn't.
var obj;
if (len && !/^\s*$/.test(body)) { // Skip all-whitespace body.
try {
obj = JSON.parse(body);
} catch (jsonErr) {
res.log.trace(jsonErr, 'Invalid JSON in response');
if (!resErr) {
// TODO: Does this mask other error statuses?
resErr = new restify.InvalidContent(
'Invalid JSON in response');
}
}
}
// Special error handling.
if (resErr) {
resErr.message = body.toString('utf8');
}
if (res && res.statusCode >= 400) {
// Upcast error to a RestError (if we can)
// Be nice and handle errors like
// { error: { code: '', message: '' } }
// in addition to { code: '', message: '' }.
if (obj && (obj.code || (obj.error && obj.error.code))) {
var _c = obj.code ||
(obj.error ? obj.error.code : '') ||
'';
var _m = obj.message ||
(obj.error ? obj.error.message : '') ||
'';
resErr = new RestError({
message: _m,
restCode: _c,
statusCode: res.statusCode
});
resErr.name = resErr.restCode;
if (!/Error$/.test(resErr.name)) {
resErr.name += 'Error';
}
} else if (!resErr) {
resErr = codeToHttpError(res.statusCode,
obj.message || '', body);
}
}
if (resErr) {
resErr.body = obj;
}
callback(resErr, req, res, obj, body);
}
if (!res) {
// Early out if we didn't even get a response.
callback(resErr, req);
return;
}
// Content-MD5 setup.
contentMd5 = res.headers['content-md5'];
if (contentMd5 && req.method !== 'HEAD' && res.statusCode !== 206) {
contentMd5Hash = crypto.createHash('md5');
}
if (res.headers['content-encoding'] === 'gzip') {
gz = zlib.createGunzip();
gz.on('data', function (chunk) {
chunks.push(chunk);
len += chunk.length;
});
gz.once('end', finish);
res.once('end', gz.end.bind(gz));
} else {
res.once('end', finish);
}
res.on('data', function onData(chunk) {
if (contentMd5Hash) {
contentMd5Hash.update(chunk.toString('utf8'));
}
if (gz) {
gz.write(chunk);
} else {
chunks.push(chunk);
len += chunk.length;
}
});
}
return (parseResponse);
};
// --- Exports
module.exports = DockerJsonClient;