Cross-language bridge error handling: JS-to-Java Example

All languages have certain semantics for dealing with error cases. C deals with them by setting error codes. Java deals with them by throwing exceptions. JavaScript deals with them by throwing exceptions as well but unlike Java, it does have any concept of checked Exceptions. The JS interpreter just stops. And this has some interesting implications in hybrid scenarios like a Webview based app.

Consider a simple Android app where most of the code is in JavaScript but is making a request to Java layer.

<html>
    <head/>
    <!-- Invoke getContacts() on the Javascript bridge object referenced via “JsInterface” tag on click -->
    <Button onClick='ContactJsInterface.getContacts()'>Click me</Button>
</html>
// MainActivity in Kotlin
class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
        ....
        // Load the above string into webview
        webView.loadDataWithBaseURL("about:blank", htmlPage, "text/html", null, null)
        webView.settings.javaScriptEnabled = true
        // Add a WebkitJsInterface object and tag it with "ContactJsInterface", so that,
        // JsInterface.getContacts maps to WebKitJsInterface.getContacts
        webView.addJavascriptInterface(WebkitJsInterface(this), "ContactJsInterface")
    }
}
// The Javascript interface object in Kotlin
class WebkitJsInterface(context: Context) {
    private val mContext = context

    // ContactJsInterface.getContacts() maps to this method
    @JavascriptInterface
    fun getContacts() {
        mContext.contentResolver.query(
            ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null)
    }
}

 

After starting the app, check that the READ_CONTACTS is revoked or revoke it with adbe

adbe permissions revoke net.ashishb.jstojavademo contacts

Now, when you click the “Click me” button, you will see a SecurityException in the logs but the app won’t crash. If you check Thread’s name via Thread.currentThread().name, it will return JavaBridge. It seems any Exception thrown on this thread is simply swallowed. This won’t show up in analytics or crash log reports. Your Javascript code on return simply won’t be executed. And your app will appear unusable. This is worse than crashes. crashes at least give the app a chance to get out of a bad state.

This is worse than crashes. crashes at least give the app a chance to get out of a bad state.

Remedy

Sending error information across languages is hard. At the bare minimum, every such call should be encapsulated with a try-catch which catches Exception. For severe unexpected errors, it might not be bad to let the app crash, as you would, while writing the Java code.

@JavascriptInterface
fun getContacts() {
    try {
        getContactsUnsafe()
    } catch (e : Exception) {
        if (isSevereException(e)) {
            rethrowOnMainThread(e)
        } else {
            logError(e)
        }
    }
}

private fun logError(e: Exception) {
    Log.e("WebkitJsInterface", "Error occurred", e)
}

private fun rethrowOnMainThread(e: Exception) {
    Handler(Looper.getMainLooper()).post { throw e }
}

private fun getContactsUnsafe() {
    mContext.contentResolver.query(
        ContactsContract.Contacts.CONTENT_URI,
        null, null, null, null
    )
}

 

Full code for this blog post is posted on Github

Testing resumable uploads

The core idea behind resumable upload is straightforward if you are uploading a big file, then you are going to encounter users in the network conditions where they cannot upload the file in a single network session. The client-side code, to avoid restarting the file upload from the beginning, must figure out what portion of the file was uploaded and “resume” the upload of the rest.

How to do resumable upload

Before starting the upload, send a unique ID generated from the file contents to the server like MD-5 or SHA-256. The server decides and declares what the format of that unique ID is. Next, the server responds with an offset which indicates how many bytes server already has. The client uploads rest of the bytes with a Content-Range header.

How to test resumable upload

The right way to verify that this code works is to break the upload intentionally and randomly in the middle and check that the next upload session does not start from zero. Note that, it might not start from the exact byte offset where it was disconnected since the client network stack can have its buffer size to fill and it might discard the buffered bytes in case of an exception.  Therefore, the ratio of the number of bytes read to the file size should be close to one but might not be one.

The right way to verify that this code works is to break the upload intentionally and randomly in the middle and check that the next upload session does not start from zero.

