@yarkivaev/scada 2.23.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 (34) 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 +2 -1
  18. package/src/application/runtime/index.js +1 -0
  19. package/src/application/runtime/opcuaTask.js +63 -0
  20. package/src/application/siteRuntime/backfillOperationPayloads.js +41 -0
  21. package/src/application/siteRuntime/edgeIngress.js +25 -0
  22. package/src/application/siteRuntime/index.js +4 -0
  23. package/src/application/siteRuntime/startAnalyticsRuntime.js +33 -0
  24. package/src/infrastructure/deploy/ci/applicationBundleLock.js +51 -0
  25. package/src/infrastructure/deploy/ci/archiveApplication.py +30 -0
  26. package/src/infrastructure/deploy/ci/packageApplication.js +63 -0
  27. package/src/infrastructure/deploy/ci/releaseArtifacts.js +55 -0
  28. package/src/infrastructure/deploy/ci/scada_gitlab.py +75 -0
  29. package/src/infrastructure/deploy/ci/scada_registry.py +91 -0
  30. package/src/infrastructure/deploy/configuredSiteAssets.js +8 -2
  31. package/src/infrastructure/deploy/executeStages.js +8 -1
  32. package/src/infrastructure/deploy/index.js +2 -1
  33. package/src/infrastructure/persistence/pg/orderedRows.js +31 -0
  34. package/stream-processing/project/plugins.sbt +2 -0
@@ -0,0 +1,51 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ function readJson(directory, file) {
5
+ return JSON.parse(readFileSync(path.join(directory, file), 'utf8'));
6
+ }
7
+
8
+ function writeJson(directory, file, value) {
9
+ writeFileSync(path.join(directory, file), JSON.stringify(value));
10
+ }
11
+
12
+ function selectDependencies(dependencies, policy) {
13
+ const { privateDependencies, providedDependencies } = policy;
14
+ Object.keys(dependencies).forEach((name) => {
15
+ if (!privateDependencies.includes(name) && !providedDependencies.includes(name)) {
16
+ throw new Error(`Classify added runtime dependency for application bundle: ${name}`);
17
+ }
18
+ });
19
+ return Object.fromEntries(privateDependencies.map((name) => {
20
+ if (!dependencies[name] || providedDependencies.includes(name)) {
21
+ throw new Error(`Invalid private application dependency: ${name}`);
22
+ }
23
+ return [name, dependencies[name]];
24
+ }));
25
+ }
26
+
27
+ export function stageApplicationLock(source, destination, policy) {
28
+ const manifest = readJson(source, 'package.json');
29
+ const lock = readJson(source, 'package-lock.json');
30
+ const { name, version, type } = manifest;
31
+ const dependencies = selectDependencies(manifest.dependencies || {}, policy);
32
+ lock.packages[''] = { name, version, dependencies };
33
+ writeJson(destination, 'package.json', { name, version, type, dependencies });
34
+ writeJson(destination, 'package-lock.json', lock);
35
+ }
36
+
37
+ export function verifyApplicationLock(source, destination, excludedDependencies) {
38
+ const original = readJson(source, 'package-lock.json').packages;
39
+ const projected = readJson(destination, 'package-lock.json').packages;
40
+ Object.entries(projected).filter(([entryPath]) => { return entryPath; }).forEach(([entryPath, entry]) => {
41
+ const packageName = entryPath.split('node_modules/').at(-1);
42
+ if (excludedDependencies.includes(packageName)) {
43
+ throw new Error(`Application bundle must resolve ${packageName} from the runtime`);
44
+ }
45
+ const pinned = original[entryPath];
46
+ if (!entry.integrity || entry.integrity !== pinned?.integrity ||
47
+ entry.version !== pinned.version || entry.resolved !== pinned.resolved) {
48
+ throw new Error(`Application dependency must match the source lock: ${entryPath}`);
49
+ }
50
+ });
51
+ }
@@ -0,0 +1,30 @@
1
+ """Write a sorted tar.gz with normalized permissions, ownership and time."""
2
+
3
+ import gzip
4
+ from pathlib import Path
5
+ import sys
6
+ import tarfile
7
+
8
+
9
+ def normalized(entry):
10
+ if not (entry.isfile() or entry.isdir()):
11
+ raise ValueError(f"Application archive only accepts regular files and directories: {entry.name}")
12
+ entry.uid = entry.gid = entry.mtime = 0
13
+ entry.uname = entry.gname = ""
14
+ entry.mode = 0o755 if entry.isdir() or entry.mode & 0o111 else 0o644
15
+ return entry
16
+
17
+
18
+ def archive(source, destination):
19
+ # Check every entry first, including types tarfile may silently ignore.
20
+ for path in Path(source).rglob("*"):
21
+ if path.is_symlink() or not (path.is_file() or path.is_dir()):
22
+ raise ValueError(f"Application archive only accepts regular files and directories: {path}")
23
+ with open(destination, "wb") as output:
24
+ with gzip.GzipFile(fileobj=output, filename="", mode="wb", mtime=0) as compressed:
25
+ with tarfile.open(fileobj=compressed, mode="w", dereference=True) as bundle:
26
+ bundle.add(source, arcname=".", filter=normalized)
27
+
28
+
29
+ if __name__ == "__main__":
30
+ archive(*sys.argv[1:])
@@ -0,0 +1,63 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { stageApplicationLock, verifyApplicationLock } from './applicationBundleLock.js';
8
+
9
+ const NPM_SAFETY_FLAGS = ['--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund'];
10
+
11
+ function stageSources(source, destination, stage, policy) {
12
+ policy.requiredPaths.forEach((entry) => {
13
+ if (!existsSync(path.join(source, entry))) {
14
+ throw new Error(`Application bundle requires ${entry}`);
15
+ }
16
+ });
17
+ const sourceArchive = path.join(stage, 'sources.tar');
18
+ const excludes = policy.excludePatterns.map((pattern) => { return `--exclude=${pattern}`; });
19
+ const env = { ...process.env, COPYFILE_DISABLE: '1' };
20
+ execFileSync('tar', ['-C', source, ...excludes, '-cf', sourceArchive, ...policy.sourcePaths], { env, stdio: 'inherit' });
21
+ execFileSync('tar', ['-C', destination, '-xf', sourceArchive], { env, stdio: 'inherit' });
22
+ }
23
+
24
+ function installDependencies(source, destination, policy) {
25
+ stageApplicationLock(source, destination, policy);
26
+ const options = { cwd: destination, stdio: 'inherit' };
27
+ execFileSync('npm', ['install', '--package-lock-only', '--offline', ...NPM_SAFETY_FLAGS], options);
28
+ verifyApplicationLock(source, destination, policy.excludedDependencies);
29
+ execFileSync('npm', ['ci', '--no-bin-links', ...NPM_SAFETY_FLAGS], options);
30
+ rmSync(path.join(destination, 'package-lock.json'));
31
+ rmSync(path.join(destination, 'node_modules', '.package-lock.json'), { force: true });
32
+ }
33
+
34
+ function createArchive(destination, stage, output) {
35
+ const archive = path.join(stage, 'application.tar.gz');
36
+ const archiveTool = fileURLToPath(new URL('./archiveApplication.py', import.meta.url));
37
+ execFileSync('python3', [archiveTool, destination, archive], { stdio: 'inherit' });
38
+ const digest = createHash('sha256').update(readFileSync(archive)).digest('hex');
39
+ mkdirSync(path.dirname(output), { recursive: true });
40
+ copyFileSync(archive, output);
41
+ writeFileSync(`${output}.sha256`, `${digest}\n`);
42
+ }
43
+
44
+ function packageApplication(source, output, policy, extraSource) {
45
+ const stage = mkdtempSync(path.join(tmpdir(), 'scada-application-'));
46
+ const destination = path.join(stage, 'app');
47
+ try {
48
+ mkdirSync(destination);
49
+ stageSources(source, destination, stage, policy);
50
+ installDependencies(source, destination, policy);
51
+ if (extraSource) { copyFileSync(extraSource, path.join(destination, policy.extraFile)); }
52
+ createArchive(destination, stage, output);
53
+ } finally {
54
+ rmSync(stage, { recursive: true, force: true });
55
+ }
56
+ }
57
+
58
+ const [source, output, policyFile, extraSource] = process.argv.slice(2);
59
+ if (!source || !output || !policyFile) {
60
+ throw new Error('Usage: packageApplication.js SOURCE OUTPUT_TAR_GZ POLICY_JSON [EXTRA_FILE]');
61
+ }
62
+ const policy = JSON.parse(readFileSync(policyFile, 'utf8'));
63
+ packageApplication(source, output, policy, extraSource);
@@ -0,0 +1,55 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdirSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ function gitOutput(args, cwd) {
6
+ return execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
7
+ }
8
+
9
+ function fetchRevision(remote, ref, cwd) {
10
+ execFileSync('git', ['fetch', '--quiet', '--', remote, ref], { cwd, stdio: 'inherit' });
11
+ return gitOutput(['rev-parse', '--verify', 'FETCH_HEAD^{commit}'], cwd);
12
+ }
13
+
14
+ export function checkoutRevision(cwd) {
15
+ return gitOutput(['rev-parse', '--verify', 'HEAD^{commit}'], cwd);
16
+ }
17
+
18
+ export function branchRevision(remote, branch, cwd) {
19
+ return fetchRevision(remote, `refs/heads/${branch}`, cwd);
20
+ }
21
+
22
+ export function tagRevision(remote, tag, cwd) {
23
+ const ref = `refs/tags/${tag}`;
24
+ execFileSync('git', ['fetch', '--quiet', '--', remote, `${ref}:${ref}`], { cwd, stdio: 'inherit' });
25
+ return gitOutput(['rev-parse', '--verify', `${ref}^{commit}`], cwd);
26
+ }
27
+
28
+ export function requireCurrentReleaseRevision(expected, checkout, current) {
29
+ if (checkout !== expected) { throw new Error('Release checkout differs from the tested CI revision'); }
30
+ if (current !== checkout) { throw new Error('Release is superseded by a newer branch revision'); }
31
+ return checkout;
32
+ }
33
+
34
+ export function stableImageTag(image, repository, tagPrefix = '') {
35
+ const prefix = `${repository}:`;
36
+ const version = image.slice(prefix.length);
37
+ if (!image.startsWith(prefix) || !/^\d+\.\d+\.\d+$/u.test(version)) {
38
+ throw new Error('Expected a stable image from the configured registry repository');
39
+ }
40
+ return `${tagPrefix}${version}`;
41
+ }
42
+
43
+ export function verifyReleaseArtifact({ remote, tag, checkout, image, verifyRevision, waitForImage }) {
44
+ const revision = tagRevision(remote, tag);
45
+ if (revision !== checkout) { verifyRevision(revision); }
46
+ waitForImage(image);
47
+ }
48
+
49
+ export async function downloadReleaseArtifact(url, destination, { headers, timeout = 60000 } = {}) {
50
+ const response = await fetch(url, { headers, redirect: 'error', signal: AbortSignal.timeout(timeout) });
51
+ if (!response.ok) { throw new Error(`Release artifact returned HTTP ${response.status}`); }
52
+ const bytes = Buffer.from(await response.arrayBuffer());
53
+ mkdirSync(path.dirname(destination), { recursive: true });
54
+ writeFileSync(destination, bytes);
55
+ }
@@ -0,0 +1,75 @@
1
+ """GitLab pipeline operations for release jobs running on Python alone."""
2
+
3
+ import json
4
+ import time
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+
9
+
10
+ def verified(pipeline, jobs, ref, sha, required):
11
+ statuses = {job["name"]: job["status"] for job in jobs}
12
+ return (pipeline.get("ref") == ref and pipeline.get("sha") == sha
13
+ and pipeline.get("status") == "success"
14
+ and all(statuses.get(name) == "success" for name in required))
15
+
16
+
17
+ class GitLab:
18
+ def __init__(self, api_url, project, headers=None):
19
+ self.base = api_url.rstrip("/") + "/projects/" + urllib.parse.quote(project, safe="")
20
+ self.headers = dict(headers or {})
21
+
22
+ def get(self, path):
23
+ request = urllib.request.Request(self.base + path, headers=self.headers)
24
+ with urllib.request.urlopen(request, timeout=30) as response:
25
+ return json.load(response)
26
+
27
+ def jobs(self, pipeline_id):
28
+ page = 1
29
+ result = []
30
+ while True:
31
+ batch = self.get(f"/pipelines/{pipeline_id}/jobs?per_page=100&page={page}")
32
+ result.extend(batch)
33
+ if len(batch) < 100:
34
+ return result
35
+ page += 1
36
+
37
+ def wait_for_verified_pipeline(self, ref, sha, required, *, timeout=480, interval=10, waiting=None):
38
+ deadline = time.monotonic() + timeout
39
+ query = urllib.parse.urlencode({
40
+ "ref": ref, "sha": sha, "per_page": 100, "order_by": "id", "sort": "desc",
41
+ })
42
+ while True:
43
+ pipelines = self.get("/pipelines?" + query)
44
+ # A previous green pipeline must never hide a newer failure.
45
+ candidates = [p for p in pipelines if p.get("ref") == ref and p.get("sha") == sha]
46
+ latest = max(candidates, key=lambda p: p["id"], default=None)
47
+ if latest and verified(latest, self.jobs(latest["id"]), ref, sha, required):
48
+ return latest["id"]
49
+ if latest and latest["status"] in ("failed", "canceled", "skipped", "success"):
50
+ raise RuntimeError(f"Latest {ref} pipeline failed or lacks successful mandatory suites")
51
+ if time.monotonic() >= deadline:
52
+ raise RuntimeError(f"No fully tested successful {ref} pipeline for release SHA")
53
+ if waiting:
54
+ waiting()
55
+ time.sleep(interval)
56
+
57
+ def trigger(self, ref, token, variables):
58
+ form = {"token": token, "ref": ref}
59
+ form.update({f"variables[{key}]": value for key, value in variables.items()})
60
+ data = urllib.parse.urlencode(form).encode("utf-8")
61
+ path = "/trigger/pipeline"
62
+ request = urllib.request.Request(
63
+ self.base + path, data=data, method="POST",
64
+ headers={**self.headers, "Content-Type": "application/x-www-form-urlencoded"},
65
+ )
66
+ try:
67
+ with urllib.request.urlopen(request, timeout=60) as response:
68
+ body = response.read()
69
+ return json.loads(body) if body else {}
70
+ except urllib.error.HTTPError as error:
71
+ with error:
72
+ detail = error.read().decode("utf-8", errors="replace")
73
+ raise RuntimeError(
74
+ f"GitLab API POST {request.selector} failed status={error.code} body={detail}"
75
+ ) from error
@@ -0,0 +1,91 @@
1
+ """OCI manifest inspection and polling with caller-supplied registry access."""
2
+
3
+ import base64
4
+ import json
5
+ import ssl
6
+ import time
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+
11
+
12
+ MANIFEST_ACCEPT = (
13
+ "application/vnd.docker.distribution.manifest.v2+json, "
14
+ "application/vnd.docker.distribution.manifest.list.v2+json, "
15
+ "application/vnd.oci.image.manifest.v1+json, "
16
+ "application/vnd.oci.image.index.v1+json"
17
+ )
18
+
19
+
20
+ class Registry:
21
+ def __init__(self, *, scheme="https", jwt_url=None, jwt_service=None, user="",
22
+ password="", tls_verify=True, emit=print):
23
+ self.scheme = scheme
24
+ self.jwt_url = jwt_url
25
+ self.jwt_service = jwt_service
26
+ self.user = user
27
+ self.password = password
28
+ self.context = ssl.create_default_context() if tls_verify else ssl._create_unverified_context()
29
+ self.emit = emit
30
+
31
+ def open(self, request):
32
+ return urllib.request.urlopen(request, timeout=30, context=self.context)
33
+
34
+ def bearer_token(self, name):
35
+ if not self.jwt_url or not self.jwt_service:
36
+ raise ValueError("Registry JWT URL and service are required with credentials")
37
+ auth = base64.b64encode(f"{self.user}:{self.password}".encode()).decode("ascii")
38
+ query = urllib.parse.urlencode(
39
+ {"service": self.jwt_service, "scope": f"repository:{name}:pull"}
40
+ )
41
+ url = urllib.parse.urlsplit(self.jwt_url)
42
+ url = url._replace(query="&".join(filter(None, (url.query, query)))).geturl()
43
+ request = urllib.request.Request(url, headers={"Authorization": f"Basic {auth}"})
44
+ with self.open(request) as response:
45
+ payload = json.load(response)
46
+ token = payload.get("token") or payload.get("access_token")
47
+ if not token:
48
+ raise RuntimeError("registry jwt response missing token")
49
+ return token
50
+
51
+ def inspect(self, image_ref):
52
+ if "/" not in image_ref or ":" not in image_ref.rsplit("/", 1)[-1]:
53
+ raise RuntimeError(f"unexpected image ref {image_ref}")
54
+ host, remainder = image_ref.split("/", 1)
55
+ name, tag = remainder.rsplit(":", 1)
56
+ url = f"{self.scheme}://{host}/v2/{name}/manifests/{tag}"
57
+ headers = {"Accept": MANIFEST_ACCEPT}
58
+ if self.user and self.password:
59
+ try:
60
+ headers["Authorization"] = f"Bearer {self.bearer_token(name)}"
61
+ except Exception as error:
62
+ raise RuntimeError(f"registry jwt failed for {image_ref}: {error}") from error
63
+ request = urllib.request.Request(url, headers=headers, method="GET")
64
+ try:
65
+ with self.open(request) as response:
66
+ return 200 <= response.status < 300
67
+ except urllib.error.HTTPError as error:
68
+ with error:
69
+ if error.code == 404:
70
+ return False
71
+ raise RuntimeError(
72
+ f"registry inspect failed for {image_ref} status={error.code}"
73
+ ) from error
74
+ except urllib.error.URLError as error:
75
+ self.emit(f"registry inspect unreachable for {image_ref}: {error}")
76
+ return False
77
+
78
+ def wait(self, image_ref, *, timeout=2700, interval=15):
79
+ if interval <= 0 or timeout < 0:
80
+ raise ValueError("Registry interval must be positive and timeout cannot be negative")
81
+ self.emit(f"waiting for image {image_ref} timeout={timeout}s")
82
+ start = time.monotonic()
83
+ while True:
84
+ if self.inspect(image_ref):
85
+ self.emit(f"image ready {image_ref} after {int(time.monotonic() - start)}s")
86
+ return True
87
+ elapsed = time.monotonic() - start
88
+ self.emit(f"image not ready {image_ref} elapsed={int(elapsed)}s")
89
+ if elapsed >= timeout:
90
+ return False
91
+ time.sleep(min(interval, timeout - elapsed))
@@ -41,15 +41,21 @@ export function secretEnvironment(name, keys) {
41
41
  }));
