Browse Source

feat: add ability to close connections for a session (#24945)

These methods are needed for closing all idle and in-flight connections after
switching to another proxy from same origin for a session, otherwise
these connections may be reused for future requests which is
unexpected for most of users.
LuoJinghua 4 years ago
parent
commit
e4213e326b

+ 9 - 0
docs/api/session.md

@@ -295,6 +295,9 @@ Sets the proxy settings.
 When `pacScript` and `proxyRules` are provided together, the `proxyRules`
 option is ignored and `pacScript` configuration is applied.
 
+You may need `ses.closeAllConnections` to close currently in flight connections to prevent
+pooled sockets using previous proxy from being reused by future requests.
+
 The `proxyRules` has to follow the rules below:
 
 ```sh
@@ -404,6 +407,12 @@ window.webContents.session.enableNetworkEmulation({ offline: true })
 
 Preconnects the given number of sockets to an origin.
 
+#### `ses.closeAllConnections()`
+
+Returns `Promise<void>` - Resolves when all connections are closed.
+
+**Note:** It will terminate / fail all requests currently in flight.
+
 #### `ses.disableNetworkEmulation()`
 
 Disables any network emulation already active for the `session`. Resets to

+ 14 - 0
shell/browser/api/electron_api_session.cc

@@ -903,6 +903,19 @@ void Session::Preconnect(const gin_helper::Dictionary& options,
                      url, num_sockets_to_preconnect));
 }
 
+v8::Local<v8::Promise> Session::CloseAllConnections() {
+  v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+  gin_helper::Promise<void> promise(isolate);
+  auto handle = promise.GetHandle();
+
+  content::BrowserContext::GetDefaultStoragePartition(browser_context_)
+      ->GetNetworkContext()
+      ->CloseAllConnections(base::BindOnce(
+          gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
+
+  return handle;
+}
+
 #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
 base::Value Session::GetSpellCheckerLanguages() {
   return browser_context_->prefs()
@@ -1106,6 +1119,7 @@ gin::ObjectTemplateBuilder Session::GetObjectTemplateBuilder(
                  &Session::RemoveWordFromSpellCheckerDictionary)
 #endif
       .SetMethod("preconnect", &Session::Preconnect)
+      .SetMethod("closeAllConnections", &Session::CloseAllConnections)
       .SetProperty("cookies", &Session::Cookies)
       .SetProperty("netLog", &Session::NetLog)
       .SetProperty("protocol", &Session::Protocol)

+ 1 - 0
shell/browser/api/electron_api_session.h

@@ -122,6 +122,7 @@ class Session : public gin::Wrappable<Session>,
   v8::Local<v8::Value> WebRequest(v8::Isolate* isolate);
   v8::Local<v8::Value> NetLog(v8::Isolate* isolate);
   void Preconnect(const gin_helper::Dictionary& options, gin::Arguments* args);
+  v8::Local<v8::Promise> CloseAllConnections();
 #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
   base::Value GetSpellCheckerLanguages();
   void SetSpellCheckerLanguages(gin_helper::ErrorThrower thrower,