@digitraffic/common 2026.11.18-1 → 2026.11.19-2

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.
@@ -1,11 +1,40 @@
1
1
  import { Writable } from "node:stream";
2
2
  import vm from "node:vm";
3
+ import { App } from "aws-cdk-lib";
4
+ import { Template } from "aws-cdk-lib/assertions";
3
5
  import { describe, expect, test } from "vitest";
6
+ import { DigitrafficDLQueue } from "../../aws/infra/sqs-queue.js";
4
7
  // Import from the internal module directly — these helpers are intentionally
5
8
  // not exported from sqs-queue.ts to keep the public API surface clean.
6
9
  import { getDlqCode, sanitizeS3BucketName, } from "../../aws/infra/sqs-queue-internal.js";
10
+ import { DigitrafficStack } from "../../aws/infra/stack/stack.js";
11
+ import { EnvKeys } from "../../aws/runtime/environment.js";
7
12
  import { DtLogger } from "../../aws/runtime/logging/dt-logger.js";
13
+ import { TrafficType } from "../../types/traffictype.js";
14
+ function createStack() {
15
+ const configuration = {
16
+ shortName: "VS",
17
+ trafficType: TrafficType.ROAD,
18
+ alarmTopicArn: "",
19
+ warningTopicArn: "",
20
+ production: false,
21
+ stackProps: {},
22
+ };
23
+ return new DigitrafficStack(new App(), "TestStack", configuration);
24
+ }
8
25
  describe("sqs-queue", () => {
26
+ test("adds APP_NAME to the generated DLQ Lambda", () => {
27
+ const stack = createStack();
28
+ DigitrafficDLQueue.create(stack, "MqttUpdates");
29
+ Template.fromStack(stack).hasResourceProperties("AWS::Lambda::Function", {
30
+ FunctionName: "VS-MqttUpdates-DLQ-Function",
31
+ Environment: {
32
+ Variables: {
33
+ [EnvKeys.APP_NAME]: "road-vs",
34
+ },
35
+ },
36
+ });
37
+ });
9
38
  test("getDlqCode generates valid JavaScript", () => {
10
39
  const inlineCode = getDlqCode("test-bucket");
11
40
  // InlineCode stores the code in the `code` property
@@ -78,6 +107,7 @@ describe("sqs-queue", () => {
78
107
  const inlineLoggerLines = [];
79
108
  const stubProcess = {
80
109
  env: {
110
+ APP_NAME: "road-vs",
81
111
  AWS_LAMBDA_FUNCTION_NAME: "test-lambda",
82
112
  AWS_EXECUTION_ENV: "test-runtime",
83
113
  },
@@ -122,6 +152,8 @@ describe("sqs-queue", () => {
122
152
  expect(inlineOutput["runtime"]).toBe(dtLoggerOutput["runtime"]);
123
153
  // biome-ignore lint/complexity/useLiteralKeys: Record<string, unknown> requires bracket notation for noPropertyAccessFromIndexSignature
124
154
  expect(inlineOutput["method"]).toBe(dtLoggerOutput["method"]);
155
+ // biome-ignore lint/complexity/useLiteralKeys: Record<string, unknown> requires bracket notation for noPropertyAccessFromIndexSignature
156
+ expect(inlineOutput["app"]).toBe("road-vs");
125
157
  });
126
158
  });
127
159
  describe("sanitizeS3BucketName", () => {
@@ -111,6 +111,88 @@ describe("stop-watch.test.ts", () => {
111
111
  sw.reset();
112
112
  expect(sw.getDuration()).toEqual(0);
113
113
  });
114
+ test("getDurationInSeconds returns duration in seconds with default precision", async () => {
115
+ const sw = new StopWatch().start();
116
+ await sleepMs(100);
117
+ sw.stop();
118
+ const durationInSeconds = sw.getDurationInSeconds();
119
+ expect(typeof durationInSeconds).toBe("string");
120
+ expect(parseFloat(durationInSeconds)).toBeGreaterThanOrEqual(0.09);
121
+ expect(parseFloat(durationInSeconds)).toBeLessThan(0.15);
122
+ // Default digits is 2, so should have at most 2 decimal places
123
+ const decimalPlaces = durationInSeconds.split(".")[1]?.length ?? 0;
124
+ expect(decimalPlaces).toBeLessThanOrEqual(2);
125
+ });
126
+ test("getDurationInSeconds with custom digits parameter", async () => {
127
+ const sw = new StopWatch().start();
128
+ await sleepMs(100);
129
+ sw.stop();
130
+ const durationInSeconds1 = sw.getDurationInSeconds("DEFAULT_INTERNAL_TASK", 1);
131
+ expect(typeof durationInSeconds1).toBe("string");
132
+ expect(parseFloat(durationInSeconds1)).toBeGreaterThanOrEqual(0.09);
133
+ expect(parseFloat(durationInSeconds1)).toBeLessThan(0.15);
134
+ const decimalPlaces1 = durationInSeconds1.split(".")[1]?.length ?? 0;
135
+ expect(decimalPlaces1).toBeLessThanOrEqual(1);
136
+ const durationInSeconds3 = sw.getDurationInSeconds("DEFAULT_INTERNAL_TASK", 3);
137
+ expect(typeof durationInSeconds3).toBe("string");
138
+ expect(parseFloat(durationInSeconds3)).toBeGreaterThanOrEqual(0.09);
139
+ expect(parseFloat(durationInSeconds3)).toBeLessThan(0.15);
140
+ const decimalPlaces3 = durationInSeconds3.split(".")[1]?.length ?? 0;
141
+ expect(decimalPlaces3).toBeLessThanOrEqual(3);
142
+ });
143
+ test("getDurationInSeconds with named task", async () => {
144
+ const sw = StopWatch.createStarted();
145
+ sw.start("namedTask");
146
+ await sleepMs(100);
147
+ sw.stop("namedTask");
148
+ const durationInSeconds = sw.getDurationInSeconds("namedTask");
149
+ expect(typeof durationInSeconds).toBe("string");
150
+ expect(parseFloat(durationInSeconds)).toBeGreaterThanOrEqual(0.09);
151
+ expect(parseFloat(durationInSeconds)).toBeLessThan(0.15);
152
+ });
153
+ test("getDurationInSeconds returns 0 for non-existent task", () => {
154
+ const sw = new StopWatch();
155
+ const durationInSeconds = sw.getDurationInSeconds("nonExistentTask");
156
+ expect(durationInSeconds).toBe("0.00");
157
+ });
158
+ test("getDurationInSeconds with running task includes current period", async () => {
159
+ const sw = StopWatch.createStarted();
160
+ sw.start("runningTask");
161
+ await sleepMs(100);
162
+ // Don't stop the task
163
+ const durationInSeconds = sw.getDurationInSeconds("runningTask");
164
+ expect(typeof durationInSeconds).toBe("string");
165
+ expect(parseFloat(durationInSeconds)).toBeGreaterThanOrEqual(0.09);
166
+ expect(parseFloat(durationInSeconds)).toBeLessThan(0.15);
167
+ });
168
+ test("getDurationInSeconds with multiple periods", async () => {
169
+ const sw = StopWatch.createStarted();
170
+ sw.start("multiPeriodTask");
171
+ await sleepMs(50);
172
+ sw.start("multiPeriodTask"); // This stops and starts a new period
173
+ await sleepMs(50);
174
+ sw.stop("multiPeriodTask");
175
+ const durationInSeconds = sw.getDurationInSeconds("multiPeriodTask");
176
+ expect(typeof durationInSeconds).toBe("string");
177
+ expect(parseFloat(durationInSeconds)).toBeGreaterThanOrEqual(0.09);
178
+ expect(parseFloat(durationInSeconds)).toBeLessThan(0.15);
179
+ });
180
+ test("getDurationInSeconds with zero digits", async () => {
181
+ const sw = new StopWatch().start();
182
+ await sleepMs(100);
183
+ sw.stop();
184
+ const durationInSeconds = sw.getDurationInSeconds("DEFAULT_INTERNAL_TASK", 0);
185
+ expect(typeof durationInSeconds).toBe("string");
186
+ expect(Number.isInteger(parseFloat(durationInSeconds))).toBe(true);
187
+ });
188
+ test("getDurationInSeconds converts milliseconds to seconds correctly", async () => {
189
+ const sw = new StopWatch().start();
190
+ await sleepMs(1000);
191
+ sw.stop();
192
+ const durationInMs = sw.getDuration();
193
+ const durationInSeconds = sw.getDurationInSeconds("DEFAULT_INTERNAL_TASK", 0);
194
+ expect(parseFloat(durationInSeconds)).toBe(Math.round(durationInMs / 1000));
195
+ });
114
196
  });
115
197
  function sleepMs(ms) {
116
198
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -18,10 +18,11 @@ const { PutObjectCommand, S3Client } = require("@aws-sdk/client-s3");
18
18
  // existing log parsing and CloudWatch alarms keep working.
19
19
  const lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME || "unknown lambda name";
20
20
  const runtime = process.env.AWS_EXECUTION_ENV || "unknown runtime";
21
+ const app = process.env.APP_NAME;
21
22
  const logger = {
22
23
  error: (msg) => {
23
24
  const message = msg.method ? msg.method + " " + (msg.message || "") : msg.message || "";
24
- process.stdout.write(JSON.stringify({ ...msg, message, level: "ERROR", lambdaName, runtime }) + "\\n");
25
+ process.stdout.write(JSON.stringify({ ...msg, message, level: "ERROR", app, lambdaName, runtime }) + "\\n");
25
26
  }
26
27
  };
27
28
 
@@ -6,6 +6,7 @@ import { Runtime } from "aws-cdk-lib/aws-lambda";
6
6
  import { SqsEventSource } from "aws-cdk-lib/aws-lambda-event-sources";
7
7
  import { BlockPublicAccess, Bucket } from "aws-cdk-lib/aws-s3";
8
8
  import { Queue, QueueEncryption } from "aws-cdk-lib/aws-sqs";
9
+ import { EnvKeys } from "../runtime/environment.js";
9
10
  // getDlqCode and sanitizeS3BucketName live in a separate internal module so they
10
11
  // are not part of the public API surface exported from this package.
11
12
  // Tests can import them directly from sqs-queue-internal.ts.
@@ -49,6 +50,10 @@ export const DigitrafficDLQueue = {
49
50
  create(stack, name) {
50
51
  const dlqName = `${stack.configuration.shortName}-${name}-DLQ`;
51
52
  const dlqFunctionName = `${dlqName}-Function`;
53
+ const appName = stack.createLambdaEnvironment()[EnvKeys.APP_NAME];
54
+ if (!appName) {
55
+ throw new Error("APP_NAME is required for the DLQ Lambda");
56
+ }
52
57
  const dlq = new DigitrafficSqsQueue(stack, dlqName, {
53
58
  queueName: dlqName,
54
59
  visibilityTimeout: Duration.seconds(60),
@@ -71,6 +76,9 @@ export const DigitrafficDLQueue = {
71
76
  handler: "index.handler",
72
77
  memorySize: 128,
73
78
  reservedConcurrentExecutions: 1,
79
+ environment: {
80
+ [EnvKeys.APP_NAME]: appName,
81
+ },
74
82
  });
75
83
  const statement = new PolicyStatement();
76
84
  statement.addActions("s3:PutObject");
@@ -2,7 +2,7 @@ import type { IVpc } from "aws-cdk-lib/aws-ec2";
2
2
  import { CfnDBProxyEndpoint, DatabaseProxy } from "aws-cdk-lib/aws-rds";
3
3
  import type { ISecret } from "aws-cdk-lib/aws-secretsmanager";
4
4
  import { Stack } from "aws-cdk-lib/core";
5
- import type { Construct } from "constructs/lib/construct.js";
5
+ import type { Construct } from "constructs";
6
6
  import type { InfraStackConfiguration } from "./intra-stack-configuration.js";
7
7
  export interface ProxyConfiguration {
8
8
  readonly secretArn: string;
@@ -3,7 +3,7 @@ import { Key } from "aws-cdk-lib/aws-kms";
3
3
  import type { AuroraPostgresEngineVersion, DatabaseClusterProps, IParameterGroup } from "aws-cdk-lib/aws-rds";
4
4
  import { DatabaseCluster } from "aws-cdk-lib/aws-rds";
5
5
  import { Stack } from "aws-cdk-lib/core";
6
- import type { Construct } from "constructs/lib/construct.js";
6
+ import type { Construct } from "constructs";
7
7
  import type { InfraStackConfiguration } from "./intra-stack-configuration.js";
8
8
  export interface DbConfiguration {
9
9
  readonly cluster?: ClusterConfiguration;
@@ -1,7 +1,7 @@
1
1
  import type { IVpc } from "aws-cdk-lib/aws-ec2";
2
2
  import { Vpc } from "aws-cdk-lib/aws-ec2";
3
3
  import { Stack } from "aws-cdk-lib/core";
4
- import type { Construct } from "constructs/lib/construct.js";
4
+ import type { Construct } from "constructs";
5
5
  import type { InfraStackConfiguration } from "./intra-stack-configuration.js";
6
6
  export interface NetworkConfiguration {
7
7
  readonly vpcName: string;
@@ -16,10 +16,32 @@ export type ReadonlyTaskRecord = Readonly<{
16
16
  totalDuration: number;
17
17
  isRunning: boolean;
18
18
  }>;
19
+ /**
20
+ * Utility class for measuring and recording task durations.
21
+ */
19
22
  export declare class StopWatch {
20
23
  private tasks;
21
24
  private static readonly DEFAULT_TASK_NAME;
22
- static createStarted(taskName?: string): StopWatch;
25
+ /**
26
+ * Creates and starts a new StopWatch instance with
27
+ * the default task name.
28
+ * @returns A new StopWatch instance with the default task started.
29
+ */
30
+ static createStarted(): StopWatch;
31
+ /**
32
+ * Creates and starts a new StopWatch instance with the given task name.
33
+ * @param taskName The name of the task to start.
34
+ * @returns A new StopWatch instance with the task started.
35
+ */
36
+ static createStarted(taskName: string): StopWatch;
37
+ /**
38
+ * Returns the duration of the specified task in seconds, formatted to the specified number of decimal places.
39
+ *
40
+ * @param taskName The name of the task to get the duration for.
41
+ * @param digits The number of decimal places to include in the result.
42
+ * @returns The duration of the task in seconds, formatted to the specified number of decimal places.
43
+ */
44
+ getDurationInSeconds(taskName?: string, digits?: number): number;
23
45
  getDuration(taskName?: string): number;
24
46
  start(taskName?: string): this;
25
47
  stop(taskName?: string): this;
@@ -1,4 +1,7 @@
1
1
  import { logger } from "../aws/runtime/logging/dt-logger-default.js";
2
+ /**
3
+ * Utility class for measuring and recording task durations.
4
+ */
2
5
  export class StopWatch {
3
6
  tasks = new Map();
4
7
  static DEFAULT_TASK_NAME = "DEFAULT_INTERNAL_TASK";
@@ -7,6 +10,16 @@ export class StopWatch {
7
10
  sw.start(taskName);
8
11
  return sw;
9
12
  }
13
+ /**
14
+ * Returns the duration of the specified task in seconds, formatted to the specified number of decimal places.
15
+ *
16
+ * @param taskName The name of the task to get the duration for.
17
+ * @param digits The number of decimal places to include in the result.
18
+ * @returns The duration of the task in seconds, formatted to the specified number of decimal places.
19
+ */
20
+ getDurationInSeconds(taskName = StopWatch.DEFAULT_TASK_NAME, digits = 2) {
21
+ return (this.getDuration(taskName) / 1000).toFixed(digits);
22
+ }
10
23
  getDuration(taskName = StopWatch.DEFAULT_TASK_NAME) {
11
24
  const task = this.getTask(taskName);
12
25
  if (!task) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@digitraffic/common",
3
- "version": "2026.11.18-1",
3
+ "version": "2026.11.19-2",
4
4
  "private": false,
5
5
  "description": "",
6
6
  "repository": {