Skip to content

State handler listen triggered multiple times #38

@christian-bromann

Description

@christian-bromann

Given you update the examples/worker_threads.js to:

import { URL } from 'url';
import { Worker, isMainThread, workerData } from 'worker_threads';
import Channel from '../dist/esm/worker_threads.js';

const filename = new URL('', import.meta.url).pathname;

const ch = new Channel('test', {});

if (isMainThread) {
    console.log(Date.now(), 'START MAIN THREAD');
    const bus = await ch.registerPromise([
        new Worker(filename, { workerData: { id: 'worker #1' } }),
        // new Worker(filename, { workerData: { id: 'worker #2' } }),
        // new Worker(filename, { workerData: { id: 'worker #3' } })
    ]);

    bus.listen('onCustomEvent', (msg) =>
        console.log(Date.now(), 'Received from worker thread:', msg));

    // bus.listen('onExit', (e) => {
    //     console.log(Date.now(), 'Bye bye');
    //     ch.providers.map((p) => p.terminate());
    // });

    setTimeout(() => bus.broadcast({ onCustomWorkerEvent: 'worker #3' }), 100);
} else {
    console.log(Date.now(), 'START WORKER THREAD', workerData.id);
    const client = ch.attach();

    /**
     * listen to events within the same sandbox
     */
    client.listen('onCustomEvent', (msg) =>
        console.log(Date.now(), `Another worker message received in ${workerData.id}; ${msg}`));

    /**
     * broadcast to all
     */
    // await new Promise((r) => setTimeout(r, 200))
    client.broadcast({ onCustomEvent: `Hello from ${workerData.id} 👋` });

    // /**
    //  * listen to messages from message bus
    //  */
    // client.listen('onCustomWorkerEvent', (id) => {
    //     if (workerData.id === id) {
    //         console.log(Date.now(), 'EMIT');
    //         client.broadcast({ 'onExit': workerData.id });
    //     }
    // });
}

You will receive the following output:

1657291971292 START MAIN THREAD
1657291971299 Received from worker thread: undefined
1657291971330 START WORKER THREAD worker #1
1657291971333 Received from worker thread: Hello from worker #1 👋
1657291971333 Another worker message received in worker #1; Hello from worker #1 👋
1657291971400 Received from worker thread: Hello from worker #1 👋
1657291971400 Another worker message received in worker #1; Hello from worker #1 👋

Which is not one I would expect. As you can see:

Received from worker thread: Hello from worker #1 👋
Another worker message received in worker #1; Hello from worker #1 👋

is printed twice even though the event is just emitted once. Commenting out this line:

setTimeout(() => bus.broadcast({ onCustomWorkerEvent: 'worker #3' }), 100);

Gives the expected result. So it seems that events are not filtered properly.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions