React Native for Android 源碼解析:Reload, Debug JS Remotely具體做了什么?

忽悠妹紙買的splatoon不會玩然后甩給我了,美滋滋

Reload, debug js remotely罪惡滔天,弄的百姓怨聲載道

最近使用0.54.0版本開發(fā)有個調試的bug非常惡心,debug js remotely總是拋

DeltaPatcher.js:58 Uncaught (in promise) Error: DeltaPatcher should receive a fresh Delta when being initialized
                                                       at DeltaPatcher.applyDelta (DeltaPatcher.js:58)
                                                       at deltaUrlToBlobUrl (deltaUrlToBlobUrl.js:34)
                                                       at <anonymous>

想再次debug就得殺掉進程重新打開,官方解釋在0.55版本會修復此問題,看了下pr改動都是js代碼,隨即更新版本修復此問題。若想以后碰到類似框架性的問題,想要自己能有排錯糾錯能力,還是老老實實啃源碼吧

Reload

首先看看Reload,先從Activity下手,初始demo里MainActivity繼承了ReactActivity,RN工程的初始化,加載jsbundle的觸發(fā)都在這個ReactActivity中,然后具體業(yè)務邏輯又交給了它的代理類ReactActivityDelegate,里面做了初始化RN框架邏輯,框架初始化的流程先不管,主要看看reload流程

onKeyUp

public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) {
      if (keyCode == KeyEvent.KEYCODE_MENU) {
        getReactNativeHost().getReactInstanceManager().showDevOptionsDialog();
        return true;
      }
      boolean didDoubleTapR = Assertions.assertNotNull(mDoubleTapReloadRecognizer)
        .didDoubleTapR(keyCode, getPlainActivity().getCurrentFocus());
      if (didDoubleTapR) {
        getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS();
        return true;
      }
    }
    return false;
  }

ReactActivity中偵聽了物理按鍵,在keyCode為82即menu按鍵的時候,獲取了RN主要的管理類ReactInstanceManager,然后調起了調試框DevOptionsDialog,具體業(yè)務邏輯在DevSupportManagerImpl這個類中,還可以看到有另外一個doubleTapR操作可以直接進行reload jsbundle,繼續(xù)跟到DevSupportManagerImpl中,這里定義了調試dialog,跟到R.string.catalyst_reloadjs這個事件,觸發(fā)了handleReloadJS,reload的流程入口就在這個方法中

handleReloadJS

@Override
  public void handleReloadJS() {

    UiThreadUtil.assertOnUiThread();

    ReactMarker.logMarker(
        ReactMarkerConstants.RELOAD,
        mDevSettings.getPackagerConnectionSettings().getDebugServerHost());

    // dismiss redbox if exists
    hideRedboxDialog();

    if (mDevSettings.isRemoteJSDebugEnabled()) {
      PrinterHolder.getPrinter()
          .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Proxy");
      mDevLoadingViewController.showForRemoteJSEnabled();
      mDevLoadingViewVisible = true;
      reloadJSInProxyMode();
    } else {
      PrinterHolder.getPrinter()
          .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Server");
      String bundleURL =
        mDevServerHelper.getDevServerBundleURL(Assertions.assertNotNull(mJSAppBundleName));
      reloadJSFromServer(bundleURL);
    }
  }

可以看到這個方法主要是在取bundleURL,還區(qū)分了debug js remotely模式,可以看到這里的mJSAppBundleName是在構造函里數(shù)獲取的,然后構造函數(shù)用IDE的函數(shù)跳轉功能并不能找到在哪里構造的,仔細觀察DevSupportManagerImpl的接口DevSupportManager,可以看到在DevSupportManagerFactory這個工廠類中有使用,這里是用的反射進行構造的

