@mcesystems/logging-g4 1.0.69 → 1.0.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Example.md ADDED
@@ -0,0 +1,44 @@
1
+ # Logging examples
2
+
3
+ This document describes the examples in `src/example/` and how to run them.
4
+
5
+ ## sendLog.ts
6
+
7
+ **Purpose:** Send a single log event using the default batch schedule.
8
+
9
+ **Setup:** Set in `.env` or environment:
10
+
11
+ - `CREDENTIALS_PATH` — path to credentials file
12
+ - `LOGGING_API_URL` — logging API base URL
13
+ - `AUTH_API_URL` — auth API URL
14
+
15
+ Optional for this example: `TIME_BETWEEN_LOG`, `MAX_OFFLINE_TIME`, `CACHED_EVENTS_PATH` (defaults: 10 min, 1 hour; `CACHED_EVENTS_PATH` must be set).
16
+
17
+ **Run (from package root):**
18
+
19
+ ```bash
20
+ pnpm exec tsx src/example/sendLog.ts
21
+ ```
22
+
23
+ **Behavior:** Creates a `LogClient`, calls `logEvent()` once with a test event. Returns `"delayed"`; the event is queued and sent at the next cron boundary.
24
+
25
+ ## sendBatchAfterOneMinute.ts
26
+
27
+ **Purpose:** Queue a batch of log events with a 15-second gap between each, and show the time when the batch is really sent (at the next 1-minute boundary).
28
+
29
+ **Setup:** Same as sendLog. The example sets `TIME_BETWEEN_LOG=60000` (1 minute) and `CACHED_EVENTS_PATH` to a temp file if not set.
30
+
31
+ **Run (from package root):**
32
+
33
+ ```bash
34
+ pnpm exec tsx src/example/sendBatchAfterOneMinute.ts
35
+ ```
36
+
37
+ **Behavior:**
38
+
39
+ 1. Logs the scheduled send time (next 1-minute boundary).
40
+ 2. Queues three events: "First event", "Second event", "Third event", with 15 seconds between each. Each log line includes the queue time.
41
+ 3. Waits until after the boundary so the cron sends the batch.
42
+ 4. Logs "Batch was sent at: <time>" with the boundary time.
43
+
44
+ Use this to verify batching and cron-style send times.
package/README.md CHANGED
@@ -1,23 +1,71 @@
1
1
  # @mcesystems/logging-g4
2
2
 
3
- Node-only logging client that sends events to the MCE logging service.
3
+ ## 1. Description
4
4
 
5
- ## Install
5
+ **What it does:** Node-only logging client that sends events to the MCE logging service. Events are queued and sent in batches on a cron-style schedule (e.g. every 10 minutes at fixed clock boundaries). Failed sends (401, network errors) are persisted to disk and retried on the next run. If the service stays offline longer than `MAX_OFFLINE_TIME`, the client throws.
6
6
 
7
- ```
7
+ **When it's used:** Use this package when your application needs to send structured log events to the MCE logging service with batching, persistence, and offline handling—for example device management tools or services that must not lose logs when the API is temporarily unavailable.
8
+
9
+ ## 2. Install
10
+
11
+ ```bash
8
12
  pnpm add @mcesystems/logging-g4
9
13
  ```
10
14
 
11
- ## Usage (Node only)
15
+ **Requirements:** Node.js 18+. This package uses Node APIs (`fs`, `os`, `path`) and is not compatible with browsers or other non-Node runtimes.
16
+
17
+ ## 3. Resources
18
+
19
+ No binary resources are required. You need a credentials file (see Setup) and network access to the auth and logging APIs.
20
+
21
+ ## 4. Examples
22
+
23
+ **Single event**
24
+
25
+ ```bash
26
+ pnpm exec tsx src/example/sendLog.ts
27
+ ```
28
+
29
+ Uses `CREDENTIALS_PATH`, `LOGGING_API_URL`, `AUTH_API_URL` from `.env` or environment. Sends one event; returns `"delayed"` (event queued for next scheduled send).
12
30
 
13
- This package uses Node APIs (`fs`, `os`, `path`) and environment variables. It is not
14
- compatible with browsers or other non-Node runtimes.
31
+ **Batch after 1 minute (with 15s gap between events)**
15
32
 
33
+ ```bash
34
+ pnpm exec tsx src/example/sendBatchAfterOneMinute.ts
16
35
  ```
36
+
37
+ Queues three events with a 15-second gap between each; shows the time when the batch is sent at the next 1-minute boundary. Sets `TIME_BETWEEN_LOG=60000` and `CACHED_EVENTS_PATH` to a temp file if not set.
38
+
39
+ For step-by-step explanations and scenarios, see [Example.md](./Example.md).
40
+
41
+ ## 5. API
42
+
43
+ ### LogClient
44
+
45
+ **Constructor**
46
+
47
+ - **Input:** none
48
+ - **Output:** new `LogClient` instance. Call `logEvent()` after creation; `init()` runs on first `logEvent()` if needed.
49
+
50
+ **logEvent(event)**
51
+
52
+ - **Input:** `event` — object with `event_severity`, `event_type`, `event_info`, `context` (and optional fields). Omit `event_id`, `event_time`, `framework_id`, `event_source`; they are set by the client.
53
+ - **Output:** `Promise<LogSendResult>` — always `"delayed"` (event queued for next scheduled send). No immediate send. The outcomes `"success"` and `"MAX_OFFLINE_TIME passed"` occur inside the cron job: when `MAX_OFFLINE_TIME` is exceeded, `sendBatch()` throws so the process receives the exception.
54
+
55
+ ### LogSendResult
56
+
57
+ Type: `"success" | "MAX_OFFLINE_TIME passed" | "delayed"`. Exported for typing; `logEvent()` returns `"delayed"` only.
58
+
59
+ ## 6. Flow
60
+
61
+ Example flow: create client, queue several events, let the cron send the batch at the next boundary.
62
+
63
+ ```typescript
17
64
  import { LogSeverity } from "@mcesystems/logging-interfaces/lib/sdk";
18
65
  import { LogClient } from "@mcesystems/logging-g4";
19
66
 
20
67
  const logClient = new LogClient();