Sample skeleton codes

// SHA-256 or MD-5 whatever the server decides
String uniqueId = generateUniqueId(File file);
// Number of already uploaded bytes (could be zero)
int alreadyUploaded = getAlreadyUploadedByteCount(uniqueId);
// Upload rest of the bytes
upload(file, uniqueId, alreadyUploaded);

boolean upload(File file, String uniqueId, int alreadyUploaded)
 throws IOException {
  InputStream in = getInputStream(file);
  uploadViaHttp(file, uniqueId, alreadyUploaded);
}
int readCount;

boolean upload(File file, String uniqueId, int alreadyUploaded) 
throws IOException {
  InputStream in = getInputStream(file);
  readCount = 0;  // Testing only
  uploadViaHttp(in, uniqueId, alreadyUploaded);
  double ratio = ((double)readCount)/file.size();  // Testing only
}


// Standard method
InputStream getInputStream(File file) throws IOException {
    return new FileInputStream(file);
}

// Enhanced method for testing
InputStream getInputStream(File file) throws IOException {
    return new FileInputStream(file) {
        int read(byte[] b, int off, int len) throws IOException {
            if (random.nextBoolean()) {
                throw new IOException("Intentionally broke the stream");
            }
            int tmp = super.read(b, 0, b.length());
            readCount += tmp;
            return tmp;
        }

        int read(byte[] b) throws IOException {
            return read(b, 0, b.length);
        }

        int read() throws IOException {
            readCount++;
            return super.read();
        }
    }
}

 

How to speed up HTML5 videos

Some video streaming websites like YouTube provides an option for speeding up/slowing down videos; some don’t. The trick is simple, find out the Video object via

document.querySelector("video")

and then set its playbackRate property to the desired value

document.querySelector("video").playbackRate = 2.0;   // For 2X speed-up

These changes have to be made in the Developer console in Chrome or Browser console in Firefox.

Introducing adb-enhanced: A swiss army knife for Android development

Android development requires tons of disconnected approaches for the development and testing. Consider some scenarios

  1. To test runtime permission – Go to Settings -> Applications -> Application info of the app you are looking for and disable that permission.
  2. To test a fresh install – adb shell pm clear-data com.example
  3. To test your app under the battery saver mode – turn on the battery saver mode by expanding the notification bar
  4. To stop the execution of an app –  kill it via activity manager, adb shell am kill com.example
  5. To test your app under doze mode – first, make the device believe that it is unplugged via “adb shell dumpsys battery unplug”, then, make it think that it is discharging via “adb shell dumpsys battery set status 3”, and then enable doze mode via “adb shell dumpsys deviceidle force-idle”. And don’t forget to execute a set of unrelated complementary commands once you are done to bring the device back to the normal state.
  6. To see the overdraw of the app – Go to the developer options and enable/disable it there.
Over time, this became a significant mental burden that I first wrote some of these flows in a text file and then converted them to automated shell scripts. But when even that felt insufficient, I created a tool for myself called adb-enhanced.
How it works:
First, install the tool. I wrote this in Python, so, if the following command does not work, install Python
pip3 install adb-enhanced # Use "pip" for python2. Both are supported.

Now, let’s look at the about use-cases again with this tool:

  1. To test a runtime permission :
    # Use grant instead of revoke to grant the permission
    adbe permission revoke com.example camera  # See all possible such permissions via "adbe -h"
  2. To test a fresh install –
    # Unlike adb shell pm clear-data com.example, this command will 
    # produce an error if com.example is not installed 
    # which is good for catching typos
    adbe clear-data com.example
  3. To test your app under the battery saver mode –
    # As you would guess, use "off" to turn the battery saver off
    adbe battery saver on
  4. To stop the execution of an app –
    # For a more aggressive kill, try adbe force-stop com.example
    adbe stop com.example
  5. To test your app under doze mode
    adbe doze on # Use "off" to turn the doze mode off
  6. To see the overdraw of the app
    adbe overdraw on