public static DevSupportManager create(
    Context applicationContext,
    ReactInstanceManagerDevHelper reactInstanceManagerHelper,
    // 這個是mJSAppBundleName
    @Nullable String packagerPathForJSBundleName,
    boolean enableOnCreate,
    @Nullable RedBoxHandler redBoxHandler,
    @Nullable DevBundleDownloadListener devBundleDownloadListener,
    int minNumShakes) {
    if (!enableOnCreate) {
      return new DisabledDevSupportManager();
    }
    try {
      // ProGuard is surprisingly smart in this case and will keep a class if it detects a call to
      // Class.forName() with a static string. So instead we generate a quasi-dynamic string to
      // confuse it.
      String className =
        new StringBuilder(DEVSUPPORT_IMPL_PACKAGE)
          .append(".")
          .append(DEVSUPPORT_IMPL_CLASS)
          .toString();
      Class<?> devSupportManagerClass =
        Class.forName(className);
      Constructor constructor =
        devSupportManagerClass.getConstructor(
          Context.class,
          ReactInstanceManagerDevHelper.class,
          String.class,
          boolean.class,
          RedBoxHandler.class,
          DevBundleDownloadListener.class,
          int.class);
      return (DevSupportManager) constructor.newInstance(
        applicationContext,
        reactInstanceManagerHelper,
        packagerPathForJSBundleName,
        true,
        redBoxHandler,
        devBundleDownloadListener,
        minNumShakes);
    } catch (Exception e) {
      throw new RuntimeException(
        "Requested enabled DevSupportManager, but DevSupportManagerImpl class was not found" +
          " or could not be created",
        e);
    }
  }

跟到最后可以發(fā)現(xiàn)是在ReactNativeHost這個抽象類的getJSMainModuleName()方法拿到的,這個方法可以給用戶重寫進行自定義,再回到handleReloadJS方法,拼接出來的bundleURL長這樣
http://localhost:8081/index.delta?platform=android&dev=true&minify=false,host就是我們本地Nodejs啟動的服務器地址

public void reloadJSFromServer(final String bundleURL) {
    ReactMarker.logMarker(ReactMarkerConstants.DOWNLOAD_START);

    mDevLoadingViewController.showForUrl(bundleURL);
    mDevLoadingViewVisible = true;

    final BundleDownloader.BundleInfo bundleInfo = new BundleDownloader.BundleInfo();
    // 觸發(fā)下載任務
    mDevServerHelper.downloadBundleFromURL(
        // 偵聽下載
        new DevBundleDownloadListener() {
          @Override
          public void onSuccess() {
            mDevLoadingViewController.hide();
            mDevLoadingViewVisible = false;
            synchronized (DevSupportManagerImpl.this) {
              mBundleStatus.isLastDownloadSucess = true;
              mBundleStatus.updateTimestamp = System.currentTimeMillis();
            }
            if (mBundleDownloadListener != null) {
              mBundleDownloadListener.onSuccess();
            }
            UiThreadUtil.runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    ReactMarker.logMarker(ReactMarkerConstants.DOWNLOAD_END, bundleInfo.toJSONString());
                    mReactInstanceManagerHelper.onJSBundleLoadedFromServer();
                  }
                });
          }

          @Override
          public void onProgress(@Nullable final String status, @Nullable final Integer done, @Nullable final Integer total) {
            mDevLoadingViewController.updateProgress(status, done, total);
            if (mBundleDownloadListener != null) {
              mBundleDownloadListener.onProgress(status, done, total);
            }
          }

          @Override
          public void onFailure(final Exception cause) {
            mDevLoadingViewController.hide();
            mDevLoadingViewVisible = false;
            synchronized (DevSupportManagerImpl.this) {
              mBundleStatus.isLastDownloadSucess = false;
            }
            if (mBundleDownloadListener != null) {
              mBundleDownloadListener.onFailure(cause);
            }
            FLog.e(ReactConstants.TAG, "Unable to download JS bundle", cause);
            UiThreadUtil.runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    if (cause instanceof DebugServerException) {
                      DebugServerException debugServerException = (DebugServerException) cause;
                      showNewJavaError(debugServerException.getMessage(), cause);
                    } else {
                      showNewJavaError(
                          mApplicationContext.getString(R.string.catalyst_jsload_error),
                          cause);
                    }
                  }
                });
          }
        },
        mJSBundleTempFile,
        bundleURL,
        bundleInfo);
  }

