Skip to content

refactor: Clean up the implementation of the registerStreamProtocol - #11357

Merged
jkleinsc merged 12 commits into
masterfrom
event-subscriber-clean
Oct 4, 2018
Merged

jkleinsc merged 12 commits into
masterfrom
event-subscriber-clean

Conversation

@zcbenz

@zcbenz zcbenz commented Dec 6, 2017 •

Copy link
Copy Markdown
Contributor

This is an alternative fix to #11283.

This PR removes the manual management of EventSubscriber's lifetime, and uses existing tools for the same purpose. It should both simplify the code and solve possible crashes.

Notes: no-notes

@zcbenz
zcbenz requested a review from a team December 6, 2017 10:35
@zcbenz

zcbenz commented Dec 6, 2017

Copy link
Copy Markdown
Contributor Author

It seems that we still have a race condition in URLRequestStreamJob, I'm going to try if I can avoid accessing the pending_io_buf_ from 2 different threads.

@tarruda tarruda left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, nice improvements. The only reason I didn't use base:Callback in the first place was because it was only being invoked once, but I see you took care of that.

Comment thread atom/browser/api/event_subscriber.cc Outdated
DCHECK(js_handlers_.find(event_name) == js_handlers_.end());
void EventSubscriber::On(const std::string& event, EventCallback&& callback) { // NOLINT
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
callbacks_[event] = callback;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe an assertion to verify the same event is not subscribed twice?


URLRequestStreamJob::~URLRequestStreamJob() {
if (subscriber_) {
content::BrowserThread::DeleteSoon(content::BrowserThread::UI, FROM_HERE,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Didn't knew this function existed 👍

Anyway, the only reason I added SafePtr was to encapsulate "deletion in the UI thread" in case other classes that are deleted outside UI thread needed to use EventSubscriber and didn't want to repeat this code in their destructors.

subscriber_->On("error", &URLRequestStreamJob::OnError);
subscriber_.reset(new mate::EventSubscriber(isolate, data.GetHandle()));
subscriber_->On("data", base::Bind(&URLRequestStreamJob::OnData,
weak_factory_.GetWeakPtr()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So if I understood correctly, the callback is thread-safe and will synchronize internally if the URLJob happens to be destroyed at the same time the event is being emitted?

@tarruda

tarruda commented Dec 6, 2017

Copy link
Copy Markdown
Contributor

@zcbenz should I close #11283 then? Just for reference, this is the crash #11283 was trying to fix:

ntdll.dll!_RtlReleaseSRWLockExclusive@4�()	Unknown
 	electron.exe!base::internal::LockImpl::Unlock() Line 27	C++
	electron.exe!mate::EventSubscriber<atom::URLRequestStreamJob>::SafePtr::Deleter(mate::EventSubscriber<atom::URLRequestStreamJob> * ptr) Line 79	C++
 	electron.exe!atom::URLRequestStreamJob::CopyMoreDataDone(scoped_refptr<net::IOBuffer> io_buf, int status) Line 139	C++
 	electron.exe!base::internal::FunctorTraits<void (__thiscall atom::URLRequestStreamJob::*)(scoped_refptr<net::IOBuffer>,int),void>::Invoke<base::WeakPtr<atom::URLRequestStreamJob> const &,scoped_refptr<net::IOBuffer> const &,int const &>(void(atom::URLRequestStreamJob::*)(scoped_refptr<net::IOBuffer>, int) method, const base::WeakPtr<atom::URLRequestStreamJob> & receiver_ptr, const scoped_refptr<net::IOBuffer> & <args_0>, const int & <args_1>) Line 215	C++
 	electron.exe!base::internal::InvokeHelper<1,void>::MakeItSo<void (__thiscall atom::URLRequestStreamJob::*const &)(scoped_refptr<net::IOBuffer>,int),base::WeakPtr<atom::URLRequestStreamJob> const &,scoped_refptr<net::IOBuffer> const &,int const &>(void(atom::URLRequestStreamJob::*)(scoped_refptr<net::IOBuffer>, int) & functor, const base::WeakPtr<atom::URLRequestStreamJob> & weak_ptr, const scoped_refptr<net::IOBuffer> & <args_0>, const int & <args_1>) Line 305	C++
 	electron.exe!base::internal::Invoker<base::internal::BindState<void (__thiscall atom::URLRequestStreamJob::*)(scoped_refptr<net::IOBuffer>,int),base::WeakPtr<atom::URLRequestStreamJob>,scoped_refptr<net::IOBuffer>,int>,void __cdecl(void)>::RunImpl<void (__thiscall atom::URLRequestStreamJob::*const &)(scoped_refptr<net::IOBuffer>,int),std::tuple<base::WeakPtr<atom::URLRequestStreamJob>,scoped_refptr<net::IOBuffer>,int> const &,0,1,2>(void(atom::URLRequestStreamJob::*)(scoped_refptr<net::IOBuffer>, int) & functor, const std::tuple<base::WeakPtr<atom::URLRequestStreamJob>,scoped_refptr<net::IOBuffer>,int> & bound, base::IndexSequence<0,1,2> __formal) Line 361	C++
 	electron.exe!base::internal::Invoker<base::internal::BindState<void (__thiscall atom::URLRequestStreamJob::*)(scoped_refptr<net::IOBuffer>,int),base::WeakPtr<atom::URLRequestStreamJob>,scoped_refptr<net::IOBuffer>,int>,void __cdecl(void)>::Run(base::internal::BindStateBase * base) Line 339	C++
 	electron.exe!base::debug::TaskAnnotator::RunTask(const char * queue_function, base::PendingTask * pending_task) Line 59	C++
 	electron.exe!base::MessageLoop::RunTask(base::PendingTask * pending_task) Line 424	C++
 	electron.exe!base::MessageLoop::DoWork() Line 527	C++
 	electron.exe!base::MessagePumpForIO::DoRunLoop() Line 475	C++
 	electron.exe!base::MessagePumpWin::Run(base::MessagePump::Delegate * delegate) Line 58	C++
 	electron.exe!base::MessageLoop::RunHandler() Line 387	C++
 	electron.exe!base::RunLoop::Run() Line 38	C++
 	electron.exe!base::Thread::Run(base::RunLoop * run_loop) Line 251	C++
 	electron.exe!content::BrowserThreadImpl::IOThreadRun(base::RunLoop * run_loop) Line 278	C++
 	electron.exe!content::BrowserThreadImpl::Run(base::RunLoop * run_loop) Line 312	C++
 	electron.exe!base::Thread::ThreadMain() Line 336	C++
 	electron.exe!base::`anonymous namespace'::ThreadFunc(void * params) Line 91	C++
 	[External Code]	

As you can see, the Deleter was running in the UI thread before the IO function that posted it could release the lock. I assume this won't be a problem with DeleteSoon + weak pointers, correct?

@tarruda

tarruda commented Dec 6, 2017

Copy link
Copy Markdown
Contributor

It seems that we still have a race condition in URLRequestStreamJob, I'm going to try if I can avoid accessing the pending_io_buf_ from 2 different threads.

I'm afraid the current tests don't exercise URLRequestStreamJob very well. Before you merge this, can you give me some time to test it? The app I'm working on can exercise this code very well since it does a bunch of concurrent requests for an extended period of time (it uses interceptStreamProtocol('https') to intercept every request made).

@tarruda

tarruda commented Dec 6, 2017 •

Copy link
Copy Markdown
Contributor

It seems that we still have a race condition in URLRequestStreamJob, I'm going to try if I can avoid accessing the pending_io_buf_ from 2 different threads.

Just to be clear, pending_io_buf_ is only set/read from the UI thread. The underlying scoped_refptr<net::IOBuffer> is sent to the UI thread via PostTask call in ReadRawData

@zcbenz

zcbenz commented Dec 6, 2017

Copy link
Copy Markdown
Contributor Author

@tarruda I have refactored the code so EventSubscriber only operates on UI thread while URLRequestStreamJob only operates on IO thread, so we should no longer worry about race conditions.

I'll merge when this change passes your tests.

};
void OnData(mate::Arguments* args);
void OnEnd(mate::Arguments* args);
void OnError(mate::Arguments* args);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are going to make this class specific to Streams instead of generic event subscribers, maybe it should be renamed to StreamSubscriber or StreamConsumer?

Comment thread atom/browser/api/event_subscriber.cc Outdated
const char* data = node::Buffer::Data(buf);
size_t length = node::Buffer::Length(buf);
std::vector<char> buffer(length);
buffer.assign(data, data + length);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip: Initialize the vector with the source buffer to avoid zeroing the buffer first only to replace the content with actual data.

std::vector<char> buffer(data, length);

Comment thread atom/browser/api/event_subscriber.cc Outdated
}

// Copy the data from Buffer.
// TODO(zcbenz): Is there a way to move the data?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's no way to guarantee that no other JS code is referencing the buffer

@tarruda

tarruda commented Dec 7, 2017 •

Copy link
Copy Markdown
Contributor

@zcbenz I just started testing this PR on our app but it crashed at startup. The following patch should fix the crash and a few problems with the refactor:

diff --git a/atom/browser/net/url_request_stream_job.cc b/atom/browser/net/url_request_stream_job.cc
index 4474f94..ae625a8 100644
--- a/atom/browser/net/url_request_stream_job.cc
+++ b/atom/browser/net/url_request_stream_job.cc
@@ -117,7 +117,9 @@ void URLRequestStreamJob::OnData(std::vector<char>&& buffer) {  // NOLINT

 void URLRequestStreamJob::OnEnd() {
   ended_ = true;
-  ReadRawDataComplete(0);
+  if (pending_buf_ && write_buffer_.empty()) {
+    ReadRawDataComplete(0);
+  }
 }

 void URLRequestStreamJob::OnError() {
@@ -126,26 +128,29 @@ void URLRequestStreamJob::OnError() {
 }

 int URLRequestStreamJob::ReadRawData(net::IOBuffer* dest, int dest_size) {
+  if (!write_buffer_.empty()) {
+    // Read from the write buffer and clear them after reading.
+    int len = BufferCopy(&write_buffer_, dest, dest_size);
+    write_buffer_.erase(write_buffer_.begin(), write_buffer_.begin() + len);
+    return len;
+  }
+
   if (ended_)
+    // Buffer empty and will no longer emit data events.
     return 0;

   // When write_buffer_ is empty, there is no data valable yet, we have to save
   // the dest buffer util DataAvailable.
-  if (write_buffer_.empty()) {
-    pending_buf_ = dest;
-    pending_buf_size_ = dest_size;
-    return net::ERR_IO_PENDING;
-  }
-
-  // Read from the write buffer and clear them after reading.
-  int len = BufferCopy(&write_buffer_, dest, dest_size);
-  write_buffer_.erase(write_buffer_.begin(), write_buffer_.begin() + len);
-  return len;
+  pending_buf_ = dest;
+  pending_buf_size_ = dest_size;
+  return net::ERR_IO_PENDING;
 }

 void URLRequestStreamJob::DoneReading() {
-  content::BrowserThread::DeleteSoon(content::BrowserThread::UI, FROM_HERE,
-                                     std::move(subscriber_));
+  if (subscriber_) {
+    content::BrowserThread::DeleteSoon(content::BrowserThread::UI, FROM_HERE,
+        std::move(subscriber_));
+  }
   write_buffer_.clear();
 }

Reasoning for each change:

  • OnEnd can be called at any time, even before the URLRequestJob requested data. If that happens, calling ReadRawDataComplete(0) will result in crash. I have reordered ReadRawData to handle all cases correctly.
  • Even if OnEnd is called after URLRequestJob request data, we should only signal EOF when the job has finished reading any buffered data.
  • DoneReading can be called at any time to signal chromium no longer wants to read data, it is theoretically possible that subscriber_ is null in this case. (Maybe there's no problem calling DeleteSoon on a null value, but I thought it would be a good idea to make it explicit)

IMHO the same reasoning behind only signaling EOF after buffered data is ready should apply to error handling, though I have not included the required changes in the above patch. For example, if the stream starts sending data and then a closed connection causes an error, we should allow the job to read the partial data and only signal the error later by passing it to ReadRawDataComplete (like it was done previously)

Since you've restructured the code quite a bit beyond using base::Callback + base::WeakPtr, please allow me a few days to test this more thoroughly.

@deepak1556

Copy link
Copy Markdown
Member

@zcbenz I have rebased this on latest master, would like to get this in soon for #14816.

@tarruda

tarruda commented Sep 26, 2018

Copy link
Copy Markdown
Contributor

@deepak1556 I discussed privately about this PR with @zcbenz and I don't recommend merging it. Last year I had created a build of this PR and asked our QA team to test it, and there were random crashes happening.

Unfortunately due to the concurrent nature of the code, I could not reliably reproduce the crashes or find what's wrong with this PR.

@deepak1556

deepak1556 commented Sep 27, 2018 •

Copy link
Copy Markdown
Member

Pasting the discussion with @tarruda from slack,

Although there are some crash experienced with these changes, they aren't reliable scenarios yet. URLRequestStreamJob currently misuses weak ptr and trying to fix it ends up with similar changes to this PR, I would like to merge this PR and follow up with fixing any crash that gets reported.

@deepak1556

Copy link
Copy Markdown
Member

@tarruda can you review this before it gets merged. Thanks!

@deepak1556
deepak1556 force-pushed the event-subscriber-clean branch from f59c95e to fc7ec26 Compare October 2, 2018 10:51
@deepak1556
deepak1556 force-pushed the event-subscriber-clean branch from fc7ec26 to df87b80 Compare October 3, 2018 12:44
@deepak1556 deepak1556 changed the title Clean up the implementation of the registerStreamProtocol refactor: Clean up the implementation of the registerStreamProtocol Oct 3, 2018
@jkleinsc
jkleinsc merged commit d3ae541 into master Oct 4, 2018
@release-clerk

release-clerk Bot commented Oct 4, 2018

Copy link
Copy Markdown

No Release Notes

@deepak1556
deepak1556 deleted the event-subscriber-clean branch October 5, 2018 13:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants