@uns-kit/temporal 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Aljoša Vister
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # @uns-kit/temporal
2
+
3
+ `@uns-kit/temporal` bridges Temporal.io workflows into the Unified Namespace. The plugin registers a `createTemporalProxy` method on `UnsProxyProcess`, tracks workflow metadata, and republishes workflow results via UNS topics.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @uns-kit/temporal
9
+ # or
10
+ npm install @uns-kit/temporal
11
+ ```
12
+
13
+ Install `@uns-kit/core` as well—the plugin augments its runtime.
14
+
15
+ ## Example
16
+
17
+ ```ts
18
+ import UnsProxyProcess from "@uns-kit/core/uns/uns-proxy-process";
19
+ import unsTemporalPlugin, { type UnsProxyProcessWithTemporal } from "@uns-kit/temporal";
20
+
21
+ const process = new UnsProxyProcess("mqtt-broker:1883", { processName: "temporal-demo" }) as UnsProxyProcessWithTemporal;
22
+ unsTemporalPlugin;
23
+
24
+ const temporal = await process.createTemporalProxy("hv-etl", "temporal:7233", "hv-namespace");
25
+ await temporal.initializeTemporalProxy({
26
+ topic: "factory/",
27
+ attribute: "hv-status",
28
+ attributeType: UnsAttributeType.Data,
29
+ });
30
+
31
+ await temporal.startWorkflow("TransformHvSclData", { coil_id: "42" }, "ETL_HV_SCL_TASK_QUEUE");
32
+ ```
33
+
34
+ ## Scripts
35
+
36
+ ```bash
37
+ pnpm run typecheck
38
+ pnpm run build
39
+ ```
40
+
41
+ ## License
42
+
43
+ MIT © Aljoša Vister
@@ -0,0 +1,3 @@
1
+ export { default } from "./uns-temporal-plugin.js";
2
+ export { UnsTemporalProxy, type UnsProxyProcessWithTemporal } from "./uns-temporal-plugin.js";
3
+ export * from "./temporal-interfaces.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { default } from "./uns-temporal-plugin.js";
2
+ export { UnsTemporalProxy } from "./uns-temporal-plugin.js";
3
+ export * from "./temporal-interfaces.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Change this file according to your specifications and rename it to index.ts
3
+ */
4
+ import UnsProxyProcess from "@uns-kit/core/uns/uns-proxy-process";
5
+ import unsTemporalPlugin from "./uns-temporal-plugin";
6
+ import { ConfigFile } from "@uns-kit/core/config-file";
7
+ import { UnsAttributeType } from "@uns-kit/core/graphql/schema";
8
+ import logger from "@uns-kit/core/logger";
9
+ /**
10
+ * Load the configuration from a file.
11
+ * On the server, this file is provided by the `uns-datahub-controller`.
12
+ * In the development environment, you are responsible for creating and maintaining this file and its contents.
13
+ */
14
+ const config = await ConfigFile.loadConfig();
15
+ /**
16
+ * Connect to the temporal and register uns topic for temporal
17
+ */
18
+ const unsProxyProcess = new UnsProxyProcess(config.infra.host, { processName: config.uns.processName });
19
+ unsTemporalPlugin;
20
+ const temporalTopic = {
21
+ attribute: "temporal-data",
22
+ topic: "sij/",
23
+ attributeType: UnsAttributeType.Data,
24
+ attributeNeedsPersistence: true,
25
+ dataGroup: "temporal",
26
+ description: "Temporal data example",
27
+ tags: ["temporal"],
28
+ };
29
+ const temporalProxy = await unsProxyProcess.createTemporalProxy("templateUnsTemporal", "temporal-1.sij.digital:7233", "hv");
30
+ await temporalProxy.initializeTemporalProxy(temporalTopic);
31
+ // Start temporal workflow
32
+ const result = await temporalProxy.startWorkflow("TransformHvSclData", { 'coil_id': "42" }, "ETL_HV_SCL_TASK_QUEUE");
33
+ logger.info(`Workflow result: ${JSON.stringify(result)}`);
@@ -0,0 +1,10 @@
1
+ import { UnsAttributeType } from "@uns-kit/core/graphql/schema";
2
+ export interface ITemporalTopic {
3
+ attribute: string;
4
+ topic: string;
5
+ attributeType: UnsAttributeType;
6
+ attributeNeedsPersistence?: boolean | undefined;
7
+ dataGroup?: string | undefined;
8
+ description?: string | undefined;
9
+ tags?: string[] | undefined;
10
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { ClientOptions, ConnectionOptions } from "@temporalio/client";
2
+ import UnsProxyProcess, { type UnsProxyProcessPlugin } from "@uns-kit/core/uns/uns-proxy-process";
3
+ import UnsTemporalProxy from "./uns-temporal-proxy.js";
4
+ declare const unsTemporalPlugin: UnsProxyProcessPlugin;
5
+ export default unsTemporalPlugin;
6
+ export { UnsTemporalProxy };
7
+ export type UnsProxyProcessWithTemporal = UnsProxyProcess & {
8
+ createTemporalProxy(instanceName: string, temporalAddress: string, temporalNamespace: string, connectionOverrides?: ConnectionOptions, clientOverrides?: ClientOptions): Promise<UnsTemporalProxy>;
9
+ };
@@ -0,0 +1,40 @@
1
+ import UnsProxyProcess from "@uns-kit/core/uns/uns-proxy-process";
2
+ import UnsTemporalProxy from "./uns-temporal-proxy.js";
3
+ const temporalProxyRegistry = new WeakMap();
4
+ const getTemporalProxies = (instance) => {
5
+ let proxies = temporalProxyRegistry.get(instance);
6
+ if (!proxies) {
7
+ proxies = [];
8
+ temporalProxyRegistry.set(instance, proxies);
9
+ }
10
+ return proxies;
11
+ };
12
+ const unsTemporalPlugin = ({ define }) => {
13
+ define({
14
+ async createTemporalProxy(instanceName, temporalAddress, temporalNamespace, connectionOverrides, clientOverrides) {
15
+ await this.waitForProcessConnection();
16
+ const internals = this;
17
+ const connectionOptions = {
18
+ address: temporalAddress,
19
+ ...connectionOverrides,
20
+ };
21
+ const clientOptions = {
22
+ namespace: temporalNamespace,
23
+ ...clientOverrides,
24
+ };
25
+ const unsTemporalProxy = new UnsTemporalProxy(internals.processName, instanceName, connectionOptions, clientOptions);
26
+ unsTemporalProxy.event.on("unsProxyProducedTopics", (event) => {
27
+ internals.processMqttProxy.publish(event.statusTopic, JSON.stringify(event.producedTopics), {
28
+ retain: true,
29
+ properties: { messageExpiryInterval: 120000 },
30
+ });
31
+ });
32
+ internals.unsTemporalProxies.push(unsTemporalProxy);
33
+ getTemporalProxies(this).push(unsTemporalProxy);
34
+ return unsTemporalProxy;
35
+ },
36
+ });
37
+ };
38
+ UnsProxyProcess.use(unsTemporalPlugin);
39
+ export default unsTemporalPlugin;
40
+ export { UnsTemporalProxy };
@@ -0,0 +1,27 @@
1
+ import UnsProxy from "@uns-kit/core/uns/uns-proxy";
2
+ import { ConnectionOptions, ClientOptions, Workflow } from '@temporalio/client';
3
+ import { ITemporalTopic } from "./temporal-interfaces.js";
4
+ export default class UnsTemporalProxy extends UnsProxy {
5
+ instanceName: string;
6
+ protected processStatusTopic: string;
7
+ private topicBuilder;
8
+ private processName;
9
+ private connectionOptions;
10
+ private clientOptions;
11
+ private client;
12
+ private unsTopic;
13
+ constructor(processName: string, instanceName: string, connectionOptions: ConnectionOptions, clientOptions: ClientOptions);
14
+ /**
15
+ * Initializes the Temporal proxy by registering the given topic and establishing a client connection.
16
+ * @param unsTopic - The topic object to register with Temporal.
17
+ * @returns A promise that resolves when initialization is complete.
18
+ * @throws If the Temporal client fails to initialize.
19
+ */
20
+ initializeTemporalProxy(temporalTopic: ITemporalTopic): Promise<void>;
21
+ /**
22
+ * Creates a temporal proxy for the UNS process.
23
+ * This method registers the UNS topic for temporal data.
24
+ */
25
+ private registerTemporalTopic;
26
+ startWorkflow(workflowTypeOrFunc: string | Workflow, arg: Record<string, any>, taskQueue: string, workflowId?: string): Promise<any>;
27
+ }
@@ -0,0 +1,101 @@
1
+ import UnsProxy from "@uns-kit/core/uns/uns-proxy";
2
+ import logger from "@uns-kit/core/logger";
3
+ import { MqttTopicBuilder } from "@uns-kit/core/uns-mqtt/mqtt-topic-builder";
4
+ import * as path from "path";
5
+ import { basePath } from "@uns-kit/core/base-path";
6
+ import { readFileSync } from "fs";
7
+ import { Connection, Client } from '@temporalio/client';
8
+ import { UnsPacket } from "@uns-kit/core/uns/uns-packet";
9
+ const packageJsonPath = path.join(basePath, "package.json");
10
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
11
+ export default class UnsTemporalProxy extends UnsProxy {
12
+ instanceName;
13
+ processStatusTopic;
14
+ topicBuilder;
15
+ processName;
16
+ connectionOptions;
17
+ clientOptions;
18
+ client;
19
+ unsTopic;
20
+ constructor(processName, instanceName, connectionOptions, clientOptions) {
21
+ super();
22
+ this.connectionOptions = connectionOptions;
23
+ this.clientOptions = clientOptions;
24
+ this.instanceName = instanceName;
25
+ this.processName = processName;
26
+ // Create the topic builder using packageJson values and the processName.
27
+ this.topicBuilder = new MqttTopicBuilder(`uns-infra/${packageJson.name}/${packageJson.version}/${processName}/`);
28
+ // Generate the processStatusTopic using the builder.
29
+ this.processStatusTopic = this.topicBuilder.getProcessStatusTopic();
30
+ // Derive the instanceStatusTopic by appending the instance name.
31
+ this.instanceStatusTopic = this.processStatusTopic + instanceName + "/";
32
+ // Concatenate processName with instanceName for the worker identification.
33
+ this.instanceNameWithSuffix = `${processName}-${instanceName}`;
34
+ }
35
+ /**
36
+ * Initializes the Temporal proxy by registering the given topic and establishing a client connection.
37
+ * @param unsTopic - The topic object to register with Temporal.
38
+ * @returns A promise that resolves when initialization is complete.
39
+ * @throws If the Temporal client fails to initialize.
40
+ */
41
+ async initializeTemporalProxy(temporalTopic) {
42
+ try {
43
+ const unsTopic = {
44
+ timestamp: UnsPacket.formatToISO8601(new Date()),
45
+ topic: temporalTopic.topic,
46
+ attribute: temporalTopic.attribute,
47
+ attributeType: temporalTopic.attributeType,
48
+ description: temporalTopic.description ?? "",
49
+ tags: temporalTopic.tags ?? [],
50
+ attributeNeedsPersistence: temporalTopic.attributeNeedsPersistence ?? true,
51
+ dataGroup: temporalTopic.dataGroup ?? "",
52
+ };
53
+ // Register the UNS topic for temporal data.
54
+ this.registerTemporalTopic(unsTopic);
55
+ this.clientOptions.connection = this.clientOptions.connection ?? await Connection.connect(this.connectionOptions);
56
+ this.client = new Client(this.clientOptions);
57
+ }
58
+ catch (error) {
59
+ logger.error(`Failed to initialize Temporal client: ${error.message}`);
60
+ throw error;
61
+ }
62
+ }
63
+ /**
64
+ * Creates a temporal proxy for the UNS process.
65
+ * This method registers the UNS topic for temporal data.
66
+ */
67
+ async registerTemporalTopic(unsTopic) {
68
+ try {
69
+ // Register the UNS topic for temporal data.
70
+ this.registerUniqueTopic(unsTopic);
71
+ this.unsTopic = unsTopic;
72
+ }
73
+ catch (error) {
74
+ logger.error(`Error creating temporal proxy: ${error.message}`);
75
+ throw error;
76
+ }
77
+ }
78
+ async startWorkflow(workflowTypeOrFunc, arg, taskQueue, workflowId) {
79
+ try {
80
+ const workflowInput = {
81
+ input_data: arg,
82
+ uns_params: {
83
+ uns_attribute: this.unsTopic.attribute,
84
+ uns_attribute_type: this.unsTopic.attributeType,
85
+ uns_topic: this.unsTopic.topic
86
+ }
87
+ };
88
+ const workflowOptions = {
89
+ args: [workflowInput], // single JSON object
90
+ taskQueue,
91
+ workflowId: workflowId ?? `${this.instanceNameWithSuffix}-${Math.floor(Date.now() / 1000)}`
92
+ };
93
+ logger.info(`Starting workflow with options: ${JSON.stringify(workflowOptions)}`);
94
+ const handle = await this.client.workflow.start(workflowTypeOrFunc, workflowOptions);
95
+ return await handle.result();
96
+ }
97
+ catch (error) {
98
+ logger.error(`Failed to start/complete workflow: ${error.message}`);
99
+ }
100
+ }
101
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@uns-kit/temporal",
3
+ "version": "0.0.1",
4
+ "description": "Temporal.io integration plugin for UnsProxyProcess, wiring workflows into the UNS.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Aljoša Vister <aljosa.vister@gmail.com>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/uns-datahub/uns-kit.git",
11
+ "directory": "packages/uns-temporal"
12
+ },
13
+ "keywords": [
14
+ "uns",
15
+ "temporal",
16
+ "workflow",
17
+ "temporalio",
18
+ "mqtt",
19
+ "typescript"
20
+ ],
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "exports": {
25
+ "./*": "./dist/*"
26
+ },
27
+ "main": "dist/index.js",
28
+ "types": "dist/index.d.ts",
29
+ "dependencies": {
30
+ "@temporalio/client": "^1.13.0",
31
+ "@uns-kit/core": "^0.0.1"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.build.json",
35
+ "typecheck": "tsc -p tsconfig.json --noEmit"
36
+ }
37
+ }