68
+
21
69
  await logClient.logEvent({
22
70
  event_severity: LogSeverity.Info,
23
71
  event_type: "device_connected",
@@ -26,8 +74,33 @@ await logClient.logEvent({
26
74
  source: "device-manager",
27
75
  timestamp: new Date().toISOString(),
28
76
  },
29
- context: {
30
- deviceId: "abc123",
31
- },
77
+ context: { deviceId: "abc123" },
32
78
  });
79
+ // result is "delayed" — batch will be sent at next TIME_BETWEEN_LOG boundary
80
+
81
+ await logClient.logEvent({
82
+ event_severity: LogSeverity.Info,
83
+ event_type: "device_disconnected",
84
+ event_info: { message: "Device disconnected", timestamp: new Date().toISOString() },
85
+ context: { deviceId: "abc123" },
86
+ });
87
+ // both events are queued; cron sends the batch at the next boundary
33
88
  ```
89
+
90
+ ## 7. Setup
91
+
92
+ **Environment variables**
93
+
94
+ - **TIME_BETWEEN_LOG** (ms): Interval between batch send attempts. Sends run at fixed clock boundaries (e.g. 10 min → 13:50, 14:00, 14:10). Default: 10 minutes.
95
+ - **MAX_OFFLINE_TIME** (ms): After this many ms since the first send failure, the client throws. If the batch was successfully persisted and still within this window, no throw. Default: 1 hour.
96
+ - **CACHED_EVENTS_PATH**: Path to a single JSON file for pending (delayed) events. **Required.** Delayed batches are written here on send failure and loaded on the next run; file is deleted after a successful send.
97
+ - **CREDENTIALS_PATH**: Path to credentials file used by `@mcesystems/auth-g4`. Required for auth.
98
+ - **LOGGING_API_URL**: Logging API base URL. Required.
99
+ - **AUTH_API_URL**: Auth API URL for token. Required.
100
+
101
+ **Resources location:** None. Credentials file path is given by `CREDENTIALS_PATH`. Pending events file path is given by `CACHED_EVENTS_PATH`.
102
+
103
+ ## 8. TODO
104
+
105
+ - [ ] Optional: Expand Example.md with more scenarios (e.g. offline handling, MAX_OFFLINE_TIME).
106
+ - [ ] Optional: Token refresh on 401 before persisting and retrying.
package/dist/index.js CHANGED
@@ -21437,16 +21437,80 @@ function v4(options, buf, offset) {
21437
21437
  }
21438
21438
  var v4_default = v4;
21439
21439
 
21440
+ // src/logic/cronSchedule.ts
21441
+ function getNextCronRun(intervalMs) {
21442
+ const now = Date.now();
21443
+ const midnight = new Date(now);
21444
+ midnight.setHours(0, 0, 0, 0);
21445
+ const msSinceMidnight = now - midnight.getTime();
21446
+ const nextBoundaryMs = Math.ceil(msSinceMidnight / intervalMs) * intervalMs;
21447
+ let nextRun = midnight.getTime() + nextBoundaryMs;
21448
+ if (nextRun <= now) {
21449
+ nextRun += intervalMs;
21450
+ }
21451
+ return nextRun;
21452
+ }
21453
+
21454
+ // src/logic/pendingEventsStorage.ts
21455
+ var import_promises = require("node:fs/promises");
21456
+ async function readPendingEvents(filePath) {
21457
+ try {
21458
+ const data = await (0, import_promises.readFile)(filePath, "utf-8");
21459
+ return JSON.parse(data);
21460
+ } catch (error) {
21461
+ const err = error;
21462
+ if (err.code === "ENOENT") {
21463
+ return [];
21464
+ }
21465
+ throw error;
21466
+ }
21467
+ }
21468
+ async function writePendingEvents(filePath, events) {
21469
+ await (0, import_promises.writeFile)(filePath, JSON.stringify(events), "utf-8");
21470
+ }
21471
+ async function deletePendingEvents(filePath) {
21472
+ try {
21473
+ await (0, import_promises.unlink)(filePath);
21474
+ } catch (error) {
21475
+ const err = error;
21476
+ if (err.code !== "ENOENT") {
21477
+ throw error;
21478
+ }
21479
+ }
21480
+ }
21481
+
21440
21482
  // src/logic/logClient.ts
21441
21483
  var LogClient = class {
21442
21484
  credentials;
21443
21485
  loggingClient;
21444
- offlinetime;
21445
21486
  cachedEvents = [];
21446
21487
  initialized = false;
21488
+ firstOfflineTime;
21489
+ sendTimeoutId;
21490
+ timeBetweenLogMs;
21491
+ maxOfflineTimeMs;
21492
+ pendingEventsPath;
21493
+ sendInProgress = false;
21494
+ schedulerStarted = false;
21447
21495
  async init() {
21448
21496
  setLogLevel2(process.env.LOG_LEVEL ?? "none");
21449
21497
  logNamespace2("logging");
21498
+ if (typeof this.timeBetweenLogMs !== "number") {
21499
+ const DEFAULT_TIME_BETWEEN_LOG_MS = 10 * 60 * 1e3;
21500
+ const DEFAULT_MAX_OFFLINE_TIME_MS = 60 * 60 * 1e3;
21501
+ const timeBetweenLog = process.env.TIME_BETWEEN_LOG;
21502
+ const maxOfflineTime = process.env.MAX_OFFLINE_TIME;
21503
+ const cachedEventsPath = process.env.CACHED_EVENTS_PATH;
21504
+ if (!cachedEventsPath) {
21505
+ throw new Error("CACHED_EVENTS_PATH must be set");
21506
+ }
21507
+ this.timeBetweenLogMs = Number(timeBetweenLog) || DEFAULT_TIME_BETWEEN_LOG_MS;
21508
+ this.maxOfflineTimeMs = Number(maxOfflineTime) || DEFAULT_MAX_OFFLINE_TIME_MS;
21509
+ this.pendingEventsPath = cachedEventsPath;
21510
+ if (!Number.isFinite(this.timeBetweenLogMs) || this.timeBetweenLogMs <= 0 || !Number.isFinite(this.maxOfflineTimeMs) || this.maxOfflineTimeMs <= 0) {
21511
+ throw new Error("TIME_BETWEEN_LOG and MAX_OFFLINE_TIME must be positive numbers");
21512
+ }
21513
+ }
21450
21514
  const os4 = await import("node:os");
21451
21515
  const path = await import("node:path");
21452
21516
  const fs = await import("node:fs/promises");
@@ -21485,18 +21549,81 @@ var LogClient = class {
21485
21549
  } else {
21486
21550
  token = tokenFile.token;
21487
21551
  }
21488
- if (!token) {
21489
- throw new Error("Token not found");
21490
- }
21491
- try {
21552
+ if (token) {
21492
21553
  const loggingApi = process.env.LOGGING_API_URL ?? "";
21493
21554
  if (!loggingApi) {
21494
21555
  throw new Error("LOGGING_API_URL is not set");
21495
21556
  }
21496
21557
  this.loggingClient = new import_gql_logging_client.default(loggingApi, token.accessToken);
21497
21558
  this.initialized = true;
21498
- } catch (error) {
21499
- logError2("Check your internet connection", error);
21559
+ } else {
21560
+ logError2("Check your internet connection - token not found");
21561
+ }
21562
+ if (!this.schedulerStarted) {
21563
+ this.schedulerStarted = true;
21564
+ this.scheduleNextRun();
21565
+ }
21566
+ }
21567
+ scheduleNextRun() {
21568
+ if (this.sendTimeoutId !== void 0) {
21569
+ clearTimeout(this.sendTimeoutId);
21570
+ this.sendTimeoutId = void 0;
21571
+ }
21572
+ const nextRun = getNextCronRun(this.timeBetweenLogMs);
21573
+ const delay = Math.max(0, nextRun - Date.now());
21574
+ this.sendTimeoutId = setTimeout(() => {
21575
+ void this.runScheduledSend();
21576
+ }, delay);
21577
+ }
21578
+ async runScheduledSend() {
21579
+ try {
21580
+ await this.sendBatch();
21581
+ } catch {
21582
+ this.sendTimeoutId = void 0;
21583
+ return;
21584
+ }
21585
+ this.scheduleNextRun();
21586
+ }
21587
+ async sendBatch() {
21588
+ if (this.sendInProgress) {
21589
+ return;
21590
+ }
21591
+ this.sendInProgress = true;
21592
+ try {
21593
+ const loaded = await readPendingEvents(this.pendingEventsPath);
21594
+ const batch = [...this.cachedEvents, ...loaded];
21595
+ this.cachedEvents = [];
21596
+ if (batch.length === 0) {
21597
+ this.firstOfflineTime = void 0;
21598
+ return;
21599
+ }
21600
+ if (!this.loggingClient) {
21601
+ if (this.firstOfflineTime === void 0) {
21602
+ this.firstOfflineTime = Date.now();
21603
+ }
21604
+ await writePendingEvents(this.pendingEventsPath, batch);
21605
+ if (Date.now() - this.firstOfflineTime > this.maxOfflineTimeMs) {
21606
+ throw new Error("Exceeded max offline time");
21607
+ }
21608
+ return;
21609
+ }
21610
+ try {
21611
+ await this.loggingClient.mutate({ events: batch }).promise();
21612
+ await deletePendingEvents(this.pendingEventsPath);
21613
+ this.firstOfflineTime = void 0;
21614
+ logInfo2(`Logging batch result: ${batch.length} events sent`);
21615
+ } catch (error) {
21616
+ logError2("Send batch failed", error);
21617
+ if (this.firstOfflineTime === void 0) {
21618
+ this.firstOfflineTime = Date.now();
21619
+ }
21620
+ await writePendingEvents(this.pendingEventsPath, batch);
21621
+ if (Date.now() - this.firstOfflineTime > this.maxOfflineTimeMs) {
21622
+ throw new Error("Exceeded max offline time");
21623
+ }
21624
+ }
21625
+ } finally {
21626
+ this.sendInProgress = false;
21500
21627
  }
21501
21628
  }
21502
21629
  async logEvent(event) {
@@ -21513,34 +21640,8 @@ var LogClient = class {
21513
21640
  ...event
21514
21641
  };
21515
21642
  logDataObject("Logging event", newEvent);
21516
- if (!this.loggingClient) {
21517
- logError2("Logging client not initialized");
21518
- if (!this.offlinetime) {
21519
- this.offlinetime = Date.now();
21520
- } else if (Date.now() - this.offlinetime > +(process.env.OFFLINE_TIME ?? 1e3 * 60 * 60)) {
21521
- if (process.env.APP_TYPE === "node") {
21522
- const { writeFile } = await import("node:fs/promises");
21523
- if (!process.env.CACHED_EVENTS_PATH) {
21524
- throw new Error("CACHED_EVENTS_PATH is not set");
21525
- }
21526
- await writeFile(
21527
- `${process.env.CACHED_EVENTS_PATH}-${Date.now()}.json`,
21528
- JSON.stringify(this.cachedEvents)
21529
- );
21530
- logInfo2(`Cached events saved to: ${process.env.CACHED_EVENTS_PATH}`);
21531
- this.offlinetime = Date.now();
21532
- this.cachedEvents = [];
21533
- }
21534
- }
21535
- this.cachedEvents.push(newEvent);
21536
- return;
21537
- }
21538
- const result = await this.loggingClient.mutate({
21539
- events: [newEvent, ...this.cachedEvents]
21540
- }).promise();
21541
- this.cachedEvents = [];
21542
- logInfo2(`Logging event result: ${JSON.stringify(result)}`);
21543
- return result;
21643
+ this.cachedEvents.push(newEvent);
21644
+ return "delayed";
21544
21645
  }
21545
21646
  };
21546
21647
  // Annotate the CommonJS export names for ESM import in node: