@yarkivaev/scada 2.22.0 → 2.24.0

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.
Files changed (48) hide show
  1. package/charts/scada-workloads/Chart.yaml +5 -0
  2. package/charts/scada-workloads/README.md +45 -0
  3. package/charts/scada-workloads/templates/_collector.tpl +103 -0
  4. package/charts/scada-workloads/templates/_control-agent.tpl +80 -0
  5. package/charts/scada-workloads/templates/_controller.tpl +69 -0
  6. package/charts/scada-workloads/templates/_etcd-member.tpl +92 -0
  7. package/charts/scada-workloads/templates/_history-maintenance.tpl +44 -0
  8. package/charts/scada-workloads/templates/_history-receiver.tpl +88 -0
  9. package/charts/scada-workloads/templates/_journal-supervisor.tpl +82 -0
  10. package/charts/scada-workloads/templates/_postgres-role.tpl +43 -0
  11. package/charts/scada-workloads/templates/_reserve-supervisor.tpl +65 -0
  12. package/charts/scada-workloads/templates/_site-server.tpl +74 -0
  13. package/charts/scada-workloads/templates/_supervisor-history.tpl +12 -0
  14. package/charts/scada-workloads/templates/_supervisor.tpl +87 -0
  15. package/charts/scada-workloads/templates/_telemetry.tpl +181 -0
  16. package/db/migrations/E0027__metric_claim_trigger.sql +33 -0
  17. package/package.json +4 -1
  18. package/src/application/runtime/applicationRuntime.js +5 -2
  19. package/src/application/runtime/index.js +3 -0
  20. package/src/application/runtime/opcuaTask.js +63 -0
  21. package/src/application/runtime/runCommand.js +10 -0
  22. package/src/application/runtime/runService.js +14 -0
  23. package/src/application/siteRuntime/backfillOperationPayloads.js +41 -0
  24. package/src/application/siteRuntime/centralConnections.js +13 -0
  25. package/src/application/siteRuntime/edgeIngress.js +25 -0
  26. package/src/application/siteRuntime/index.js +5 -0
  27. package/src/application/siteRuntime/startAnalyticsRuntime.js +33 -0
  28. package/src/infrastructure/deploy/ci/applicationBundleLock.js +51 -0
  29. package/src/infrastructure/deploy/ci/archiveApplication.py +30 -0
  30. package/src/infrastructure/deploy/ci/packageApplication.js +63 -0
  31. package/src/infrastructure/deploy/ci/releaseArtifacts.js +55 -0
  32. package/src/infrastructure/deploy/ci/scada_gitlab.py +75 -0
  33. package/src/infrastructure/deploy/ci/scada_registry.py +91 -0
  34. package/src/infrastructure/deploy/configuredSiteAssets.js +8 -2
  35. package/src/infrastructure/deploy/executeStages.js +8 -1
  36. package/src/infrastructure/deploy/index.js +3 -1
  37. package/src/infrastructure/deploy/installVerifiedTools.js +44 -0
  38. package/src/infrastructure/deploy/stagedSitePlan.js +3 -1
  39. package/src/infrastructure/deploy/useApplicationBundle.sh +22 -0
  40. package/src/infrastructure/opcua/index.js +2 -0
  41. package/src/infrastructure/opcua/opcuaRecord.js +44 -0
  42. package/src/infrastructure/opcua/publishOpcuaRecord.js +23 -0
  43. package/src/infrastructure/persistence/pg/orderedRows.js +31 -0
  44. package/src/testing/boundedQueue.js +50 -0
  45. package/stream-processing/project/plugins.sbt +2 -0
  46. package/stream-processing/src/main/resources/logback.xml +16 -0
  47. package/stream-processing/src/main/scala/scada/processing/runtime/DurableMachineInput.scala +6 -0
  48. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +31 -2
@@ -0,0 +1,65 @@
1
+ {{- define "scada.workloads.reserveSupervisor" -}}
2
+ apiVersion: v1
3
+ kind: ConfigMap
4
+ metadata:
5
+ name: {{ .name }}
6
+ data:
7
+ application.conf: |
8
+ {{ .supervisor.config | indent 4 }}
9
+ ---
10
+ apiVersion: apps/v1
11
+ kind: Deployment
12
+ metadata:
13
+ name: {{ .name }}
14
+ spec:
15
+ replicas: 1
16
+ strategy: {type: Recreate}
17
+ selector:
18
+ matchLabels: {app: {{ .app }}}
19
+ template:
20
+ metadata:
21
+ labels:
22
+ {{- toYaml .labels | nindent 8 }}
23
+ annotations:
24
+ checksum/config: {{ .supervisor.config | sha256sum }}
25
+ {{- with .supervisor.podAnnotations }}
26
+ {{- toYaml . | nindent 8 }}
27
+ {{- end }}
28
+ spec:
29
+ imagePullSecrets:
30
+ - name: {{ .pullSecret }}
31
+ containers:
32
+ - name: supervisor
33
+ image: {{ .supervisor.image | quote }}
34
+ args: [/app/config/application.conf]
35
+ {{- with .supervisor.env }}
36
+ env:
37
+ {{- range $name, $value := . }}
38
+ - name: {{ $name }}
39
+ {{- if kindIs "map" $value }}
40
+ {{- toYaml $value | nindent 14 }}
41
+ {{- else }}
42
+ value: {{ $value | quote }}
43
+ {{- end }}
44
+ {{- end }}
45
+ {{- end }}
46
+ ports:
47
+ - {name: health, containerPort: 9092}
48
+ readinessProbe:
49
+ httpGet: {path: /health, port: health}
50
+ initialDelaySeconds: 15
51
+ livenessProbe:
52
+ httpGet: {path: /health, port: health}
53
+ initialDelaySeconds: 30
54
+ volumeMounts:
55
+ - {name: config, mountPath: /app/config/application.conf, subPath: application.conf, readOnly: true}
56
+ {{- with .supervisor.volumeMounts }}
57
+ {{- toYaml . | nindent 12 }}
58
+ {{- end }}
59
+ volumes:
60
+ - name: config
61
+ configMap: {name: {{ .name }}}
62
+ {{- with .supervisor.volumes }}
63
+ {{- toYaml . | nindent 8 }}
64
+ {{- end }}
65
+ {{- end -}}
@@ -0,0 +1,74 @@
1
+ {{- define "scada.workloads.siteServer" -}}
2
+ apiVersion: apps/v1
3
+ kind: Deployment
4
+ metadata:
5
+ name: {{ .name }}
6
+ labels:
7
+ {{- toYaml .labels | nindent 4 }}
8
+ spec:
9
+ replicas: 1
10
+ strategy:
11
+ type: Recreate
12
+ selector:
13
+ matchLabels: {app: {{ .app }}}
14
+ template:
15
+ metadata:
16
+ labels:
17
+ {{- toYaml .labels | nindent 8 }}
18
+ spec:
19
+ imagePullSecrets:
20
+ - name: {{ .pullSecret }}
21
+ containers:
22
+ - name: site-server
23
+ image: {{ .site.image | quote }}
24
+ command: {{ .command | toJson }}
25
+ ports:
26
+ - {name: http, containerPort: 3000}
27
+ - {name: state-http, containerPort: 8081}
28
+ {{- with .site.envFrom }}
29
+ envFrom:
30
+ {{- toYaml . | nindent 12 }}
31
+ {{- end }}
32
+ env:
33
+ {{- range $key, $value := .site.env }}
34
+ - name: {{ $key }}
35
+ {{- if kindIs "map" $value }}
36
+ {{- toYaml $value | nindent 14 }}
37
+ {{- else }}
38
+ value: {{ $value | quote }}
39
+ {{- end }}
40
+ {{- end }}
41
+ readinessProbe:
42
+ httpGet: {path: /api/v1/machines, port: http}
43
+ initialDelaySeconds: 5
44
+ periodSeconds: 10
45
+ livenessProbe:
46
+ httpGet: {path: /api/v1/machines, port: http}
47
+ initialDelaySeconds: 15
48
+ periodSeconds: 30
49
+ resources:
50
+ {{- toYaml .resources | nindent 12 }}
51
+ ---
52
+ apiVersion: v1
53
+ kind: Service
54
+ metadata:
55
+ name: {{ .name }}
56
+ spec:
57
+ selector: {app: {{ .app }}}
58
+ ports:
59
+ - {name: http, port: 3000, targetPort: http}
60
+ - {name: state-http, port: 8081, targetPort: state-http}
61
+ ---
62
+ apiVersion: v1
63
+ kind: Service
64
+ metadata:
65
+ name: {{ .nodePortName }}
66
+ spec:
67
+ type: NodePort
68
+ selector: {app: {{ .app }}}
69
+ ports:
70
+ - name: http
71
+ port: 3000
72
+ targetPort: http
73
+ nodePort: {{ .site.nodePort }}
74
+ {{- end -}}
@@ -0,0 +1,12 @@
1
+ {{- define "scada.workloads.supervisorHistory" -}}
2
+ apiVersion: v1
3
+ kind: ConfigMap
4
+ metadata:
5
+ name: {{ .name }}
6
+ data:
7
+ application.conf: |
8
+ include required(file("/app/config/application.conf"))
9
+ history.enabled = true
10
+ history.writer-epoch = {{ required "writerEpoch required for local history" .writerEpoch }}
11
+ checkpoint-api.base-url = {{ required "checkpointUrl required for local history" .checkpointUrl | quote }}
12
+ {{- end -}}
@@ -0,0 +1,87 @@
1
+ {{- define "scada.workloads.supervisor" -}}
2
+ {{- if .values.config }}
3
+ apiVersion: v1
4
+ kind: ConfigMap
5
+ metadata:
6
+ name: {{ .release.Name }}-config
7
+ namespace: {{ .release.Namespace }}
8
+ data:
9
+ application.conf: |
10
+ {{ .values.config | indent 4 }}
11
+ ---
12
+ {{- end }}
13
+ apiVersion: apps/v1
14
+ kind: Deployment
15
+ metadata:
16
+ name: {{ .release.Name }}
17
+ namespace: {{ .release.Namespace }}
18
+ labels:
19
+ app: {{ .values.app | default .release.Name }}
20
+ spec:
21
+ replicas: 1
22
+ strategy:
23
+ type: Recreate
24
+ selector:
25
+ matchLabels:
26
+ app: {{ .values.app | default .release.Name }}
27
+ template:
28
+ metadata:
29
+ {{- if or .values.config .values.podAnnotations }}
30
+ annotations:
31
+ {{- if .values.config }}
32
+ checksum/config: {{ .values.config | sha256sum | quote }}
33
+ {{- end }}
34
+ {{- with .values.podAnnotations }}
35
+ {{- toYaml . | nindent 8 }}
36
+ {{- end }}
37
+ {{- end }}
38
+ labels:
39
+ app: {{ .values.app | default .release.Name }}
40
+ spec:
41
+ {{- with .values.pullSecret }}
42
+ imagePullSecrets:
43
+ - name: {{ . | quote }}
44
+ {{- end }}
45
+ containers:
46
+ - name: supervisor
47
+ image: {{ required "image is required" .values.image | quote }}
48
+ args: [/app/config/application.conf]
49
+ {{- with .values.env }}
50
+ env:
51
+ {{- range $name, $value := . }}
52
+ - name: {{ $name }}
53
+ {{- if kindIs "map" $value }}
54
+ {{- toYaml $value | nindent 14 }}
55
+ {{- else }}
56
+ value: {{ $value | quote }}
57
+ {{- end }}
58
+ {{- end }}
59
+ {{- end }}
60
+ {{- with .values.resources }}
61
+ resources:
62
+ {{- toYaml . | nindent 12 }}
63
+ {{- end }}
64
+ {{- if or .values.config .values.volumeMounts }}
65
+ volumeMounts:
66
+ {{- if .values.config }}
67
+ - name: config
68
+ mountPath: /app/config/application.conf
69
+ subPath: application.conf
70
+ readOnly: true
71
+ {{- end }}
72
+ {{- with .values.volumeMounts }}
73
+ {{- toYaml . | nindent 12 }}
74
+ {{- end }}
75
+ {{- end }}
76
+ {{- if or .values.config .values.volumes }}
77
+ volumes:
78
+ {{- if .values.config }}
79
+ - name: config
80
+ configMap:
81
+ name: {{ .release.Name }}-config
82
+ {{- end }}
83
+ {{- with .values.volumes }}
84
+ {{- toYaml . | nindent 8 }}
85
+ {{- end }}
86
+ {{- end }}
87
+ {{- end -}}
@@ -0,0 +1,181 @@
1
+ {{- define "scada.workloads.telemetry" -}}
2
+ {{- $telemetry := .telemetry }}
3
+ apiVersion: v1
4
+ kind: ConfigMap
5
+ metadata:
6
+ name: {{ .databaseName }}
7
+ data:
8
+ edge.xml: {{ $telemetry.config | quote }}
9
+ users.xml: {{ $telemetry.users | quote }}
10
+ schema.sql: {{ $telemetry.schema | quote }}
11
+ history.sh: {{ $telemetry.retentionMigration | quote }}
12
+ client.xml: {{ printf `<clickhouse><host>%s</host><user from_env="CLICKHOUSE_USER"/><password from_env="CLICKHOUSE_PASSWORD"/></clickhouse>` .databaseName | quote }}
13
+ ---
14
+ apiVersion: v1
15
+ kind: Service
16
+ metadata:
17
+ name: {{ .databaseName }}
18
+ spec:
19
+ selector: {app: {{ .databaseApp }}}
20
+ ports:
21
+ - {name: http, port: 8123, targetPort: http}
22
+ - {name: native, port: 9000, targetPort: native}
23
+ - {name: metrics, port: 9363, targetPort: metrics}
24
+ ---
25
+ apiVersion: apps/v1
26
+ kind: StatefulSet
27
+ metadata:
28
+ name: {{ .databaseName }}
29
+ spec:
30
+ serviceName: {{ .databaseName }}
31
+ replicas: 1
32
+ selector:
33
+ matchLabels: {app: {{ .databaseApp }}}
34
+ template:
35
+ metadata:
36
+ labels:
37
+ {{- toYaml .databaseLabels | nindent 8 }}
38
+ annotations:
39
+ checksum/config: {{ printf "%s%s" $telemetry.config $telemetry.users | sha256sum }}
40
+ prometheus.io/scrape: "true"
41
+ prometheus.io/port: "9363"
42
+ spec:
43
+ imagePullSecrets:
44
+ - name: {{ .pullSecret }}
45
+ containers:
46
+ - name: clickhouse
47
+ image: {{ $telemetry.serverImage | quote }}
48
+ env:
49
+ - {name: CLICKHOUSE_DB, value: {{ .database | quote }}}
50
+ - name: CLICKHOUSE_USER
51
+ valueFrom:
52
+ secretKeyRef: {name: {{ $telemetry.secret }}, key: user}
53
+ - name: CLICKHOUSE_PASSWORD
54
+ valueFrom:
55
+ secretKeyRef: {name: {{ $telemetry.secret }}, key: password}
56
+ - {name: CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT, value: "1"}
57
+ ports:
58
+ - {name: http, containerPort: 8123}
59
+ - {name: native, containerPort: 9000}
60
+ - {name: metrics, containerPort: 9363}
61
+ startupProbe:
62
+ httpGet: {path: /ping, port: http}
63
+ periodSeconds: 5
64
+ failureThreshold: 60
65
+ readinessProbe:
66
+ httpGet: {path: /ping, port: http}
67
+ periodSeconds: 5
68
+ livenessProbe:
69
+ httpGet: {path: /ping, port: http}
70
+ periodSeconds: 15
71
+ failureThreshold: 5
72
+ resources:
73
+ {{- toYaml .resources.database | nindent 12 }}
74
+ volumeMounts:
75
+ - {name: data, mountPath: /var/lib/clickhouse}
76
+ - {name: config, mountPath: /etc/clickhouse-server/config.d/edge.xml, subPath: edge.xml, readOnly: true}
77
+ - {name: config, mountPath: /etc/clickhouse-server/users.d/edge.xml, subPath: users.xml, readOnly: true}
78
+ - {name: config, mountPath: /docker-entrypoint-initdb.d/00-telemetry.sql, subPath: schema.sql, readOnly: true}
79
+ volumes:
80
+ - name: config
81
+ configMap: {name: {{ .databaseName }}}
82
+ volumeClaimTemplates:
83
+ - metadata:
84
+ name: data
85
+ spec:
86
+ accessModes: [ReadWriteOnce]
87
+ storageClassName: {{ .storageClass | quote }}
88
+ resources:
89
+ requests:
90
+ storage: {{ $telemetry.storage | quote }}
91
+ ---
92
+ apiVersion: apps/v1
93
+ kind: Deployment
94
+ metadata:
95
+ name: {{ .ingesterName }}
96
+ spec:
97
+ replicas: 1
98
+ strategy: {type: Recreate}
99
+ selector:
100
+ matchLabels: {app: {{ .ingesterApp }}}
101
+ template:
102
+ metadata:
103
+ labels:
104
+ {{- toYaml .ingesterLabels | nindent 8 }}
105
+ spec:
106
+ terminationGracePeriodSeconds: 60
107
+ imagePullSecrets:
108
+ - name: {{ .pullSecret }}
109
+ containers:
110
+ - name: telemetry
111
+ image: {{ $telemetry.image | quote }}
112
+ command: {{ .command | toJson }}
113
+ env:
114
+ {{- with .extraEnv }}
115
+ {{- . | nindent 12 }}
116
+ {{- end }}
117
+ - {name: AMQP_METRICS_QUEUE, value: {{ $telemetry.queue | quote }}}
118
+ - {name: CLICKHOUSE_URL, value: {{ printf "http://%s:8123" .databaseName | quote }}}
119
+ - name: CLICKHOUSE_USER
120
+ valueFrom:
121
+ secretKeyRef: {name: {{ $telemetry.secret }}, key: user}
122
+ - name: CLICKHOUSE_PASSWORD
123
+ valueFrom:
124
+ secretKeyRef: {name: {{ $telemetry.secret }}, key: password}
125
+ - {name: AMQP_PREFETCH, value: {{ $telemetry.prefetch | quote }}}
126
+ - {name: BATCH_SIZE, value: {{ $telemetry.batchSize | quote }}}
127
+ - {name: BATCH_WAIT_MS, value: {{ $telemetry.maxWaitMs | quote }}}
128
+ ports:
129
+ - {name: health, containerPort: 9093}
130
+ readinessProbe:
131
+ httpGet: {path: /ready, port: health}
132
+ periodSeconds: 5
133
+ livenessProbe:
134
+ httpGet: {path: /live, port: health}
135
+ initialDelaySeconds: 30
136
+ periodSeconds: 10
137
+ resources:
138
+ {{- toYaml .resources.ingester | nindent 12 }}
139
+ ---
140
+ apiVersion: batch/v1
141
+ kind: Job
142
+ metadata:
143
+ name: {{ $telemetry.schemaJob }}
144
+ spec:
145
+ backoffLimit: 4
146
+ activeDeadlineSeconds: 300
147
+ ttlSecondsAfterFinished: 86400
148
+ template:
149
+ spec:
150
+ restartPolicy: OnFailure
151
+ imagePullSecrets:
152
+ - name: {{ .pullSecret }}
153
+ containers:
154
+ - name: schema
155
+ image: {{ $telemetry.serverImage | quote }}
156
+ command: [bash, -ec]
157
+ args:
158
+ - |
159
+ for attempt in {1..60}; do
160
+ if clickhouse-client --config-file=/schema/client.xml --query='SELECT 1' >/dev/null 2>&1; then break; fi
161
+ sleep 2
162
+ done
163
+ clickhouse-client --config-file=/schema/client.xml --multiquery < /schema/schema.sql
164
+ {{- if $telemetry.coordinatedRetention }}
165
+ bash /schema/history.sh
166
+ {{- end }}
167
+ env:
168
+ - name: CLICKHOUSE_USER
169
+ valueFrom:
170
+ secretKeyRef: {name: {{ $telemetry.secret }}, key: user}
171
+ - name: CLICKHOUSE_PASSWORD
172
+ valueFrom:
173
+ secretKeyRef: {name: {{ $telemetry.secret }}, key: password}
174
+ volumeMounts:
175
+ - {name: schema, mountPath: /schema, readOnly: true}
176
+ resources:
177
+ {{- toYaml .resources.schemaJob | nindent 12 }}
178
+ volumes:
179
+ - name: schema
180
+ configMap: {name: {{ .databaseName }}}
181
+ {{- end -}}
@@ -0,0 +1,33 @@
1
+ -- Install a claim-preserving metric trigger function for applications to select.
2
+ -- The existing metrics_history binding remains the default.
3
+ CREATE OR REPLACE FUNCTION history_from_metric_claim()
4
+ RETURNS trigger
5
+ LANGUAGE plpgsql
6
+ AS $function$
7
+ DECLARE
8
+ mapping RECORD;
9
+ moment BIGINT;
10
+ inserted INTEGER;
11
+ BEGIN
12
+ moment := floor(extract(epoch FROM NEW.ts) * 1000)::bigint;
13
+ FOR mapping IN SELECT * FROM history_topics WHERE topic = NEW.topic ORDER BY machine LOOP
14
+ INSERT INTO history_observations(machine, channel, time_ms, event_id, value)
15
+ VALUES (mapping.machine, mapping.channel, moment, md5(NEW.topic || ':' || moment::text || ':' || NEW.value::text), NEW.value)
16
+ ON CONFLICT DO NOTHING;
17
+ GET DIAGNOSTICS inserted = ROW_COUNT;
18
+
19
+ IF inserted > 0 AND NEW.ts >= now() - make_interval(days => mapping.retention_days) THEN
20
+ -- The bucket row serializes producers. A recorded cursor or end invalidates the token.
21
+ INSERT INTO history_work(id, machine, from_ms, until_ms)
22
+ VALUES (md5(mapping.machine || ':' || (moment / mapping.bucket_ms)::text)::uuid, mapping.machine, moment, moment)
23
+ ON CONFLICT (id) DO UPDATE SET
24
+ token = CASE WHEN history_work.cursor_ms IS NULL AND history_work.end_ms IS NULL
25
+ THEN history_work.token ELSE gen_random_uuid() END,
26
+ cursor_ms = NULL,
27
+ end_ms = NULL,
28
+ from_ms = least(history_work.from_ms, excluded.from_ms),
29
+ until_ms = greatest(history_work.until_ms, excluded.until_ms);
30
+ END IF;
31
+ END LOOP;
32
+ RETURN NEW;
33
+ END $function$;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.22.0",
3
+ "version": "2.24.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,6 +19,7 @@
19
19
  "./opcua": "./src/infrastructure/opcua/index.js",
