@impz/testing 7.7.0 → 7.8.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 (2) hide show
  1. package/dist/index.js +290 -217
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -18983,7 +18983,8 @@ var ImageSchema = z4.object({
18983
18983
  source: ImageSourceSchema,
18984
18984
  createdAt: z4.date(),
18985
18985
  sizeBytes: z4.int().nonnegative(),
18986
- pinned: z4.boolean().default(false)
18986
+ pinned: z4.boolean().default(false),
18987
+ aliases: z4.array(NameSchema).default([])
18987
18988
  });
18988
18989
 
18989
18990
  // packages/api/src/schemas/image-op-event-schema.ts
@@ -20164,6 +20165,7 @@ var SystemFeaturesSchema = z34.object({
20164
20165
  execDropSysAdmin: z34.boolean().optional(),
20165
20166
  guestScratch: z34.boolean().optional(),
20166
20167
  imagePins: z34.boolean().optional(),
20168
+ imageAliases: z34.boolean().optional(),
20167
20169
  buildContextUpload: z34.boolean().optional(),
20168
20170
  destroyIdCheck: z34.boolean().optional(),
20169
20171
  secretIdentity: z34.boolean().optional(),
@@ -20539,7 +20541,9 @@ var callerContract = {
20539
20541
  builds: contractBase.meta(ACCESS.readHost).output(z43.array(ImageBuildRunSchema)),
20540
20542
  delete: contractBase.meta(ACCESS.manageHost).input(NameInputSchema).output(EmptySchema),
20541
20543
  pin: contractBase.meta(ACCESS.manageHeldImage).input(NameInputSchema).output(ImageSchema),
20542
- unpin: contractBase.meta(ACCESS.manageHeldImage).input(NameInputSchema).output(ImageSchema)
20544
+ unpin: contractBase.meta(ACCESS.manageHeldImage).input(NameInputSchema).output(ImageSchema),
20545
+ alias: contractBase.meta(ACCESS.manageHost).input(z43.object({ alias: NameSchema, image: NameSchema })).output(ImageSchema),
20546
+ unalias: contractBase.meta(ACCESS.manageHost).input(z43.object({ alias: NameSchema })).output(EmptySchema)
20543
20547
  },
20544
20548
  exec: {
20545
20549
  ticket: contractBase.meta({ access: { scope: "exec", on: "imp", fields: ["name"], audit: false } }).input(NameInputSchema).output(z43.object({ ticket: z43.string(), expiresAt: z43.date() }))
@@ -22147,14 +22151,13 @@ import { join as join49 } from "path";
22147
22151
  // packages/daemon/package.json
22148
22152
  var package_default = {
22149
22153
  name: "@impz/daemon",
22150
- version: "7.7.0",
22154
+ version: "7.8.1",
22151
22155
  private: true,
22152
22156
  description: "impd: the imp host daemon",
22153
22157
  type: "module",
22154
22158
  exports: {
22155
22159
  ".": "./src/index.ts",
22156
22160
  "./read-text": "./src/platform/process/read-text.ts",
22157
- "./real-clock": "./src/platform/process/real-clock.ts",
22158
22161
  "./test-utils": "./src/test-utils/index.ts",
22159
22162
  "./test-utils/*": "./src/test-utils/*.ts",
22160
22163
  "./host/config": "./src/config.ts",
@@ -22174,7 +22177,7 @@ var package_default = {
22174
22177
  "./host/platform/db/open-database": "./src/platform/db/open-database.ts",
22175
22178
  "./host/platform/db/read-names": "./src/platform/db/read-names.ts",
22176
22179
  "./host/platform/db/run-migrations": "./src/platform/db/run-migrations.ts",
22177
- "./host/platform/process/clock": "./src/platform/process/clock.ts",
22180
+ "./host/platform/process/start-timer": "./src/platform/process/start-timer.ts",
22178
22181
  "./host/platform/process/get-impd-logger": "./src/platform/process/get-impd-logger.ts",
22179
22182
  "./host/platform/process/read-host-load": "./src/platform/process/read-host-load.ts",
22180
22183
  "./host/platform/process/read-text": "./src/platform/process/read-text.ts",
@@ -22240,6 +22243,7 @@ var package_default = {
22240
22243
  "@faker-js/faker": "catalog:",
22241
22244
  "@impz/cli": "workspace:*",
22242
22245
  "@impz/e2e-harness": "workspace:*",
22246
+ "@impz/scripts": "workspace:*",
22243
22247
  "@impz/testing": "workspace:*",
22244
22248
  "@modelcontextprotocol/client": "catalog:",
22245
22249
  "@msw/data": "catalog:",
@@ -25386,17 +25390,23 @@ async function writeChangedBlocks(source, target) {
25386
25390
 
25387
25391
  // packages/daemon/src/platform/db/create-image.ts
25388
25392
  async function createImage(db, image, now = Date.now()) {
25389
- const row = await db.insertInto("images").values({
25390
- id: Bun.randomUUIDv7(),
25391
- name: image.name,
25392
- ref: image.ref,
25393
- digest: image.digest,
25394
- size_bytes: image.sizeBytes,
25395
- source: image.source ?? "oci",
25396
- source_imp: image.sourceImp ?? null,
25397
- created_at: now,
25398
- last_used_at: now
25399
- }).returningAll().executeTakeFirstOrThrow();
25393
+ const row = await db.transaction().execute(async (trx) => {
25394
+ const alias = await trx.selectFrom("image_aliases").select("name").where("name", "=", image.name).executeTakeFirst();
25395
+ if (alias !== undefined) {
25396
+ throw buildConflictError("image", image.name, `image name ${image.name} is held by an alias; remove the alias first`);
25397
+ }
25398
+ return trx.insertInto("images").values({
25399
+ id: Bun.randomUUIDv7(),
25400
+ name: image.name,
25401
+ ref: image.ref,
25402
+ digest: image.digest,
25403
+ size_bytes: image.sizeBytes,
25404
+ source: image.source ?? "oci",
25405
+ source_imp: image.sourceImp ?? null,
25406
+ created_at: now,
25407
+ last_used_at: now
25408
+ }).returningAll().executeTakeFirstOrThrow();
25409
+ });
25400
25410
  return toImageRecord(row);
25401
25411
  }
25402
25412
  async function readImageByName(db, name) {
@@ -25478,7 +25488,8 @@ async function listImageUses(db) {
25478
25488
  "images.size_bytes",
25479
25489
  "images.last_used_at",
25480
25490
  "images.pinned",
25481
- eb.fn.count("imps.id").as("imp_count")
25491
+ eb.fn.count("imps.id").as("imp_count"),
25492
+ eb.exists(eb.selectFrom("image_aliases").select("image_aliases.name").whereRef("image_aliases.image_id", "=", "images.id")).as("is_aliased")
25482
25493
  ]).groupBy("images.id").orderBy("images.name").execute();
25483
25494
  return rows.map((row) => ({
25484
25495
  id: row.id,
@@ -25488,12 +25499,13 @@ async function listImageUses(db) {
25488
25499
  sizeBytes: row.size_bytes,
25489
25500
  lastUsedAt: row.last_used_at,
25490
25501
  impCount: row.imp_count,
25491
- isPinned: row.pinned === 1
25502
+ isPinned: row.pinned === 1,
25503
+ isAliased: Boolean(row.is_aliased)
25492
25504
  }));
25493
25505
  }
25494
25506
  function removeUnusedImage(db, id, lastUsedAt) {
25495
25507
  return db.transaction().execute(async (trx) => {
25496
- const row = await trx.deleteFrom("images").where("id", "=", id).where("last_used_at", "=", lastUsedAt).where("pinned", "=", 0).where((eb) => eb.not(eb.exists(eb.selectFrom("imps").select("imps.id").whereRef("imps.image_id", "=", "images.id")))).returning("digest").executeTakeFirst();
25508
+ const row = await trx.deleteFrom("images").where("id", "=", id).where("last_used_at", "=", lastUsedAt).where("pinned", "=", 0).where((eb) => eb.not(eb.exists(eb.selectFrom("imps").select("imps.id").whereRef("imps.image_id", "=", "images.id")))).where((eb) => eb.not(eb.exists(eb.selectFrom("image_aliases").select("image_aliases.name").whereRef("image_aliases.image_id", "=", "images.id")))).returning("digest").executeTakeFirst();
25497
25509
  if (row === undefined) {
25498
25510
  return false;
25499
25511
  }
@@ -25512,6 +25524,12 @@ async function removeImageRemoval(db, digest) {
25512
25524
  await db.deleteFrom("image_removals").where("digest", "=", digest).execute();
25513
25525
  }
25514
25526
 
25527
+ // packages/daemon/src/platform/db/probe-image-alias.ts
25528
+ async function probeImageAlias(db, name) {
25529
+ const row = await db.selectFrom("image_aliases").select("name").where("name", "=", name).executeTakeFirst();
25530
+ return row !== undefined;
25531
+ }
25532
+
25515
25533
  // packages/daemon/src/imp-ops/imp-import/build-digest-tag.ts
25516
25534
  function buildDigestTag(digest) {
25517
25535
  if (digest.startsWith("imp-")) {
@@ -25522,17 +25540,24 @@ function buildDigestTag(digest) {
25522
25540
 
25523
25541
  // packages/daemon/src/imp-ops/imp-import/resolve-imported-image-name.ts
25524
25542
  async function resolveImportedImageName(db, name, digest) {
25525
- const taken = await readImageByName(db, name);
25526
- if (taken === undefined) {
25543
+ const isTaken = await probeNameTaken(db, name);
25544
+ if (!isTaken) {
25527
25545
  return name;
25528
25546
  }
25529
25547
  const fallback = `${name.slice(0, 22)}-${buildDigestTag(digest)}`;
25530
- const fallbackTaken = await readImageByName(db, fallback);
25531
- if (fallbackTaken !== undefined) {
25532
- throw buildConflictError("image", fallback, `images ${name} and ${fallback} both exist; remove one to import this image`);
25548
+ const isFallbackTaken = await probeNameTaken(db, fallback);
25549
+ if (isFallbackTaken) {
25550
+ throw buildConflictError("image", fallback, `images ${name} and ${fallback} both exist, or an alias holds one of them; remove one to import this image`);
25533
25551
  }
25534
25552
  return fallback;
25535
25553
  }
25554
+ async function probeNameTaken(db, name) {
25555
+ const image = await readImageByName(db, name);
25556
+ if (image !== undefined) {
25557
+ return true;
25558
+ }
25559
+ return probeImageAlias(db, name);
25560
+ }
25536
25561
 
25537
25562
  // packages/daemon/src/imp-ops/imp-import/create-image-from-file.ts
25538
25563
  function createImageFromFile(deps, image) {
@@ -25546,7 +25571,10 @@ function createImageFromFile(deps, image) {
25546
25571
  sizeBytes: image.sizeBytes,
25547
25572
  source: image.source,
25548
25573
  sourceImp: image.sourceImp
25549
- }, deps.now());
25574
+ }, deps.now()).catch(async (error) => {
25575
+ await deps.images.removeIdleRootfs(image.digest);
25576
+ throw error;
25577
+ });
25550
25578
  return name;
25551
25579
  });
25552
25580
  }
@@ -25906,6 +25934,7 @@ function removeSnapshot(paths) {
25906
25934
  // packages/daemon/src/vm/vmm/start-firecracker.ts
25907
25935
  import { closeSync as closeSync6, existsSync as existsSync5, readFileSync as readFileSync7, rmSync as rmSync6 } from "fs";
25908
25936
  import { basename } from "path";
25937
+ import { systemClock } from "@zgeoff/std";
25909
25938
 
25910
25939
  // packages/daemon/src/platform/process/impd-user.ts
25911
25940
  var IMPD_USER = { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };
@@ -25929,13 +25958,6 @@ function stopPid(pid, signal = "SIGKILL") {
25929
25958
  } catch {}
25930
25959
  }
25931
25960
 
25932
- // packages/daemon/src/platform/process/real-clock.ts
25933
- var REAL_CLOCK = {
25934
- now: () => Date.now(),
25935
- startTimer: startRealTimer,
25936
- sleep: (durationMs) => Bun.sleep(durationMs)
25937
- };
25938
-
25939
25961
  // packages/daemon/src/vm/vmm/read-process-uid.ts
25940
25962
  import { closeSync as closeSync5, readFileSync as readFileSync6 } from "fs";
25941
25963
  import { join as join7 } from "path";
@@ -26068,7 +26090,7 @@ function probeProcessAlive(pid, socket, procRoot = "/proc") {
26068
26090
  }
26069
26091
  }
26070
26092
  async function waitForExit(pid, apiSocket, timeoutMs, watch = {}) {
26071
- const clock = watch.clock ?? REAL_CLOCK;
26093
+ const clock = watch.clock ?? systemClock;
26072
26094
  const deadline = clock.now() + timeoutMs;
26073
26095
  while (probeProcessAlive(pid, apiSocket, watch.procRoot)) {
26074
26096
  if (clock.now() > deadline) {
@@ -26708,7 +26730,7 @@ function createCheckpointService(deps) {
26708
26730
  try {
26709
26731
  const fork = await deps.imps.createImp({
26710
26732
  name: input.name,
26711
- image: source.imp.image,
26733
+ image: await deps.images.resolveImage(source.imp.image),
26712
26734
  imageDigest: source.imageDigest,
26713
26735
  vcpus: source.imp.vcpus,
26714
26736
  memoryMib: source.imp.memoryMib,
@@ -28190,6 +28212,14 @@ var MIGRATION_046_MOVE_GRANTS_TO_MCP_AUTH = {
28190
28212
  }
28191
28213
  };
28192
28214
 
28215
+ // packages/daemon/src/platform/db/migrations/migration-047-add-image-aliases.ts
28216
+ var MIGRATION_047_ADD_IMAGE_ALIASES = {
28217
+ async up(db) {
28218
+ await db.schema.createTable("image_aliases").addColumn("name", "text", (column) => column.primaryKey()).addColumn("image_id", "text", (column) => column.notNull().references("images.id")).addColumn("updated_at", "integer", (column) => column.notNull()).execute();
28219
+ await db.schema.createIndex("image_aliases_image_id").on("image_aliases").column("image_id").execute();
28220
+ }
28221
+ };
28222
+
28193
28223
  // packages/daemon/src/platform/db/read-names.ts
28194
28224
  import * as z68 from "zod";
28195
28225
  var NameRowsSchema = z68.array(z68.object({ name: z68.string() }));
@@ -28244,7 +28274,8 @@ var MIGRATIONS = {
28244
28274
  "043_merge_secret_kinds": MIGRATION_043_MERGE_SECRET_KINDS,
28245
28275
  "044_add_imp_image_digests": MIGRATION_044_ADD_IMP_IMAGE_DIGESTS,
28246
28276
  "045_add_imp_last_request": MIGRATION_045_ADD_IMP_LAST_REQUEST,
28247
- "046_move_grants_to_mcp_auth": MIGRATION_046_MOVE_GRANTS_TO_MCP_AUTH
28277
+ "046_move_grants_to_mcp_auth": MIGRATION_046_MOVE_GRANTS_TO_MCP_AUTH,
28278
+ "047_add_image_aliases": MIGRATION_047_ADD_IMAGE_ALIASES
28248
28279
  };
28249
28280
  var DURABLE_MIGRATION_TABLE = "kysely_migration_durable";
28250
28281
  async function runMigrations(db) {
@@ -28529,7 +28560,7 @@ async function createRestoredImp(deps, options) {
28529
28560
  ...imp.clonedDigest !== undefined && { imageDigest: imp.clonedDigest },
28530
28561
  name: target.name,
28531
28562
  networkIds: networks.ids,
28532
- image: target.image,
28563
+ image: await deps.images.resolveImage(target.image),
28533
28564
  vcpus: imp.vcpus,
28534
28565
  memoryMib: imp.memoryMib,
28535
28566
  maxMemoryMib: imp.maxMemoryMib ?? undefined,
@@ -29089,6 +29120,9 @@ function createIdleLoop(deps) {
29089
29120
  };
29090
29121
  }
29091
29122
 
29123
+ // packages/daemon/src/imps/images/builders/create-builders.ts
29124
+ import { systemClock as systemClock2 } from "@zgeoff/std";
29125
+
29092
29126
  // packages/daemon/src/imps/images/builders/guest-exec.ts
29093
29127
  var STDOUT_MAX_BYTES = 1024 ** 2;
29094
29128
  var STDERR_TAIL_BYTES = 64 * 1024;
@@ -29214,7 +29248,7 @@ var BUILDER_IMAGE = "imp-builder";
29214
29248
  var REMOVE_RETRY_MS = 30000;
29215
29249
  function createBuilders(deps) {
29216
29250
  const startTimer = deps.startTimer ?? ((fire, durationMs) => startRealTimer(fire, durationMs, { isUnref: true }));
29217
- const clock = deps.clock ?? REAL_CLOCK;
29251
+ const clock = deps.clock ?? systemClock2;
29218
29252
  const pickBuilderName = deps.pickBuilderName ?? pickRandomBuilderName;
29219
29253
  const logger = getImpdLogger("image");
29220
29254
  const retrying = new Set;
@@ -29264,7 +29298,7 @@ function createBuilders(deps) {
29264
29298
  await deps.imps.createImp({
29265
29299
  id,
29266
29300
  name,
29267
- image: BUILDER_IMAGE,
29301
+ image: await deps.images.resolveImage(BUILDER_IMAGE),
29268
29302
  memoryMib: deps.config.build.memoryMib,
29269
29303
  maxMemoryMib: deps.config.build.maxMemoryMib ?? undefined,
29270
29304
  diskMib: Math.ceil(deps.config.build.diskBytes / 1024 ** 2),
@@ -35280,7 +35314,7 @@ import { ORPCError as ORPCError3 } from "@orpc/server";
35280
35314
  import invariant9 from "tiny-invariant";
35281
35315
 
35282
35316
  // packages/daemon/src/surface/to-api-image.ts
35283
- function toApiImage(image) {
35317
+ function toApiImage(image, aliases) {
35284
35318
  return {
35285
35319
  id: image.id,
35286
35320
  name: image.name,
@@ -35289,16 +35323,22 @@ function toApiImage(image) {
35289
35323
  source: image.source,
35290
35324
  createdAt: image.createdAt,
35291
35325
  sizeBytes: image.sizeBytes,
35292
- pinned: image.isPinned
35326
+ pinned: image.isPinned,
35327
+ aliases: [...aliases]
35293
35328
  };
35294
35329
  }
35295
35330
 
35296
35331
  // packages/daemon/src/surface/create-image-routes.ts
35297
35332
  function createImageRoutes(os, deps) {
35333
+ const readApiImage = async (image) => {
35334
+ const aliases = await deps.images.listImageAliases([image.id]);
35335
+ return toApiImage(image, aliases.get(image.id) ?? []);
35336
+ };
35298
35337
  return {
35299
35338
  list: os.images.list.handler(async () => {
35300
35339
  const images = await deps.images.listImages();
35301
- return images.map((image) => toApiImage(image));
35340
+ const aliases = await deps.images.listImageAliases(images.map((image) => image.id));
35341
+ return images.map((image) => toApiImage(image, aliases.get(image.id) ?? []));
35302
35342
  }),
35303
35343
  add: os.images.add.handler(async (context) => {
35304
35344
  const input = context.input;
@@ -35307,7 +35347,7 @@ function createImageRoutes(os, deps) {
35307
35347
  context.context.auditDetail.value = reference;
35308
35348
  };
35309
35349
  const image = "imp" in input ? await deps.templates.createTemplate(input.imp, input.name) : await deps.images.addImage(input.ref, input.name, { signal, onResolved });
35310
- return toApiImage(image);
35350
+ return readApiImage(image);
35311
35351
  }),
35312
35352
  addStream: os.images.addStream.handler((context) => {
35313
35353
  const input = context.input;
@@ -35321,7 +35361,7 @@ function createImageRoutes(os, deps) {
35321
35361
  setPhase: report.setPhase,
35322
35362
  onResolved
35323
35363
  });
35324
- return toApiImage(image);
35364
+ return readApiImage(image);
35325
35365
  }, buildImageOpOptions(deps, context, "images.addStream", firstPhase));
35326
35366
  }),
35327
35367
  buildStream: os.images.buildStream.handler((context) => {
@@ -35349,7 +35389,7 @@ function createImageRoutes(os, deps) {
35349
35389
  },
35350
35390
  setBuilder: run.setBuilder
35351
35391
  });
35352
- return toApiImage(image);
35392
+ return await readApiImage(image);
35353
35393
  } finally {
35354
35394
  upload.release();
35355
35395
  }
@@ -35361,13 +35401,13 @@ function createImageRoutes(os, deps) {
35361
35401
  setPhase: report.setPhase,
35362
35402
  output: report.output
35363
35403
  });
35364
- return toApiImage(image);
35404
+ return readApiImage(image);
35365
35405
  }), { ...buildImageOpOptions(deps, context, "images.buildStream", "pack"), logs });
35366
35406
  }),
35367
35407
  builds: os.images.builds.handler(() => deps.images.listBuildRuns()),
35368
35408
  build: os.images.build.handler(async (context) => {
35369
35409
  const image = await deps.images.runImageBuild(context.input.contextDir, context.input.name, context.input.dockerfile, { ...context.signal !== undefined && { signal: context.signal } });
35370
- return toApiImage(image);
35410
+ return readApiImage(image);
35371
35411
  }),
35372
35412
  delete: os.images.delete.handler(async (context) => {
35373
35413
  await deps.images.removeImage(context.input.name);
@@ -35375,11 +35415,19 @@ function createImageRoutes(os, deps) {
35375
35415
  }),
35376
35416
  pin: os.images.pin.handler(async (context) => {
35377
35417
  const image = await deps.images.updateImagePin(context.input.name, true, findPinRefPrefix(context.context.caller));
35378
- return toApiImage(image);
35418
+ return readApiImage(image);
35379
35419
  }),
35380
35420
  unpin: os.images.unpin.handler(async (context) => {
35381
35421
  const image = await deps.images.updateImagePin(context.input.name, false, findPinRefPrefix(context.context.caller));
35382
- return toApiImage(image);
35422
+ return readApiImage(image);
35423
+ }),
35424
+ alias: os.images.alias.handler(async (context) => {
35425
+ const image = await deps.images.updateImageAlias(context.input.alias, context.input.image);
35426
+ return readApiImage(image);
35427
+ }),
35428
+ unalias: os.images.unalias.handler(async (context) => {
35429
+ await deps.images.removeImageAlias(context.input.alias);
35430
+ return {};
35383
35431
  })
35384
35432
  };
35385
35433
  }
@@ -35435,14 +35483,12 @@ function createImpRoutes(os, deps, views) {
35435
35483
  if (networks !== undefined && caller.imps !== null) {
35436
35484
  throw buildForbiddenError(`${formatCaller(caller)} is limited to some imps, so it cannot put an imp on a network`);
35437
35485
  }
35438
- if (caller.imps !== null) {
35439
- const image = await deps.images.resolveImage(input.image);
35440
- if (image.sourceImp !== null && !isCallerAllowed(caller, "manage", image.sourceImp)) {
35441
- throw buildForbiddenError(`${formatCaller(caller)} may not copy imp ${image.sourceImp}, the source of template ${image.name}`);
35442
- }
35486
+ const image = await deps.images.resolveImage(input.image);
35487
+ if (caller.imps !== null && image.sourceImp !== null && !isCallerAllowed(caller, "manage", image.sourceImp)) {
35488
+ throw buildForbiddenError(`${formatCaller(caller)} may not copy imp ${image.sourceImp}, the source of template ${image.name}`);
35443
35489
  }
35444
35490
  const networkIds = await deps.networks.resolveNetworkIds(networks ?? []);
35445
- return views.readCallerImp(caller, deps.imps.createImp({ ...input, networkIds, isBackedUp: backup }));
35491
+ return views.readCallerImp(caller, deps.imps.createImp({ ...input, image, networkIds, isBackedUp: backup }));
35446
35492
  }),
35447
35493
  list: os.imps.list.handler(async (context) => {
35448
35494
  const caller = context.context.caller;
@@ -44078,7 +44124,7 @@ function createImpCommands(parts) {
44078
44124
  return {
44079
44125
  createImp: async (input) => {
44080
44126
  const received = performance.now();
44081
- const image = await context.images.resolveImage(input.image);
44127
+ const image = input.image;
44082
44128
  if (input.policy !== undefined) {
44083
44129
  context.egress.requirePolicy(input.policy);
44084
44130
  }
@@ -44416,7 +44462,8 @@ function createDiskBudget(deps) {
44416
44462
  }
44417
44463
 
44418
44464
  // packages/daemon/src/vm/storage/storage-gate.ts
44419
- function createStorageGate(clock = REAL_CLOCK) {
44465
+ import { systemClock as systemClock3 } from "@zgeoff/std";
44466
+ function createStorageGate(clock = systemClock3) {
44420
44467
  const state = {
44421
44468
  inFlight: 0,
44422
44469
  waiting: 0,
@@ -44454,7 +44501,7 @@ function createStorageGate(clock = REAL_CLOCK) {
44454
44501
  return { ran: false };
44455
44502
  }
44456
44503
  const expired = Promise.withResolvers();
44457
- const cancel = clock.startTimer(() => {
44504
+ const cancel = clock.schedule(() => {
44458
44505
  expired.resolve();
44459
44506
  }, left);
44460
44507
  try {
@@ -46636,7 +46683,6 @@ function createImpContext(deps) {
46636
46683
  execStartTimer: deps.execStartTimer ?? startRealTimer
46637
46684
  };
46638
46685
  const vms = {
46639
- images: deps.images,
46640
46686
  taps: deps.taps,
46641
46687
  vms: deps.vms,
46642
46688
  storage: deps.storage,
@@ -48301,8 +48347,9 @@ import { resolve as resolve3 } from "path";
48301
48347
  import { mkdirSync as mkdirSync22, rmSync as rmSync27 } from "fs";
48302
48348
 
48303
48349
  // packages/daemon/src/vm/agent-client/wait-for-agent.ts
48350
+ import { systemClock as systemClock4 } from "@zgeoff/std";
48304
48351
  async function waitForAgent(vsockPath, options) {
48305
- const clock = options.clock ?? REAL_CLOCK;
48352
+ const clock = options.clock ?? systemClock4;
48306
48353
  const deadline = clock.now() + options.deadlineMs;
48307
48354
  const maxDelay = options.maxDelayMs ?? 100;
48308
48355
  let delay = options.firstDelayMs ?? 5;
@@ -50621,6 +50668,7 @@ function probeUffdDevice(path = "/dev/userfaultfd") {
50621
50668
 
50622
50669
  // packages/daemon/src/vm/vmm/vm-runner.ts
50623
50670
  import { lstatSync as lstatSync4, mkdirSync as mkdirSync24, renameSync as renameSync7, rmSync as rmSync28 } from "fs";
50671
+ import { systemClock as systemClock5 } from "@zgeoff/std";
50624
50672
 
50625
50673
  // packages/daemon/src/vm/vmm/build-boot-args.ts
50626
50674
  function buildBootArgs(plan) {
@@ -50700,7 +50748,7 @@ function createVmRunner(jails, options) {
50700
50748
  const createClient = options.createClient ?? createFirecrackerClient;
50701
50749
  const readFile = options.readFile;
50702
50750
  const uffdHandlerBin = options.uffdHandlerBin ?? null;
50703
- const clock = options.clock ?? REAL_CLOCK;
50751
+ const clock = options.clock ?? systemClock5;
50704
50752
  const uffdWatch = createUffdWatch({
50705
50753
  probeVmAlive: (pid, paths) => probeProcessAlive(pid, paths.apiSocket, procRoot),
50706
50754
  readHandlerState: (paths) => readHandlerState(paths, procRoot),
@@ -51049,7 +51097,6 @@ function createImpdImps(config, deps, parts) {
51049
51097
  const serviceDeps = {
51050
51098
  config,
51051
51099
  db: deps.db,
51052
- images: parts.storage.images,
51053
51100
  taps: deps.taps ?? createTapDevices(),
51054
51101
  vms,
51055
51102
  storage: deps.storage,
@@ -51301,9 +51348,10 @@ function readReceipt(receipt, secret) {
51301
51348
  var COMMIT_WINDOW_MS = 24 * 60 * 60 * 1000;
51302
51349
 
51303
51350
  // packages/daemon/src/imp-ops/moves/create-part-pipe.ts
51351
+ import { systemClock as systemClock6 } from "@zgeoff/std";
51304
51352
  var MOVE_PART_BYTES = 256 * 1024 * 1024;
51305
51353
  var PART_WAIT_MS = 60000;
51306
- function createPartPipe(waitMs = PART_WAIT_MS, timer = REAL_CLOCK) {
51354
+ function createPartPipe(waitMs = PART_WAIT_MS, timer = systemClock6) {
51307
51355
  const parts = [];
51308
51356
  const state = {
51309
51357
  isEnded: false,
@@ -51328,7 +51376,7 @@ function createPartPipe(waitMs = PART_WAIT_MS, timer = REAL_CLOCK) {
51328
51376
  }
51329
51377
  const waiter = Promise.withResolvers();
51330
51378
  state.waiter = waiter;
51331
- const cancel = timer.startTimer(() => {
51379
+ const cancel = timer.schedule(() => {
51332
51380
  waiter.resolve();
51333
51381
  }, Math.max(0, deadline - timer.now()));
51334
51382
  await waiter.promise;
@@ -52198,7 +52246,7 @@ async function readMoveStream(deps, options) {
52198
52246
  await deps.imps.createImp({
52199
52247
  id: header.imp.id,
52200
52248
  name: header.imp.name,
52201
- image: image.name,
52249
+ image: await deps.images.resolveImage(image.name),
52202
52250
  ...header.imp.clonedDigest !== undefined && { imageDigest: header.imp.clonedDigest },
52203
52251
  vcpus: header.imp.vcpus,
52204
52252
  memoryMib: header.imp.memoryMib,
@@ -53583,6 +53631,7 @@ function createImpdMoves(config, deps, parts, hooks) {
53583
53631
  // packages/daemon/src/imps/images/template-service.ts
53584
53632
  import { copyFileSync as copyFileSync4, existsSync as existsSync28, statSync as statSync16, writeFileSync as writeFileSync14 } from "fs";
53585
53633
  import { join as join42 } from "path";
53634
+ import { systemClock as systemClock7 } from "@zgeoff/std";
53586
53635
 
53587
53636
  // packages/daemon/src/imps/images/read-held-image.ts
53588
53637
  async function readHeldImage(db, name, at) {
@@ -53601,6 +53650,14 @@ function requireClientImageName(name) {
53601
53650
  return imageName;
53602
53651
  }
53603
53652
 
53653
+ // packages/daemon/src/imps/images/require-unaliased-name.ts
53654
+ async function requireUnaliasedName(db, name) {
53655
+ const isAliased = await probeImageAlias(db, name);
53656
+ if (isAliased) {
53657
+ throw buildConflictError("image", name, `image name ${name} is held by an alias; remove the alias first`);
53658
+ }
53659
+ }
53660
+
53604
53661
  // packages/daemon/src/imps/images/rootfs/remove-unused-rootfs.ts
53605
53662
  async function removeUnusedRootfs(db, storage, digest) {
53606
53663
  if (await countImageDigestUses(db, digest) === 0) {
@@ -53619,7 +53676,7 @@ function writeImageRow(db, existing, image, at) {
53619
53676
  // packages/daemon/src/imps/images/template-service.ts
53620
53677
  var TEMPLATE_DIGEST_PREFIX = "imp-";
53621
53678
  function createTemplateService(deps) {
53622
- const clock = deps.clock ?? REAL_CLOCK;
53679
+ const clock = deps.clock ?? systemClock7;
53623
53680
  const storage = deps.storage;
53624
53681
  const withConsistentDisk = createConsistentDisk({
53625
53682
  storage,
@@ -53638,6 +53695,7 @@ function createTemplateService(deps) {
53638
53695
  };
53639
53696
  const writeTemplate = async (impName, name) => {
53640
53697
  requireClientImageName(name);
53698
+ await requireUnaliasedName(deps.db, name);
53641
53699
  await deps.diskBudget.requireRoom(0);
53642
53700
  return deps.storageGate.join(() => deps.imps.lockImp(impName, async (imp) => {
53643
53701
  if (imp.state === "creating") {
@@ -53948,6 +54006,7 @@ function createImpdServices(config, deps, parts) {
53948
54006
  config,
53949
54007
  db,
53950
54008
  imps: parts.imps,
54009
+ images: parts.storage.images,
53951
54010
  storage,
53952
54011
  diskBudget: parts.storage.diskBudget,
53953
54012
  ...freezer
@@ -53974,6 +54033,61 @@ function createImpdServices(config, deps, parts) {
53974
54033
  return { checkpoints, templates, networks, gc, audit };
53975
54034
  }
53976
54035
 
54036
+ // packages/daemon/src/imps/images/image-service.ts
54037
+ import { systemClock as systemClock8 } from "@zgeoff/std";
54038
+
54039
+ // packages/daemon/src/platform/db/is-foreign-key-error.ts
54040
+ function isForeignKeyError(error) {
54041
+ return typeof error === "object" && error !== null && "code" in error && error.code === "SQLITE_CONSTRAINT_FOREIGNKEY";
54042
+ }
54043
+
54044
+ // packages/daemon/src/platform/db/list-image-aliases.ts
54045
+ async function listImageAliases(db, imageIds) {
54046
+ const aliases = new Map;
54047
+ if (imageIds.length === 0) {
54048
+ return aliases;
54049
+ }
54050
+ const rows = await db.selectFrom("image_aliases").select(["name", "image_id"]).where("image_id", "in", imageIds).orderBy("name").execute();
54051
+ for (const row of rows) {
54052
+ aliases.set(row.image_id, [...aliases.get(row.image_id) ?? [], row.name]);
54053
+ }
54054
+ return aliases;
54055
+ }
54056
+
54057
+ // packages/daemon/src/platform/db/read-image-by-alias.ts
54058
+ async function readImageByAlias(db, alias) {
54059
+ const row = await db.selectFrom("images").selectAll("images").innerJoin("image_aliases", "image_aliases.image_id", "images.id").where("image_aliases.name", "=", alias).executeTakeFirst();
54060
+ return row === undefined ? undefined : toImageRecord(row);
54061
+ }
54062
+
54063
+ // packages/daemon/src/platform/db/remove-image-alias.ts
54064
+ async function removeImageAlias(db, alias) {
54065
+ const row = await db.deleteFrom("image_aliases").where("name", "=", alias).returning("name").executeTakeFirst();
54066
+ return row !== undefined;
54067
+ }
54068
+
54069
+ // packages/daemon/src/platform/db/update-aliased-image-use.ts
54070
+ async function updateAliasedImageUse(db, alias, atMs) {
54071
+ const row = await db.updateTable("images").set((eb) => ({ last_used_at: eb.fn("max", ["last_used_at", eb.val(atMs)]) })).where("id", "=", (eb) => eb.selectFrom("image_aliases").select("image_aliases.image_id").where("name", "=", alias)).returningAll().executeTakeFirst();
54072
+ return row === undefined ? undefined : toImageRecord(row);
54073
+ }
54074
+
54075
+ // packages/daemon/src/platform/db/update-image-alias.ts
54076
+ function updateImageAlias(db, alias, imageName, atMs) {
54077
+ return db.transaction().execute(async (trx) => {
54078
+ const written = await trx.insertInto("image_aliases").columns(["name", "image_id", "updated_at"]).expression((eb) => eb.selectFrom("images").select([
54079
+ eb.val(alias).as("name"),
54080
+ "images.id as image_id",
54081
+ eb.val(atMs).as("updated_at")
54082
+ ]).where("images.name", "=", imageName).where((inner) => inner.not(inner.exists(inner.selectFrom("images as taken").select("taken.id").where("taken.name", "=", alias))))).onConflict((conflict) => conflict.column("name").doUpdateSet((eb) => ({
54083
+ image_id: eb.ref("excluded.image_id"),
54084
+ updated_at: eb.ref("excluded.updated_at")
54085
+ }))).returning("image_id").executeTakeFirst();
54086
+ const row = written === undefined ? undefined : await trx.selectFrom("images").selectAll().where("id", "=", written.image_id).executeTakeFirst();
54087
+ return row === undefined ? undefined : toImageRecord(row);
54088
+ });
54089
+ }
54090
+
53977
54091
  // packages/daemon/src/imps/images/build/create-image-builds.ts
53978
54092
  import { existsSync as existsSync30, mkdirSync as mkdirSync27, rmSync as rmSync31, statSync as statSync17 } from "fs";
53979
54093
  import { join as join44, posix as posix3 } from "path";
@@ -55658,6 +55772,7 @@ function createImageBuilds(deps, writer) {
55658
55772
  const createFromContext = async (tarPath, name, givenDockerfile, options) => {
55659
55773
  const signal = options.signal;
55660
55774
  const imageName = requireClientImageName(name);
55775
+ await requireUnaliasedName(deps.db, imageName);
55661
55776
  const tag = `imp/${imageName}:latest`;
55662
55777
  const tarBytes = statSync17(tarPath).size;
55663
55778
  const dockerfilePath = normalizeDockerfilePath(givenDockerfile);
@@ -55740,6 +55855,7 @@ function createImageBuilds(deps, writer) {
55740
55855
  }
55741
55856
  };
55742
55857
  const createOnHost = async (contextDir, name, dockerfile, options) => {
55858
+ await requireUnaliasedName(deps.db, requireClientImageName(name));
55743
55859
  if (!contextDir.startsWith("/")) {
55744
55860
  throw new ImpdError("BAD_REQUEST", {
55745
55861
  message: `build context ${JSON.stringify(contextDir)} is not an absolute path`
@@ -56230,6 +56346,7 @@ function createImageAdds(deps, writer) {
56230
56346
  }
56231
56347
  const givenName = name ?? deriveImageName(ref);
56232
56348
  const imageName = isImpds ? NameSchema.parse(givenName) : requireClientImageName(givenName);
56349
+ await requireUnaliasedName(deps.db, imageName);
56233
56350
  const taken = await readImageByName(deps.db, imageName);
56234
56351
  requireDockerImage(taken);
56235
56352
  return createImageInBuilder(ref, imageName, options);
@@ -56259,6 +56376,7 @@ function createImageAdds(deps, writer) {
56259
56376
  if (image?.ref === ref) {
56260
56377
  return;
56261
56378
  }
56379
+ await requireUnaliasedName(deps.db, BUILDER_IMAGE);
56262
56380
  await waitForPull(builderImage.run(BUILDER_IMAGE, () => createBuilderImage(ref)), signal);
56263
56381
  };
56264
56382
  return {
@@ -56348,7 +56466,7 @@ function pickEvictedImages(state, marks) {
56348
56466
  }
56349
56467
  var RECENT_USE_MS = 3600000;
56350
56468
  function isEvictable(state, use) {
56351
- return use.impCount === 0 && !use.isPinned && !state.keptNames.has(use.name) && state.now - use.lastUsedAt >= RECENT_USE_MS;
56469
+ return use.impCount === 0 && !use.isPinned && !use.isAliased && !state.keptNames.has(use.name) && state.now - use.lastUsedAt >= RECENT_USE_MS;
56352
56470
  }
56353
56471
 
56354
56472
  // packages/daemon/src/imps/images/eviction/create-image-eviction.ts
@@ -56440,7 +56558,7 @@ function createImageEviction(deps) {
56440
56558
 
56441
56559
  // packages/daemon/src/imps/images/image-service.ts
56442
56560
  function createImageService(deps) {
56443
- const clock = deps.clock ?? REAL_CLOCK;
56561
+ const clock = deps.clock ?? systemClock8;
56444
56562
  const writer = createImageWriter({
56445
56563
  ...deps,
56446
56564
  clock
@@ -56476,17 +56594,42 @@ function createImageService(deps) {
56476
56594
  if (image !== undefined) {
56477
56595
  return image;
56478
56596
  }
56597
+ const aliased = await readImageByAlias(deps.db, name);
56598
+ if (aliased !== undefined) {
56599
+ return aliased;
56600
+ }
56479
56601
  }
56480
56602
  return;
56481
56603
  };
56604
+ const resolveImageName = async (name) => {
56605
+ await updateImageUse(deps.db, "name", [name], clock.now());
56606
+ const image = await readImageByName(deps.db, name);
56607
+ return image ?? updateAliasedImageUse(deps.db, name, clock.now());
56608
+ };
56482
56609
  const resolveImage = async (name) => {
56483
56610
  const names = name === undefined ? [deps.config.defaultImage, FALLBACK_DEFAULT_IMAGE] : [name];
56484
- await updateImageUse(deps.db, "name", names, clock.now());
56485
- const image = name === undefined ? await readDefaultImage() : await readImageByName(deps.db, name);
56486
- if (image === undefined) {
56487
- throw buildNotFoundError("image", name ?? deps.config.defaultImage);
56611
+ for (const candidate of names) {
56612
+ const image = await resolveImageName(candidate);
56613
+ if (image !== undefined) {
56614
+ return image;
56615
+ }
56616
+ }
56617
+ throw buildNotFoundError("image", name ?? deps.config.defaultImage);
56618
+ };
56619
+ const requireUnusedImage = async (image) => {
56620
+ const users = await countImpsUsingImage(deps.db, image.id);
56621
+ const found = await listImageAliases(deps.db, [image.id]);
56622
+ const aliases = found.get(image.id) ?? [];
56623
+ const reasons = [];
56624
+ if (users > 0) {
56625
+ reasons.push(`used by ${String(users)} imp(s)`);
56626
+ }
56627
+ if (aliases.length > 0) {
56628
+ reasons.push(`pointed at by alias ${aliases.join(", ")}; remove ${aliases.length === 1 ? "it" : "them"} with image unalias first`);
56629
+ }
56630
+ if (reasons.length > 0) {
56631
+ throw buildConflictError("image", image.name, `image ${image.name} is ${reasons.join(" and ")}`);
56488
56632
  }
56489
- return image;
56490
56633
  };
56491
56634
  return {
56492
56635
  ...adds,
@@ -56501,12 +56644,15 @@ function createImageService(deps) {
56501
56644
  if (image === undefined) {
56502
56645
  throw buildNotFoundError("image", name);
56503
56646
  }
56504
- const users = await countImpsUsingImage(deps.db, image.id);
56505
- if (users > 0) {
56506
- throw buildConflictError("image", name, `image ${name} is used by ${String(users)} imp(s)`);
56507
- }
56647
+ await requireUnusedImage(image);
56508
56648
  await deps.storageGate.join(async () => {
56509
- await removeImage(deps.db, image.id);
56649
+ await removeImage(deps.db, image.id).catch(async (error) => {
56650
+ if (!isForeignKeyError(error)) {
56651
+ throw error;
56652
+ }
56653
+ await requireUnusedImage(image);
56654
+ throw buildConflictError("image", name, `image ${name} is in use again; check its imps and aliases, then retry`);
56655
+ });
56510
56656
  const isRemoved = await writer.removeIdleRootfs(image.digest);
56511
56657
  if (isRemoved) {
56512
56658
  await removeImageRemoval(deps.db, image.digest);
@@ -56525,9 +56671,27 @@ function createImageService(deps) {
56525
56671
  throw buildNotFoundError("image", name);
56526
56672
  },
56527
56673
  resolveImage,
56674
+ updateImageAlias: async (alias, imageName) => {
56675
+ const image = await updateImageAlias(deps.db, alias, imageName, clock.now());
56676
+ if (image !== undefined) {
56677
+ return image;
56678
+ }
56679
+ const target = await readImageByName(deps.db, imageName);
56680
+ if (target === undefined) {
56681
+ throw buildNotFoundError("image", imageName);
56682
+ }
56683
+ throw buildConflictError("image", alias, `alias ${alias} is the name of an image; pick another alias`);
56684
+ },
56685
+ removeImageAlias: async (alias) => {
56686
+ if (!await removeImageAlias(deps.db, alias)) {
56687
+ throw buildNotFoundError("image alias", alias);
56688
+ }
56689
+ },
56690
+ listImageAliases: (imageIds) => listImageAliases(deps.db, imageIds),
56528
56691
  findDefaultImage: readDefaultImage,
56529
56692
  runImageEviction: runEviction,
56530
- withImagePublisher: writer.withPublisher
56693
+ withImagePublisher: writer.withPublisher,
56694
+ removeIdleRootfs: writer.removeIdleRootfs
56531
56695
  };
56532
56696
  }
56533
56697
 
@@ -60181,6 +60345,7 @@ async function startImpdParts(config, boundaries, plan) {
60181
60345
  config,
60182
60346
  db,
60183
60347
  imps: { ...imps, ...deps.agent },
60348
+ images: stored.images,
60184
60349
  ensureImage: stored.images.ensureBuilderImage,
60185
60350
  testRegistry: firewall.testRegistry
60186
60351
  });
@@ -60366,8 +60531,7 @@ async function startImpdParts(config, boundaries, plan) {
60366
60531
  async function setupDefaultImage(config, images) {
60367
60532
  try {
60368
60533
  await images.addDefaultImage();
60369
- const existing = await images.listImages();
60370
- if (!existing.some((image) => image.name === config.defaultImage)) {
60534
+ if (!await probeDefaultImageName(config, images)) {
60371
60535
  getImpdLogger("image").warning("no image named {defaultImage} (IMP_DEFAULT_IMAGE); impz new uses ubuntu until `impz image add <ref> --name {defaultImage}` adds it", { defaultImage: config.defaultImage });
60372
60536
  }
60373
60537
  } catch (error) {
@@ -60376,136 +60540,44 @@ async function setupDefaultImage(config, images) {
60376
60540
  });
60377
60541
  }
60378
60542
  }
60379
-
60380
- // packages/shared/src/test-utils/claim-free-ports.ts
60381
- import { onTestFinished } from "bun:test";
60382
- import { randomInt } from "crypto";
60383
- import { existsSync as existsSync33, readFileSync as readFileSync39 } from "fs";
60384
- var PICK_SPAN = 4000;
60385
- function claimFreePorts(count, options = {}) {
60386
- const top = readEphemeralStart();
60387
- const pick = options.pick ?? (() => randomInt(top - PICK_SPAN, top));
60388
- const claims = [];
60389
- const ports = [];
60390
- const onRelease = options.onRelease ?? onTestFinished;
60391
- onRelease(() => {
60392
- for (const claim of claims) {
60393
- claim.stop(true);
60394
- }
60395
- });
60396
- while (ports.length < count) {
60397
- const port = pick();
60398
- const claim = claimPort(port);
60399
- if (claim === null) {
60400
- continue;
60401
- }
60402
- claims.push(claim);
60403
- if (!readBusyPorts().has(port)) {
60404
- ports.push(port);
60405
- }
60406
- }
60407
- return {
60408
- take: () => {
60409
- const port = ports.shift();
60410
- if (port === undefined) {
60411
- throw new Error(`only ${String(count)} free ports were asked for`);
60412
- }
60413
- return port;
60414
- }
60415
- };
60416
- }
60417
- function readEphemeralStart() {
60418
- const range = readFileSync39("/proc/sys/net/ipv4/ip_local_port_range", "utf8");
60419
- return Number(range.trim().split(/\s+/u)[0]);
60420
- }
60421
- function claimPort(port) {
60422
- try {
60423
- return Bun.listen({ unix: `\x00imp-test-port-${String(port)}`, socket: { data: () => {} } });
60424
- } catch {
60425
- return null;
60543
+ async function probeDefaultImageName(config, images) {
60544
+ const found = await images.findDefaultImage();
60545
+ if (found === undefined) {
60546
+ return false;
60426
60547
  }
60427
- }
60428
- var SOCKET_TABLES = ["tcp", "tcp6", "udp", "udp6"].map((name) => `/proc/net/${name}`);
60429
- function readBusyPorts() {
60430
- const busy = new Set;
60431
- for (const table of SOCKET_TABLES.filter((path) => existsSync33(path))) {
60432
- const lines = readFileSync39(table, "utf8").trim().split(`
60433
- `);
60434
- for (const line of lines.slice(1)) {
60435
- const local = line.trim().split(/\s+/u)[1] ?? "";
60436
- const hexPort = local.slice(local.lastIndexOf(":") + 1);
60437
- busy.add(Number.parseInt(hexPort, 16));
60438
- }
60548
+ if (found.name === config.defaultImage) {
60549
+ return true;
60439
60550
  }
60440
- return busy;
60551
+ const aliases = await images.listImageAliases([found.id]);
60552
+ return aliases.get(found.id)?.includes(config.defaultImage) ?? false;
60441
60553
  }
60442
60554
 
60443
60555
  // packages/testing/src/stand-in/start-test-impd.ts
60444
60556
  import { createORPCClient as createORPCClient2 } from "@orpc/client";
60445
60557
  import { RPCLink } from "@orpc/client/fetch";
60558
+ import { createFakeClock } from "@zgeoff/testing/clock";
60559
+ import { claimFreePorts } from "@zgeoff/testing/process";
60446
60560
  import invariant16 from "tiny-invariant";
60447
60561
 
60448
60562
  // packages/testing/src/test-token.ts
60449
60563
  var TEST_TOKEN = "test-token";
60450
60564
 
60565
+ // packages/testing/src/stand-in/build-imps-with-resolved-images.ts
60566
+ function buildImpsWithResolvedImages(imps, images) {
60567
+ return {
60568
+ ...imps,
60569
+ createImp: async (input) => {
60570
+ const image = typeof input.image === "object" ? input.image : await images.resolveImage(input.image);
60571
+ return imps.createImp({ ...input, image });
60572
+ }
60573
+ };
60574
+ }
60575
+
60451
60576
  // packages/testing/src/stand-in/network/read-no-tailscale.ts
60452
60577
  function readNoTailscale() {
60453
60578
  return Promise.resolve({ state: null, hostname: null, dnsName: null, ip: null, ips: [] });
60454
60579
  }
60455
60580
 
60456
- // packages/testing/src/stand-in/platform/build-stub-clock.ts
60457
- function buildStubClock(options = {}) {
60458
- const state = { nowMs: options.startMs ?? 0, nextId: 0 };
60459
- const pending = new Map;
60460
- const delays = [];
60461
- const sleeps = [];
60462
- const runFor = (durationMs) => {
60463
- const until = state.nowMs + durationMs;
60464
- for (;; ) {
60465
- const [due] = [...pending].filter(([, timer]) => timer.at <= until).toSorted(([, left], [, right]) => left.at - right.at);
60466
- if (due === undefined) {
60467
- break;
60468
- }
60469
- const [id, timer] = due;
60470
- pending.delete(id);
60471
- state.nowMs = Math.max(state.nowMs, timer.at);
60472
- timer.fire();
60473
- }
60474
- state.nowMs = until;
60475
- };
60476
- const startTimer = (fire, durationMs) => {
60477
- state.nextId += 1;
60478
- const id = state.nextId;
60479
- delays.push(durationMs);
60480
- pending.set(id, { at: state.nowMs + durationMs, durationMs, fire });
60481
- return () => {
60482
- pending.delete(id);
60483
- };
60484
- };
60485
- const sleep = (durationMs) => {
60486
- sleeps.push(durationMs);
60487
- runFor(durationMs);
60488
- return Promise.resolve();
60489
- };
60490
- const clock = { now: () => state.nowMs, startTimer, sleep };
60491
- return {
60492
- ...clock,
60493
- delays,
60494
- sleeps,
60495
- runFor,
60496
- firePending: () => {
60497
- const pendingNow = [...pending];
60498
- for (const [id, timer] of pendingNow) {
60499
- if (pending.delete(id)) {
60500
- timer.fire();
60501
- }
60502
- }
60503
- },
60504
- readPendingMs: () => [...pending.values()].map((timer) => timer.durationMs),
60505
- countPending: () => pending.size
60506
- };
60507
- }
60508
-
60509
60581
  // packages/testing/src/stand-in/platform/build-stub-ticker-timer.ts
60510
60582
  function buildStubTickerTimer() {
60511
60583
  const pending = new Map;
@@ -60552,13 +60624,6 @@ async function serializeMigratedDatabase() {
60552
60624
  return bytes;
60553
60625
  }
60554
60626
 
60555
- // packages/testing/src/stand-in/platform/pick-impd-port.ts
60556
- var FIRST_PORT = 10100;
60557
- var PORT_SPAN = 9900;
60558
- function pickImpdPort(draw) {
60559
- return FIRST_PORT + Math.floor(draw * PORT_SPAN);
60560
- }
60561
-
60562
60627
  // packages/testing/src/stand-in/platform/read-run-owner.ts
60563
60628
  import { readlinkSync as readlinkSync2 } from "fs";
60564
60629
  function readRunOwner() {
@@ -60618,7 +60683,7 @@ function startImpdLogCapture(onLine) {
60618
60683
  }
60619
60684
 
60620
60685
  // packages/testing/src/stand-in/vm/build-stub-vmm.ts
60621
- import { existsSync as existsSync34, mkdirSync as mkdirSync31, renameSync as renameSync9, writeFileSync as writeFileSync16 } from "fs";
60686
+ import { existsSync as existsSync33, mkdirSync as mkdirSync31, renameSync as renameSync9, writeFileSync as writeFileSync16 } from "fs";
60622
60687
  var STUB_AGENT_VERSION = "0.1.0";
60623
60688
  var IMPD_OWNER = { uid: process.getuid?.() ?? 0, cgroup: null };
60624
60689
 
@@ -60768,7 +60833,7 @@ log tail`);
60768
60833
  }),
60769
60834
  wakeVm: (plan) => runInGeneration(async () => {
60770
60835
  const files = [plan.paths.disk, plan.paths.vmstate, plan.paths.memFile];
60771
- wakeJails.push({ jail: plan.jail, files: files.filter((file) => existsSync34(file)) });
60836
+ wakeJails.push({ jail: plan.jail, files: files.filter((file) => existsSync33(file)) });
60772
60837
  wakePlans.push(plan);
60773
60838
  const drive = readLoadingMeta(plan.paths)?.systemDrivePath;
60774
60839
  if (plan.jail !== null && drive !== undefined && !plan.readOnlyFiles.includes(drive)) {
@@ -61022,7 +61087,7 @@ log tail`);
61022
61087
  }
61023
61088
 
61024
61089
  // packages/testing/src/stand-in/vm/create-stub-uffd-handler.ts
61025
- import { existsSync as existsSync35, readFileSync as readFileSync40, writeFileSync as writeFileSync17 } from "fs";
61090
+ import { existsSync as existsSync34, readFileSync as readFileSync39, writeFileSync as writeFileSync17 } from "fs";
61026
61091
  import { join as join50 } from "path";
61027
61092
  import * as z105 from "zod";
61028
61093
  var StartSchema = z105.object({
@@ -61056,7 +61121,7 @@ exec '${process.execPath}' '${script}' '${mode}' '${recorded}' '${warmAnswer}' "
61056
61121
  };
61057
61122
  }
61058
61123
  function readRecords(path, schema) {
61059
- return existsSync35(path) ? readFileSync40(path, "utf8").trimEnd().split(`
61124
+ return existsSync34(path) ? readFileSync39(path, "utf8").trimEnd().split(`
61060
61125
  `).map((line) => schema.parse(JSON.parse(line))) : [];
61061
61126
  }
61062
61127
 
@@ -61089,10 +61154,8 @@ async function startTestImpd(stack, options = {}) {
61089
61154
  await db.destroy();
61090
61155
  options.onLog?.("test harness: database closed");
61091
61156
  });
61092
- const ports = claimFreePorts(3, {
61093
- pick: () => pickImpdPort(Math.random()),
61094
- onRelease: stack.defer.bind(stack)
61095
- });
61157
+ const ports = claimFreePorts(3, { cleanup: "manual" });
61158
+ stack.defer(ports.release);
61096
61159
  const config = {
61097
61160
  ...loadConfig({
61098
61161
  IMP_DATA_DIR: dataDir,
@@ -61102,6 +61165,7 @@ async function startTestImpd(stack, options = {}) {
61102
61165
  IMP_BROKER_PORT: String(ports.take()),
61103
61166
  IMP_EGRESS_DNS_PORT: String(ports.take()),
61104
61167
  IMP_SSH_PORT: "0",
61168
+ IMP_PORT_BASE: "40000",
61105
61169
  IMP_UFFD_HANDLER: uffdHandler.path,
61106
61170
  ...options.env
61107
61171
  }),
@@ -61109,7 +61173,7 @@ async function startTestImpd(stack, options = {}) {
61109
61173
  };
61110
61174
  const fake = buildStubVmm();
61111
61175
  const tickers = buildStubTickerTimer();
61112
- const reconcilerTimers = buildStubClock();
61176
+ const reconcilerTimers = createFakeClock();
61113
61177
  const taps = [];
61114
61178
  const removedTaps = [];
61115
61179
  const logs = [];
@@ -61164,7 +61228,7 @@ async function startTestImpd(stack, options = {}) {
61164
61228
  logRpcFailure: printRpcFailure,
61165
61229
  now: readClock,
61166
61230
  readTailscale: extra.readTailscale ?? readNoTailscale,
61167
- readDiskSpace: () => Promise.resolve({ ...diskUsage }),
61231
+ readDiskSpace: extra.readDiskSpace ?? (() => Promise.resolve({ ...diskUsage })),
61168
61232
  resolveIpv6: () => Promise.resolve(options.ipv6 ?? null),
61169
61233
  readIdentity: () => identity,
61170
61234
  cgroups,
@@ -61177,7 +61241,7 @@ async function startTestImpd(stack, options = {}) {
61177
61241
  hostKernelRelease: extra.hostKernelRelease ?? KSM_KERNEL,
61178
61242
  readKsmHostStats: options.readKsmHostStats ?? (() => IDLE_KSM),
61179
61243
  tickerTimer: tickers.timer,
61180
- reconcilerTimer: reconcilerTimers.startTimer,
61244
+ reconcilerTimer: reconcilerTimers.schedule,
61181
61245
  proxyPorts: extra.proxyPorts ?? { proxy: 0, slot: () => 0 },
61182
61246
  apiHostname: "127.0.0.1",
61183
61247
  images: { seedRef: null, ...extra.images },
@@ -61292,6 +61356,15 @@ async function startTestImpd(stack, options = {}) {
61292
61356
  return impd;
61293
61357
  };
61294
61358
  const current = { impd: await startImpd(host.identity, fake.startGeneration()) };
61359
+ const seededImpds = new WeakMap;
61360
+ const buildImpdWithResolvedImages = (impd) => {
61361
+ const seeded = seededImpds.get(impd) ?? {
61362
+ ...impd,
61363
+ imps: buildImpsWithResolvedImages(impd.imps, impd.images)
61364
+ };
61365
+ seededImpds.set(impd, seeded);
61366
+ return seeded;
61367
+ };
61295
61368
  const sendRequest = (request) => current.impd.api.app.handle(request);
61296
61369
  const buildClient = (token) => createORPCClient2(new RPCLink({
61297
61370
  url: "http://impd.test/rpc",
@@ -61330,7 +61403,7 @@ async function startTestImpd(stack, options = {}) {
61330
61403
  now: readClock,
61331
61404
  advance: (durationMs) => {
61332
61405
  clock.offsetMs += durationMs;
61333
- reconcilerTimers.runFor(durationMs);
61406
+ reconcilerTimers.advance(durationMs);
61334
61407
  },
61335
61408
  setClock: (nowMs) => {
61336
61409
  invariant16(options.frozenClockMs !== undefined, "setClock needs a frozen clock");
@@ -61347,10 +61420,10 @@ async function startTestImpd(stack, options = {}) {
61347
61420
  return `http://127.0.0.1:${String(current.impd.app.server?.port)}`;
61348
61421
  },
61349
61422
  get impd() {
61350
- return current.impd;
61423
+ return buildImpdWithResolvedImages(current.impd);
61351
61424
  },
61352
61425
  get imps() {
61353
- return current.impd.imps;
61426
+ return buildImpdWithResolvedImages(current.impd).imps;
61354
61427
  },
61355
61428
  get governor() {
61356
61429
  return current.impd.governor;
@@ -61396,7 +61469,7 @@ async function startTestImpd(stack, options = {}) {
61396
61469
  await stopImpd(current.impd);
61397
61470
  host.identity = identity;
61398
61471
  current.impd = await startImpd(identity, runner);
61399
- return current.impd;
61472
+ return buildImpdWithResolvedImages(current.impd);
61400
61473
  }
61401
61474
  };
61402
61475
  }
@@ -61898,7 +61971,7 @@ import { randomBytes as randomBytes12 } from "crypto";
61898
61971
  import { Duplex } from "stream";
61899
61972
 
61900
61973
  // packages/testing/src/stand-in/vm/start-stub-agent.ts
61901
- import { onTestFinished as onTestFinished2 } from "bun:test";
61974
+ import { onTestFinished } from "bun:test";
61902
61975
  import { mkdirSync as mkdirSync33 } from "fs";
61903
61976
  import { createServer as createServer4 } from "net";
61904
61977
  import { dirname as dirname16 } from "path";
@@ -61939,7 +62012,7 @@ async function startStubAgent(path, agent, options = {}) {
61939
62012
  server.close();
61940
62013
  };
61941
62014
  if (options.stack === undefined) {
61942
- onTestFinished2(stopServer);
62015
+ onTestFinished(stopServer);
61943
62016
  } else {
61944
62017
  options.stack.defer(stopServer);
61945
62018
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@impz/testing",
3
- "version": "7.7.0",
3
+ "version": "7.8.1",
4
4
  "description": "A real impd on stand-ins, for Bun tests of code that drives impd through @impz/client",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -34,6 +34,7 @@
34
34
  "@zgeoff/kysely-bun-sqlite": "^0.3.3",
35
35
  "@zgeoff/mcp-auth": "^0.3.0",
36
36
  "@zgeoff/std": "^0.4.5",
37
+ "@zgeoff/testing": "^0.4.1",
37
38
  "dns-packet": "^5.6.1",
38
39
  "elysia": "^2.0.0-rc.3",
39
40
  "ipaddr.js": "^2.5.0",
@@ -46,7 +47,7 @@
46
47
  "ts-pattern": "^5.9.2",
47
48
  "xstate": "^5.33.3",
48
49
  "zod": "^4.6.7",
49
- "@impz/client": "7.7.0"
50
+ "@impz/client": "7.8.1"
50
51
  },
51
52
  "engines": {
52
53
  "bun": ">=1.4.3"