Refactoring net module, adding a ClientRequest and IncomingMessage classes.

This commit is contained in:
ali.ibrahim 2016-09-27 10:21:11 +02:00
parent fcaf9cb031
commit 9498a5738a
5 changed files with 191 additions and 172 deletions

View file

@ -115,8 +115,6 @@ mate::WrappableBase* URLRequest::New(mate::Arguments* args) {
auto session = Session::FromPartition(args->isolate(), session_name); auto session = Session::FromPartition(args->isolate(), session_name);
auto browser_context = session->browser_context(); auto browser_context = session->browser_context();
auto api_url_request = new URLRequest(args->isolate(), args->GetThis()); auto api_url_request = new URLRequest(args->isolate(), args->GetThis());
auto weak_ptr = api_url_request->weak_ptr_factory_.GetWeakPtr(); auto weak_ptr = api_url_request->weak_ptr_factory_.GetWeakPtr();
auto atom_url_request = AtomURLRequest::Create( auto atom_url_request = AtomURLRequest::Create(
@ -127,11 +125,9 @@ mate::WrappableBase* URLRequest::New(mate::Arguments* args) {
api_url_request->atom_request_ = atom_url_request; api_url_request->atom_request_ = atom_url_request;
return api_url_request; return api_url_request;
} }
// static // static
void URLRequest::BuildPrototype(v8::Isolate* isolate, void URLRequest::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) { v8::Local<v8::FunctionTemplate> prototype) {
@ -139,17 +135,17 @@ void URLRequest::BuildPrototype(v8::Isolate* isolate,
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
// Request API // Request API
.MakeDestroyable() .MakeDestroyable()
.SetMethod("_writeBuffer", &URLRequest::WriteBuffer) .SetMethod("writeBuffer", &URLRequest::WriteBuffer)
.SetMethod("abort", &URLRequest::Abort) .SetMethod("abort", &URLRequest::Abort)
.SetMethod("_setHeader", &URLRequest::SetHeader) .SetMethod("setExtraHeader", &URLRequest::SetExtraHeader)
.SetMethod("_getHeader", &URLRequest::GetHeader) .SetMethod("removeExtraHeader", &URLRequest::RemoveExtraHeader)
.SetMethod("_removaHeader", &URLRequest::RemoveHeader) .SetMethod("setChunkedUpload", &URLRequest::SetChunkedUpload)
// Response APi // Response APi
.SetProperty("_statusCode", &URLRequest::StatusCode) .SetProperty("statusCode", &URLRequest::StatusCode)
.SetProperty("_statusMessage", &URLRequest::StatusMessage) .SetProperty("statusMessage", &URLRequest::StatusMessage)
.SetProperty("_rawResponseHeaders", &URLRequest::RawResponseHeaders) .SetProperty("rawResponseHeaders", &URLRequest::RawResponseHeaders)
.SetProperty("_httpVersionMajor", &URLRequest::ResponseHttpVersionMajor) .SetProperty("httpVersionMajor", &URLRequest::ResponseHttpVersionMajor)
.SetProperty("_httpVersionMinor", &URLRequest::ResponseHttpVersionMinor); .SetProperty("httpVersionMinor", &URLRequest::ResponseHttpVersionMinor);
} }
@ -166,7 +162,7 @@ void URLRequest::Abort() {
atom_request_->Abort(); atom_request_->Abort();
} }
bool URLRequest::SetHeader(const std::string& name, bool URLRequest::SetExtraHeader(const std::string& name,
const std::string& value) { const std::string& value) {
if (!net::HttpUtil::IsValidHeaderName(name)) { if (!net::HttpUtil::IsValidHeaderName(name)) {
return false; return false;
@ -176,14 +172,16 @@ bool URLRequest::SetHeader(const std::string& name,
return false; return false;
} }
atom_request_->SetHeader(name, value); atom_request_->SetExtraHeader(name, value);
return true; return true;
} }
std::string URLRequest::GetHeader(const std::string& name) {
return atom_request_->GetHeader(name); void URLRequest::RemoveExtraHeader(const std::string& name) {
atom_request_->RemoveExtraHeader(name);
} }
void URLRequest::RemoveHeader(const std::string& name) {
atom_request_->RemoveHeader(name); void URLRequest::SetChunkedUpload(bool is_chunked_upload) {
atom_request_->SetChunkedUpload(is_chunked_upload);
} }
void URLRequest::OnAuthenticationRequired( void URLRequest::OnAuthenticationRequired(
@ -196,7 +194,7 @@ void URLRequest::OnAuthenticationRequired(
void URLRequest::OnResponseStarted() { void URLRequest::OnResponseStarted() {
EmitRequestEvent("response"); Emit("response");
} }
void URLRequest::OnResponseData( void URLRequest::OnResponseData(

View file

@ -35,9 +35,9 @@ private:
bool WriteBuffer(scoped_refptr<const net::IOBufferWithSize> buffer, bool WriteBuffer(scoped_refptr<const net::IOBufferWithSize> buffer,
bool is_last); bool is_last);
void Abort(); void Abort();
bool SetHeader(const std::string& name, const std::string& value); bool SetExtraHeader(const std::string& name, const std::string& value);
std::string GetHeader(const std::string& name); void RemoveExtraHeader(const std::string& name);
void RemoveHeader(const std::string& name); void SetChunkedUpload(bool is_chunked_upload);
friend class AtomURLRequest; friend class AtomURLRequest;
void OnAuthenticationRequired( void OnAuthenticationRequired(

View file

@ -95,13 +95,13 @@ bool AtomURLRequest::WriteBuffer(
base::Bind(&AtomURLRequest::DoWriteBuffer, this, buffer, is_last)); base::Bind(&AtomURLRequest::DoWriteBuffer, this, buffer, is_last));
} }
void AtomURLRequest::SetChunkedUpload() { void AtomURLRequest::SetChunkedUpload(bool is_chunked_upload) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// The method can be called only before switching to multi-threaded mode, // The method can be called only before switching to multi-threaded mode,
// i.e. before the first call to write. // i.e. before the first call to write.
// So it is safe to change the object in the UI thread. // So it is safe to change the object in the UI thread.
is_chunked_upload_ = true; is_chunked_upload_ = is_chunked_upload;
} }
@ -109,26 +109,14 @@ void AtomURLRequest::Abort() const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
} }
void AtomURLRequest::SetHeader(const std::string& name, void AtomURLRequest::SetExtraHeader(const std::string& name,
const std::string& value) const { const std::string& value) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
request_->SetExtraRequestHeaderByName(name, value, true); request_->SetExtraRequestHeaderByName(name, value, true);
} }
std::string AtomURLRequest::GetHeader(const std::string& name) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::string result;
const auto& extra_headers = request_->extra_request_headers();
if (!extra_headers.GetHeader(name, &result)) {
net::HttpRequestHeaders* request_headers = nullptr;
if (request_->GetFullRequestHeaders(request_headers) && request_headers) {
request_headers->GetHeader(name, &result);
}
}
return result;
}
void AtomURLRequest::RemoveHeader(const std::string& name) const { void AtomURLRequest::RemoveExtraHeader(const std::string& name) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
request_->RemoveRequestHeaderByName(name); request_->RemoveRequestHeaderByName(name);
} }

