port.postMessage() : doesn't always work

Hi,

I am not an expert web/application developer, so please bear with me. I am trying, and trying, and trying , … to debug an addon that I wrote for Thunderbird 78.10.2. It sends message to a python backend and then reads the reply back:

async function buttonListener(tab) {

tabId = tab.id;

port = browser.runtime.connectNative("backendMyEd");

cD = await browser.compose.getComposeDetails(tab.id);

var body = extractBody(cD);

await port.postMessage(body);

port.onMessage.addListener(getReply);

}

The listener is just a python script that is doing:

def get_message():

if sys.version_info < (3, 0):

    len_field = sys.stdin.read(4)

else:

    len_field = sys.stdin.buffer.read(4)

if not len_field:

    sys.exit(0)

message_length = struct.unpack('=I', len_field)[0]

message = sys.stdin.read(message_length)  <=====

return json.loads(message)

This works sometimes but not always. When it doesn’t, my printfs tell me that it’s stuck in stdin read, but port.postMessage() has returned. If I quit TB or remove my add on, the sys.stdin.read() finishes.

Several things come to mind:

  1. Is there a flush needed after port.postMessage()? maybe its not flushing all the time?

  2. could it be related to message size? i tested with different sizes, and for less than 8k it often works. For larger ones, it seems to not work more often.

  3. Could there be some special characters in message causing this?

4. Something to do with JS being single threaded? But the function is async, and python should be a different process. I also tried doing a fork in python, still hangs off and on in sys.stdin.read()... 

Any ideas on whats going on, or how I could debug further?

Thanks

MR