Skip to content

Commit

Permalink
Added new example HelloWorldComChannelEndpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
kaisalmen committed Oct 1, 2024
1 parent 996fd71 commit c81982c
Show file tree
Hide file tree
Showing 13 changed files with 146 additions and 6 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"name": "Chrome",
"url": "http://localhost:23001",
"webRoot": "${workspaceFolder}",
"userDataDir": "${workspaceFolder}/.vscode/profile"
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 3.1.0 - 2024-10-01

- ComChannelEndpoint has been extracted from WorkerTask
- Now Worker, MessageChannel or DedicatedWorkerGlobalScope can be channel endpoints. Both ends of the communication channel can use the same implementation to send message and await responses if needed.
- Added new example **HelloWorldComChannelEndpoint**

## 3.0.0 - 2024-01-05

- Make the worker lifecylce no longer mandatory if not using `WorkerTaskDirector`.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Build applications with workers with less boiler plate code.
There are multiple examples available demonstarting the features described above (listed from simpler to more advanced):

- Using [wtd-core](https://www.npmjs.com/package/wtd-core) only:
- **ComChannelEndpoint: Hello World**: [html](https://github.com/kaisalmen/wtd/blob/main/packages/examples/helloWorldComChannelEndpoint.html), [ts](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/helloWorld/HelloWorldComChannelEndpoint.ts), [worker](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/worker/HelloWorldComChannelEndpointWorker.ts)
- **WorkerTask: Hello World**: [html](https://github.com/kaisalmen/wtd/blob/main/packages/examples/helloWorldWorkerTask.html), [ts](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/helloWorld/HelloWorldWorkerTask.ts), [worker](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/worker/HelloWorldWorker.ts)
- **WorkerTaskDirector: Hello World**: [html](https://github.com/kaisalmen/wtd/blob/main/packages/examples/helloWorldWorkerTaskDirector.html), [ts](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/helloWorld/helloWorldWorkerTaskDirector.ts), [worker](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/worker/HelloWorldWorker.ts)
- **WorkerTask: Inter-Worker Communication**: [html](https://github.com/kaisalmen/wtd/blob/main/packages/examples/workerCom.html), [ts](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/com/WorkerCom.ts), **Worker**: [1](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/worker/Com1Worker.ts) and [2](https://github.com/kaisalmen/wtd/blob/main/packages/examples/src/worker/Com2Worker.ts)
Expand Down
2 changes: 2 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
<div style="padding: 5px">
<h1>Examples</h1>

<a href="packages/examples/helloWorldComChannelEndpoint.html">ComChannelEndpoint: Hello World</a>
<br>
<a href="packages/examples/helloWorldWorkerTask.html">WorkerTask: Hello World</a>
<br>
<a href="packages/examples/helloWorldWorkerTaskDirector.html">WorkerTaskDirector: Hello World</a>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import path from 'path';
import { defineConfig } from 'vite';

const config = defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, '../src/worker/HelloWorldComChannelEndpointWorker.ts'),
name: 'HelloWorldComChannelEndpointWorker',
fileName: (format) => `HelloWorldComChannelEndpointWorker-${format}.js`,
formats: ['es', 'iife']
},
outDir: 'src/worker/generated',
emptyOutDir: false
}
});

export default config;
15 changes: 15 additions & 0 deletions packages/examples/helloWorldComChannelEndpoint.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>ComChannelEndpoint: Hello World</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="./main.css">
</head>

<body>
<canvas id="example" style="width: 100%; height: 100vh;"></canvas>
<div id="info">ComChannelEndpoint: Hello World</div>
<script type="module" src="./src/helloWorld/HelloWorldComChannelEndpoint.ts"></script>
</body>
</html>
3 changes: 3 additions & 0 deletions packages/examples/scripts/buildWorker.mts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import shell from 'shelljs';
shell.rm('-f', './src/worker/generated/HelloWorldWorker*.js');
shell.exec('vite -c build/vite.config.HelloWorldWorker.ts build');

shell.rm('-f', './src/worker/generated/HelloWorldComChannelEndpointWorker*.js');
shell.exec('vite -c build/vite.config.HelloWorldComChannelEndpointWorker.ts build');

shell.rm('-f', './src/worker/generated/Com1Worker*.js');
shell.exec('vite -c build/vite.config.Com1Worker.ts build');

Expand Down
47 changes: 47 additions & 0 deletions packages/examples/src/helloWorld/HelloWorldComChannelEndpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { WorkerMessage, ComChannelEndpoint, RawPayload } from 'wtd-core';

