kubernetes-fluent-client 3.0.3 → 4.0.0-rc-http2-watch

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 (42) hide show
  1. package/.prettierignore +4 -0
  2. package/README.md +24 -0
  3. package/dist/cli.js +21 -1
  4. package/dist/fileSystem.d.ts +11 -0
  5. package/dist/fileSystem.d.ts.map +1 -0
  6. package/dist/fileSystem.js +42 -0
  7. package/dist/fileSystem.test.d.ts +2 -0
  8. package/dist/fileSystem.test.d.ts.map +1 -0
  9. package/dist/fileSystem.test.js +75 -0
  10. package/dist/fluent/watch.d.ts +2 -0
  11. package/dist/fluent/watch.d.ts.map +1 -1
  12. package/dist/fluent/watch.js +147 -27
  13. package/dist/generate.d.ts +71 -11
  14. package/dist/generate.d.ts.map +1 -1
  15. package/dist/generate.js +130 -117
  16. package/dist/generate.test.js +293 -346
  17. package/dist/postProcessing.d.ts +246 -0
  18. package/dist/postProcessing.d.ts.map +1 -0
  19. package/dist/postProcessing.js +497 -0
  20. package/dist/postProcessing.test.d.ts +2 -0
  21. package/dist/postProcessing.test.d.ts.map +1 -0
  22. package/dist/postProcessing.test.js +550 -0
  23. package/e2e/cli.e2e.test.ts +127 -0
  24. package/e2e/crds/policyreports.default.expected/policyreport-v1alpha1.ts +332 -0
  25. package/e2e/crds/policyreports.default.expected/policyreport-v1alpha2.ts +360 -0
  26. package/e2e/crds/policyreports.default.expected/policyreport-v1beta1.ts +360 -0
  27. package/e2e/crds/policyreports.no.post.expected/policyreport-v1alpha1.ts +331 -0
  28. package/e2e/crds/policyreports.no.post.expected/policyreport-v1alpha2.ts +360 -0
  29. package/e2e/crds/policyreports.no.post.expected/policyreport-v1beta1.ts +360 -0
  30. package/e2e/crds/test.yaml/policyreports.test.yaml +1008 -0
  31. package/e2e/crds/test.yaml/uds-podmonitors.test.yaml +1245 -0
  32. package/e2e/crds/uds-podmonitors.default.expected/podmonitor-v1.ts +1333 -0
  33. package/e2e/crds/uds-podmonitors.no.post.expected/podmonitor-v1.ts +1360 -0
  34. package/package.json +6 -5
  35. package/src/cli.ts +25 -1
  36. package/src/fileSystem.test.ts +67 -0
  37. package/src/fileSystem.ts +25 -0
  38. package/src/fluent/watch.ts +174 -35
  39. package/src/generate.test.ts +368 -358
  40. package/src/generate.ts +173 -154
  41. package/src/postProcessing.test.ts +742 -0
  42. package/src/postProcessing.ts +568 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kubernetes-fluent-client",
3
- "version": "3.0.3",
3
+ "version": "4.0.0-rc-http2-watch",
4
4
  "description": "A @kubernetes/client-node fluent API wrapper that leverages K8s Server Side Apply.",
5
5
  "bin": "./dist/cli.js",
6
6
  "main": "dist/index.js",
@@ -10,6 +10,7 @@
10
10
  "build": "tsc",
11
11
  "semantic-release": "semantic-release",
12
12
  "test": "jest src --coverage",
13
+ "test:e2e": "jest e2e",
13
14
  "format:check": "eslint src && prettier . --check",
14
15
  "format:fix": "eslint --fix src && prettier . --write"
15
16
  },
@@ -52,13 +53,13 @@
52
53
  "@types/readable-stream": "4.0.15",
53
54
  "@types/urijs": "^1.19.25",
54
55
  "@types/yargs": "17.0.33",
55
- "@typescript-eslint/eslint-plugin": "8.5.0",
56
- "@typescript-eslint/parser": "8.5.0",
57
- "eslint-plugin-jsdoc": "50.2.3",
56
+ "@typescript-eslint/eslint-plugin": "8.8.1",
57
+ "@typescript-eslint/parser": "8.8.1",
58
+ "eslint-plugin-jsdoc": "50.3.1",
58
59
  "jest": "29.7.0",
