Initial implementation of new protocol API

This commit is contained in:
Cheng Zhao 2015-08-12 13:30:19 +08:00
parent 1e9eaba423
commit 96d53d279e
16 changed files with 345 additions and 743 deletions

View file

@ -1,148 +0,0 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/net/adapter_request_job.h"
#include "base/threading/sequenced_worker_pool.h"
#include "atom/browser/net/url_request_buffer_job.h"
#include "atom/browser/net/url_request_fetch_job.h"
#include "atom/browser/net/url_request_string_job.h"
#include "atom/browser/net/asar/url_request_asar_job.h"
#include "atom/common/asar/asar_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_file_job.h"
namespace atom {
AdapterRequestJob::AdapterRequestJob(ProtocolHandler* protocol_handler,
net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: URLRequestJob(request, network_delegate),
protocol_handler_(protocol_handler),
weak_factory_(this) {
}
void AdapterRequestJob::Start() {
DCHECK(!real_job_.get());
GetJobType();
}
void AdapterRequestJob::Kill() {
if (real_job_.get()) // Kill could happen when real_job_ is created.
real_job_->Kill();
}
bool AdapterRequestJob::ReadRawData(net::IOBuffer* buf,
int buf_size,
int *bytes_read) {
DCHECK(!real_job_.get());
// Read post-filtered data if available.
if (real_job_->HasFilter())
return real_job_->Read(buf, buf_size, bytes_read);
else
return real_job_->ReadRawData(buf, buf_size, bytes_read);
}
bool AdapterRequestJob::IsRedirectResponse(GURL* location,
int* http_status_code) {
DCHECK(!real_job_.get());
return real_job_->IsRedirectResponse(location, http_status_code);
}
net::Filter* AdapterRequestJob::SetupFilter() const {
DCHECK(!real_job_.get());
return real_job_->SetupFilter();
}
bool AdapterRequestJob::GetMimeType(std::string* mime_type) const {
DCHECK(!real_job_.get());
return real_job_->GetMimeType(mime_type);
}
bool AdapterRequestJob::GetCharset(std::string* charset) {
DCHECK(!real_job_.get());
return real_job_->GetCharset(charset);
}
void AdapterRequestJob::GetResponseInfo(net::HttpResponseInfo* info) {
real_job_->GetResponseInfo(info);
}
int AdapterRequestJob::GetResponseCode() const {
return real_job_->GetResponseCode();
}
void AdapterRequestJob::GetLoadTimingInfo(
net::LoadTimingInfo* load_timing_info) const {
real_job_->GetLoadTimingInfo(load_timing_info);
}
base::WeakPtr<AdapterRequestJob> AdapterRequestJob::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void AdapterRequestJob::CreateErrorJobAndStart(int error_code) {
real_job_ = new net::URLRequestErrorJob(
request(), network_delegate(), error_code);
real_job_->Start();
}
void AdapterRequestJob::CreateStringJobAndStart(const std::string& mime_type,
const std::string& charset,
const std::string& data) {
real_job_ = new URLRequestStringJob(
request(), network_delegate(), mime_type, charset, data);
real_job_->Start();
}
void AdapterRequestJob::CreateBufferJobAndStart(
const std::string& mime_type,
const std::string& charset,
scoped_refptr<base::RefCountedBytes> data) {
real_job_ = new URLRequestBufferJob(
request(), network_delegate(), mime_type, charset, data);
real_job_->Start();
}
void AdapterRequestJob::CreateFileJobAndStart(const base::FilePath& path) {
real_job_ = asar::CreateJobFromPath(
path,
request(),
network_delegate(),
content::BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
real_job_->Start();
}
void AdapterRequestJob::CreateHttpJobAndStart(
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
const GURL& url,
const std::string& method,
const std::string& referrer) {
if (!url.is_valid()) {
CreateErrorJobAndStart(net::ERR_INVALID_URL);
return;
}
real_job_ = new URLRequestFetchJob(request_context_getter, request(),
network_delegate(), url, method, referrer);
real_job_->Start();
}
void AdapterRequestJob::CreateJobFromProtocolHandlerAndStart() {
real_job_ = protocol_handler_->MaybeCreateJob(request(),
network_delegate());
if (!real_job_.get()) {
CreateErrorJobAndStart(net::ERR_NOT_IMPLEMENTED);
} else {
// Copy headers from original request.
real_job_->SetExtraRequestHeaders(request()->extra_request_headers());
real_job_->Start();
}
}
} // namespace atom

View file

@ -1,88 +0,0 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_NET_ADAPTER_REQUEST_JOB_H_
#define ATOM_BROWSER_NET_ADAPTER_REQUEST_JOB_H_
#include <string>
#include "base/memory/ref_counted_memory.h"
#include "base/memory/weak_ptr.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_factory.h"
#include "v8/include/v8.h"
namespace base {
class FilePath;
}
namespace atom {
class AtomBrowserContext;
// Ask JS which type of job it wants, and then delegate corresponding methods.
class AdapterRequestJob : public net::URLRequestJob {
public:
typedef net::URLRequestJobFactory::ProtocolHandler ProtocolHandler;
AdapterRequestJob(ProtocolHandler* protocol_handler,
net::URLRequest* request,
net::NetworkDelegate* network_delegate);
public:
// net::URLRequestJob:
void Start() override;
void Kill() override;
bool ReadRawData(net::IOBuffer* buf,
int buf_size,
int *bytes_read) override;
bool IsRedirectResponse(GURL* location,
int* http_status_code) override;
net::Filter* SetupFilter() const override;
bool GetMimeType(std::string* mime_type) const override;
bool GetCharset(std::string* charset) override;
void GetResponseInfo(net::HttpResponseInfo* info) override;
int GetResponseCode() const override;
void GetLoadTimingInfo(
net::LoadTimingInfo* load_timing_info) const override;
base::WeakPtr<AdapterRequestJob> GetWeakPtr();
ProtocolHandler* default_protocol_handler() { return protocol_handler_; }
// Override this function to determine which job should be started.
virtual void GetJobType() = 0;
void CreateErrorJobAndStart(int error_code);
void CreateStringJobAndStart(const std::string& mime_type,
const std::string& charset,
const std::string& data);
void CreateBufferJobAndStart(const std::string& mime_type,
const std::string& charset,
scoped_refptr<base::RefCountedBytes> data);
void CreateFileJobAndStart(const base::FilePath& path);
void CreateHttpJobAndStart(
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
const GURL& url,
const std::string& method,
const std::string& referrer);
void CreateJobFromProtocolHandlerAndStart();
private:
// The delegated request job.
scoped_refptr<net::URLRequestJob> real_job_;
// Default protocol handler.
ProtocolHandler* protocol_handler_;
base::WeakPtrFactory<AdapterRequestJob> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(AdapterRequestJob);
};
} // namespace atom
#endif // ATOM_BROWSER_NET_ADAPTER_REQUEST_JOB_H_

View file

@ -23,10 +23,7 @@ AtomURLRequestJobFactory::~AtomURLRequestJobFactory() {
}
bool AtomURLRequestJobFactory::SetProtocolHandler(
const std::string& scheme,
ProtocolHandler* protocol_handler) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
const std::string& scheme, scoped_ptr<ProtocolHandler> protocol_handler) {
if (!protocol_handler) {
ProtocolHandlerMap::iterator it = protocol_handler_map_.find(scheme);
if (it == protocol_handler_map_.end())
@ -39,21 +36,17 @@ bool AtomURLRequestJobFactory::SetProtocolHandler(
if (ContainsKey(protocol_handler_map_, scheme))
return false;
protocol_handler_map_[scheme] = protocol_handler;
protocol_handler_map_[scheme] = protocol_handler.release();
return true;
}
ProtocolHandler* AtomURLRequestJobFactory::ReplaceProtocol(
const std::string& scheme,
ProtocolHandler* protocol_handler) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(protocol_handler);
scoped_ptr<ProtocolHandler> AtomURLRequestJobFactory::ReplaceProtocol(
const std::string& scheme, scoped_ptr<ProtocolHandler> protocol_handler) {
if (!ContainsKey(protocol_handler_map_, scheme))
return nullptr;
ProtocolHandler* original_protocol_handler = protocol_handler_map_[scheme];
protocol_handler_map_[scheme] = protocol_handler;
return original_protocol_handler;
protocol_handler_map_[scheme] = protocol_handler.release();
return make_scoped_ptr(original_protocol_handler);
}
ProtocolHandler* AtomURLRequestJobFactory::GetProtocolHandler(

View file

@ -10,8 +10,7 @@
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/synchronization/lock.h"
#include "net/url_request/url_request_job_factory.h"
@ -25,13 +24,13 @@ class AtomURLRequestJobFactory : public net::URLRequestJobFactory {
// Sets the ProtocolHandler for a scheme. Returns true on success, false on
// failure (a ProtocolHandler already exists for |scheme|). On success,
// URLRequestJobFactory takes ownership of |protocol_handler|.
bool SetProtocolHandler(const std::string& scheme,
ProtocolHandler* protocol_handler);
bool SetProtocolHandler(
const std::string& scheme, scoped_ptr<ProtocolHandler> protocol_handler);
// Intercepts the ProtocolHandler for a scheme. Returns the original protocol
// handler on success, otherwise returns NULL.
ProtocolHandler* ReplaceProtocol(const std::string& scheme,
ProtocolHandler* protocol_handler);
scoped_ptr<ProtocolHandler> ReplaceProtocol(
const std::string& scheme, scoped_ptr<ProtocolHandler> protocol_handler);
// Returns the protocol handler registered with scheme.
ProtocolHandler* GetProtocolHandler(const std::string& scheme) const;

View file

@ -0,0 +1,106 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/net/js_asker.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/v8_value_converter.h"
#include "native_mate/function_template.h"
namespace atom {
namespace internal {
namespace {
struct CallbackHolder {
ResponseCallback callback;
};
// Cached JavaScript version of |HandlerCallback|.
v8::Persistent<v8::FunctionTemplate> g_handler_callback_;
// Cached C++ version of |Function.prototype.bind|.
base::Callback<v8::Local<v8::Value>(
v8::Local<v8::Value>, v8::Local<v8::Value>, v8::Local<v8::Value>)> g_bind;
// The callback which is passed to |handler|.
void HandlerCallback(v8::Local<v8::External> external, mate::Arguments* args) {
scoped_ptr<CallbackHolder> holder(
static_cast<CallbackHolder*>(external->Value()));
CHECK(holder);
v8::Local<v8::Value> value;
if (!args->GetNext(&value)) {
holder->callback.Run(false, nullptr);
return;
}
V8ValueConverter converter;
v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
scoped_ptr<base::Value> options(converter.FromV8Value(value, context));
holder->callback.Run(true, options.Pass());
}
// func.bind(...).
template<typename... ArgTypes>
v8::Local<v8::Value> BindFunctionWith(v8::Isolate* isolate,
v8::Local<v8::Context> context,
v8::Local<v8::Function> func,
ArgTypes... args) {
v8::MaybeLocal<v8::Value> bind = func->Get(mate::StringToV8(isolate, "bind"));
CHECK(!bind.IsEmpty());
v8::Local<v8::Function> bind_func =
v8::Local<v8::Function>::Cast(bind.ToLocalChecked());
std::vector<v8::Local<v8::Value>> converted = {
func, mate::ConvertToV8(isolate, args)...,
};
return bind_func->Call(
context, func, converted.size(), &converted.front()).ToLocalChecked();
}
// Generate the callback that will be passed to |handler|.
v8::MaybeLocal<v8::Value> GenerateCallback(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const ResponseCallback& callback) {
// The FunctionTemplate is cached.
if (g_handler_callback_.IsEmpty())
g_handler_callback_.Reset(
isolate,
mate::CreateFunctionTemplate(isolate, base::Bind(&HandlerCallback)));
v8::Local<v8::FunctionTemplate> handler_callback =
v8::Local<v8::FunctionTemplate>::New(isolate, g_handler_callback_);
CallbackHolder* holder = new CallbackHolder;
holder->callback = callback;
return BindFunctionWith(isolate, context,
handler_callback->GetFunction(),
v8::External::New(isolate, holder));
}
} // namespace
void AskForOptions(v8::Isolate* isolate,
const JavaScriptHandler& handler,
net::URLRequest* request,
const ResponseCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
v8::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Context::Scope context_scope(context);
// We don't convert the callback to C++ directly because creating
// FunctionTemplate will cause memory leak since V8 never releases it. So we
// have to create the function object in JavaScript to work around it.
v8::MaybeLocal<v8::Value> wrapped_callback = GenerateCallback(
isolate, context, callback);
if (wrapped_callback.IsEmpty()) {
callback.Run(false, nullptr);
return;
}
handler.Run(request, wrapped_callback.ToLocalChecked());
}
} // namespace internal
} // namespace atom

View file

@ -0,0 +1,85 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_NET_JS_ASKER_H_
#define ATOM_BROWSER_NET_JS_ASKER_H_
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request_job.h"
#include "v8/include/v8.h"
namespace atom {
using JavaScriptHandler =
base::Callback<void(const net::URLRequest*, v8::Local<v8::Value>)>;
namespace internal {
using ResponseCallback =
base::Callback<void(bool, scoped_ptr<base::Value> options)>;
// Ask handler for options in UI thread.
void AskForOptions(v8::Isolate* isolate,
const JavaScriptHandler& handler,
net::URLRequest* request,
const ResponseCallback& callback);
} // namespace internal
template<typename RequestJob>
class JsAsker : public RequestJob {
public:
JsAsker(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
v8::Isolate* isolate,
const JavaScriptHandler& handler)
: RequestJob(request, network_delegate),
isolate_(isolate),
handler_(handler),
weak_factory_(this) {}
// Subclass should do initailze work here.
virtual void StartAsync(scoped_ptr<base::Value> options) {
RequestJob::Start();
}
private:
// RequestJob:
void Start() override {
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&internal::AskForOptions,
isolate_,
handler_,
RequestJob::request(),
base::Bind(&JsAsker::OnResponse,
weak_factory_.GetWeakPtr())));
}
// Called when the JS handler has sent the response, we need to decide whether
// to start, or fail the job.
void OnResponse(bool success, scoped_ptr<base::Value> options) {
if (success) {
StartAsync(options.Pass());
} else {
RequestJob::NotifyStartError(
net::URLRequestStatus(net::URLRequestStatus::FAILED,
net::ERR_NOT_IMPLEMENTED));
}
}
v8::Isolate* isolate_;
JavaScriptHandler handler_;
base::WeakPtrFactory<JsAsker> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(JsAsker);
};
} // namespace atom
#endif // ATOM_BROWSER_NET_JS_ASKER_H_

View file

@ -12,13 +12,25 @@ namespace atom {
URLRequestStringJob::URLRequestStringJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const std::string& mime_type,
const std::string& charset,
const std::string& data)
: net::URLRequestSimpleJob(request, network_delegate),
mime_type_(mime_type),
charset_(charset),
data_(data) {
v8::Isolate* isolate,
const JavaScriptHandler& handler)
: JsAsker<net::URLRequestSimpleJob>(request, network_delegate, isolate,
handler) {
}
void URLRequestStringJob::StartAsync(scoped_ptr<base::Value> options) {
if (options) {
if (options->IsType(base::Value::TYPE_DICTIONARY)) {
base::DictionaryValue* dict =
static_cast<base::DictionaryValue*>(options.get());
dict->GetString("mimeType", &mime_type_);
dict->GetString("charset", &charset_);
dict->GetString("data", &data_);
} else if (options->IsType(base::Value::TYPE_STRING)) {
options->GetAsString(&data_);
}
}
net::URLRequestSimpleJob::Start();
}
int URLRequestStringJob::GetData(

View file

@ -5,19 +5,22 @@
#ifndef ATOM_BROWSER_NET_URL_REQUEST_STRING_JOB_H_
#define ATOM_BROWSER_NET_URL_REQUEST_STRING_JOB_H_
#include "atom/browser/net/js_asker.h"
#include "net/url_request/url_request_simple_job.h"
#include <string>
namespace atom {
class URLRequestStringJob : public net::URLRequestSimpleJob {
class URLRequestStringJob : public JsAsker<net::URLRequestSimpleJob> {
public:
URLRequestStringJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const std::string& mime_type,
const std::string& charset,
const std::string& data);
v8::Isolate* isolate,
const JavaScriptHandler& handler);
// JsAsker:
void StartAsync(scoped_ptr<base::Value> options) override;
// URLRequestSimpleJob:
int GetData(std::string* mime_type,