42
42
  }
43
43
 
44
+ /** Require a concrete startup history repair decision from deployment policy. */
45
+ export function startupHistoryPolicy(value) {
46
+ if (typeof value !== 'boolean') { throw new TypeError('repairHistoryOnStart must be boolean'); }
47
+ return value;
48
+ }
49
+
44
50
  /** Render concrete site environment, Kubernetes objects and supervisor file assets. */
45
- export function configuredSiteAssets(settings, base, startupHistoryPolicy) {
51
+ export function configuredSiteAssets(settings, base, repairPolicy = startupHistoryPolicy) {
46
52
  function text(file) { return readFileSync(new URL(file, base), 'utf8'); }
47
53
  const observationUrl = configuredObservationUrl(settings.observation);
48
54
  return {
49
55
  observationUrl,
50
56
  supervisorConfig: supervisorConfig(settings.supervisor, text, observationUrl),
51
57
  siteEnvironment(cluster, app, security) {
52
- const repairHistoryOnStart = startupHistoryPolicy(app.ingest.stomp.repairHistoryOnStart);
58
+ const repairHistoryOnStart = repairPolicy(app.ingest.stomp.repairHistoryOnStart);
53
59
  const bindings = { app, number: cluster.at(-1), repairHistoryOnStart };
54
60
  const environment = deploymentTemplate(settings.apiEnvironment, bindings);
55
61
  return databaseEnvironment({ ...environment,
@@ -1,12 +1,19 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import executeRelease from './executeRelease.js';
2
+ import executeRelease, { requireReleaseAction } from './executeRelease.js';
3
3
 
4
4
  /** Execute ordered full release plans, preflighting every stage before mutations.
5
5
  * Stage rollout/afterReady and beforeApply gates must succeed before continuing.
6
6
  * Read-only actions execute each stage without invoking mutation gates.
7
+ * Stages with buildDependencies enabled build their chart from its Helm lock.
7
8
  */
8
9
  export default function executeStages(stages, action = 'render', execute = execFileSync) {
9
10
  if (!Array.isArray(stages) || !stages.length) { throw new Error('stages must be a nonempty array'); }
11
+ requireReleaseAction(action);
12
+ const charts = new Set(stages.filter(({ buildDependencies }) => { return buildDependencies === true; })
13
+ .map(({ chart }) => { return chart; }));
14
+ for (const chart of charts) {
15
+ execute('helm', ['dependency', 'build', '--skip-refresh', chart], { stdio: 'pipe' });
16
+ }
10
17
  if (['apply', 'adopt'].includes(action)) {
11
18
  for (const stage of stages) {
12
19
  // SSA can claim legacy fields only after the stage's CSA handoff.
@@ -77,7 +77,7 @@ export { default as configuredRuntimeCapabilities } from './configuredRuntimeCap
77
77
  export { classificationEnvironment, configuredClassification, configuredSupervisor } from './configuredClassification.js';
78
78
  export { default as configuredArchivePlan } from './configuredArchivePlan.js';
79
79
  export { default as configuredEtcdInventory } from './configuredEtcdInventory.js';
80
- export { configuredSiteAssets } from './configuredSiteAssets.js';
80
+ export { configuredSiteAssets, startupHistoryPolicy } from './configuredSiteAssets.js';
81
81
  export { default as configuredBrokerRoutes } from './configuredBrokerRoutes.js';
82
82
  export { default as controlPlaneCli } from './controlPlaneCli.js';
83
83
  export { default as configuredCollectorChartDeployment } from './configuredCollectorChartDeployment.js';
@@ -85,3 +85,4 @@ export { default as configuredRuntimeArtifacts } from './configuredRuntimeArtifa
85
85
  export { secretEnvironment } from './configuredSiteAssets.js';
86
86
  export { default as configuredBundleCapabilities } from './configuredBundleCapabilities.js';
87
87
  export { default as installVerifiedTools } from './installVerifiedTools.js';
88
+ export { branchRevision, checkoutRevision, downloadReleaseArtifact, requireCurrentReleaseRevision, stableImageTag, verifyReleaseArtifact } from './ci/releaseArtifacts.js';
@@ -0,0 +1,31 @@
1
+ function identifier(name) {
2
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/u.test(name)) { throw new TypeError('Invalid PostgreSQL identifier'); }
3
+ return /^[a-z_][a-z0-9_]*$/u.test(name) ? name : `"${name}"`;
4
+ }
5
+
6
+ /** Query a configured PostgreSQL relation by timestamp and a stable tie-break value. */
7
+ export default function orderedRows(pool, { relation, group, timestamp, tieBreak }) {
8
+ const table = relation.split('.').map(identifier).join('.');
9
+ const object = identifier(group);
10
+ const at = identifier(timestamp);
11
+ const id = identifier(tieBreak);
12
+ const select = `SELECT * FROM ${table} WHERE ${object} = $1`;
13
+ const order = `ORDER BY ${at}, ${id}`;
14
+
15
+ async function fetch(value, cursor, limit) {
16
+ const values = [value];
17
+ let filter = '';
18
+ if (cursor.kind === 'cursor') {
19
+ values.push(cursor.at.toISOString());
20
+ filter = ` AND ${at} > $2`;
21
+ if (cursor.id !== undefined) {
22
+ values.push(cursor.id);
23
+ filter = ` AND (${at}, ${id}) > ($2, $3)`;
24
+ }
25
+ }
26
+ values.push(limit);
27
+ return (await pool.query(`${select}${filter} ${order} LIMIT $${values.length}`, values)).rows;
28
+ }
29
+
30
+ return fetch;
31
+ }
@@ -0,0 +1,2 @@
1
+ addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.2")
2
+ addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.0")