這個方法觸發(fā)了下載任務和下載成功后續(xù)的操作,跟進mDevServerHelper.downloadBundleFromUR()方法,走到BundleDownloader類的downloadBundleFromURL方法

public void downloadBundleFromURL(
      final DevBundleDownloadListener callback,
      final File outputFile,
      final String bundleURL,
      final @Nullable BundleInfo bundleInfo) {

    // 實例化okhttp請求
    final Request request =
        new Request.Builder()
            .url(mBundleDeltaClient.toDeltaUrl(bundleURL))
            // FIXME: there is a bug that makes MultipartStreamReader to never find the end of the
            // multipart message. This temporarily disables the multipart mode to work around it,
            // but
            // it means there is no progress bar displayed in the React Native overlay anymore.
            // .addHeader("Accept", "multipart/mixed")
            .build();
    mDownloadBundleFromURLCall = Assertions.assertNotNull(mClient.newCall(request));
    mDownloadBundleFromURLCall.enqueue(
        new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
            // ignore callback if call was cancelled
            if (mDownloadBundleFromURLCall == null || mDownloadBundleFromURLCall.isCanceled()) {
              mDownloadBundleFromURLCall = null;
              return;
            }
            mDownloadBundleFromURLCall = null;

            callback.onFailure(
                DebugServerException.makeGeneric(
                    "Could not connect to development server.",
                    "URL: " + call.request().url().toString(),
                    e));
          }

          @Override
          public void onResponse(Call call, final Response response) throws IOException {
            // ignore callback if call was cancelled
            if (mDownloadBundleFromURLCall == null || mDownloadBundleFromURLCall.isCanceled()) {
              mDownloadBundleFromURLCall = null;
              return;
            }
            mDownloadBundleFromURLCall = null;

            final String url = response.request().url().toString();

            // Make sure the result is a multipart response and parse the boundary.
            String contentType = response.header("content-type");
            Pattern regex = Pattern.compile("multipart/mixed;.*boundary=\"([^\"]+)\"");
            Matcher match = regex.matcher(contentType);
            try (Response r = response) {
              if (match.find()) {
                processMultipartResponse(
                  url, r, match.group(1), outputFile, bundleInfo, callback);
              } else {
                // In case the server doesn't support multipart/mixed responses, fallback to normal
                // download.
                processBundleResult(
                  url,
                  r.code(),
                  r.headers(),
                  Okio.buffer(r.body().source()),
                  outputFile,
                  bundleInfo,
                  callback);
              }
            }
          }
        });
  }

先看看這個方法的形參

  • DevBundleDownloadListener callback:jsbundle下載回調
  • File outputFile:Bundle緩存地址,我這里具體為
    /data/data/com.socketclientrn/files/ReactNativeDevBundle.js
  • String bundleURL:下載jsbundle的URL

再看函數(shù)具體邏輯,內部使用了okhttp進行下載,下載成功后,onResponse回調中對返回數(shù)據(jù)進行了緩存。

private void processBundleResult(
      String url,
      int statusCode,
      Headers headers,
      BufferedSource body,
      File outputFile,
      BundleInfo bundleInfo,
      DevBundleDownloadListener callback)
      throws IOException {
    // Check for server errors. If the server error has the expected form, fail with more info.
    if (statusCode != 200) {
      String bodyString = body.readUtf8();
      DebugServerException debugServerException = DebugServerException.parse(bodyString);
      if (debugServerException != null) {
        callback.onFailure(debugServerException);
      } else {
        StringBuilder sb = new StringBuilder();
        sb.append("The development server returned response error code: ").append(statusCode).append("\n\n")
          .append("URL: ").append(url).append("\n\n")
          .append("Body:\n")
          .append(bodyString);
        callback.onFailure(new DebugServerException(sb.toString()));
      }
      return;
    }

    if (bundleInfo != null) {
      populateBundleInfo(url, headers, bundleInfo);
    }

    File tmpFile = new File(outputFile.getPath() + ".tmp");

    boolean bundleUpdated;

    if (BundleDeltaClient.isDeltaUrl(url)) {
      // If the bundle URL has the delta extension, we need to use the delta patching logic.
      bundleUpdated = mBundleDeltaClient.storeDeltaInFile(body, tmpFile);
    } else {
      mBundleDeltaClient.reset();
      bundleUpdated = storePlainJSInFile(body, tmpFile);
    }

    if (bundleUpdated) {
      // If we have received a new bundle from the server, move it to its final destination.
      if (!tmpFile.renameTo(outputFile)) {
        throw new IOException("Couldn't rename " + tmpFile + " to " + outputFile);
      }
    }

    callback.onSuccess();
  }

內部具體的流操作使用了okio,具體緩存的時候在參數(shù)outputFile后面加了個.tmp然后進行存儲,存儲ok后回調DevBundleDownloadListener。
再回到DevSupportManagerImplreloadJSFromServer方法,可以在onSuccess回調中看到判空mBundleDownloadListener然后調用的邏輯,這個回調是初始化DevSupportManagerImpl傳進來的,調用鏈跟到最后是在ReactNativeHostcreateReactInstanceManager方法中構建ReactInstanceManager時傳遞的,這個方法開發(fā)者是可以重寫的,提供給開發(fā)者偵聽jsbundle下載是否成功與失敗

createCachedBundleFromNetworkLoader

private ReactInstanceManagerDevHelper createDevHelperInterface() {
    return new ReactInstanceManagerDevHelper() {
      @Override
      public void onReloadWithJSDebugger(JavaJSExecutor.Factory jsExecutorFactory) {
        ReactInstanceManager.this.onReloadWithJSDebugger(jsExecutorFactory);
      }

      @Override
      public void onJSBundleLoadedFromServer() {
        ReactInstanceManager.this.onJSBundleLoadedFromServer();
      }

      @Override
      public void toggleElementInspector() {
        ReactInstanceManager.this.toggleElementInspector();
      }

      @Override
      public @Nullable Activity getCurrentActivity() {
        return ReactInstanceManager.this.mCurrentActivity;
      }
    };
  }

跟著調用鏈,最后走到了createCachedBundleFromNetworkLoader方法里

public static JSBundleLoader createCachedBundleFromNetworkLoader(
      final String sourceURL,
      final String cachedFileLocation) {
    return new JSBundleLoader() {
      @Override
      public String loadScript(CatalystInstanceImpl instance) {
        try {
          instance.loadScriptFromFile(cachedFileLocation, sourceURL, false);
          return sourceURL;
        } catch (Exception e) {
          throw DebugServerException.makeGeneric(e.getMessage(), e);
        }
      }
    };
  }

createCachedBundleFromNetworkLoader構造完JSBundleLoader后,就開始調用CatalystInstanceImpl去加載jsbundle了,CatalystInstance是Java,C,JavaScript三端通信的入口。

/* package */ void loadScriptFromFile(String fileName, String sourceURL, boolean loadSynchronously) {
    mSourceURL = sourceURL;
    jniLoadScriptFromFile(fileName, sourceURL, loadSynchronously);
  }

  private native void jniLoadScriptFromFile(String fileName, String sourceURL, boolean loadSynchronously);

可以看到最終加載jsbundle是在C里面完成的

Reload總流程

reload總的流程可以總結為:點擊reload -> DevSupportManagerImpl拼接URL,觸發(fā)下載 -> BundleDownloader請求服務器下載jsbundle -> 回調DevSupportManagerImpl -> 調用CatalystInstanceImpl通知C加載新的jsbundle

