pepr 0.35.0 → 0.36.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.
package/src/lib/types.ts CHANGED
@@ -94,6 +94,7 @@ export type Binding = {
94
94
  namespaces: string[];
95
95
  labels: Record<string, string>;
96
96
  annotations: Record<string, string>;
97
+ deletionTimestamp: boolean;
97
98
  };
98
99
  readonly mutateCallback?: MutateAction<GenericClass, InstanceType<GenericClass>>;
99
100
  readonly validateCallback?: ValidateAction<GenericClass, InstanceType<GenericClass>>;
@@ -137,6 +138,8 @@ export type BindingFilter<T extends GenericClass> = CommonActionChain<T> & {
137
138
  * @param value
138
139
  */
139
140
  WithAnnotation: (key: string, value?: string) => BindingFilter<T>;
141
+ /** Only apply the action if the resource has a deletionTimestamp. */
142
+ WithDeletionTimestamp: () => BindingFilter<T>;
140
143
  };
141
144
 
142
145
  export type BindingWithName<T extends GenericClass> = BindingFilter<T> & {
@@ -1,11 +1,11 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
3
- import { afterAll, beforeEach, beforeAll, describe, expect, it, jest } from "@jest/globals";
3
+ import { afterAll, beforeEach, describe, expect, it, jest } from "@jest/globals";
4
4
  import { GenericClass, K8s, KubernetesObject, kind } from "kubernetes-fluent-client";
5
5
  import { K8sInit, WatchPhase } from "kubernetes-fluent-client/dist/fluent/types";
6
6
  import { WatchCfg, WatchEvent, Watcher } from "kubernetes-fluent-client/dist/fluent/watch";
7
7
  import { Capability } from "./capability";
8
- import { setupWatch, logEvent, queueRecordKey } from "./watch-processor";
8
+ import { setupWatch, logEvent, queueKey, getOrCreateQueue } from "./watch-processor";
9
9
  import Log from "./logger";
10
10
  import { metricsCollector } from "./metrics";
11
11
 
@@ -40,6 +40,7 @@ describe("WatchProcessor", () => {
40
40
  bindings: [
41
41
  {
42
42
  isWatch: true,
43
+ isQueue: false,
43
44
  model: "someModel",
44
45
  filters: {},
45
46
  event: "Create",
@@ -93,8 +94,15 @@ describe("WatchProcessor", () => {
93
94
 
94
95
  capabilities.push({
95
96
  bindings: [
96
- { isWatch: true, model: "someModel", filters: { name: "bleh" }, event: "Create", watchCallback: jest.fn() },
97
- { isWatch: false, model: "someModel", filters: {}, event: "Create", watchCallback: jest.fn() },
97
+ {
98
+ isWatch: true,
99
+ isQueue: true,
100
+ model: "someModel",
101
+ filters: { name: "bleh" },
102
+ event: "Create",
103
+ watchCallback: jest.fn(),
104
+ },
105
+ { isWatch: false, isQueue: false, model: "someModel", filters: {}, event: "Create", watchCallback: jest.fn() },
98
106
  ],
99
107
  } as unknown as Capability);
100
108
 
@@ -321,133 +329,90 @@ describe("logEvent function", () => {
321
329
  });
322
330
  });
323
331
 
324
- describe("queueRecordKey", () => {
325
- describe("PEPR_RECONCILE_STRATEGY=sharded", () => {
326
- const original = process.env.PEPR_RECONCILE_STRATEGY;
327
-
328
- beforeAll(() => {
329
- process.env.PEPR_RECONCILE_STRATEGY = "sharded";
330
- });
331
- afterAll(() => {
332
- process.env.PEPR_RECONCILE_STRATEGY = original;
333
- });
334
-
335
- it("should return correct key for an object with 'kind/name/namespace'", () => {
336
- const obj: KubernetesObject = {
337
- kind: "Pod",
338
- metadata: {
339
- name: "my-pod",
340
- namespace: "my-namespace",
341
- },
342
- };
343
-
344
- expect(queueRecordKey(obj)).toBe("Pod/my-pod/my-namespace");
345
- });
346
-
347
- it("should handle objects with missing namespace", () => {
348
- const obj: KubernetesObject = {
349
- kind: "Pod",
350
- metadata: {
351
- name: "my-pod",
352
- },
353
- };
354
-
355
- expect(queueRecordKey(obj)).toBe("Pod/my-pod/cluster-scoped");
356
- });
357
-
358
- it("should handle objects with missing name", () => {
359
- const obj: KubernetesObject = {
360
- kind: "Pod",
361
- metadata: {
362
- namespace: "my-namespace",
363
- },
364
- };
365
-
366
- expect(queueRecordKey(obj)).toBe("Pod/Unnamed/my-namespace");
367
- });
368
-
369
- it("should handle objects with missing metadata", () => {
370
- const obj: KubernetesObject = {
371
- kind: "Pod",
372
- };
373
-
374
- expect(queueRecordKey(obj)).toBe("Pod/Unnamed/cluster-scoped");
375
- });
376
-
377
- it("should handle objects with missing kind", () => {
378
- const obj: KubernetesObject = {
379
- metadata: {
380
- name: "my-pod",
381
- namespace: "my-namespace",
382
- },
383
- };
384
-
385
- expect(queueRecordKey(obj)).toBe("UnknownKind/my-pod/my-namespace");
386
- });
387
-
388
- it("should handle completely empty objects", () => {
389
- const obj: KubernetesObject = {};
390
-
391
- expect(queueRecordKey(obj)).toBe("UnknownKind/Unnamed/cluster-scoped");
392
- });
332
+ describe("queueKey", () => {
333
+ const withKindNsName = { kind: "Pod", metadata: { namespace: "my-ns", name: "my-name" } } as KubernetesObject;
334
+ const withKindNs = { kind: "Pod", metadata: { namespace: "my-ns" } } as KubernetesObject;
335
+ const withKindName = { kind: "Pod", metadata: { name: "my-name" } } as KubernetesObject;
336
+ const withNsName = { metadata: { namespace: "my-ns", name: "my-name" } } as KubernetesObject;
337
+ const withKind = { kind: "Pod" } as KubernetesObject;
338
+ const withNs = { metadata: { namespace: "my-ns" } } as KubernetesObject;
339
+ const withName = { metadata: { name: "my-name" } } as KubernetesObject;
340
+ const withNone = {} as KubernetesObject;
341
+
342
+ const original = process.env.PEPR_RECONCILE_STRATEGY;
343
+
344
+ it.each([
345
+ ["kind", withKindNsName, "Pod"],
346
+ ["kind", withKindNs, "Pod"],
347
+ ["kind", withKindName, "Pod"],
348
+ ["kind", withNsName, "UnknownKind"],
349
+ ["kind", withKind, "Pod"],
350
+ ["kind", withNs, "UnknownKind"],
351
+ ["kind", withName, "UnknownKind"],
352
+ ["kind", withNone, "UnknownKind"],
353
+ ["kindNs", withKindNsName, "Pod/my-ns"],
354
+ ["kindNs", withKindNs, "Pod/my-ns"],
355
+ ["kindNs", withKindName, "Pod/cluster-scoped"],
356
+ ["kindNs", withNsName, "UnknownKind/my-ns"],
357
+ ["kindNs", withKind, "Pod/cluster-scoped"],
358
+ ["kindNs", withNs, "UnknownKind/my-ns"],
359
+ ["kindNs", withName, "UnknownKind/cluster-scoped"],
360
+ ["kindNs", withNone, "UnknownKind/cluster-scoped"],
361
+ ["kindNsName", withKindNsName, "Pod/my-ns/my-name"],
362
+ ["kindNsName", withKindNs, "Pod/my-ns/Unnamed"],
363
+ ["kindNsName", withKindName, "Pod/cluster-scoped/my-name"],
364
+ ["kindNsName", withNsName, "UnknownKind/my-ns/my-name"],
365
+ ["kindNsName", withKind, "Pod/cluster-scoped/Unnamed"],
366
+ ["kindNsName", withNs, "UnknownKind/my-ns/Unnamed"],
367
+ ["kindNsName", withName, "UnknownKind/cluster-scoped/my-name"],
368
+ ["kindNsName", withNone, "UnknownKind/cluster-scoped/Unnamed"],
369
+ ["global", withKindNsName, "global"],
370
+ ["global", withKindNs, "global"],
371
+ ["global", withKindName, "global"],
372
+ ["global", withNsName, "global"],
373
+ ["global", withKind, "global"],
374
+ ["global", withNs, "global"],
375
+ ["global", withName, "global"],
376
+ ["global", withNone, "global"],
377
+ ])("PEPR_RECONCILE_STRATEGY='%s' over '%j' becomes '%s'", (strat, obj, key) => {
378
+ process.env.PEPR_RECONCILE_STRATEGY = strat;
379
+ expect(queueKey(obj)).toBe(key);
393
380
  });
394
381
 
395
- describe("PEPR_RECONCILE_STRATEGY=singular", () => {
396
- const original = process.env.PEPR_RECONCILE_STRATEGY;
397
-
398
- beforeAll(() => {
399
- process.env.PEPR_RECONCILE_STRATEGY = "singular";
400
- });
401
- afterAll(() => {
402
- process.env.PEPR_RECONCILE_STRATEGY = original;
403
- });
404
-
405
- it("should return correct key for an object with 'kind/namespace'", () => {
406
- const obj: KubernetesObject = {
407
- kind: "Pod",
408
- metadata: {
409
- name: "my-pod",
410
- namespace: "my-namespace",
411
- },
412
- };
413
-
414
- expect(queueRecordKey(obj)).toBe("Pod/my-namespace");
415
- });
416
-
417
- it("should handle objects with missing namespace", () => {
418
- const obj: KubernetesObject = {
419
- kind: "Pod",
420
- metadata: {
421
- name: "my-pod",
422
- },
423
- };
424
-
425
- expect(queueRecordKey(obj)).toBe("Pod/cluster-scoped");
426
- });
382
+ afterAll(() => {
383
+ process.env.PEPR_RECONCILE_STRATEGY = original;
384
+ });
385
+ });
427
386
 
428
- it("should handle objects with missing metadata", () => {
429
- const obj: KubernetesObject = {
430
- kind: "Pod",
431
- };
387
+ describe("getOrCreateQueue", () => {
388
+ it("creates a Queue instance on first call", () => {
389
+ const obj: KubernetesObject = {
390
+ kind: "queue",
391
+ metadata: {
392
+ name: "nm",
393
+ namespace: "ns",
394
+ },
395
+ };
432
396
 
433
- expect(queueRecordKey(obj)).toBe("Pod/cluster-scoped");
434
- });
397
+ const firstQueue = getOrCreateQueue(obj);
398
+ expect(firstQueue.label()).toBeDefined();
399
+ });
435
400
 
436
- it("should handle objects with missing kind", () => {
437
- const obj: KubernetesObject = {
438
- metadata: {
439
- name: "my-pod",
440
- namespace: "my-namespace",
441
- },
442
- };
401
+ it("returns same Queue instance on subsequent calls", () => {
402
+ const obj: KubernetesObject = {
403
+ kind: "queue",
404
+ metadata: {
405
+ name: "nm",
406
+ namespace: "ns",
407
+ },
408
+ };
443
409
 
444
- expect(queueRecordKey(obj)).toBe("UnknownKind/my-namespace");
445
- });
410
+ const firstQueue = getOrCreateQueue(obj);
411
+ expect(firstQueue.label()).toBeDefined();
446
412
 
447
- it("should handle completely empty objects", () => {
448
- const obj: KubernetesObject = {};
413
+ const secondQueue = getOrCreateQueue(obj);
414
+ expect(secondQueue.label()).toBeDefined();
449
415
 
450
- expect(queueRecordKey(obj)).toBe("UnknownKind/cluster-scoped");
451
- });
416
+ expect(firstQueue).toBe(secondQueue);
452
417
  });
453
418
  });
@@ -9,18 +9,18 @@ import { Queue } from "./queue";
9
9
  import { Binding, Event } from "./types";
10
10
  import { metricsCollector } from "./metrics";
11
11
 
12
- // init a queueRecord record to store Queue instances for a given Kubernetes Object
13
- const queueRecord: Record<string, Queue<KubernetesObject>> = {};
12
+ // stores Queue instances
13
+ const queues: Record<string, Queue<KubernetesObject>> = {};
14
14
 
15
15
  /**
16
- * Get the key for a record in the queueRecord
16
+ * Get the key for an entry in the queues
17
17
  *
18
- * @param obj The object to get the key for
19
- * @returns The key for the object
18
+ * @param obj The object to derive a key from
19
+ * @returns The key to a Queue in the list of queues
20
20
  */
21
- export function queueRecordKey(obj: KubernetesObject) {
22
- const options = ["singular", "sharded"]; // TODO : ts-type this fella
23
- const d3fault = "singular";
21
+ export function queueKey(obj: KubernetesObject) {
22
+ const options = ["kind", "kindNs", "kindNsName", "global"];
23
+ const d3fault = "kind";
24
24
 
25
25
  let strat = process.env.PEPR_RECONCILE_STRATEGY || d3fault;
26
26
  strat = options.includes(strat) ? strat : d3fault;
@@ -29,7 +29,21 @@ export function queueRecordKey(obj: KubernetesObject) {
29
29
  const kind = obj.kind ?? "UnknownKind";
30
30
  const name = obj.metadata?.name ?? "Unnamed";
31
31
 
32
- return strat === "singular" ? `${kind}/${ns}` : `${kind}/${name}/${ns}`;
32
+ const lookup: Record<string, string> = {
33
+ kind: `${kind}`,
34
+ kindNs: `${kind}/${ns}`,
35
+ kindNsName: `${kind}/${ns}/${name}`,
36
+ global: "global",
37
+ };
38
+ return lookup[strat];
39
+ }
40
+
41
+ export function getOrCreateQueue(obj: KubernetesObject) {
42
+ const key = queueKey(obj);
43
+ if (!queues[key]) {
44
+ queues[key] = new Queue<KubernetesObject>(key);
45
+ }
46
+ return queues[key];
33
47
  }
34
48
 
35
49
  // Watch configuration
@@ -77,16 +91,16 @@ async function runBinding(binding: Binding, capabilityNamespaces: string[]) {
77
91
  const phaseMatch: WatchPhase[] = eventToPhaseMap[binding.event] || eventToPhaseMap[Event.Any];
78
92
 
79
93
  // The watch callback is run when an object is received or dequeued
80
-
81
94
  Log.debug({ watchCfg }, "Effective WatchConfig");
82
- const watchCallback = async (obj: KubernetesObject, type: WatchPhase) => {
95
+
96
+ const watchCallback = async (obj: KubernetesObject, phase: WatchPhase) => {
83
97
  // First, filter the object based on the phase
84
- if (phaseMatch.includes(type)) {
98
+ if (phaseMatch.includes(phase)) {
85
99
  try {
86
100
  // Then, check if the object matches the filter
87
101
  const filterMatch = filterNoMatchReason(binding, obj, capabilityNamespaces);
88
102
  if (filterMatch === "") {
89
- await binding.watchCallback?.(obj, type);
103
+ await binding.watchCallback?.(obj, phase);
90
104
  } else {
91
105
  Log.debug(filterMatch);
92
106
  }
@@ -97,26 +111,15 @@ async function runBinding(binding: Binding, capabilityNamespaces: string[]) {
97
111
  }
98
112
  };
99
113
 
100
- function getOrCreateQueue(key: string): Queue<KubernetesObject> {
101
- if (!queueRecord[key]) {
102
- queueRecord[key] = new Queue<KubernetesObject>();
103
- queueRecord[key].setReconcile(watchCallback);
104
- }
105
- return queueRecord[key];
106
- }
107
-
108
114
  // Setup the resource watch
109
- const watcher = K8s(binding.model, binding.filters).Watch(async (obj, type) => {
110
- Log.debug(obj, `Watch event ${type} received`);
111
-
112
- const queue = getOrCreateQueue(queueRecordKey(obj));
115
+ const watcher = K8s(binding.model, binding.filters).Watch(async (obj, phase) => {
116
+ Log.debug(obj, `Watch event ${phase} received`);
113
117
 
114
- // If the binding is a queue, enqueue the object
115
118
  if (binding.isQueue) {
116
- await queue.enqueue(obj, type);
119
+ const queue = getOrCreateQueue(obj);
120
+ await queue.enqueue(obj, phase, watchCallback);
117
121
  } else {
118
- // Otherwise, run the watch callback directly
119
- await watchCallback(obj, type);
122
+ await watchCallback(obj, phase);
120
123
  }
121
124
  }, watchCfg);
122
125
 
@@ -160,8 +163,8 @@ async function runBinding(binding: Binding, capabilityNamespaces: string[]) {
160
163
  }
161
164
  }
162
165
 
163
- export function logEvent(type: WatchEvent, message: string = "", obj?: KubernetesObject) {
164
- const logMessage = `Watch event ${type} received${message ? `. ${message}.` : "."}`;
166
+ export function logEvent(event: WatchEvent, message: string = "", obj?: KubernetesObject) {
167
+ const logMessage = `Watch event ${event} received${message ? `. ${message}.` : "."}`;
165
168
  if (obj) {
166
169
  Log.debug(obj, logMessage);
167
170
  } else {
@@ -11,6 +11,7 @@ import { beforeEach, describe, it, jest } from "@jest/globals";
11
11
  import { GenericKind } from "kubernetes-fluent-client";
12
12
  import { K8s, kind } from "kubernetes-fluent-client";
13
13
  import { Mock } from "jest-mock";
14
+ import { V1OwnerReference } from "@kubernetes/client-node";
14
15
 
15
16
  jest.mock("kubernetes-fluent-client", () => ({
16
17
  K8s: jest.fn(),
@@ -163,23 +164,55 @@ describe("writeEvent", () => {
163
164
  });
164
165
 
165
166
  describe("getOwnerRefFrom", () => {
166
- it("should return the owner reference for the CRD", () => {
167
- const cr = {
167
+ const customResource = {
168
+ apiVersion: "v1",
169
+ kind: "Package",
170
+ metadata: { name: "test", namespace: "default", uid: "1" },
171
+ };
172
+
173
+ const ownerRef = [
174
+ {
168
175
  apiVersion: "v1",
169
176
  kind: "Package",
170
- metadata: { name: "test", namespace: "default", uid: "1" },
171
- };
172
- const ownerRef = getOwnerRefFrom(cr as GenericKind);
173
- expect(ownerRef).toEqual([
174
- {
175
- apiVersion: "v1",
176
- kind: "Package",
177
- name: "test",
178
- uid: "1",
179
- },
180
- ]);
177
+ name: "test",
178
+ uid: "1",
179
+ },
180
+ ];
181
+
182
+ const ownerRefWithController = ownerRef.map(item => ({
183
+ ...item,
184
+ controller: true,
185
+ }));
186
+ const ownerRefWithBlockOwnerDeletion = ownerRef.map(item => ({
187
+ ...item,
188
+ blockOwnerDeletion: false,
189
+ }));
190
+ const ownerRefWithAllFields = ownerRef.map(item => ({
191
+ ...item,
192
+ blockOwnerDeletion: true,
193
+ controller: false,
194
+ }));
195
+
196
+ test.each([
197
+ [true, false, ownerRefWithAllFields],
198
+ [false, undefined, ownerRefWithBlockOwnerDeletion],
199
+ [undefined, true, ownerRefWithController],
200
+ [undefined, undefined, ownerRef],
201
+ ])(
202
+ "should return owner reference for the CRD for combinations of V1OwnerReference fields - Optionals: blockOwnerDeletion (%s), controller (%s)",
203
+ (blockOwnerDeletion, controller, expected) => {
204
+ const result = getOwnerRefFrom(customResource, blockOwnerDeletion, controller);
205
+ expect(result).toStrictEqual(expected);
206
+ },
207
+ );
208
+
209
+ it("should support all defined fields in the V1OwnerReference type", () => {
210
+ const V1OwnerReferenceFieldCount = Object.getOwnPropertyNames(V1OwnerReference).length;
211
+ const result = getOwnerRefFrom(customResource, false, true);
212
+ expect(Object.keys(result[0]).length).toEqual(V1OwnerReferenceFieldCount);
181
213
  });
182
214
  });
215
+
183
216
  describe("sanitizeResourceName Fuzzing Tests", () => {
184
217
  test("should handle any random string input", () => {
185
218
  fc.assert(
package/src/sdk/sdk.ts CHANGED
@@ -79,18 +79,27 @@ export async function writeEvent(
79
79
 
80
80
  /**
81
81
  * Get the owner reference for a custom resource
82
- * @param cr the custom resource to get the owner reference for
83
- * @returns the owner reference for the custom resource
82
+ * @param customResource the custom resource to get the owner reference for
83
+ * @param blockOwnerDeletion if true, AND if the owner has the "foregroundDeletion" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed.
84
+ * @param controller if true, this reference points to the managing controller.
85
+ * @returns the owner reference array for the custom resource
84
86
  */
85
- export function getOwnerRefFrom(cr: GenericKind): V1OwnerReference[] {
86
- const { name, uid } = cr.metadata!;
87
+ export function getOwnerRefFrom(
88
+ customResource: GenericKind,
89
+ blockOwnerDeletion?: boolean,
90
+ controller?: boolean,
91
+ ): V1OwnerReference[] {
92
+ const { apiVersion, kind, metadata } = customResource;
93
+ const { name, uid } = metadata!;
87
94
 
88
95
  return [
89
96
  {
90
- apiVersion: cr.apiVersion!,
91
- kind: cr.kind!,
97
+ apiVersion: apiVersion!,
98
+ kind: kind!,
92
99
  uid: uid!,
93
100
  name: name!,
101
+ ...(blockOwnerDeletion !== undefined && { blockOwnerDeletion }),
102
+ ...(controller !== undefined && { controller }),
94
103
  },
95
104
  ];
96
105
  }