I open-sourced the code at https://github.com/ashishb/adb-enhanced. See the GitHub repository for what all this tool can do. Feedbacks and pull requests are welcome.

Swift, Kotlin, and Go

It is impressive to see the amount of similarity which exists in Swift, Kotlin and Go, the three new languages for iOS, Android, and server-development respectively.

Consider a simple, Hello World program.

Swift

func printHello() {
  // Type automatically inferred to string
  let name = "Ashish" // let declares a read-only variable
  print("Hello world from \(name)!")
}

Kotlin

fun printHello() {
  // Type automatically inferred to string
  val name = "Ashish"  // val declares a read-only value, var declares a read-write variable
  println("Hello world from ${name}")
}

Go

import fmt

func printHello() {
  // Type automatically inferred to string
  const name = "ashish"  // const declares a constant value
  fmt.Printf("Hello world from %s", name);
}

 

Server vs mobile development: Where the code runs matter

When the code runs on your servers, you have much more control over the “context” in which it runs. On the mobile devices, the device OS and the user control the context. This difference leads to some subtle implications.

One significant set of differences comes from the lack of control of the platform. For server-side code, one can choose from a wide array of languages. For the mobile code, however, the best choice would almost always be the one dictated by the platform – Java/Kotlin on Android and  Objective-C/Swift on iOS. Further, for the server-side where one can stick to a particular version of the language. In the case of mobile, the platform controls the language version. Same goes regarding the hardware choices – one can choose to use different types of server machines specialized in handling those jobs, eg. GPUs for math-intensive computes. While for the mobile-code, one had to write a good enough fallback to support a wide-enough set the devices. Similarly, the server-side has to rarely worry about the server killing a running process while it is normal for mobile OSes to kill backgrounded processes eventually.

The other set of differences comes from the temporary changes to the platform introduced by the carrier and the user. A network request running on mobile has to be robust enough to deal with intermittent broken connectivity to outright unavailability of a data connection, e.g., due to the user switching to the airplane mode. On mobile, network type matters as well. A network request on cellular would usually cost more than a network request on Wi-Fi to the user and a network request on roaming even more. On mobile, the code has to be aware of not doing unnecessary work when the user is low on battery. Server-side code is rarely subjected to such constraints.

Lastly, it is possible to parallelize and speed up the server-side code by adding more resources like RAM or better CPUs. If a certain number of servers are not enough, you can add more. There isn’t usually a way to offload compute-intensive or memory-intensive work off of the mobile devices without trading it off for network latency and sometimes, user’s privacy as well. While it might be preferable to go with a multi-processing approach in the server code to avoid concurrency issues, on the mobile, however, multi-threading being more straightforward and less resource-intensive is almost always the choice.

Google I/O 2018: Android Notes

Highlights

  1. All android support library code is moving to androidx namespace. No more android.support.v4 or android.support.v7 namespaces.
  2. Android app bundle to split the app into downloadable modules
  3. Navigation library to set up navigation between different activities/fragments.
  4. Use WorkMananger for background work – this is an improvement to JobScheduler
  5. Major improvements to Android Studio. Most standalone tools deprecated in favor of adding the same functionality into Android Studio.
  6. Major improvements to Android Vitals which in Google Play to learn more about what’s going on with Android app’s performance.
  7. Android P does more profiling to improve code locality for faster execution.