Debug JS Remotely

onKeyUp

先看看Debug JS Remotely的點擊事件,

options.put(
        remoteJsDebugMenuItemTitle,
        new DevOptionHandler() {
          @Override
          public void onOptionSelected() {
            mDevSettings.setRemoteJSDebugEnabled(!mDevSettings.isRemoteJSDebugEnabled());
            handleReloadJS();
          }
        });

先設置反了一下remote_js_debug這個key,使用SharedPreference存儲,然后就走到handleReloadJS方法里

handleReloadJS

if (mDevSettings.isRemoteJSDebugEnabled()) {
      PrinterHolder.getPrinter()
          .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Proxy");
      mDevLoadingViewController.showForRemoteJSEnabled();
      mDevLoadingViewVisible = true;
      reloadJSInProxyMode();
    } else {
      PrinterHolder.getPrinter()
          .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Server");
      String bundleURL =
        mDevServerHelper.getDevServerBundleURL(Assertions.assertNotNull(mJSAppBundleName));
      reloadJSFromServer(bundleURL);
    }

這里區(qū)分了debug js remotely模式與普通開發(fā)模式,主要看看reloadJSInProxyMode方法

private void reloadJSInProxyMode() {
    // When using js proxy, there is no need to fetch JS bundle as proxy executor will do that
    // anyway
    mDevServerHelper.launchJSDevtools();

    JavaJSExecutor.Factory factory = new JavaJSExecutor.Factory() {
      @Override
      public JavaJSExecutor create() throws Exception {
        WebsocketJavaScriptExecutor executor = new WebsocketJavaScriptExecutor();
        SimpleSettableFuture<Boolean> future = new SimpleSettableFuture<>();
        executor.connect(
            mDevServerHelper.getWebsocketProxyURL(),
            getExecutorConnectCallback(future));
        // TODO(t9349129) Don't use timeout
        try {
          future.get(90, TimeUnit.SECONDS);
          return executor;
        } catch (ExecutionException e) {
          throw (Exception) e.getCause();
        } catch (InterruptedException | TimeoutException e) {
          throw new RuntimeException(e);
        }
      }
    };
    mReactInstanceManagerHelper.onReloadWithJSDebugger(factory);
  }

先調用了launchJSDevtools方法,里面僅僅做了一個簡單的request,URL為
http://localhost:8081/launch-js-devtools,目的應該是打開調試網(wǎng)頁,然后實例化了一個實現(xiàn)JavaJSExecutor.Factory接口的匿名類,create方法會在調用recreateReactContextInBackground方法里的子線程中調用,跟進到connectInternal方法

private void connectInternal(
      String webSocketServerUrl,
      final JSExecutorConnectCallback callback) {
    final JSDebuggerWebSocketClient client = new JSDebuggerWebSocketClient();
    final Handler timeoutHandler = new Handler(Looper.getMainLooper());
    client.connect(
        webSocketServerUrl, new JSDebuggerWebSocketClient.JSDebuggerCallback() {
          // It's possible that both callbacks can fire on an error so make sure we only
          // dispatch results once to our callback.
          private boolean didSendResult = false;

          @Override
          public void onSuccess(@Nullable String response) {
            client.prepareJSRuntime(
                new JSDebuggerWebSocketClient.JSDebuggerCallback() {
                  @Override
                  public void onSuccess(@Nullable String response) {
                    timeoutHandler.removeCallbacksAndMessages(null);
                    mWebSocketClient = client;
                    if (!didSendResult) {
                      callback.onSuccess();
                      didSendResult = true;
                    }
                  }

                  @Override
                  public void onFailure(Throwable cause) {
                    timeoutHandler.removeCallbacksAndMessages(null);
                    if (!didSendResult) {
                      callback.onFailure(cause);
                      didSendResult = true;
                    }
                  }
                });
          }

          @Override
          public void onFailure(Throwable cause) {
            timeoutHandler.removeCallbacksAndMessages(null);
            if (!didSendResult) {
              callback.onFailure(cause);
              didSendResult = true;
            }
          }
        });
    timeoutHandler.postDelayed(
        new Runnable() {
          @Override
          public void run() {
            client.closeQuietly();
            callback.onFailure(
                new WebsocketExecutorTimeoutException(
                    "Timeout while connecting to remote debugger"));
          }
        },
        CONNECT_TIMEOUT_MS);
  }

