blob: 67fa6e494d661bfd14807d7c0d8a8decd5768b21 [file] [log] [blame]
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <map>
#include <string>
#include "base/macros.h"
#include "v8/include/v8.h"
namespace base {
class ListValue;
namespace extensions {
class IPCMessageSender;
class ScriptContext;
struct PendingRequest;
// Responsible for sending requests for named extension API functions to the
// extension host and routing the responses back to the caller.
class RequestSender {
// Source represents a user of RequestSender. Every request is associated with
// a Source object, which will be notified when the corresponding response
// arrives. When a Source object is going away and there are pending requests,
// it should call InvalidateSource() to make sure no notifications are sent to
// it later.
class Source {
virtual ~Source() {}
virtual ScriptContext* GetContext() = 0;
virtual void OnResponseReceived(const std::string& name,
int request_id,
bool success,
const base::ListValue& response,
const std::string& error) = 0;
explicit RequestSender(IPCMessageSender* ipc_message_sender);
// In order to avoid collision, all |request_id|s passed into StartRequest()
// should be generated by this method.
int GetNextRequestId() const;
// Makes a call to the API function |name| that is to be handled by the
// extension host. The response to this request will be received in
// HandleResponse().
// TODO(koz): Remove |request_id| and generate that internally.
// There are multiple of these per render view though, so we'll
// need to vend the IDs centrally.
// Returns true if the request is successfully sent.
bool StartRequest(Source* source,
const std::string& name,
int request_id,
bool has_callback,
bool for_io_thread,
base::ListValue* value_args);
// Handles responses from the extension host to calls made by StartRequest().
void HandleResponse(int request_id,
bool success,
const base::ListValue& response,
const std::string& error);
// Notifies this that a request source is no longer valid.
// TODO(kalman): Do this in a generic/safe way.
void InvalidateSource(Source* source);
friend class ScopedTabID;
using PendingRequestMap = std::map<int, std::unique_ptr<PendingRequest>>;
void InsertRequest(int request_id,
std::unique_ptr<PendingRequest> pending_request);
std::unique_ptr<PendingRequest> RemoveRequest(int request_id);
PendingRequestMap pending_requests_;
// Guaranteed to outlive this object.
IPCMessageSender* const ipc_message_sender_;
} // namespace extensions