20
20
  "./opcua/config": "./src/infrastructure/opcua/config.js",
21
21
  "./runtime": "./src/application/runtime/index.js",
22
+ "./testing/bounded-queue": "./src/testing/boundedQueue.js",
22
23
  "./streams": "./src/infrastructure/streams/index.js",
23
24
  "./control": "./src/application/control/index.js",
24
25
  "./mdmesh": "./src/infrastructure/mdmesh/index.js",
@@ -73,6 +74,8 @@
73
74
  "charts/",
74
75
  "db/",
75
76
  "stream-processing/src/main/scala/",
77
+ "stream-processing/src/main/resources/",
78
+ "stream-processing/project/plugins.sbt",
76
79
  "stream-processing/vendor/",
77
80
  "stream-processing/dependencies/stream-worker.jar",
78
81
  "stream-processing/stream-worker.lock",
@@ -7,11 +7,13 @@ const identifier = z.string().regex(/^[a-z0-9][a-z0-9-]*$/u);
7
7
  const qualified = /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/u;
8
8
  const workload = z.strictObject({
9
9
  driver: z.string().regex(qualified),
10
+ profile: identifier.optional(),
10
11
  config: z.record(z.string(), z.unknown()).default({}),
11
12
  args: z.array(z.string()).default([])
12
13
  });
13
14
  const runtimeDocument = z.strictObject({
14
15
  modules: z.array(z.strictObject({ id: identifier, entry: z.string().min(1) })).default([]),
16
+ configProfiles: z.record(identifier, z.record(z.string(), z.unknown())).default({}),
15
17
  services: z.record(identifier, workload).default({}),
16
18
  jobs: z.record(identifier, workload).default({})
17
19
  });
@@ -71,13 +73,14 @@ export default async function applicationRuntime(file, { kind, name, args = [] }
71
73
  core, env = process.env, write = (body) => { process.stdout.write(body); }
72
74
  }) {
73
75
  if (!['service', 'job'].includes(kind)) { throw new TypeError('expected service or job'); }
74
- const { modules, services, jobs } = runtimeDocument.parse(readDocumentFile(file));
76
+ const { modules, configProfiles, services, jobs } = runtimeDocument.parse(readDocumentFile(file));
75
77
  const declarations = kind === 'service' ? services : jobs;
76
78
  if (!Object.hasOwn(declarations, name)) { throw new Error(`unknown ${kind} ${name}`); }
77
79
  const selected = declarations[name];
80
+ if (selected.profile && !Object.hasOwn(configProfiles, selected.profile)) { throw new Error(`unknown configuration profile ${selected.profile}`); }
78
81
  const load = moduleResolver(file, moduleEntries(modules), core);
79
82
  const driver = await resolveExport(selected.driver, `${kind}s`, load);
80
83
  if (typeof driver !== 'function') { throw new TypeError(`driver ${selected.driver} must be a function`); }
81
- const config = await configuration(selected.config, load);
84
+ const config = await configuration({ ...(selected.profile && configProfiles[selected.profile]), ...selected.config }, load);
82
85
  return driver({ config, args: [...selected.args, ...args], env, write, file });
83
86
  }
