@digitraffic/common 2026.11.13-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", () => {
@@ -28,7 +28,7 @@ describe("HttpLogger", () => {
28
28
  httpLogger.logResponse(200, 512);
29
29
  expect(infoSpy).toHaveBeenCalledWith({
30
30
  method: "HttpLogger.logStatus",
31
- [WIDE_CONTEXT.LOGGING.CONTEXT]: "port_call",
31
+ [WIDE_CONTEXT.CONTEXT]: "port_call",
32
32
  [WIDE_CONTEXT.TRACE_ID]: "trace-123",
33
33
  [WIDE_CONTEXT.HTTP_KEYS.URL]: "https://example.test/visits/1",
34
34
  [WIDE_CONTEXT.HTTP_KEYS.URL_TEMPLATE]: "/visits/{id}",
@@ -42,7 +42,7 @@ describe("HttpLogger", () => {
42
42
  ["https://example.test/visits/{id}", "/visits/{id}"],
43
43
  ["http://example.test:8080/visits/{id}?a=1", "/visits/{id}?a=1"],
44
44
  ["HTTPS://example.test/visits/{id}", "/visits/{id}"],
45
- ["https://example.test", ""],
45
+ ["https://example.test", "/"],
46
46
  ["https://example.test?a=1", "?a=1"],
47
47
  ["/visits/{id}", "/visits/{id}"],
48
48
  ["/redirect/https://other.test/{id}", "/redirect/https://other.test/{id}"],
@@ -91,7 +91,7 @@ describe("HttpLogger", () => {
91
91
  httpLogger.logError(new TypeError("request failed"));
92
92
  expect(infoSpy).toHaveBeenCalledWith(expect.objectContaining({
93
93
  method: "HttpLogger.logStatus",
94
- [WIDE_CONTEXT.LOGGING.CONTEXT]: "test",
94
+ [WIDE_CONTEXT.CONTEXT]: "test",
95
95
  [WIDE_CONTEXT.HTTP_KEYS.ERROR_TYPE]: "TypeError",
96
96
  [WIDE_CONTEXT.HTTP_KEYS.STATUS_CODE]: undefined,
97
97
  [WIDE_CONTEXT.HTTP_KEYS.CONTENT_LENGTH]: undefined,
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,124 @@
1
+ import { afterEach, describe, expect, test, vi } from "vitest";
2
+ import { logger } from "../../aws/runtime/logging/dt-logger-default.js";
3
+ import { MaintenanceLogger } from "../../aws/runtime/logging/maintenance-logger.js";
4
+ import { WIDE_CONTEXT } from "../../aws/runtime/logging/wide-context.js";
5
+ vi.mock("../../aws/runtime/logging/dt-logger-default.js", () => ({
6
+ logger: {
7
+ info: vi.fn(),
8
+ error: vi.fn(),
9
+ },
10
+ }));
11
+ describe("maintenance-logger", () => {
12
+ afterEach(() => {
13
+ vi.restoreAllMocks();
14
+ });
15
+ describe("logCleanup", () => {
16
+ test("logs successful cleanup with all required fields", () => {
17
+ const infoSpy = vi
18
+ .spyOn(logger, "info")
19
+ .mockImplementation(() => undefined);
20
+ MaintenanceLogger.instance().logCleanup("users", 150, 10, 2.5);
21
+ expect(infoSpy).toHaveBeenCalledWith({
22
+ method: "MaintenanceLogger.logCleanup",
23
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_SUCCESS,
24
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
25
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: "users",
26
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_DELETED_COUNT]: 150,
27
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_BATCH_SIZE]: 10,
28
+ [WIDE_CONTEXT.DURATION]: 2.5,
29
+ });
30
+ });
31
+ test("logs cleanup with different table names", () => {
32
+ const infoSpy = vi
33
+ .spyOn(logger, "info")
34
+ .mockImplementation(() => undefined);
35
+ MaintenanceLogger.instance().logCleanup("events", 500, 50, 5.0);
36
+ expect(infoSpy).toHaveBeenCalledWith({
37
+ method: "MaintenanceLogger.logCleanup",
38
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_SUCCESS,
39
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
40
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: "events",
41
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_DELETED_COUNT]: 500,
42
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_BATCH_SIZE]: 50,
43
+ [WIDE_CONTEXT.DURATION]: 5.0,
44
+ });
45
+ });
46
+ test("logs cleanup with zero deleted count", () => {
47
+ const infoSpy = vi
48
+ .spyOn(logger, "info")
49
+ .mockImplementation(() => undefined);
50
+ MaintenanceLogger.instance().logCleanup("archive", 0, 100, 0.5);
51
+ expect(infoSpy).toHaveBeenCalledWith({
52
+ method: "MaintenanceLogger.logCleanup",
53
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_SUCCESS,
54
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
55
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: "archive",
56
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_DELETED_COUNT]: 0,
57
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_BATCH_SIZE]: 100,
58
+ [WIDE_CONTEXT.DURATION]: 0.5,
59
+ });
60
+ });
61
+ });
62
+ describe("logError", () => {
63
+ test("logs error with all required fields", () => {
64
+ const errorSpy = vi
65
+ .spyOn(logger, "error")
66
+ .mockImplementation(() => undefined);
67
+ const error = new Error("Database connection failed");
68
+ MaintenanceLogger.instance().logError("users", 1.2, error);
69
+ expect(errorSpy).toHaveBeenCalledWith(expect.objectContaining({
70
+ method: "MaintenanceLogger.logError",
71
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_ERROR,
72
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
73
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: "users",
74
+ [WIDE_CONTEXT.DURATION]: 1.2,
75
+ error,
76
+ }));
77
+ });
78
+ test("logs error with string error", () => {
79
+ const errorSpy = vi
80
+ .spyOn(logger, "error")
81
+ .mockImplementation(() => undefined);
82
+ MaintenanceLogger.instance().logError("events", 0.5, "Timeout occurred");
83
+ expect(errorSpy).toHaveBeenCalledWith(expect.objectContaining({
84
+ method: "MaintenanceLogger.logError",
85
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_ERROR,
86
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
87
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: "events",
88
+ [WIDE_CONTEXT.DURATION]: 0.5,
89
+ error: "Timeout occurred",
90
+ }));
91
+ });
92
+ test("logs error with Error object", () => {
93
+ const errorSpy = vi
94
+ .spyOn(logger, "error")
95
+ .mockImplementation(() => undefined);
96
+ const error = new Error("Connection lost");
97
+ MaintenanceLogger.instance().logError("archive", 2.0, error);
98
+ expect(errorSpy).toHaveBeenCalledWith(expect.objectContaining({
99
+ method: "MaintenanceLogger.logError",
100
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_ERROR,
101
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
102
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: "archive",
103
+ [WIDE_CONTEXT.DURATION]: 2.0,
104
+ error,
105
+ }));
106
+ });
107
+ test("logs error with custom error object", () => {
108
+ const errorSpy = vi
109
+ .spyOn(logger, "error")
110
+ .mockImplementation(() => undefined);
111
+ const customError = { code: "DB_ERROR", message: "Query failed" };
112
+ MaintenanceLogger.instance().logError("users", 0.8, customError);
113
+ expect(errorSpy).toHaveBeenCalledWith(expect.objectContaining({
114
+ method: "MaintenanceLogger.logError",
115
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_ERROR,
116
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
117
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: "users",
118
+ [WIDE_CONTEXT.DURATION]: 0.8,
119
+ error: customError,
120
+ }));
121
+ });
122
+ });
123
+ });
124
+ //# sourceMappingURL=maintenance-logger.test.js.map
@@ -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");
@@ -42,6 +42,10 @@ export interface LoggableType extends CustomParams {
42
42
  method: LoggerMethodType;
43
43
  /** Message to log, optional */
44
44
  message?: string;
45
+ /** context, optional */
46
+ context?: string;
47
+ /** Duration of the operation in seconds, optional */
48
+ duration?: number;
45
49
  /** Type of message, optional */
46
50
  type?: string;
47
51
  /** Stack trace, optional */
@@ -49,7 +49,9 @@ export class HttpLogger {
49
49
  this._context = snakeCase(parameters.context);
50
50
  this._url = parameters.url;
51
51
  this._traceId = parameters.traceId;
52
- this._urlTemplate = parameters.urlTemplate?.replace(/^https?:\/\/[^/?#]+/i, "");
52
+ this._urlTemplate = parameters.urlTemplate
53
+ ? parameters.urlTemplate.replace(/^(?:[a-z][a-z0-9+.-]*:)?\/\/[^/?#]+/i, "") || "/"
54
+ : undefined;
53
55
  this._startTime = Date.now();
54
56
  }
55
57
  start() {
@@ -88,7 +90,7 @@ export class HttpLogger {
88
90
  logger.info({
89
91
  method: METHOD,
90
92
  [WIDE_CONTEXT.TRACE_ID]: this._traceId,
91
- [WIDE_CONTEXT.LOGGING.CONTEXT]: this._context,
93
+ [WIDE_CONTEXT.CONTEXT]: this._context,
92
94
  [WIDE_CONTEXT.HTTP_KEYS.URL]: this._url,
93
95
  [WIDE_CONTEXT.HTTP_KEYS.URL_TEMPLATE]: this._urlTemplate,
94
96
  [WIDE_CONTEXT.HTTP_KEYS.ERROR_TYPE]: parameters.errorType,
@@ -0,0 +1,21 @@
1
+ export declare class MaintenanceLogger {
2
+ private static _maintenanceLogger?;
3
+ static instance(): MaintenanceLogger;
4
+ /**
5
+ * Logs a successful database cleanup operation with structured metrics.
6
+ *
7
+ * @param tableName - The name of the table being cleaned up
8
+ * @param deletedCount - Number of rows deleted
9
+ * @param batchSize - Size of the batch processed
10
+ * @param seconds - Duration of the operation in seconds
11
+ */
12
+ logCleanup(tableName: string, deletedCount: number, batchSize: number, seconds: number): void;
13
+ /**
14
+ * Logs a database cleanup operation error with relevant context.
15
+ *
16
+ * @param tableName - The name of the table where the error occurred
17
+ * @param seconds - Duration of the operation before the error in seconds
18
+ * @param error - The error that occurred
19
+ */
20
+ logError(tableName: string, seconds: number, error: unknown): void;
21
+ }
@@ -0,0 +1,50 @@
1
+ import { logger } from "./dt-logger-default.js";
2
+ import { WIDE_CONTEXT } from "./wide-context.js";
3
+ const METHOD_CLEANUP = "MaintenanceLogger.logCleanup";
4
+ const METHOD_ERROR = "MaintenanceLogger.logError";
5
+ export class MaintenanceLogger {
6
+ static _maintenanceLogger;
7
+ static instance() {
8
+ if (!MaintenanceLogger._maintenanceLogger) {
9
+ MaintenanceLogger._maintenanceLogger = new MaintenanceLogger();
10
+ }
11
+ return MaintenanceLogger._maintenanceLogger;
12
+ }
13
+ /**
14
+ * Logs a successful database cleanup operation with structured metrics.
15
+ *
16
+ * @param tableName - The name of the table being cleaned up
17
+ * @param deletedCount - Number of rows deleted
18
+ * @param batchSize - Size of the batch processed
19
+ * @param seconds - Duration of the operation in seconds
20
+ */
21
+ logCleanup(tableName, deletedCount, batchSize, seconds) {
22
+ logger.info({
23
+ method: METHOD_CLEANUP,
24
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_SUCCESS,
25
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
26
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: tableName,
27
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_DELETED_COUNT]: deletedCount,
28
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_BATCH_SIZE]: batchSize,
29
+ [WIDE_CONTEXT.DURATION]: seconds,
30
+ });
31
+ }
32
+ /**
33
+ * Logs a database cleanup operation error with relevant context.
34
+ *
35
+ * @param tableName - The name of the table where the error occurred
36
+ * @param seconds - Duration of the operation before the error in seconds
37
+ * @param error - The error that occurred
38
+ */
39
+ logError(tableName, seconds, error) {
40
+ logger.error({
41
+ method: METHOD_ERROR,
42
+ [WIDE_CONTEXT.OUTCOME.KEY]: WIDE_CONTEXT.OUTCOME.VALUE_ERROR,
43
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_CLEANUP]: true,
44
+ [WIDE_CONTEXT.DB_MAINTENANCE.KEY_TABLENAME]: tableName,
45
+ [WIDE_CONTEXT.DURATION]: seconds,
46
+ error,
47
+ });
48
+ }
49
+ }
50
+ //# sourceMappingURL=maintenance-logger.js.map
@@ -1,14 +1,25 @@
1
1
  export declare const WIDE_CONTEXT: {
2
+ readonly METHOD: "method";
2
3
  readonly TRACE_ID: "customTrace_id";
3
- readonly LOGGING: {
4
- readonly CONTEXT: "customLogging.context";
5
- };
4
+ readonly CONTEXT: "context";
5
+ readonly DURATION: "duration";
6
6
  readonly HTTP_KEYS: {
7
+ readonly URL: "customUrl_full";
8
+ readonly URL_TEMPLATE: "customUrl_template";
9
+ readonly ERROR_TYPE: "customError_type";
7
10
  readonly DURATION: "customHttp.client.request.duration";
8
- readonly ERROR_TYPE: "customRequest.error.type";
9
11
  readonly STATUS_CODE: "customHttp.response.status_code";
10
- readonly URL: "customRequest.url.full";
11
- readonly URL_TEMPLATE: "customRequest.url.template";
12
12
  readonly CONTENT_LENGTH: "customHttp.response.body.size";
13
13
  };
14
+ readonly OUTCOME: {
15
+ readonly KEY: "customOutcome";
16
+ readonly VALUE_SUCCESS: "success";
17
+ readonly VALUE_ERROR: "error";
18
+ };
19
+ readonly DB_MAINTENANCE: {
20
+ readonly KEY_CLEANUP: "customMaintenance.db.cleanup.enabled";
21
+ readonly KEY_TABLENAME: "customMaintenance.db.table.name";
22
+ readonly KEY_DELETED_COUNT: "customMaintenance.db.cleanup.deleted.count";
23
+ readonly KEY_BATCH_SIZE: "customMaintenance.db.cleanup.batch.size";
24
+ };
14
25
  };
@@ -1,15 +1,27 @@
1
1
  export const WIDE_CONTEXT = {
2
+ METHOD: "method",
2
3
  TRACE_ID: "customTrace_id",
3
- LOGGING: {
4
- CONTEXT: "customLogging.context",
5
- },
4
+ CONTEXT: "context",
5
+ DURATION: "duration",
6
6
  HTTP_KEYS: {
7
+ // temporary keys, change to url.full etc later
8
+ URL: "customUrl_full",
9
+ URL_TEMPLATE: "customUrl_template",
10
+ ERROR_TYPE: "customError_type",
7
11
  DURATION: "customHttp.client.request.duration",
8
- ERROR_TYPE: "customRequest.error.type",
9
12
  STATUS_CODE: "customHttp.response.status_code",
10
- URL: "customRequest.url.full",
11
- URL_TEMPLATE: "customRequest.url.template",
12
13
  CONTENT_LENGTH: "customHttp.response.body.size",
13
14
  },
15
+ OUTCOME: {
16
+ KEY: "customOutcome",
17
+ VALUE_SUCCESS: "success",
18
+ VALUE_ERROR: "error",
19
+ },
20
+ DB_MAINTENANCE: {
21
+ KEY_CLEANUP: "customMaintenance.db.cleanup.enabled",
22
+ KEY_TABLENAME: "customMaintenance.db.table.name",
23
+ KEY_DELETED_COUNT: "customMaintenance.db.cleanup.deleted.count",
24
+ KEY_BATCH_SIZE: "customMaintenance.db.cleanup.batch.size",
25
+ },
14
26
  };
15
27
  //# sourceMappingURL=wide-context.js.map
@@ -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.13-1",
3
+ "version": "2026.11.19-2",
4
4
  "private": false,
5
5
  "description": "",
6
6
  "repository": {
@@ -97,6 +97,7 @@
97
97
  "./dist/aws/runtime/logging/http-logger": "./dist/aws/runtime/logging/http-logger.js",
98
98
  "./dist/aws/runtime/logging/wide-context": "./dist/aws/runtime/logging/wide-context.js",
99
99
  "./dist/aws/runtime/logging/http-interceptors": "./dist/aws/runtime/logging/http-interceptors.js",
100
+ "./dist/aws/runtime/logging/maintenance-logger": "./dist/aws/runtime/logging/maintenance-logger.js",
100
101
  "./dist/aws/runtime/secrets/secret": "./dist/aws/runtime/secrets/secret.js",
101
102
  "./dist/aws/runtime/secrets/proxy-holder": "./dist/aws/runtime/secrets/proxy-holder.js",
102
103
  "./dist/aws/runtime/secrets/dbsecret": "./dist/aws/runtime/secrets/dbsecret.js",