/**
* Hello World example just using the ComChannelEndpoint
*/
class HelloWorldComChannelEndpointExample {

async run() {
const url = new URL(import.meta.env.DEV ? '../worker/HelloWorldComChannelEndpointWorker.ts' : '../worker/generated/HelloWorldComChannelEndpointWorker-es.js', import.meta.url);
const endpoint = new ComChannelEndpoint({
endpointName: 'HelloWorldWorker',
endpointId: 1,
endpointConfig: {
$type: 'WorkerConfigParams',
url,
workerType: 'module',
},
verbose: true
});
endpoint.connect();

try {
const t0 = performance.now();

const result = await endpoint.sentMessage({
message: WorkerMessage.createNew({
cmd: 'hello_world'
}),
awaitAnswer: true,
answer: 'hello_world_confirm'
},);

const rawPayload = result.payloads[0] as RawPayload;
const answer = `Worker said: command: ${result.cmd} message: ${rawPayload.message.raw?.hello}`;
const t1 = performance.now();

const msg = `${answer}\nWorker execution has been completed after ${t1 - t0}ms.`;
console.log(msg);
alert(msg);
} catch (e) {
console.error(e);
}
}
}

const app = new HelloWorldComChannelEndpointExample();
app.run();
41 changes: 41 additions & 0 deletions packages/examples/src/worker/HelloWorldComChannelEndpointWorker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { RawPayload, WorkerMessage, ComRouter, ComChannelEndpoint } from 'wtd-core';

/// <reference lib="WebWorker" />

declare const self: DedicatedWorkerGlobalScope;

class ExampleComRouterWorker implements ComRouter {

private endpointFs?: ComChannelEndpoint;

setComChannelEndpoint(comChannelEndpoint: ComChannelEndpoint): void {
this.endpointFs = comChannelEndpoint;
}

async hello_world(message: WorkerMessage) {
// burn some time
for (let i = 0; i < 25000000; i++) {
i++;
}

await this.endpointFs?.sentAnswer({
message: WorkerMessage.createFromExisting(message, {
overrideCmd: 'hello_world_confirm',
overridePayloads: new RawPayload({
hello: 'Hello! I just incremented "i" 25 million times.'
})
}),
awaitAnswer: false
});
}
}

new ComChannelEndpoint({
endpointId: 2000,
endpointConfig: {
$type: 'WorkerConfigDirect',
worker: self
},
verbose: true,
endpointName: 'HelloWorldComChannelEndpointWorker'
}).connect(new ExampleComRouterWorker());
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ class InfiniteWorkerExternalGeometry implements WorkerTaskWorker {
private bufferGeometry?: BufferGeometry = undefined;

init(message: WorkerMessage) {
const wtm = WorkerMessage.unpack(message, false);
if (wtm.payloads.length > 0) {
this.bufferGeometry = (wtm.payloads[0] as MeshPayload).message.bufferGeometry as BufferGeometry;
const wm = WorkerMessage.unpack(message, false);
if (wm.payloads.length > 0) {
this.bufferGeometry = (wm.payloads[0] as MeshPayload).message.bufferGeometry as BufferGeometry;
}

const initComplete = WorkerMessage.createFromExisting(message, {
Expand Down
5 changes: 5 additions & 0 deletions packages/wtd-core/src/ComChannelEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ export class ComChannelEndpoint {
});
}

sentAnswer(def: WorkerMessageDef): Promise<WorkerMessage> {
def.message.answer = true;
return this.sentMessage(def);
}

protected updateAwaitHandlers(wm: WorkerMessage, awaitHandlers: AwaitHandler[]) {
wm.endpointdId = this.endpointId;
wm.uuid = this.buildUuid();
Expand Down
3 changes: 3 additions & 0 deletions packages/wtd-core/src/WorkerMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export class WorkerMessage {
static createFromExisting(message: WorkerMessage, options?: {
overrideCmd?: WorkerCommand,
overrideUuid?: string,
overridePayloads?: Payload | Payload[],
answer?: boolean
}) {
const wm = WorkerMessage.createNew(message);
Expand All @@ -59,6 +60,8 @@ export class WorkerMessage {
if (options?.answer !== undefined) {
wm.answer = options.answer;
}
wm.addPayload(options?.overridePayloads);

return wm;
}

Expand Down
4 changes: 2 additions & 2 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ export default defineConfig(({ command }) => {
rollupOptions: {
input: {
main: path.resolve(__dirname, 'index.html'),
helloWorld: path.resolve(__dirname, 'packages/examples/helloWorld.html'),
helloWorldStandard: path.resolve(__dirname, 'packages/examples/helloWorldStandard.html'),
helloWorldWorkerTask: path.resolve(__dirname, 'packages/examples/helloWorldWorkerTask.html'),
helloWorldComChannelEndpoint: path.resolve(__dirname, 'packages/examples/helloWorldComChannelEndpoint.html'),
helloWorldWorkerTaskDirector: path.resolve(__dirname, 'packages/examples/helloWorldWorkerTaskDirector.html'),
transferables: path.resolve(__dirname, 'packages/examples/transferables.html'),
threejs: path.resolve(__dirname, 'packages/examples/threejs.html'),
potentiallyInfinite: path.resolve(__dirname, 'packages/examples/potentially_infinite.html')
Expand Down

0 comments on commit c81982c

Please sign in to comment.