@@ -16,3 +16,6 @@ export { default as embeddedCollectors } from './embeddedCollectors.js';
16
16
  export { collectorLaunch, launchCollectorCommand } from './collectorLaunch.js';
17
17
  export { default as pagedDelivery } from './pagedDelivery.js';
18
18
  export { default as runApplication } from './runApplication.js';
19
+ export { default as runCommand } from './runCommand.js';
20
+ export { default as runService } from './runService.js';
21
+ export { default as opcuaTask } from './opcuaTask.js';
@@ -0,0 +1,63 @@
1
+ import opcuaSource from '../../infrastructure/opcua/source.js';
2
+ import opcuaHealth from '../../infrastructure/opcua/health.js';
3
+ import { TELEMETRY } from '../../infrastructure/opcua/publishOpcuaRecord.js';
4
+ import amqpSink from '../../infrastructure/streams/amqpSink.js';
5
+ import compositeLifecycle from './compositeLifecycle.js';
6
+ import spooledOutput, { amqpDestinations } from './spooledOutput.js';
7
+
8
+ function schedulePulse(fn) {
9
+ const timer = setInterval(fn, 1000);
10
+ timer.unref();
11
+ return () => { clearInterval(timer); };
12
+ }
13
+
14
+ function validate(spec) {
15
+ if (!['live', 'spooled'].includes(spec.delivery)) { throw new TypeError('OPC UA requires explicit live delivery'); }
16
+ if (!Array.isArray(spec.source?.connections) || !spec.source.connections.length || !spec.sink?.url) {
17
+ throw new TypeError('OPC UA connections and telemetry sink required');
18
+ }
19
+ if (spec.source.connections.some(({ healthRequired }) => { return healthRequired !== undefined && typeof healthRequired !== 'boolean'; })) {
20
+ throw new TypeError('OPC UA healthRequired must be boolean');
21
+ }
22
+ }
23
+
24
+ function outputFor(spec, context, sink, failed) {
25
+ if (spec.delivery === 'spooled') {
26
+ return spooledOutput({ ...context, report(event) { if (event.state !== 'running') { context.report?.(event); } } },
27
+ spec.sinks ?? amqpDestinations(spec.sink.url, TELEMETRY));
28
+ }
29
+ return sink(spec.sink.url, { exchanges: [{ name: TELEMETRY, type: 'topic', options: { durable: true } }], onError: failed });
30
+ }
31
+
32
+ function taskFor(spec, context, { publish, source, sink, now, schedule }) {
33
+ const { connections } = spec.source;
34
+ const emit = {};
35
+ const health = opcuaHealth(connections, context.report, { now, schedule, pulse(value, device) {
36
+ return emit.publish?.({ device, key: 'source_alive' }, value);
37
+ } });
38
+ const output = outputFor(spec, context, sink, health.failed);
39
+ emit.publish = publish(output);
40
+ const input = source(connections, { async accept({ channel, value }) {
41
+ context.signal.throwIfAborted();
42
+ try {
43
+ await emit.publish(channel, value);
44
+ health.good(channel);
45
+ } catch (error) {
46
+ health.failed(error);
47
+ throw error;
48
+ }
49
+ } }, { signal: context.signal, budget: context.budget, onError: health.failed });
50
+ const lifecycle = compositeLifecycle({ inputs: [input], outputs: [output] });
51
+ return { start: () => { return lifecycle.start(); }, async stop() { health.stop(); await lifecycle.stop(); } };
52
+ }
53
+
54
+ /** Own OPC UA input, health and delivery around an application sample mapper. */
55
+ export default function opcuaTask({ publish, source = opcuaSource, sink = amqpSink, now = Date.now, schedule = schedulePulse }) {
56
+ return {
57
+ validate,
58
+ resources(spec) {
59
+ return spec.source.connections.map((connection) => { return `opcua:${connection.url}`; });
60
+ },
61
+ create(spec, context) { return taskFor(spec, context, { publish, source, sink, now, schedule }); }
62
+ };
63
+ }
@@ -0,0 +1,10 @@
1
+ /** Write a command result and preserve the exit status of a failed subprocess. */
2
+ export default async function runCommand(command) {
3
+ try {
4
+ const output = await command();
5
+ if (output) { process.stdout.write(output); }
6
+ } catch (error) {
7
+ process.stderr.write(`${error.message}\n`);
8
+ process.exitCode = error.status || 1;
9
+ }
10
+ }
@@ -0,0 +1,14 @@
1
+ function exitOnFailure(message, reason) {
2
+ console.error(message, reason); // eslint-disable-line no-console
3
+ process.exit(1);
4
+ }
5
+
6
+ /** Keep process failures fatal after an asynchronous service has started. */
7
+ export default async function runService(name, start) {
8
+ process.on('unhandledRejection', (reason) => { exitOnFailure('Unhandled rejection:', reason); });
9
+ try {
10
+ await start();
11
+ } catch (error) {
12
+ exitOnFailure(`Failed to start ${name}:`, error);
13
+ }
14
+ }
@@ -0,0 +1,41 @@
1
+ import pg from 'pg';
2
+
3
+ function operations(pool) {
4
+ return {
5
+ async listForMachine(machine, kind) {
6
+ const result = await pool.query(`SELECT machine, occurred_at, kind, key, payload
7
+ FROM operations WHERE machine = $1 AND kind = $2 ORDER BY occurred_at, key`, [machine, kind]);
8
+ return result.rows;
9
+ },
10
+ upsert({ machine, key, payload }) {
11
+ return pool.query('UPDATE operations SET payload = $1::jsonb WHERE machine = $2 AND key = $3',
12
+ [JSON.stringify(payload), machine, key]);
13
+ }
14
+ };
15
+ }
16
+
17
+ async function machines(pool, kind, filter) {
18
+ if (filter) { return filter.split(',').map((id) => { return id.trim(); }).filter(Boolean); }
19
+ const result = await pool.query('SELECT DISTINCT machine FROM operations WHERE kind = $1 ORDER BY machine', [kind]);
20
+ return result.rows.map(({ machine }) => { return machine; });
21
+ }
22
+
23
+ /** Rewrite stored operation payloads in order. The application supplies the transformation and output. */
24
+ export default async function backfillOperationPayloads(url, { kind, filter, rewrite, report,
25
+ open = (connectionString) => { return new pg.Pool({ connectionString }); }
26
+ }) {
27
+ const pool = open(url);
28
+ try {
29
+ const port = operations(pool);
30
+ const ids = await machines(pool, kind, filter);
31
+ const total = await ids.reduce(async (previous, machine) => {
32
+ const done = await previous;
33
+ const count = await rewrite(port, machine);
34
+ report?.(count, machine);
35
+ return done + count;
36
+ }, Promise.resolve(0));
37
+ return { total, machines: ids.length };
38
+ } finally {
39
+ await pool.end();
40
+ }
41
+ }
@@ -0,0 +1,13 @@
1
+ import clickhouseConnection from '../../infrastructure/persistence/clickhouse/connection.js';
2
+ import { openPostgresPool } from '../../infrastructure/persistence/postgresPool.js';
3
+
4
+ /** Prepare an application schema and open the shared central-site connections. */
5
+ export default async function centralConnections(env, { prepare, postgresPurpose, openClickHouse = clickhouseConnection,
6
+ openPostgres = openPostgresPool }) {
7
+ const clickhouse = env.CLICKHOUSE_HOST || 'localhost';
8
+ const clickhouseOptions = { username: env.CLICKHOUSE_USER, password: env.CLICKHOUSE_PASSWORD };
9
+ await prepare?.(env, openPostgres);
10
+ const connection = await openClickHouse(clickhouse, clickhouseOptions);
11
+ if (!env.POSTGRES_URL) { throw new Error(`POSTGRES_URL is required for ${postgresPurpose}`); }
12
+ return { clickhouse, clickhouseOptions, connection, pool: openPostgres(env.POSTGRES_URL) };
13
+ }