59
60
  "nock": "13.5.5",
60
61
  "prettier": "3.3.3",
61
- "semantic-release": "24.1.1",
62
+ "semantic-release": "24.1.2",
62
63
  "ts-jest": "29.2.5",
63
64
  "typescript": "5.6.2"
64
65
  },
package/src/cli.ts CHANGED
@@ -7,6 +7,8 @@ import { hideBin } from "yargs/helpers";
7
7
  import yargs from "yargs/yargs";
8
8
  import { GenerateOptions, generate } from "./generate";
9
9
  import { version } from "../package.json";
10
+ import { postProcessing } from "./postProcessing";
11
+ import { NodeFileSystem } from "./fileSystem"; // Import your new file system
10
12
 
11
13
  void yargs(hideBin(process.argv))
12
14
  .version("version", "Display version number", `kubernetes-fluent-client v${version}`)
@@ -37,14 +39,36 @@ void yargs(hideBin(process.argv))
37
39
  description:
38
40
  "the language to generate types in, see https://github.com/glideapps/quicktype#target-languages for a list of supported languages",
39
41
  })
42
+ .option("noPost", {
43
+ alias: "x",
44
+ type: "boolean",
45
+ default: false,
46
+ description: "disable post-processing after generating the types",
47
+ })
40
48
  .demandOption(["source", "directory"]);
41
49
  },
