@highstate/backend 0.20.0 → 0.21.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.
@@ -0,0 +1,149 @@
1
+ import { access } from "node:fs/promises"
2
+ import { dirname, isAbsolute, resolve } from "node:path"
3
+ import { fileURLToPath } from "node:url"
4
+
5
+ /**
6
+ * Polyfill for resolving the path to a package.json file for a given module specifier and base URL.
7
+ *
8
+ * Context: https://github.com/oven-sh/bun/issues/23898
9
+ */
10
+ export async function findPackageJSONCompat(
11
+ specifier: string | URL,
12
+ base?: string | URL,
13
+ ): Promise<string | undefined> {
14
+ const parsedSpecifier = toPathSpecifier(specifier)
15
+
16
+ if (parsedSpecifier.type === "bare") {
17
+ if (!base) {
18
+ return undefined
19
+ }
20
+
21
+ const basePath = resolveBasePath(base)
22
+ const baseDir = await normalizePathForLookup(basePath)
23
+
24
+ return await findPackageJsonForBareSpecifier(baseDir, parsedSpecifier.value)
25
+ }
26
+
27
+ const resolvedPath = resolvePathSpecifier(parsedSpecifier.value, base)
28
+ const lookupStart = await normalizePathForLookup(resolvedPath)
29
+
30
+ return await findNearestPackageJson(lookupStart)
31
+ }
32
+
33
+ type PathSpecifier = { type: "bare"; value: string } | { type: "path"; value: string }
34
+
35
+ function toPathSpecifier(specifier: string | URL): PathSpecifier {
36
+ if (specifier instanceof URL) {
37
+ if (specifier.protocol !== "file:") {
38
+ throw new Error(`Unsupported URL protocol "${specifier.protocol}"`)
39
+ }
40
+
41
+ return { type: "path", value: fileURLToPath(specifier) }
42
+ }
43
+
44
+ if (specifier.startsWith("file:")) {
45
+ return { type: "path", value: fileURLToPath(new URL(specifier)) }
46
+ }
47
+
48
+ if (isBareSpecifier(specifier)) {
49
+ return { type: "bare", value: specifier }
50
+ }
51
+
52
+ return { type: "path", value: specifier }
53
+ }
54
+
55
+ function isBareSpecifier(specifier: string): boolean {
56
+ return !specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.startsWith("file:")
57
+ }
58
+
59
+ function resolvePathSpecifier(specifierPath: string, base?: string | URL): string {
60
+ if (isAbsolute(specifierPath)) {
61
+ return specifierPath
62
+ }
63
+
64
+ const basePath = base ? resolveBasePath(base) : process.cwd()
65
+
66
+ if (specifierPath.startsWith(".")) {
67
+ const baseDir = isLikelyFilePath(basePath) ? dirname(basePath) : basePath
68
+ return resolve(baseDir, specifierPath)
69
+ }
70
+
71
+ return specifierPath
72
+ }
73
+
74
+ function resolveBasePath(base: string | URL): string {
75
+ if (base instanceof URL) {
76
+ if (base.protocol !== "file:") {
77
+ throw new Error(`Unsupported base URL protocol "${base.protocol}"`)
78
+ }
79
+
80
+ return fileURLToPath(base)
81
+ }
82
+
83
+ if (base.startsWith("file:")) {
84
+ return fileURLToPath(new URL(base))
85
+ }
86
+
87
+ return base
88
+ }
89
+
90
+ async function normalizePathForLookup(pathValue: string): Promise<string> {
91
+ const existsAsFile = await pathExists(pathValue)
92
+ if (existsAsFile && isLikelyFilePath(pathValue)) {
93
+ return dirname(pathValue)
94
+ }
95
+
96
+ return pathValue
97
+ }
98
+
99
+ function isLikelyFilePath(pathValue: string): boolean {
100
+ return pathValue.endsWith(".json") || pathValue.endsWith(".mjs") || pathValue.endsWith(".js")
101
+ }
102
+
103
+ async function findNearestPackageJson(startPath: string): Promise<string | undefined> {
104
+ let current = startPath
105
+
106
+ while (true) {
107
+ const candidate = resolve(current, "package.json")
108
+ if (await pathExists(candidate)) {
109
+ return candidate
110
+ }
111
+
112
+ const parent = dirname(current)
113
+ if (parent === current) {
114
+ return undefined
115
+ }
116
+
117
+ current = parent
118
+ }
119
+ }
120
+
121
+ async function findPackageJsonForBareSpecifier(
122
+ startDirectory: string,
123
+ packageName: string,
124
+ ): Promise<string | undefined> {
125
+ let current = startDirectory
126
+
127
+ while (true) {
128
+ const candidate = resolve(current, "node_modules", packageName, "package.json")
129
+ if (await pathExists(candidate)) {
130
+ return candidate
131
+ }
132
+
133
+ const parent = dirname(current)
134
+ if (parent === current) {
135
+ return undefined
136
+ }
137
+
138
+ current = parent
139
+ }
140
+ }
141
+
142
+ async function pathExists(pathValue: string): Promise<boolean> {
143
+ try {
144
+ await access(pathValue)
145
+ return true
146
+ } catch {
147
+ return false
148
+ }
149
+ }
@@ -1,8 +1,8 @@
1
1
  import { realpath } from "node:fs/promises"