View file

@ -36,11 +36,10 @@ public:
bool WriteBuffer(scoped_refptr<const net::IOBufferWithSize> buffer, bool WriteBuffer(scoped_refptr<const net::IOBufferWithSize> buffer,
bool is_last); bool is_last);
void SetChunkedUpload(); void SetChunkedUpload(bool is_chunked_upload);
void Abort() const; void Abort() const;
void SetHeader(const std::string& name, const std::string& value) const; void SetExtraHeader(const std::string& name, const std::string& value) const;
std::string GetHeader(const std::string& name) const; void RemoveExtraHeader(const std::string& name) const;
void RemoveHeader(const std::string& name) const;
void PassLoginInformation(const base::string16& username, void PassLoginInformation(const base::string16& username,
const base::string16& password) const; const base::string16& password) const;
scoped_refptr<const net::HttpResponseHeaders> GetResponseHeaders() const; scoped_refptr<const net::HttpResponseHeaders> GetResponseHeaders() const;

View file

@ -8,22 +8,22 @@ const {URLRequest} = net
Object.setPrototypeOf(Net.prototype, EventEmitter.prototype) Object.setPrototypeOf(Net.prototype, EventEmitter.prototype)
Object.setPrototypeOf(URLRequest.prototype, EventEmitter.prototype) Object.setPrototypeOf(URLRequest.prototype, EventEmitter.prototype)
class URLResponse extends EventEmitter { class IncomingMessage extends EventEmitter {
constructor(request) { constructor(url_request) {
super(); super();
this.request = request; this._url_request = url_request;
} }
get statusCode() { get statusCode() {
return this.request._statusCode; return this._url_request.statusCode;
} }
get statusMessage() { get statusMessage() {
return this.request._statusMessage; return this._url_request.statusMessage;
} }
get headers() { get headers() {
return this.request._rawResponseHeaders; return this._url_request.rawResponseHeaders;
} }
get httpVersion() { get httpVersion() {
@ -31,31 +31,32 @@ class URLResponse extends EventEmitter {
} }
get httpVersionMajor() { get httpVersionMajor() {
return this.request._httpVersionMajor; return this._url_request.httpVersionMajor;
} }
get httpVersionMinor() { get httpVersionMinor() {
return this.request._httpVersionMinor; return this._url_request.httpVersionMinor;
} }
get rawHeaders() { get rawHeaders() {
return this.request._rawResponseHeaders; return this._url_request.rawResponseHeaders;
} }
} }
Net.prototype.request = function(options, callback) { URLRequest.prototype._emitRequestEvent = function() {
let request = new URLRequest(options) this._request.emit.apply(this._request, arguments);
if (callback) {
request.once('response', callback)
}
return request
} }
URLRequest.prototype._init = function() { URLRequest.prototype._emitResponseEvent = function() {
this._response.emit.apply(this._response, arguments);
}
class ClientRequest extends EventEmitter {
constructor(options, callback) {
super();
// Flag to prevent writings after end. // Flag to prevent writings after end.
this._finished = false; this._finished = false;
@ -66,10 +67,38 @@ URLRequest.prototype._init = function() {
// Flag to prevent request's headers modifications after // Flag to prevent request's headers modifications after
// headers flush. // headers flush.
this._headersSent = false; this._headersSent = false;
}
// This is a copy of the extra headers structure held by the native
// net::URLRequest. The main reason is to keep the getHeader API synchronous
// after the request starts.
this._extra_headers = {};
let url = options.url;
let method = options.method;
let session = options.session;
let url_request = new URLRequest({
url: url,
method: method,
session: session
});
this._url_request = url_request;
url_request._request = this;
url_request.on('response', ()=> {
let response = new IncomingMessage(url_request);
url_request._response = response;
this.emit('response', response);
});
if (callback) {
this.once('response', callback)
}
}
URLRequest.prototype.setHeader = function(name, value) { setHeader(name, value) {
if (typeof name !== 'string') if (typeof name !== 'string')
throw new TypeError('`name` should be a string in setHeader(name, value).'); throw new TypeError('`name` should be a string in setHeader(name, value).');
if (value === undefined) if (value === undefined)
@ -77,20 +106,27 @@ URLRequest.prototype.setHeader = function(name, value) {
if (this._headersSent) if (this._headersSent)
throw new Error('Can\'t set headers after they are sent.'); throw new Error('Can\'t set headers after they are sent.');
this._setHeader(name, value) let key = name.toLowerCase();
}; this._extra_headers[key] = value;
this._url_request.setExtraHeader(name, value)
}
URLRequest.prototype.getHeader = function(name) { getHeader(name) {
if (arguments.length < 1) { if (arguments.length < 1) {
throw new Error('`name` is required for getHeader(name).'); throw new Error('`name` is required for getHeader(name).');
} }
return this._getHeader(name); if (!this._extra_headers) {
}; return;
}
var key = name.toLowerCase();
return this._extra_headers[key];
}
URLRequest.prototype.removeHeader = function(name) { removeHeader(name) {
if (arguments.length < 1) { if (arguments.length < 1) {
throw new Error('`name` is required for removeHeader(name).'); throw new Error('`name` is required for removeHeader(name).');
} }
@ -99,25 +135,13 @@ URLRequest.prototype.removeHeader = function(name) {
throw new Error('Can\'t remove headers after they are sent.'); throw new Error('Can\'t remove headers after they are sent.');
} }
this._removeHeader(name); var key = name.toLowerCase();
}; delete this._extra_headers[key];
this._url_request.removeExtraHeader(name);
URLRequest.prototype._emitRequestEvent = function(name) {
if (name === 'response') {
this.response = new URLResponse(this);
this.emit(name, this.response);
} else {
this.emit.apply(this, arguments);
} }
}
URLRequest.prototype._emitResponseEvent = function() {
this.response.emit.apply(this.response, arguments);
}
URLRequest.prototype._write = function(chunk, encoding, callback, is_last) { _write(chunk, encoding, callback, is_last) {
let chunk_is_string = typeof chunk === 'string'; let chunk_is_string = typeof chunk === 'string';
let chunk_is_buffer = chunk instanceof Buffer; let chunk_is_buffer = chunk instanceof Buffer;
@ -132,12 +156,15 @@ URLRequest.prototype._write = function(chunk, encoding, callback, is_last) {
// Headers are assumed to be sent on first call to _writeBuffer, // Headers are assumed to be sent on first call to _writeBuffer,
// i.e. after the first call to write or end. // i.e. after the first call to write or end.
let result = this._writeBuffer(chunk, is_last); let result = this._url_request.writeBuffer(chunk, is_last);
// Since writing to the network is asynchronous, we conservatively // Since writing to the network is asynchronous, we conservatively
// assume that request headers are written after delivering the first // assume that request headers are written after delivering the first
// buffer to the network IO thread. // buffer to the network IO thread.
if (!this._headersSent) {
this._url_request.setChunkedUpload(this._chunkedEncoding);
this._headersSent = true; this._headersSent = true;
}
// The write callback is fired asynchronously to mimic Node.js. // The write callback is fired asynchronously to mimic Node.js.
if (callback) { if (callback) {
@ -145,9 +172,9 @@ URLRequest.prototype._write = function(chunk, encoding, callback, is_last) {
} }
return result; return result;
} }
URLRequest.prototype.write = function(data, encoding, callback) { write(data, encoding, callback) {
if (this._finished) { if (this._finished) {
let error = new Error('Write after end.'); let error = new Error('Write after end.');
@ -156,10 +183,10 @@ URLRequest.prototype.write = function(data, encoding, callback) {
} }
return this._write(data, encoding, callback, false); return this._write(data, encoding, callback, false);
}; }
URLRequest.prototype.end = function(data, encoding, callback) { end(data, encoding, callback) {
if (this._finished) { if (this._finished) {
return false; return false;
} }
@ -178,8 +205,9 @@ URLRequest.prototype.end = function(data, encoding, callback) {
data = data || ''; data = data || '';
return this._write(data, encoding, callback, true); return this._write(data, encoding, callback, true);
}; }
}
function writeAfterEndNT(self, error, callback) { function writeAfterEndNT(self, error, callback) {
self.emit('error', error); self.emit('error', error);
@ -187,5 +215,11 @@ function writeAfterEndNT(self, error, callback) {
} }
Net.prototype.request = function(options, callback) {
return new ClientRequest(options, callback);
}
net.ClientRequest = ClientRequest;
module.exports = net module.exports = net