42
50
  async argv => {
43
51
  const opts = argv as unknown as GenerateOptions;
44
52
  opts.logFn = console.log;
45
53
 
54
+ // Pass the `post` flag to opts
55
+ opts.noPost = argv.noPost as boolean;
56
+
57
+ // Use NodeFileSystem as the file system for post-processing
58
+ const fileSystem = new NodeFileSystem(); // Create an instance of NodeFileSystem
59
+
60
+ if (!opts.noPost) {
61
+ console.log("\n✅ Post-processing has been enabled.\n");
62
+ }
63
+
46
64
  try {
47
- await generate(opts);
65
+ // Capture the results returned by generate
66
+ const allResults = await generate(opts);
67
+
68
+ // If noPost is false, run post-processing
69
+ if (!opts.noPost) {
70
+ await postProcessing(allResults, opts, fileSystem); // Pass the file system to postProcessing
71
+ }
48
72
  } catch (e) {
49
73
  console.log(`\n❌ ${e.message}`);
50
74
  }
@@ -0,0 +1,67 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2023-Present The Kubernetes Fluent Client Authors
3
+
4
+ import * as fs from "fs";
5
+ import { NodeFileSystem } from "./fileSystem";
6
+ import { beforeEach, describe, expect, jest, test } from "@jest/globals";
7
+
8
+ // Mock the fs module
9
+ jest.mock("fs");
10
+
11
+ describe("NodeFileSystem", () => {
12
+ let nodeFileSystem: NodeFileSystem;
13
+
14
+ beforeEach(() => {
15
+ nodeFileSystem = new NodeFileSystem();
16
+ jest.clearAllMocks(); // Clear all mocks before each test
17
+ });
18
+
19
+ describe("readFile", () => {
20
+ test("should call fs.readFileSync with correct arguments", () => {
21
+ const mockFilePath = "test-file.txt";
22
+ const mockFileContent = "This is a test file";
23
+
24
+ // Mock the fs.readFileSync method to return the mock file content
25
+ (fs.readFileSync as jest.Mock).mockReturnValue(mockFileContent);
26
+
27
+ const result = nodeFileSystem.readFile(mockFilePath);
28
+
29
+ // Assert that fs.readFileSync was called with the correct file path and encoding
30
+ expect(fs.readFileSync).toHaveBeenCalledWith(mockFilePath, "utf8");
31
+
32
+ // Assert that the returned content matches the mock file content
33
+ expect(result).toBe(mockFileContent);
34
+ });
35
+ });
36
+
37
+ describe("writeFile", () => {
38
+ test("should call fs.writeFileSync with correct arguments", () => {
39
+ const mockFilePath = "test-file.txt";
40
+ const mockFileContent = "This is a test file";
41
+
42
+ // Call the writeFile method
43
+ nodeFileSystem.writeFile(mockFilePath, mockFileContent);
44
+
45
+ // Assert that fs.writeFileSync was called with the correct arguments
46
+ expect(fs.writeFileSync).toHaveBeenCalledWith(mockFilePath, mockFileContent, "utf8");
47
+ });
48
+ });
49
+
50
+ describe("readdirSync", () => {
51
+ test("should call fs.readdirSync with correct arguments and return file list", () => {
52
+ const mockDirectoryPath = "test-directory";
53
+ const mockFileList = ["file1.txt", "file2.txt"];
54
+
55
+ // Mock the fs.readdirSync method to return the mock file list
56
+ (fs.readdirSync as jest.Mock).mockReturnValue(mockFileList);
57
+
58
+ const result = nodeFileSystem.readdirSync(mockDirectoryPath);
59
+
60
+ // Assert that fs.readdirSync was called with the correct directory path
61
+ expect(fs.readdirSync).toHaveBeenCalledWith(mockDirectoryPath);
62
+
63
+ // Assert that the returned file list matches the mock file list
64
+ expect(result).toEqual(mockFileList);
65
+ });
66
+ });
67
+ });
@@ -0,0 +1,25 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2023-Present The Kubernetes Fluent Client Authors
3
+
4
+ import * as fs from "fs";
5
+
6
+ export interface FileSystem {
7
+ readFile(filePath: string): string;
8
+ writeFile(filePath: string, content: string): void;
9
+ readdirSync(directory: string): string[];
10
+ }
11
+
12
+ /* eslint class-methods-use-this: "off" */
13
+ export class NodeFileSystem implements FileSystem {
14
+ readFile(filePath: string): string {
15
+ return fs.readFileSync(filePath, "utf8");
16
+ }
17
+
18
+ writeFile(filePath: string, content: string): void {
19
+ fs.writeFileSync(filePath, content, "utf8");
20
+ }
21
+
22
+ readdirSync(directory: string): string[] {
23
+ return fs.readdirSync(directory);
24
+ }
25
+ }
@@ -4,12 +4,14 @@
4
4
  import byline from "byline";
5
5
  import { createHash } from "crypto";
6
6
  import { EventEmitter } from "events";
7
+ import https from "https";
8
+ import http2 from "http2";
7
9
  import fetch from "node-fetch";
8
-
9
10
  import { fetch as wrappedFetch } from "../fetch";
10
11
  import { GenericClass, KubernetesListObject } from "../types";
11
12
  import { Filters, WatchAction, WatchPhase } from "./types";
12
13
  import { k8sCfg, pathBuilder } from "./utils";
14
+ import fs from "fs";
13
15
 
14
16
  export enum WatchEvent {
15
17
  /** Watch is connected successfully */
@@ -52,6 +54,8 @@ export type WatchCfg = {
52
54
  relistIntervalSec?: number;
53
55
  /** Max amount of seconds to go without receiving an event before reconciliation starts. Defaults to 300 (5 minutes). */
54
56
  lastSeenLimitSeconds?: number;
57
+ /** Use http2 for the Watch */
58
+ useHTTP2?: boolean;
55
59
  };
56
60
 
57
61
  const NONE = 50;
@@ -65,6 +69,7 @@ export class Watcher<T extends GenericClass> {
65
69
  #callback: WatchAction<T>;
66
70
  #watchCfg: WatchCfg;
67
71
  #latestRelistWindow: string = "";
72
+ #useHTTP2: boolean = false;
68
73
 
69
74
  // Track the last time data was received
70
75
  #lastSeenTime = NONE;
@@ -97,6 +102,8 @@ export class Watcher<T extends GenericClass> {
97
102
  // Track the list of items in the cache
98
103
  #cache = new Map<string, InstanceType<T>>();
99
104
 
105
+ // Token Path
106
+ #TOKEN_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/token";
100
107
  /**
101
108
  * Setup a Kubernetes watcher for the specified model and filters. The callback function will be called for each event received.
102
109
  * The watch can be aborted by calling {@link Watcher.close} or by calling abort() on the AbortController returned by {@link Watcher.start}.
@@ -125,6 +132,9 @@ export class Watcher<T extends GenericClass> {
125
132
  // Set the latest relist interval to now
126
133
  this.#latestRelistWindow = new Date().toISOString();
127
134
 
135
+ // Set the latest relist interval to now
136
+ this.#useHTTP2 = watchCfg.useHTTP2 ?? false;
137
+
128
138
  // Add random jitter to the relist/resync intervals (up to 1 second)
129
139
  const jitter = Math.floor(Math.random() * 1000);
130
140
 
@@ -158,7 +168,11 @@ export class Watcher<T extends GenericClass> {
158
168
  */
159
169
  public async start(): Promise<AbortController> {
160
170
  this.#events.emit(WatchEvent.INIT_CACHE_MISS, this.#latestRelistWindow);
161
- await this.#watch();
171
+ if (this.#useHTTP2) {
172
+ await this.#http2Watch();
173
+ } else {
174
+ await this.#watch();
175
+ }
162
176
  return this.#abortController;
163
177
  }
164
178
 
@@ -198,6 +212,19 @@ export class Watcher<T extends GenericClass> {
198
212
  return this.#events;
199
213
  }
200
214
 
215
+ /**
216
+ * Read the serviceAccount Token
217
+ *
218
+ * @returns token or null
219
+ */
220
+ async #getToken() {
221
+ try {
222
+ return (await fs.promises.readFile(this.#TOKEN_PATH, "utf8")).trim();
223
+ } catch {
224
+ return null;
225
+ }
226
+ }
227
+
201
228
  /**
202
229
  * Build the URL and request options for the watch.
203
230
  *
@@ -351,6 +378,42 @@ export class Watcher<T extends GenericClass> {
351
378
  }
352
379
  };
353
380
 
381
+ // process a line from the chunk
382
+ #processLine = async (
383
+ line: string,
384
+ process: (payload: InstanceType<T>, phase: WatchPhase) => Promise<void>,
385
+ ) => {
386
+ try {
387
+ // Parse the event payload
388
+ const { object: payload, type: phase } = JSON.parse(line) as {
389
+ type: WatchPhase;
390
+ object: InstanceType<T>;
391
+ };
392
+
393
+ // Update the last seen time
394
+ this.#lastSeenTime = Date.now();
395
+
396
+ // If the watch is too old, remove the resourceVersion and reload the watch
397
+ if (phase === WatchPhase.Error && payload.code === 410) {
398
+ throw {
399
+ name: "TooOld",
400
+ message: this.#resourceVersion!,
401
+ };
402
+ }
403
+
404
+ // Process the event payload, do not update the resource version as that is handled by the list operation
405
+ await process(payload, phase);
406
+ } catch (err) {
407
+ if (err.name === "TooOld") {
408
+ // Reload the watch
409
+ void this.#errHandler(err);
410
+ return;
411
+ }
412
+
413
+ this.#events.emit(WatchEvent.DATA_ERROR, err);
414
+ }
415
+ };
416
+
354
417
  /**
355
418
  * Watch for changes to the resource.
356
419
  */
@@ -388,38 +451,7 @@ export class Watcher<T extends GenericClass> {
388
451
 
389
452
  // Listen for events and call the callback function
390
453
  this.#stream.on("data", async line => {
391
- try {
392
- // Parse the event payload
393
- const { object: payload, type: phase } = JSON.parse(line) as {
394
- type: WatchPhase;
395
- object: InstanceType<T>;
396
- };
397
-
398
- // Update the last seen time
399
- this.#lastSeenTime = Date.now();
400
-
401
- // If the watch is too old, remove the resourceVersion and reload the watch
402
- if (phase === WatchPhase.Error && payload.code === 410) {
403
- throw {
404
- name: "TooOld",
405
- message: this.#resourceVersion!,
406
- };
407
- }
408
-
409
- // Process the event payload, do not update the resource version as that is handled by the list operation
410
- await this.#process(payload, phase);
411
- } catch (err) {
412
- if (err.name === "TooOld") {
413
- // Prevent any body events from firing
414
- body.removeAllListeners();
415
-
416
- // Reload the watch
417
- void this.#errHandler(err);
418
- return;
419
- }
420
-
421
- this.#events.emit(WatchEvent.DATA_ERROR, err);
422
- }
454
+ await this.#processLine(line, this.#process);
423
455
  });
424
456
 
425
457
  // Bind the body events
@@ -437,6 +469,108 @@ export class Watcher<T extends GenericClass> {
437
469
  }
438
470
  };
439
471
 
472
+ /**
473
+ * Watch for changes to the resource.
474
+ */
475
+ #http2Watch = async () => {
476
+ try {
477
+ // Start with a list operation
478
+ await this.#list();
479
+
480
+ // Build the URL and request options
481
+ const { opts, url } = await this.#buildURL(true, this.#resourceVersion);
482
+ let agentOptions;
483
+
484
+ if (opts.agent && opts.agent instanceof https.Agent) {
485
+ agentOptions = {
486
+ key: opts.agent.options.key,
487
+ cert: opts.agent.options.cert,
488
+ ca: opts.agent.options.ca,
489
+ rejectUnauthorized: false,
490
+ };
491
+ }
492
+
493
+ // HTTP/2 client connection setup
494
+ const client = http2.connect(url.origin, {
495
+ ca: agentOptions?.ca,
496
+ cert: agentOptions?.cert,
497
+ key: agentOptions?.key,
498
+ rejectUnauthorized: agentOptions?.rejectUnauthorized,
499
+ });
500
+
501
+ // Set up headers for the HTTP/2 request
502
+ const token = await this.#getToken();
503
+ const headers: Record<string, string> = {
504
+ ":method": "GET",
505
+ ":path": url.pathname + url.search,
506
+ "content-type": "application/json",
507
+ "user-agent": "kubernetes-fluent-client",
508
+ };
509
+
510
+ if (token) {
511
+ headers["Authorization"] = `Bearer ${token}`;
512
+ }
513
+
514
+ // Make the HTTP/2 request
515
+ const req = client.request(headers);
516
+
517
+ req.setEncoding("utf8");
518
+
519
+ let buffer = "";
520
+
521
+ // Handle response data
522
+ req.on("response", headers => {
523
+ const statusCode = headers[":status"];
524
+
525
+ if (statusCode && statusCode >= 200 && statusCode < 300) {
526
+ this.#pendingReconnect = false;
527
+ this.#events.emit(WatchEvent.CONNECT, url.pathname);
528
+
529
+ // Reset the retry count
530
+ this.#resyncFailureCount = 0;
531
+ this.#events.emit(WatchEvent.INC_RESYNC_FAILURE_COUNT, this.#resyncFailureCount);
532
+
533
+ req.on("data", async chunk => {
534
+ try {
535
+ buffer += chunk;
536
+ const lines = buffer.split("\n");
537
+ // Avoid Watch event data_error received. Unexpected end of JSON input.
538
+ buffer = lines.pop()!;
539
+
540
+ for (const line of lines) {
541
+ await this.#processLine(line, this.#process);
542
+ }
543
+ } catch (err) {
544
+ void this.#errHandler(err);
545
+ }
546
+ });
547
+
548
+ req.on("end", () => {
549
+ this.#streamCleanup();
550
+ client.close();
551
+ });
552
+
553
+ req.on("close", () => {
554
+ this.#streamCleanup();
555
+ client.close();
556
+ });
557
+
558
+ req.on("error", err => {
559
+ void this.#errHandler(err);
560
+ client.close();
561
+ });
562
+ } else {
563
+ const statusMessage = headers[":status-text"] || "Unknown";
564
+ throw new Error(`watch connect failed: ${statusCode} ${statusMessage}`);
565
+ }
566
+ });
567
+
568
+ req.end();
569
+ } catch (e) {
570
+ void this.#errHandler(e);
571
+ }
572
+ };
573
+
440
574
  /** Clear the resync timer and schedule a new one. */
441
575
  #checkResync = () => {
442
576
  // Ignore if the last seen time is not set
@@ -468,7 +602,9 @@ export class Watcher<T extends GenericClass> {
468
602
  this.#events.emit(WatchEvent.RECONNECT, this.#resyncFailureCount);
469
603
  this.#streamCleanup();
470
604
 
471
- void this.#watch();
605
+ if (!this.#useHTTP2) {
606
+ void this.#watch();
607
+ }
472
608
  }
473
609
  } else {
474
610
  // Otherwise, call the finally function if it exists
@@ -516,5 +652,8 @@ export class Watcher<T extends GenericClass> {
516
652
  this.#stream.removeAllListeners();
517
653
  this.#stream.destroy();
518
654
  }
655
+ if (this.#useHTTP2) {
656
+ void this.#http2Watch();
657
+ }
519
658
  };
520
659
  }