@kumulo/core 0.1.1

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 (46) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +15 -0
  3. package/dist/config/decode.d.ts +5 -0
  4. package/dist/config/index.d.ts +3 -0
  5. package/dist/config/schema.d.ts +400 -0
  6. package/dist/config/yaml.d.ts +5 -0
  7. package/dist/dns/index.d.ts +2 -0
  8. package/dist/dns/ownership.d.ts +6 -0
  9. package/dist/dns-noop/index.d.ts +7 -0
  10. package/dist/domain/capabilities.d.ts +6 -0
  11. package/dist/domain/types.d.ts +175 -0
  12. package/dist/errors/renderer.d.ts +12 -0
  13. package/dist/errors/retryable.d.ts +2 -0
  14. package/dist/errors/tagged.d.ts +138 -0
  15. package/dist/index.d.ts +39 -0
  16. package/dist/index.mjs +602 -0
  17. package/dist/k8s/client.d.ts +23 -0
  18. package/dist/k8s/index.d.ts +7 -0
  19. package/dist/k8s/kubeconfig.d.ts +18 -0
  20. package/dist/k8s/node-ops.d.ts +19 -0
  21. package/dist/k8s/readiness.d.ts +12 -0
  22. package/dist/plan/diff.d.ts +12 -0
  23. package/dist/plan/hash.d.ts +2 -0
  24. package/dist/plan/index.d.ts +4 -0
  25. package/dist/plan/naming.d.ts +8 -0
  26. package/dist/plan/types.d.ts +29 -0
  27. package/dist/ports/addon.d.ts +13 -0
  28. package/dist/ports/cloud-provider.d.ts +19 -0
  29. package/dist/ports/credentials-sink.d.ts +10 -0
  30. package/dist/ports/distro.d.ts +29 -0
  31. package/dist/ports/dns-provider.d.ts +12 -0
  32. package/dist/ports/object-storage-provider.d.ts +14 -0
  33. package/dist/ports/provider-profile.d.ts +27 -0
  34. package/dist/ports/validation.d.ts +5 -0
  35. package/dist/ports/volume-provider.d.ts +14 -0
  36. package/dist/present/decide.d.ts +15 -0
  37. package/dist/present/index.d.ts +3 -0
  38. package/dist/present/render.d.ts +2 -0
  39. package/dist/profiles/generic.d.ts +22 -0
  40. package/dist/profiles/index.d.ts +1 -0
  41. package/dist/reconcile/apply.d.ts +8 -0
  42. package/dist/reconcile/index.d.ts +3 -0
  43. package/dist/reconcile/phases.d.ts +5 -0
  44. package/dist/reconcile/pipeline.d.ts +9 -0
  45. package/dist/reconcile/poll.d.ts +12 -0
  46. package/package.json +58 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,602 @@