Modern Android Development

  1. hierarchy viewer replaced by ViewTree in Android Studio
  2. TraceView replaced by Systrace in Android Studio
  3. Profiler (DDMS) replaced by Android Profiler in Android Studio
  4. Dalvik replaced by ART
  5. Java replaced by Kotlin as preferred language
  6. Layouts
    1. Absolute Layout – deprecated
    2. Linear Layout – still OK
    3. Frame Layout – still OK
    4. Grid Layout – discouraged
    5. Relative Layout – discouraged
    6. ConstraintLayout – recommended
  7. ListView, GridView, and Gallery are deprecated. RecyclerView is recommended with ListAdapter for updations.
  8. Platform Fragments (android.app.fragments) are deprecated. Support library fragments recommended.
  9. Single activity app recommended
  10. Rather than managing activity lifecycle use Lifecycle to observe state changes
  11. Rather than keeping plain data with views, use LiveData to update views automatically. Use ViewModel to deal with screen rotation.
  12. Room is recommended in place of SQLite
  13. CursorAdapter and AsyncListUtil are discouraged. Use Paging instead with a neat, graceful offline use-case handling trick.
  14. Don’t do manual bitmap management. Use Glide, Picasso, or Lottie instead.
  15. Between TextureView and SurfaceView, use SurfaceView.
  16. Nine-patches are discouraged. Use Vector Drawables.
  17. Use FusedLocationProviderClient for fetching device location. Wi-Fi access triangulation is coming to Android P. FusedLocationProvider will eventually add support for that for indoor location tracking.
  18. MediaPlayer is discouraged, use ExoPlayer instead. A detailed hands-on presentation on ExoPlayer

Performance

  1. 42% 1-star reviews mention crashes/bugs
  2. ANR/crash rate reduces engagement – use StrictMode to catch them early
  3. Avoid IPC on the main thread, StrictMode won’t catch the violation, and you would never know what’s happening on the other side of the IPC call which can block the main thread
  4. If BroadcastReceiver#onReceive is going to take more than 10 seconds, then call goAsync for background processing and call PendingResult#onFinish() once that’s finished
  5. WakeLocks – avoid using them. All except PARTIAL_WAKE_LOCK are deprecated with Android P.
    1. Use FLAG_KEEP_SCREEN_ON for keeping the screen on in an activity
    2. Use WorkMananger for background work
    3. Use AlarmManager for short interval callbacks
  6. enums are not discouraged anymore. Platform code avoids it but unlike in prior Android versions, the penalty for enums is low now.
  7. A good introduction to Android’s display rendering
  8. A good introduction to Android’s text handling
  9. Text handling issues
    1. Only framework spans can be parceled, don’t mix custom spans with framework spans since only the frameworks will be part of the copied text
    2. After ~250 spans or more, SpannableStringBuilder ends up being more performant than SpannableString since the former internally uses trees.
    3. Metrics affecting spans cause measure-layout-draw calls, while appearance affecting spans cause layout-draw calls, therefore, the former is more expensive.
    4. Text measurement takes a lot of time on the UI thread, consider creating PrecomputedText on the background thread.
    5. android:autoLink = true works via RegEx and has bad performance. Consider using Linkify on the background thread. Android P also supports deep learning based TextClassifier which is also invoked on the background thread.
  10. Testing your app for background restriction – adb shell appops set <package name> RUN_ANY_IN_BACKGROUND ignore # applies background restriction (change “ignore” to “allow” to remove restriction)

Next Billion Users

  1. 28% searches in India are voice searches
  2. 2-wheeler mode added to Google Maps
  3. Google Tez uses Ultrasound for pairing and sending money to the nearby receiver
  4. Files Go – Folder based hierarchy won’t work for users who have never had PC before. Therefore, shows photos based on associations like “WhatsApp Images” or “Camera”. Supports P2P file sharing for fast transfers.
  5. Design for next billion users – http://design.google/nbu
  6. Android Go
    1. 25% devices in 2018 shipped with <= 1GB RAM (target for Android Go)
    2. Every 6 MB app size reduces install rate by 1%
    3. India – largest market for Go. The USA – second largest market for Go.
    4. 5 seconds cold start goal
    5. Users opt for smaller apk size with a lower rating.
    6. Average apk size is 30 MB. Go recommends 40MB max app size for non-game and 65MB for game apps.

MLKit

  1. On-device + cloud APIs. On device APIs are free.
  2. Firebase support to download model and even do A/B testing.
  3. Experimental support to convert TensorFlow models to TensorFlow Lite models.