這里使用了websocket與本地服務器進行連接,服務器URL為:
ws://localhost:8081/debugger-proxy?role=client,
繼續(xù)跟到JSDebuggerWebSocketClientconnect方法

public void connect(String url, JSDebuggerCallback callback) {
    if (mHttpClient != null) {
      throw new IllegalStateException("JSDebuggerWebSocketClient is already initialized.");
    }
    mConnectCallback = callback;
    mHttpClient = new OkHttpClient.Builder()
      .connectTimeout(10, TimeUnit.SECONDS)
      .writeTimeout(10, TimeUnit.SECONDS)
      .readTimeout(0, TimeUnit.MINUTES) // Disable timeouts for read
      .build();

    Request request = new Request.Builder().url(url).build();
    mHttpClient.newWebSocket(request, this);
  }

這里是使用okhttp來和本地服務器進行長連接,建立起連接后可以看到JSDebuggerWebSocketClientonMessage,sendMessage方法與服務器通信的邏輯。這里我們先回到reloadJSInProxyMode方法,跟到onReloadWithJSDebugger方法

private void onReloadWithJSDebugger(JavaJSExecutor.Factory jsExecutorFactory) {
    Log.d(ReactConstants.TAG, "ReactInstanceManager.onReloadWithJSDebugger()");
    recreateReactContextInBackground(
        new ProxyJavaScriptExecutor.Factory(jsExecutorFactory),
        JSBundleLoader.createRemoteDebuggerBundleLoader(
            mDevSupportManager.getJSBundleURLForRemoteDebugging(),
            mDevSupportManager.getSourceUrl()));
  }

這里邏輯與普通debug模式差不多,都是構造JSBundleLoaderJavaScriptExecutorFactory,跟到createRemoteDebuggerBundleLoader方法中

createRemoteDebuggerBundleLoader

/**
   * This loader is used when proxy debugging is enabled. In that case there is no point in fetching
   * the bundle from device as remote executor will have to do it anyway.
   */
  public static JSBundleLoader createRemoteDebuggerBundleLoader(
      final String proxySourceURL,
      final String realSourceURL) {
    return new JSBundleLoader() {
      @Override
      public String loadScript(CatalystInstanceImpl instance) {
        instance.setSourceURLs(realSourceURL, proxySourceURL);
        return realSourceURL;
      }
    };
  }

 /**
   * This API is used in situations where the JS bundle is being executed not on
   * the device, but on a host machine. In that case, we must provide two source
   * URLs for the JS bundle: One to be used on the device, and one to be used on
   * the remote debugging machine.
   *
   * @param deviceURL A source URL that is accessible from this device.
   * @param remoteURL A source URL that is accessible from the remote machine
   * executing the JS.
   */
  /* package */ void setSourceURLs(String deviceURL, String remoteURL) {
    mSourceURL = deviceURL;
    jniSetSourceURL(remoteURL);
  }

可以從注釋中看出,此時jsbundle也是從本地服務器下載的

跳出邏輯看看JSBundleLoader,暴露了四個方法

  • createAssetLoader 從asset目錄中創(chuàng)建loader
  • createFileLoader 從具體某個文件中創(chuàng)建loader
  • createCachedBundleFromNetworkLoader 從URL中加載
  • createRemoteDebuggerBundleLoader 同上

所以加載JSBundle可以歸類為以上三種方式

finally

開頭的問題是js層面的,好像跟我分析的Java層并沒什么卵關系。。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容