1
+ import { Context, Data, Effect, Layer, Option, Ref, Schedule, Schema, SchemaIssue } from "effect";
2
+ import { parse, stringify } from "yaml";
3
+ import { HttpClientRequest } from "effect/unstable/http";
4
+ //#region src/errors/tagged.ts
5
+ var HttpTransportError = class extends Data.TaggedError("HttpTransportError") {};
6
+ var ResponseDecodeError = class extends Data.TaggedError("ResponseDecodeError") {};
7
+ var AuthenticationFailed = class extends Data.TaggedError("AuthenticationFailed") {};
8
+ var QuotaExceeded = class extends Data.TaggedError("QuotaExceeded") {};
9
+ var RateLimited = class extends Data.TaggedError("RateLimited") {};
10
+ var ProviderApiError = class extends Data.TaggedError("ProviderApiError") {};
11
+ var ResourceNotFound = class extends Data.TaggedError("ResourceNotFound") {};
12
+ var ResourceConflict = class extends Data.TaggedError("ResourceConflict") {};
13
+ var CapabilityMissing = class extends Data.TaggedError("CapabilityMissing") {};
14
+ var ProvisioningTimeout = class extends Data.TaggedError("ProvisioningTimeout") {};
15
+ var ConfigInvalid = class extends Data.TaggedError("ConfigInvalid") {};
16
+ var PlanRejected = class extends Data.TaggedError("PlanRejected") {};
17
+ var BootstrapFailed = class extends Data.TaggedError("BootstrapFailed") {};
18
+ var AddonInstallFailed = class extends Data.TaggedError("AddonInstallFailed") {};
19
+ var BucketNotEmpty = class extends Data.TaggedError("BucketNotEmpty") {};
20
+ var SinkUnavailable = class extends Data.TaggedError("SinkUnavailable") {};
21
+ //#endregion
22
+ //#region src/errors/retryable.ts
23
+ const retryableByTag = {
24
+ HttpTransportError: true,
25
+ ResponseDecodeError: false,
26
+ AuthenticationFailed: false,
27
+ QuotaExceeded: false,
28
+ RateLimited: true,
29
+ ProviderApiError: true,
30
+ ResourceNotFound: false,
31
+ ResourceConflict: true,
32
+ CapabilityMissing: false,
33
+ ProvisioningTimeout: true,
34
+ ConfigInvalid: false,
35
+ PlanRejected: false,
36
+ BootstrapFailed: false,
37
+ AddonInstallFailed: false,
38
+ BucketNotEmpty: false,
39
+ SinkUnavailable: false
40
+ };
41
+ const isRetryable = (error) => retryableByTag[error._tag];
42
+ //#endregion
43
+ //#region src/errors/renderer.ts
44
+ const renderError = (args) => args.registry[args.error._tag](args.error);
45
+ //#endregion
46
+ //#region src/config/schema.ts
47
+ const octet = "(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
48
+ const isCidr = Schema.isPattern(new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}/(3[0-2]|[12]?\\d)$`), { message: "must be a CIDR in a.b.c.d/n form with valid octets (0-255) and prefix (0-32)" });
49
+ const Cidr = Schema.String.check(isCidr);
50
+ const isOddCount = Schema.makeFilter((count) => count >= 1 && count % 2 === 1 ? void 0 : "must be 1 or an odd number (embedded etcd quorum)");
51
+ const PositiveInt = Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0));
52
+ const NonNegativeInt = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
53
+ const Provider = Schema.Literals([
54
+ "ovh",
55
+ "generic",
56
+ "hetzner"
57
+ ]);
58
+ const PublicAccess = Schema.Literals(["bastionless", "nat"]);
59
+ const AuthMethod = Schema.Literals([
60
+ "application_credential",
61
+ "clouds_yaml",
62
+ "env",
63
+ "api_token"
64
+ ]);
65
+ const Cni = Schema.Literals(["flannel", "cilium"]);
66
+ const AccessMode = Schema.Literals([
67
+ "ReadWriteOnce",
68
+ "ReadWriteMany",
69
+ "ReadOnlyMany"
70
+ ]);
71
+ const K3sVersion = Schema.String.check(Schema.isPattern(/^v\d+\.\d+\.\d+\+k3s\d+$/, { message: "must be a k3s version like v1.31.4+k3s1" }));
72
+ const PlainK8sVersion = Schema.String.check(Schema.isPattern(/^v?\d+\.\d+\.\d+$/, { message: "must be a Kubernetes version like v1.31.4" }));
73
+ const isSecretsRequiredForObjectStorage = Schema.makeFilter((config) => config.object_storage.module === "ovh" && config.secrets.sink === "none" ? "secrets.sink must not be none when object_storage.module is ovh" : void 0);
74
+ const isAuthMethodConsistentWithProvider = Schema.makeFilter((config) => config.provider === "hetzner" !== (config.auth.method === "api_token") ? "auth.method must be api_token if and only if provider is hetzner" : void 0);
75
+ const isVolumesModuleConsistentWithProvider = Schema.makeFilter((config) => {
76
+ if (config.volumes.module === "hcloud" && config.provider !== "hetzner") return "volumes.module hcloud requires provider hetzner";
77
+ if (config.volumes.module === "cinder" && config.provider === "hetzner") return "volumes.module cinder is not available on provider hetzner";
78
+ });
79
+ const isAddonsConsistentWithProvider = Schema.makeFilter((config) => {
80
+ if (config.addons === void 0) return void 0;
81
+ if (config.addons.hcloud_csi.enabled && config.provider !== "hetzner") return "addons.hcloud_csi can only be enabled when provider is hetzner";
82
+ if (config.addons.cinder_csi.enabled && config.provider === "hetzner") return "addons.cinder_csi cannot be enabled when provider is hetzner";
83
+ });
84
+ const Auth = Schema.Struct({
85
+ method: AuthMethod,
86
+ region: Schema.NonEmptyString
87
+ });
88
+ const Network = Schema.Struct({
89
+ cidr: Cidr,
90
+ public_access: PublicAccess
91
+ });
92
+ const ApiServer = Schema.Struct({
93
+ high_availability: Schema.Boolean,
94
+ allowed_cidrs: Schema.Array(Cidr)
95
+ });
96
+ const Ssh = Schema.Struct({
97
+ public_key_path: Schema.NonEmptyString,
98
+ allowed_cidrs: Schema.Array(Cidr)
99
+ });
100
+ const Masters = Schema.Struct({
101
+ flavor: Schema.NonEmptyString,
102
+ count: Schema.Number.check(Schema.isInt()).check(isOddCount),
103
+ image: Schema.NonEmptyString
104
+ });
105
+ const Autoscaling = Schema.Struct({
106
+ enabled: Schema.Boolean,
107
+ min: NonNegativeInt,
108
+ max: PositiveInt
109
+ });
110
+ const WorkerPool = Schema.Struct({
111
+ name: Schema.NonEmptyString,
112
+ flavor: Schema.NonEmptyString,
113
+ count: NonNegativeInt,
114
+ labels: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
115
+ taints: Schema.optionalKey(Schema.Array(Schema.String)),
116
+ autoscaling: Schema.optionalKey(Autoscaling)
117
+ });
118
+ const DnsRecord = Schema.Struct({
119
+ name: Schema.NonEmptyString,
120
+ target: Schema.NonEmptyString
121
+ });
122
+ const Dns = Schema.Union([Schema.Struct({ module: Schema.Literal("none") }), Schema.Struct({
123
+ module: Schema.Literals(["ovh", "hetzner"]),
124
+ zone: Schema.NonEmptyString,
125
+ ttl: PositiveInt,
126
+ records: Schema.Array(DnsRecord)
127
+ })]);
128
+ const Pvc = Schema.Struct({
129
+ namespace: Schema.NonEmptyString,
130
+ access_modes: Schema.Array(AccessMode)
131
+ });
132
+ const ManagedVolume = Schema.Struct({
133
+ name: Schema.NonEmptyString,
134
+ size_gb: PositiveInt,
135
+ type: Schema.NonEmptyString,
136
+ retain: Schema.Boolean,
137
+ pvc: Schema.optionalKey(Pvc)
138
+ });
139
+ const NoVolumes = Schema.Struct({ module: Schema.Literal("none") });
140
+ const CinderVolumes = Schema.Struct({
141
+ module: Schema.Literal("cinder"),
142
+ managed: Schema.Array(ManagedVolume)
143
+ });
144
+ const HcloudVolumes = Schema.Struct({
145
+ module: Schema.Literal("hcloud"),
146
+ managed: Schema.Array(ManagedVolume)
147
+ });
148
+ const Volumes = Schema.Union([
149
+ NoVolumes,
150
+ CinderVolumes,
151
+ HcloudVolumes
152
+ ]);
153
+ const OpenStackVolumes = Schema.Union([NoVolumes, CinderVolumes]);
154
+ const isS3BucketName = Schema.isPattern(/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/, { message: "must be 3-63 chars, lowercase alphanumeric/dots/hyphens, and start/end alphanumeric" });
155
+ const BucketName = Schema.String.check(isS3BucketName);
156
+ const Bucket = Schema.Struct({
157
+ name: BucketName,
158
+ region: Schema.NonEmptyString,
159
+ versioning: Schema.Boolean,
160
+ encryption: Schema.Boolean,
161
+ retain: Schema.Boolean
162
+ });
163
+ const ObjectStorage = Schema.Union([Schema.Struct({ module: Schema.Literal("none") }), Schema.Struct({
164
+ module: Schema.Literal("ovh"),
165
+ buckets: Schema.Array(Bucket)
166
+ })]);
167
+ const isAgeRecipient = Schema.isPattern(/^age1/, { message: "must be an age recipient key starting with age1" });
168
+ const Sops = Schema.Struct({ age_recipient: Schema.String.check(isAgeRecipient) });
169
+ const Secrets = Schema.Union([Schema.Struct({ sink: Schema.Literal("none") }), Schema.Struct({
170
+ sink: Schema.Literal("sops"),
171
+ dir: Schema.NonEmptyString,
172
+ sops: Sops
173
+ })]);
174
+ const CinderCsi = Schema.Struct({
175
+ enabled: Schema.Boolean,
176
+ default_volume_type: Schema.NonEmptyString
177
+ });
178
+ const HcloudCsi = Schema.Struct({ enabled: Schema.Boolean });
179
+ const Addons = Schema.Struct({
180
+ cloud_controller_manager: Schema.Boolean,
181
+ cinder_csi: CinderCsi,
182
+ hcloud_csi: HcloudCsi,
183
+ system_upgrade_controller: Schema.Boolean,
184
+ cni: Cni
185
+ });
186
+ const K3sPassthrough = Schema.Struct({
187
+ extra_server_args: Schema.Array(Schema.String),
188
+ extra_agent_args: Schema.Array(Schema.String)
189
+ });
190
+ const OutputsFormat = Schema.Literals(["yaml", "json"]);
191
+ const Outputs = Schema.Struct({ format: OutputsFormat });
192
+ const _commonFields = {
193
+ name: Schema.NonEmptyString,
194
+ outputs: Schema.optionalKey(Outputs),
195
+ auth: Auth,
196
+ worker_pools: Schema.Array(WorkerPool),
197
+ volumes: Volumes,
198
+ object_storage: ObjectStorage,
199
+ secrets: Secrets
200
+ };
201
+ const K3sClusterConfig = Schema.Struct({
202
+ ..._commonFields,
203
+ provider: Provider,
204
+ distro: Schema.Literal("k3s"),
205
+ version: K3sVersion,
206
+ dns: Dns,
207
+ network: Network,
208
+ api_server: ApiServer,
209
+ ssh: Ssh,
210
+ masters: Masters,
211
+ addons: Addons,
212
+ k3s: K3sPassthrough
213
+ }).check(isSecretsRequiredForObjectStorage, isAuthMethodConsistentWithProvider, isVolumesModuleConsistentWithProvider, isAddonsConsistentWithProvider);
214
+ const MksClusterConfig = Schema.Struct({
215
+ ..._commonFields,
216
+ provider: Schema.Literal("ovh"),
217
+ distro: Schema.Literal("ovh-mks"),
218
+ version: PlainK8sVersion,
219
+ dns: Dns,
220
+ volumes: OpenStackVolumes
221
+ }).check(isSecretsRequiredForObjectStorage, isAuthMethodConsistentWithProvider);
222
+ const ClusterConfig = Schema.Union([K3sClusterConfig, MksClusterConfig]);
223
+ //#endregion
224
+ //#region src/config/decode.ts
225
+ const formatIssue = SchemaIssue.makeFormatterStandardSchemaV1();
226
+ const _toPropertyKey = (segment) => typeof segment === "object" ? segment.key : segment;
227
+ const _toConfigInvalid = (error) => new ConfigInvalid({ issues: formatIssue(error.issue).issues.map((issue) => ({
228
+ path: (issue.path ?? []).map(_toPropertyKey),
229
+ message: issue.message
230
+ })) });
231
+ const decodeConfig = (input) => Schema.decodeUnknownEffect(ClusterConfig)(input, { errors: "all" }).pipe(Effect.mapError(_toConfigInvalid));
232
+ const encodeConfig = (config) => Schema.encodeEffect(ClusterConfig)(config).pipe(Effect.mapError(_toConfigInvalid));
233
+ //#endregion
234
+ //#region src/config/yaml.ts
235
+ const parseConfigYaml = (text) => Effect.try({
236
+ try: () => parse(text),
237
+ catch: (cause) => new ConfigInvalid({ issues: [{
238
+ path: [],
239
+ message: String(cause)
240
+ }] })
241
+ }).pipe(Effect.flatMap(decodeConfig));
242
+ const stringifyConfigYaml = (config) => stringify(config);
243
+ //#endregion
244
+ //#region src/ports/addon.ts
245
+ var Addon = class extends Context.Service()("@kumulo/core/Addon") {};
246
+ //#endregion
247
+ //#region src/ports/cloud-provider.ts
248
+ var CloudProvider = class extends Context.Service()("@kumulo/core/CloudProvider") {};
249
+ //#endregion
250
+ //#region src/ports/credentials-sink.ts
251
+ var CredentialsSink = class extends Context.Service()("@kumulo/core/CredentialsSink") {};
252
+ //#endregion
253
+ //#region src/ports/distro.ts
254
+ var Distro = class extends Context.Service()("@kumulo/core/Distro") {};
255
+ //#endregion
256
+ //#region src/ports/dns-provider.ts
257
+ var DnsProvider = class extends Context.Service()("@kumulo/core/DnsProvider") {};
258
+ //#endregion
259
+ //#region src/ports/object-storage-provider.ts
260
+ var ObjectStorageProvider = class extends Context.Service()("@kumulo/core/ObjectStorageProvider") {};
261
+ //#endregion
262
+ //#region src/ports/provider-profile.ts
263
+ var ProviderProfile = class extends Context.Service()("@kumulo/core/ProviderProfile") {};
264
+ //#endregion
265
+ //#region src/domain/capabilities.ts
266
+ const distroCapabilities = {
267
+ "k3s": {
268
+ autoscaling: false,
269
+ selectableCni: true
270
+ },
271
+ "ovh-mks": {
272
+ autoscaling: true,
273
+ selectableCni: false
274
+ }
275
+ };
276
+ //#endregion
277
+ //#region src/ports/validation.ts
278
+ const validateAutoscaling = (config) => !distroCapabilities[config.distro].autoscaling && config.worker_pools.some((pool) => pool.autoscaling?.enabled === true) ? Option.some(new PlanRejected({ reason: "autoscaling is not yet implemented for k3s" })) : Option.none();
279
+ const validateCni = (config) => !distroCapabilities[config.distro].selectableCni && config.addons.cni === "cilium" ? Option.some(new PlanRejected({ reason: "cilium is not selectable under ovh-mks; CNI is fixed by OVH" })) : Option.none();
280
+ //#endregion
281
+ //#region src/ports/volume-provider.ts
282
+ var VolumeProvider = class extends Context.Service()("@kumulo/core/VolumeProvider") {};
283
+ //#endregion
284
+ //#region src/plan/hash.ts
285
+ const _canonical = (value) => Array.isArray(value) ? value.map(_canonical) : value !== null && typeof value === "object" ? Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => [key, _canonical(entry)])) : value;
286
+ const _fnv1a = (text) => [...text].reduce((hash, char) => BigInt.asUintN(64, (hash ^ BigInt(char.codePointAt(0) ?? 0)) * 1099511628211n), 14695981039346656037n);
287
+ const CONFIG_HASH_KEY = "kumulo-config-hash";
288
+ const configHash = (spec) => _fnv1a(JSON.stringify(_canonical(spec)) ?? "undefined").toString(16).padStart(16, "0");
289
+ //#endregion
290
+ //#region src/plan/naming.ts
291
+ const resourceName = ({ cluster, role, pool, index }) => `kumulo-${cluster}-${role}-${pool}-${index}`;
292
+ //#endregion
293
+ //#region src/plan/diff.ts
294
+ const toTaggedResource = (desired) => ({
295
+ name: resourceName(desired),
296
+ configHash: configHash(desired.spec)
297
+ });
298
+ const _actionFor = (desired, actual) => {
299
+ const name = resourceName(desired);
300
+ if (actual === void 0) return {
301
+ _tag: "Create",
302
+ name
303
+ };
304
+ if (actual.configHash === void 0) return {
305
+ _tag: "NoOp",
306
+ name
307
+ };
308
+ return actual.configHash === configHash(desired.spec) ? {
309
+ _tag: "NoOp",
310
+ name
311
+ } : {
312
+ _tag: "ReplaceNeedsConfirm",
313
+ name,
314
+ reason: "config-hash drifted from desired spec"
315
+ };
316
+ };
317
+ /**
318
+ * The names the plan says must be replaced. Callers hand this to the
319
+ * reconciler *only* once the operator confirmed, so execution never
320
+ * re-derives replace intent from names or inventory.
321
+ */
322
+ const namesToReplace = (plan) => new Set(plan.actions.filter((action) => action._tag === "ReplaceNeedsConfirm").map((action) => action.name));
323
+ const computePlan = ({ actual, desired }) => {
324
+ const byName = new Map(actual.map((resource) => [resource.name, resource]));
325
+ const desiredNames = new Set(desired.map(resourceName));
326
+ return { actions: [...desired.map((resource) => _actionFor(resource, byName.get(resourceName(resource)))), ...actual.filter((resource) => !desiredNames.has(resource.name)).map((resource) => ({
327
+ _tag: "Delete",
328
+ name: resource.name
329
+ }))] };
330
+ };
331
+ //#endregion
332
+ //#region src/reconcile/poll.ts
333
+ const pollUntil = (options) => Effect.gen(function* () {
334
+ const last = yield* Ref.make(void 0);
335
+ return yield* options.check.pipe(Effect.tap((status) => Ref.set(last, status)), Effect.repeat({
336
+ until: options.isDone,
337
+ schedule: Schedule.spaced(options.interval)
338
+ })).pipe(Effect.timeoutOrElse({
339
+ duration: options.timeout,
340
+ orElse: () => Ref.get(last).pipe(Effect.flatMap((status) => Effect.fail(new ProvisioningTimeout({
341
+ kind: options.kind,
342
+ ref: options.ref,
343
+ lastStatus: status === void 0 ? "unknown" : String(status)
344
+ }))))
345
+ }));
346
+ });
347
+ //#endregion
348
+ //#region src/reconcile/apply.ts
349
+ const applyServers = ({ concurrency, specs }) => Effect.gen(function* () {
350
+ const cloudProvider = yield* CloudProvider;
351
+ yield* Effect.forEach(specs, cloudProvider.ensureServer, {
352
+ concurrency,
353
+ discard: true
354
+ });
355
+ });
356
+ //#endregion
357
+ //#region src/present/decide.ts
358
+ const decidePlanAction = ({ plan, yes, dryRun }) => {
359
+ if (dryRun) return { _tag: "DryRun" };
360
+ if (plan.actions.every((action) => action._tag === "NoOp")) return { _tag: "NothingToDo" };
361
+ if (yes) return { _tag: "Proceed" };
362
+ return { _tag: "NeedsConfirm" };
363
+ };
364
+ //#endregion
365
+ //#region src/present/render.ts
366
+ const _renderLine = (action) => {
367
+ if (action._tag === "Create") return ` + ${action.name}`;
368
+ if (action._tag === "Delete") return ` - ${action.name}`;
369
+ if (action._tag === "NoOp") return ` = ${action.name}`;
370
+ if (action._tag === "Update") return ` ~ ${action.name} (${action.reason})`;
371
+ return ` -/+ ${action.name} (${action.reason})`;
372
+ };
373
+ const _count = (actions, tag) => actions.filter((action) => action._tag === tag).length;
374
+ const _groupOrder = [
375
+ "Create",
376
+ "Update",
377
+ "ReplaceNeedsConfirm",
378
+ "Delete",
379
+ "NoOp"
380
+ ];
381
+ const renderPlan = (plan) => {
382
+ const summary = `Plan: ${_count(plan.actions, "Create")} to create, ${_count(plan.actions, "Delete")} to delete, ${_count(plan.actions, "Update")} to update, ${_count(plan.actions, "ReplaceNeedsConfirm")} to replace, ${_count(plan.actions, "NoOp")} unchanged.`;
383
+ if (plan.actions.length === 0) return summary;
384
+ return [
385
+ summary,
386
+ "",
387
+ ..._groupOrder.flatMap((tag) => plan.actions.filter((action) => action._tag === tag)).map(_renderLine)
388
+ ].join("\n");
389
+ };
390
+ //#endregion
391
+ //#region src/profiles/generic.ts
392
+ const genericProfile = {
393
+ name: "generic",
394
+ auth: {
395
+ keystoneUrlPattern: "",
396
+ domainDefault: "Default"
397
+ },
398
+ capabilities: {
399
+ octavia: (_region) => true,
400
+ floatingIps: true,
401
+ volumeTypes: []
402
+ },
403
+ defaults: {
404
+ externalNetworkName: "",
405
+ imageAliases: {},
406
+ dnsServers: []
407
+ },
408
+ validate: (_config) => Effect.void
409
+ };
410
+ const genericProfileLive = Layer.succeed(ProviderProfile, genericProfile);
411
+ //#endregion
412
+ //#region src/dns-noop/index.ts
413
+ const dnsNoop = {
414
+ ensureRecords: () => Effect.void,
415
+ removeClusterRecords: () => Effect.void
416
+ };
417
+ const dnsNoopLive = Layer.succeed(DnsProvider, dnsNoop);
418
+ //#endregion
419
+ //#region src/dns/ownership.ts
420
+ const OWNERSHIP_PREFIX = "kumulo.cluster=";
421
+ const ownershipTarget = (tag) => `${OWNERSHIP_PREFIX}${tag}`;
422
+ const ownerTagOf = (target) => target.startsWith("kumulo.cluster=") ? target.slice(15) : void 0;
423
+ const _isIpv4 = (target) => /^\d{1,3}(\.\d{1,3}){3}$/.test(target) && target.split(".").every((o) => Number(o) <= 255);
424
+ const _isIpv6 = (target) => target.includes(":") && /^[0-9a-fA-F:]+$/.test(target);
425
+ /** Record type inferred from the resolved target value (no explicit field on `DesiredRecord`). */
426
+ const recordKind = (target) => ownerTagOf(target) !== void 0 ? "TXT" : _isIpv4(target) ? "A" : _isIpv6(target) ? "AAAA" : "CNAME";
427
+ //#endregion
428
+ //#region src/k8s/client.ts
429
+ var K8sClient = class extends Context.Service()("@kumulo/core/K8sClient") {};
430
+ const _transportError = (cause) => new HttpTransportError({ cause });
431
+ const _statusError = (ref, status) => status === 404 ? new ResourceNotFound({
432
+ kind: ref.kind,
433
+ ref: ref.path
434
+ }) : _transportError(`status ${status}`);
435
+ const K8sManifestSchema = Schema.StructWithRest(Schema.Struct({
436
+ apiVersion: Schema.String,
437
+ kind: Schema.String
438
+ }), [Schema.Record(Schema.String, Schema.Unknown)]);
439
+ const K8sListSchema = Schema.Struct({ items: Schema.optional(Schema.Array(Schema.Unknown)) });
440
+ const _emptyListing = { items: [] };
441
+ const _url = (server, path) => new URL(path, server);
442
+ const _decodeManifest = (body) => Schema.decodeUnknownEffect(K8sManifestSchema)(body).pipe(Effect.mapError(() => _transportError("response body was not a K8s manifest")));
443
+ const _decodeManifestOption = (item) => Schema.decodeUnknownEffect(K8sManifestSchema)(item).pipe(Effect.option);
444
+ const makeK8sClient = (options) => {
445
+ const { client, server } = options;
446
+ const get = (ref) => Effect.gen(function* () {
447
+ const response = yield* client.execute(HttpClientRequest.get(_url(server, ref.path))).pipe(Effect.mapError(_transportError));
448
+ if (response.status !== 200) return yield* Effect.fail(_statusError(ref, response.status));
449
+ const body = yield* response.json.pipe(Effect.mapError(_transportError));
450
+ return yield* _decodeManifest(body);
451
+ });
452
+ const list = (ref) => Effect.gen(function* () {
453
+ const response = yield* client.execute(HttpClientRequest.get(_url(server, ref.path))).pipe(Effect.mapError(_transportError));
454
+ if (response.status !== 200) return yield* Effect.fail(_transportError(`status ${response.status}`));
455
+ const body = yield* response.json.pipe(Effect.mapError(_transportError));
456
+ const listing = yield* Schema.decodeUnknownEffect(K8sListSchema)(body).pipe(Effect.orElseSucceed(() => _emptyListing));
457
+ return (yield* Effect.forEach(listing.items ?? [], _decodeManifestOption)).flatMap(Option.toArray);
458
+ });
459
+ const apply = (ref, manifest) => Effect.gen(function* () {
460
+ const request = HttpClientRequest.patch(_url(server, `${ref.path}?fieldManager=kumulo&force=true`)).pipe(HttpClientRequest.bodyText(_toYaml(manifest), "application/apply-patch+yaml"));
461
+ const response = yield* client.execute(request).pipe(Effect.mapError(_transportError));
462
+ if (response.status === 409) return yield* Effect.fail(new ResourceConflict({
463
+ kind: ref.kind,
464
+ ref: ref.path
465
+ }));
466
+ if (response.status !== 200 && response.status !== 201) return yield* Effect.fail(_transportError(`status ${response.status}`));
467
+ const body = yield* response.json.pipe(Effect.mapError(_transportError));
468
+ return yield* _decodeManifest(body);
469
+ });
470
+ const deleteResource = (ref) => client.execute(HttpClientRequest.delete(_url(server, ref.path))).pipe(Effect.mapError(_transportError), Effect.flatMap((response) => response.status === 200 || response.status === 202 || response.status === 404 ? Effect.void : Effect.fail(_statusError(ref, response.status))));
471
+ const evict = (namespace, pod) => Effect.gen(function* () {
472
+ const path = `/api/v1/namespaces/${namespace}/pods/${pod}/eviction`;
473
+ const body = {
474
+ apiVersion: "policy/v1",
475
+ kind: "Eviction",
476
+ metadata: {
477
+ name: pod,
478
+ namespace
479
+ }
480
+ };
481
+ const request = HttpClientRequest.post(_url(server, path)).pipe(HttpClientRequest.bodyText(JSON.stringify(body), "application/json"));
482
+ const response = yield* client.execute(request).pipe(Effect.mapError(_transportError));
483
+ if (response.status === 200 || response.status === 201) return;
484
+ if (response.status === 404) return yield* Effect.fail(new ResourceNotFound({
485
+ kind: "Pod",
486
+ ref: path
487
+ }));
488
+ if (response.status === 409) return yield* Effect.fail(new ResourceConflict({
489
+ kind: "Pod",
490
+ ref: path
491
+ }));
492
+ return yield* Effect.fail(_transportError(`status ${response.status}`));
493
+ });
494
+ return {
495
+ get,
496
+ list,
497
+ apply,
498
+ delete: deleteResource,
499
+ evict
500
+ };
501
+ };
502
+ const _toYaml = (manifest) => JSON.stringify(manifest);
503
+ //#endregion
504
+ //#region src/k8s/kubeconfig.ts
505
+ const _invalid = (message) => new ConfigInvalid({ issues: [{
506
+ path: [],
507
+ message
508
+ }] });
509
+ const _base64Decode = (value) => globalThis.atob(value);
510
+ const _KubeconfigDoc = Schema.Struct({
511
+ clusters: Schema.optional(Schema.Array(Schema.Struct({ cluster: Schema.optional(Schema.Struct({
512
+ server: Schema.optional(Schema.String),
513
+ "certificate-authority-data": Schema.optional(Schema.String)
514
+ })) }))),
515
+ users: Schema.optional(Schema.Array(Schema.Struct({ user: Schema.optional(Schema.Struct({
516
+ token: Schema.optional(Schema.String),
517
+ "client-certificate-data": Schema.optional(Schema.String),
518
+ "client-key-data": Schema.optional(Schema.String)
519
+ })) })))
520
+ });
521
+ const _parseAuth = (user) => {
522
+ if (user?.token !== void 0) return {
523
+ kind: "token",
524
+ token: user.token
525
+ };
526
+ const certData = user?.["client-certificate-data"];
527
+ const keyData = user?.["client-key-data"];
528
+ if (certData !== void 0 && keyData !== void 0) return {
529
+ kind: "clientCert",
530
+ certPem: _base64Decode(certData),
531
+ keyPem: _base64Decode(keyData)
532
+ };
533
+ };
534
+ const parseKubeconfig = (text) => Effect.try({
535
+ try: () => parse(text),
536
+ catch: (cause) => _invalid(String(cause))
537
+ }).pipe(Effect.flatMap((yaml) => Schema.decodeUnknownEffect(_KubeconfigDoc)(yaml).pipe(Effect.mapError(() => _invalid("kubeconfig is not a valid document")))), Effect.flatMap((doc) => {
538
+ const cluster = doc.clusters?.[0]?.cluster;
539
+ const user = doc.users?.[0]?.user;
540
+ const auth = _parseAuth(user);
541
+ if (cluster?.server === void 0 || auth === void 0) return Effect.fail(_invalid("kubeconfig missing cluster.server or a token/client-cert user"));
542
+ return Effect.succeed({
543
+ server: cluster.server,
544
+ caPem: cluster["certificate-authority-data"] === void 0 ? void 0 : _base64Decode(cluster["certificate-authority-data"]),
545
+ auth
546
+ });
547
+ }));
548
+ //#endregion
549
+ //#region src/k8s/readiness.ts
550
+ const _ConditionsShape = Schema.Struct({ status: Schema.optional(Schema.Struct({ conditions: Schema.optional(Schema.Array(Schema.Struct({
551
+ type: Schema.String,
552
+ status: Schema.String
553
+ }))) })) });
554
+ const _conditionStatus = (manifest, type) => {
555
+ const decoded = Schema.decodeUnknownExit(_ConditionsShape)(manifest);
556
+ if (decoded._tag !== "Success") return void 0;
557
+ return decoded.value.status?.conditions?.find((c) => c.type === type)?.status;
558
+ };
559
+ const waitForDeploymentAvailable = (options) => pollUntil({
560
+ check: options.get(options.ref),
561
+ isDone: (manifest) => _conditionStatus(manifest, "Available") === "True",
562
+ interval: options.interval,
563
+ timeout: options.timeout,
564
+ kind: "Deployment",
565
+ ref: options.ref.path
566
+ });
567
+ const waitForNodeReady = (options) => pollUntil({
568
+ check: options.get(options.ref),
569
+ isDone: (manifest) => _conditionStatus(manifest, "Ready") === "True",
570
+ interval: options.interval,
571
+ timeout: options.timeout,
572
+ kind: "Node",
573
+ ref: options.ref.path
574
+ });
575
+ //#endregion
576
+ //#region src/k8s/node-ops.ts
577
+ const _nodeRef = (name) => ({
578
+ path: `/api/v1/nodes/${name}`,
579
+ kind: "Node"
580
+ });
581
+ const cordonNode = (options) => options.client.apply(_nodeRef(options.name), {
582
+ apiVersion: "v1",
583
+ kind: "Node",
584
+ metadata: { name: options.name },
585
+ spec: { unschedulable: true }
586
+ });
587
+ const _PodMetadata = Schema.Struct({ metadata: Schema.Struct({
588
+ name: Schema.String,
589
+ namespace: Schema.String
590
+ }) });
591
+ const _podRef = (pod) => Schema.decodeUnknownEffect(_PodMetadata)(pod).pipe(Effect.map(({ metadata }) => ({
592
+ name: metadata.name,
593
+ namespace: metadata.namespace
594
+ })), Effect.option);
595
+ const _podRefs = (pods) => Effect.forEach(pods, _podRef).pipe(Effect.map((refs) => refs.flatMap(Option.toArray)));
596
+ const drainNode = (options) => options.client.list(options.podsRef).pipe(Effect.flatMap(_podRefs), Effect.flatMap((pods) => Effect.forEach(pods, (pod) => options.client.evict(pod.namespace, pod.name), { discard: true })));
597
+ const deleteNode = (options) => options.client.delete(_nodeRef(options.name));
598
+ //#endregion
599
+ //#region src/index.ts
600
+ const packageName = "@kumulo/core";
601
+ //#endregion
602
+ export { Addon, AddonInstallFailed, AuthenticationFailed, BootstrapFailed, BucketNotEmpty, CONFIG_HASH_KEY, CapabilityMissing, CloudProvider, ClusterConfig, ConfigInvalid, CredentialsSink, Distro, DnsProvider, HttpTransportError, K3sClusterConfig, K8sClient, MksClusterConfig, OWNERSHIP_PREFIX, ObjectStorageProvider, OutputsFormat, PlanRejected, ProviderApiError, ProviderProfile, ProvisioningTimeout, QuotaExceeded, RateLimited, ResourceConflict, ResourceNotFound, ResponseDecodeError, SinkUnavailable, VolumeProvider, applyServers, computePlan, configHash, cordonNode, decidePlanAction, decodeConfig, deleteNode, distroCapabilities, dnsNoop, dnsNoopLive, drainNode, encodeConfig, genericProfile, genericProfileLive, isRetryable, makeK8sClient, namesToReplace, ownerTagOf, ownershipTarget, packageName, parseConfigYaml, parseKubeconfig, pollUntil, recordKind, renderError, renderPlan, resourceName, stringifyConfigYaml, toTaggedResource, validateAutoscaling, validateCni, waitForDeploymentAvailable, waitForNodeReady };
@@ -0,0 +1,23 @@
1
+ import { Context, Effect } from "effect";
2
+ import type { HttpClient } from "effect/unstable/http";
3
+ import { HttpTransportError, ResourceConflict, ResourceNotFound } from "../errors/tagged";
4
+ import type { K8sManifest } from "../domain/types";
5
+ export interface ResourceRef {
6
+ readonly path: string;
7
+ readonly kind: string;
8
+ }
9
+ declare const K8sClient_base: Context.ServiceClass<K8sClient, "@kumulo/core/K8sClient", {
10
+ readonly get: (ref: ResourceRef) => Effect.Effect<K8sManifest, ResourceNotFound | HttpTransportError>;
11
+ readonly list: (ref: ResourceRef) => Effect.Effect<ReadonlyArray<K8sManifest>, HttpTransportError>;
12
+ readonly apply: (ref: ResourceRef, manifest: K8sManifest) => Effect.Effect<K8sManifest, ResourceConflict | HttpTransportError>;
13
+ readonly delete: (ref: ResourceRef) => Effect.Effect<void, ResourceNotFound | HttpTransportError>;
14
+ readonly evict: (namespace: string, pod: string) => Effect.Effect<void, ResourceNotFound | ResourceConflict | HttpTransportError>;
15
+ }>;
16
+ export declare class K8sClient extends K8sClient_base {
17
+ }
18
+ export interface K8sClientOptions {
19
+ readonly client: HttpClient.HttpClient;
20
+ readonly server: string;
21
+ }
22
+ export declare const makeK8sClient: (options: K8sClientOptions) => K8sClient["Service"];
23
+ export {};
@@ -0,0 +1,7 @@
1
+ export { K8sClient, makeK8sClient } from "./client";
2
+ export type { K8sClientOptions, ResourceRef } from "./client";
3
+ export { parseKubeconfig } from "./kubeconfig";
4
+ export type { ClientCertAuth, KubeconfigAuth, KubeconfigContext, TokenAuth } from "./kubeconfig";
5
+ export { waitForDeploymentAvailable, waitForNodeReady } from "./readiness";
6
+ export type { WaitOptions } from "./readiness";
7
+ export { cordonNode, deleteNode, drainNode } from "./node-ops";
@@ -0,0 +1,18 @@
1
+ import { Effect } from "effect";
2
+ import { ConfigInvalid } from "../errors/tagged";
3
+ export interface TokenAuth {
4
+ readonly kind: "token";
5
+ readonly token: string;
6
+ }
7
+ export interface ClientCertAuth {
8
+ readonly kind: "clientCert";
9
+ readonly certPem: string;
10
+ readonly keyPem: string;
11
+ }
12
+ export type KubeconfigAuth = TokenAuth | ClientCertAuth;
13
+ export interface KubeconfigContext {
14
+ readonly server: string;
15
+ readonly caPem?: string;
16
+ readonly auth: KubeconfigAuth;
17
+ }
18
+ export declare const parseKubeconfig: (text: string) => Effect.Effect<KubeconfigContext, ConfigInvalid>;
@@ -0,0 +1,19 @@
1
+ import { Effect } from "effect";
2
+ import type { HttpTransportError, ResourceConflict, ResourceNotFound } from "../errors/tagged";
3
+ import type { K8sManifest } from "../domain/types";
4
+ import type { K8sClient, ResourceRef } from "./client";
5
+ export interface CordonNodeOptions {
6
+ readonly client: K8sClient["Service"];
7
+ readonly name: string;
8
+ }
9
+ export declare const cordonNode: (options: CordonNodeOptions) => Effect.Effect<K8sManifest, ResourceConflict | HttpTransportError>;
10
+ export interface DrainNodeOptions {
11
+ readonly client: K8sClient["Service"];
12
+ readonly podsRef: ResourceRef;
13
+ }
14
+ export declare const drainNode: (options: DrainNodeOptions) => Effect.Effect<void, ResourceNotFound | ResourceConflict | HttpTransportError>;
15
+ export interface DeleteNodeOptions {
16
+ readonly client: K8sClient["Service"];
17
+ readonly name: string;
18
+ }
19
+ export declare const deleteNode: (options: DeleteNodeOptions) => Effect.Effect<void, ResourceNotFound | HttpTransportError>;