Compiler

  1. D8 – new Dexer, now default. Enable/disable via “android.enableD8 = true/false”
  2. R8 – new optimizer, now default replacing proguard, still opt-in in 3.2. Enable via android.enableR8 = true

Kotlin – talk can be here

  1. Use properties in lieu of default getters/setters
  2. Use data classes to generate equals, hash method etc.
  3. Use default args instead of method overloading
  4. Use top-level functions as well as local functions (function inside functions for better encapsulation
  5.  Use function extensions to make the code more readable, eg. extend String class with isDigit to be able to later write the code like “1234”.isDigit
  6. Use smart casts
  7. Use sealed classes for a superclass which should not be extendable beyond the compile-time
  8. Use string interpolation in println, eg. println(“name is ${name}”)
  9. Use val (read-only values) by default, only use var (read-write variable) when there is a strong reason
  10. Declare lambda functions as inline to remove the cost of having an extra class
  11. Use co-routines via async instead of creating new threads
  12. Use suspend + async to convert callbacks into more readable synchronously written code

Diagnosing Mac apps which won’t open (error -10810)

Occasionally, my mac applications end up in a corrupt state where they won’t open. I recently encountered this with Deluge. The first step to diagnose is to open Terminal and open them in the terminal via

$ open -a deluge  # This name is same as the name of the app (minus the ".app" portion).
LSOpenURLsWithRole() failed for the application /usr/local/Caskroom/deluge/1.3.12/Deluge.app with error -10810.

Now, the error is more diagnosable but still cryptic. Deluge.app above is a directory and we can navigate to the binary located at Deluge.app/Contents/MacOS/Deluge and execute the actual binary to see a more actionable error

$ /usr/local/Caskroom/deluge/1.3.12/Deluge.app/Contents/MacOS/Deluge
Traceback (most recent call last):
  File "/usr/local/Caskroom/deluge/1.3.12/Deluge.app/Contents/MacOS/Deluge-bin", line 5, in <module>
    from pkg_resources import load_entry_point
  File "pkg_resources/__init__.pyc", line 37, in <module>
  File "email/parser.pyc", line 12, in <module>
  File "email/feedparser.pyc", line 27, in <module>
  File "email/message.pyc", line 16, in <module>
  File "email/charset.pyc", line 13, in <module>
  File "email/base64mime.pyc", line 40, in <module>
  File "email/utils.pyc", line 29, in <module>
  File "urllib.pyc", line 1414, in <module>

ImportError: dlopen(/usr/local/Caskroom/deluge/1.3.12/Deluge.app/Contents/Resources/lib/python/lib-dynload/_scproxy.so, 2): Symbol not found: _inflateValidate
  Referenced from: /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libPng.dylib
  Expected in: /usr/local/Caskroom/deluge/1.3.12/Deluge.app/Contents/Resources/lib/libz.1.dylib
 in /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libPng.dylib

Now, this is something meaningful and Google search worthy. Googling for “Symbol not found: _inflateValidate” takes us to the most likely cause. In my case, uninstall followed by the reinstall of Deluge fixed it.

Java Musings – initializing a final variable with an uninitialized final variable

Java has fewer quirks compared to C++, but sometimes I do come across surprises.
A code like following will fail to compile since you are trying to initialize a variable with an uninitialized variable.

public class Sample {

  private final String mField1;
  private final String mField2 = mField1 + " two";

  private Sample(String field1) {
    mField1 = field1;
  }
}

But if instead of directly referencing mField1, you reference indirectly via a getter method code will compile, and mField2 will get “null” value for mField1.

public class Sample {

  private final String mField1;
  private final String mField2 = getField1() + " two";

  private Sample(String field1) {
    mField1 = field1;
  }

  private String getField1() {
    return mField1;
  }

  private String getField2() {
    return mField2;
  }

  public static void main (String[] args) {
    Sample sample = new Sample("one");
    // prints "Field 1 is one"
    System.out.println("Field 1 is " + sample.getField1());
    // prints "Field 2 is null two"!!!
    System.out.println("Field 2 is " + sample.getField2());
  }
}
-->