2
- import { findPackageJSON } from "node:module"
3
2
  import { dirname } from "node:path"
4
3
  import { parentPort, workerData } from "node:worker_threads"
5
4
  import pino, { type Level } from "pino"
5
+ import { findPackageJSONCompat } from "./find-package-json"
6
6
 
7
7
  export type PackageResolutionWorkerData = {
8
8
  importPath: string
@@ -37,9 +37,13 @@ const results: PackageResult[] = []
37
37
 
38
38
  for (const packageName of packageNames) {
39
39
  try {
40
- const path = findPackageJSON(packageName, rootDir)
40
+ const path = await findPackageJSONCompat(packageName, rootDir)
41
41
  if (!path) {
42
- throw new Error(`Package "${packageName}" not found`)
42
+ results.push({
43
+ type: "not-found",
44
+ packageName,
45
+ })
46
+ continue
43
47
  }
44
48
 
45
49
  results.push({
@@ -425,6 +425,8 @@ export class RuntimeOperation {
425
425
  state.status === "deployed" &&
426
426
  state.selfHash != null &&
427
427
  state.dependencyOutputHash != null &&
428
+ // do not short-circuit after destroy phase in recreate operations
429
+ state.lastOperationState?.status !== "destroyed" &&
428
430
  // ignore explicitly requested updates
429
431
  !this.operation.requestedInstanceIds.includes(instance.id) &&
430
432
  // ignore when side effects are requested
@@ -202,4 +202,90 @@ describe("RuntimeOperation - Update Short-Circuit", () => {
202
202
  })
203
203
  },
204
204
  )
205
+
206
+ operationTest(
207
+ "does not short-circuit update for instances destroyed earlier in recreate",
208
+ async ({
209
+ project,
210
+ logger,
211
+ runnerBackend,
212
+ libraryBackend,
213
+ artifactService,
214
+ instanceLockService,
215
+ operationService,
216
+ secretService,
217
+ instanceStateService,
218
+ projectModelService,
219
+ unitExtraService,
220
+ entitySnapshotService,
221
+ unitOutputService,
222
+ createUnit,
223
+ createDeployedUnitState,
224
+ createContext,
225
+ createOperation,
226
+ setupImmediateLocking,
227
+ setupPersistenceMocks,
228
+ expect,
229
+ }) => {
230
+ // arrange
231
+ const unit = createUnit("A")
232
+ const state = createDeployedUnitState(unit)
233
+
234
+ const context = await createContext({ instances: [unit], states: [state] })
235
+
236
+ const expected = await context.getUpToDateInputHashOutput(unit)
237
+ state.selfHash = expected.selfHash
238
+ state.dependencyOutputHash = expected.dependencyOutputHash
239
+ instanceStateService.getInstanceStates.mockResolvedValue([state])
240
+
241
+ setupImmediateLocking()
242
+ setupPersistenceMocks({ instances: [unit] })
243
+
244
+ const operation = createOperation({
245
+ type: "recreate",
246
+ requestedInstanceIds: [unit.id],
247
+ phases: [
248
+ {
249
+ type: "destroy",
250
+ instances: [{ id: unit.id, message: "explicitly requested", parentId: undefined }],
251
+ },
252
+ {
253
+ type: "update",
254
+ instances: [{ id: unit.id, message: "explicitly requested", parentId: undefined }],
255
+ },
256
+ ],
257
+ })
258
+
259
+ const runtimeOperation = new RuntimeOperation(
260
+ project,
261
+ operation,
262
+ runnerBackend,
263
+ libraryBackend,
264
+ artifactService,
265
+ instanceLockService,
266
+ operationService,
267
+ secretService,
268
+ instanceStateService,
269
+ projectModelService,
270
+ unitExtraService,
271
+ entitySnapshotService,
272
+ unitOutputService,
273
+ logger,
274
+ )
275
+
276
+ // act
277
+ await runtimeOperation.operateSafe()
278
+
279
+ // assert
280
+ expect(runnerBackend.destroy).toHaveBeenCalledTimes(1)
281
+ expect(runnerBackend.update).toHaveBeenCalledTimes(1)
282
+
283
+ const skipCall = instanceStateService.updateOperationState.mock.calls.find(
284
+ ([, stateId, , options]) =>
285
+ stateId === unit.id && options.operationState?.status === "skipped",
286
+ )
287
+
288
+ expect(skipCall).toBeUndefined()
289
+ },
290
+ )
205
291
  })
@@ -12,19 +12,19 @@ export const runnerBackendConfig = z.object({
12
12
  ...localRunnerBackendConfig.shape,
13
13
  })
14
14
 
15
- export function createRunnerBackend(
15
+ export async function createRunnerBackend(
16
16
  config: z.infer<typeof runnerBackendConfig>,
17
17
  libraryBackend: LibraryBackend,
18
18
  artifactManager: ArtifactService,
19
19
  artifactBackend: ArtifactBackend,
20
20
  secretService: SecretService,
21
21
  logger: Logger,
22
- ): RunnerBackend {
22
+ ): Promise<RunnerBackend> {
23
23
  switch (config.HIGHSTATE_RUNNER_BACKEND_TYPE) {
24
24
  case "local": {
25
25
  const localPulumiHost = LocalPulumiHost.create(secretService, logger)
26
26
 
27
- return LocalRunnerBackend.create(
27
+ return await LocalRunnerBackend.create(
28
28
  config,
29
29
  localPulumiHost,
30
30
  libraryBackend,
@@ -3,7 +3,8 @@
3
3
 
4
4
  import type { PulumiCommand } from "@pulumi/pulumi/automation/index.js"
5
5
  import * as os from "node:os"
6
- import path from "node:path"
6
+ import { homedir } from "node:os"
7
+ import path, { resolve } from "node:path"
7
8
  import { execa } from "execa"
8
9
 
9
10
  /**
@@ -20,7 +21,11 @@ export async function createForceAbortableCommand(): Promise<PulumiCommand> {
20
21
  "@pulumi/pulumi/automation/index.js"
21
22
  )
22
23
 
23
- const command: any = await PulumiCommand.get()
24
+ const commandOptions = {
25
+ root: resolve(homedir(), ".pulumi"),
26
+ }
27
+
28
+ const command: any = await PulumiCommand.get(commandOptions)
24
29
 
25
30
  // replicate the run method from PulumiCommand
26
31
  command.run = function (
@@ -16,7 +16,7 @@ import type {
16
16
  import type { DualAbortSignal } from "./force-abort"
17
17
  import { EventEmitter, on } from "node:events"
18
18
  import { mkdir, rm } from "node:fs/promises"
19
- import { cpus } from "node:os"
19
+ import { cpus, homedir } from "node:os"
20
20
  import { join, resolve } from "node:path"
21
21
  import {
22
22
  getInstanceId,
@@ -649,14 +649,19 @@ export class LocalRunnerBackend implements RunnerBackend {
649
649
  return options.stateId
650
650
  }
651
651
 
652
- public static create(
652
+ public static async create(
653
653
  config: z.infer<typeof localRunnerBackendConfig>,
654
654
  pulumiProjectHost: LocalPulumiHost,
655
655
  libraryBackend: LibraryBackend,
656
656
  artifactManager: ArtifactService,
657
657
  artifactBackend: ArtifactBackend,
658
658
  logger: Logger,
659
- ): RunnerBackend {
659
+ ): Promise<RunnerBackend> {
660
+ const { PulumiCommand } = await import("@pulumi/pulumi/automation/index.js")
661
+ await PulumiCommand.install({
662
+ root: resolve(homedir(), ".pulumi"),
663
+ })
664
+
660
665
  let cacheDir = config.HIGHSTATE_RUNNER_BACKEND_LOCAL_CACHE_DIR
661
666
  if (!cacheDir) {
662
667
  const homeDir = process.env.HOME ?? process.env.USERPROFILE
@@ -2,6 +2,7 @@ import type {
2
2
  ConfigMap,
3
3
  OpMap,
4
4
  OpType,
5
+ ProjectRuntime,
5
6
  Stack,
6
7
  WhoAmIResult,
7
8
  } from "@pulumi/pulumi/automation/index.js"
@@ -63,7 +64,7 @@ export class LocalPulumiHost {
63
64
  {
64
65
  projectSettings: {
65
66
  name: pulumiProjectName,
66
- runtime: "nodejs",
67
+ runtime: "bun" as ProjectRuntime,
67
68
  },
68
69
  envVars: {
69
70
  PULUMI_CONFIG_PASSPHRASE: await this.secretService.getPulumiPassword(projectId),
@@ -112,10 +113,7 @@ export class LocalPulumiHost {
112
113
  projectSettings: {
113
114
  name: pulumiProjectName,
114
115
  runtime: {
115
- name: "nodejs",
116
- options: {
117
- nodeargs: "--no-deprecation",
118
- },
116
+ name: "bun",
119
117
  },
120
118
  main: "index.js",
121
119
  },
package/src/services.ts CHANGED
@@ -214,7 +214,7 @@ export async function createServices({
214
214
  )
215
215
  sessionService ??= new TerminalSessionService(database)
216
216
 
217
- runnerBackend ??= createRunnerBackend(
217
+ runnerBackend ??= await createRunnerBackend(
218
218
  config,
219
219
  libraryBackend,
220
220
  artifactService,
@@ -23,10 +23,15 @@ for key in "\${filesKeys[@]}"; do
23
23
  continue
24
24
  fi
25
25
 
26
- # Handle embedded content
27
- if [ "$contentType" = "embedded" ]; then
28
- content=$(jq -r ".files[\\"$key\\"].content.value" <<<"$data")
29
- isBinary=$(jq -r ".files[\\"$key\\"].meta.isBinary // false" <<<"$data")
26
+ # Handle embedded and embedded-secret content
27
+ if [ "$contentType" = "embedded" ] || [ "$contentType" = "embedded-secret" ]; then
28
+ if [ "$contentType" = "embedded-secret" ]; then
29
+ content=$(jq -r ".files[\\"$key\\"].content.value.value" <<<"$data")
30
+ else
31
+ content=$(jq -r ".files[\\"$key\\"].content.value" <<<"$data")
32
+ fi
33
+
34
+ isBinary=$(jq -r ".files[\\"$key\\"].content.isBinary // .files[\\"$key\\"].meta.isBinary // false" <<<"$data")
30
35
  mode=$(jq -r ".files[\\"$key\\"].meta.mode // 0" <<<"$data")
31
36
 
32
37
  mkdir -p "$(dirname "$key")"
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Exeteres
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.