From bf9ee4037bb22628ad7f470bca7c551a8f6e65e2 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 8 Oct 2026 21:44:17 -0500 Subject: [PATCH] feat(start): give each instance its own Docker resource namespace and base URL (#31) --- AGENTS.md | 4 +- README.md | 28 ++++++- .../java/io/floci/cli/ProductProfile.java | 15 ++++ .../io/floci/cli/commands/RestartCommand.java | 5 ++ .../io/floci/cli/commands/StartCommand.java | 53 ++++++++++++ .../commands/config/ConfigProfileCommand.java | 29 +++++-- .../commands/config/ConfigShowCommand.java | 4 + .../java/io/floci/cli/config/Profile.java | 1 + .../io/floci/cli/config/ProfileDefaults.java | 1 + .../io/floci/cli/unit/ConfigCommandsTest.java | 51 +++++++++++ .../io/floci/cli/unit/ProductProfileTest.java | 12 +++ .../floci/cli/unit/ProfileDefaultsTest.java | 3 + .../io/floci/cli/unit/RestartCommandTest.java | 28 +++++++ .../floci/cli/unit/StartCommandArgsTest.java | 84 +++++++++++++++++++ 14 files changed, 310 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 669b85f..aea0aad 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -124,7 +124,9 @@ An instance is a profile: its container name is its identity, its port is the on - Local state about one running instance (certificates, generated vendor-CLI config) lives under `InstanceState.dir(product, container)`, which is `~/.floci///`. Never a fixed per-product path: a second instance would overwrite the first. `floci az setup` is the reference (its az cloud is also named after the container). - Hints that tell the user to re-run a command append `global.instanceSelector()` so they select the same instance again. - Instance-independent state (the OCI CLI profile from `floci oci setup`) may stay shared. -- `config profile create` takes `--container --port --persist --services --image` (and `--endpoint`); it reads only flags the user typed (`ParseResult.hasMatchedOption`), never values the profile provider or `FLOCI_*` env vars applied. +- `StartCommand.resourceNamespace()` passes the emulator's `_DOCKER_RESOURCE_NAMESPACE`: explicit `--namespace`/profile `namespace` (verbatim), else `ProductProfile.resourceNamespace(container)`: nothing for the default container, otherwise the container name minus the `-` prefix (the emulator adds `floci--` itself, so keeping it would stutter). It scopes the child containers each emulator launches and its orphan sweeps; never derive one for the default container (it would rename existing users' child containers). +- On a non-default `--port`, `start` also passes `_BASE_URL`, the endpoint with that port (`http://localhost:` by default): every emulator builds returned URLs (SQS `QueueUrl`, OCI invoke endpoint) from it, and its default names the product port. +- `config profile create` takes `--container --port --persist --services --image --namespace` (and `--endpoint`); it reads only flags the user typed (`ParseResult.hasMatchedOption`), never values the profile provider or `FLOCI_*` env vars applied. ### Self-update diff --git a/README.md b/README.md index 4dc9cca..73b3b18 100644 --- a/README.md +++ b/README.md @@ -345,21 +345,38 @@ floci start --services s3,dynamodb # enable specific services floci start --persist ./data # persist state to a host directory floci start --pull always # always pull the latest image floci start --detach # return immediately, don't wait +floci start --namespace team-b # scope the containers it launches (see below) # GCP floci gcp start # default port 4588 floci gcp start --persist ./data # persist state to a host directory +floci gcp start --namespace team-b # scope the containers it launches # Azure floci az start # default port 4577 floci az start --port 4578 # custom host port floci az start --persist ./data # persist state to a host directory +floci az start --namespace team-b # scope the containers it launches # OCI floci oci start # default port 4599 floci oci start --persist ./data # persist state to a host directory +floci oci start --namespace team-b # scope the containers it launches ``` +`--namespace` sets the emulator's Docker resource namespace (`FLOCI_DOCKER_RESOURCE_NAMESPACE`, +`FLOCI_GCP_…`, `FLOCI_AZ_…`, `FLOCI_OCI_…`). The emulator puts it in the names and the +`floci_namespace` label of the containers and volumes it launches (Lambda, ECS, RDS, Cloud Run, +Service Bus, ...) and only cleans up leftovers in its own namespace. When `--container` is not the +product default, the namespace is derived from it, without the default-container prefix the +emulator already adds (`floci-gcp-b` → `b`, so children are `floci-gcp-b-…`; `team-b` stays +`team-b`). The default container gets none. + +On a `--port` other than the product default, `start` also sets the emulator's base URL +(`FLOCI_BASE_URL`, `FLOCI_GCP_BASE_URL`, ...) to the endpoint with that port (`http://localhost:` +unless `--endpoint` names another host), so URLs it returns +(SQS `QueueUrl`, presigned URLs, the OCI functions invoke endpoint) point at that instance. + #### Docker daemon resolution (Podman, rootless, remote contexts) The Floci container needs access to a Docker-compatible daemon (for Lambda, EC2, @@ -632,7 +649,7 @@ floci config show # show active configuration floci config default-product aws|gcp|az|oci # set the default product (persisted to ~/.floci/config.yaml) floci config profile list # list saved profiles: container, port, data dir floci config profile create # create a new profile with the tree's defaults -floci config profile create --container --port

--persist

--services --image +floci config profile create --container --port

--persist

--services --image --namespace floci config profile show # show a profile floci config profile delete # delete a profile floci config validate -f docker-compose.yml # validate a Compose file @@ -652,6 +669,7 @@ image: floci/floci:enforced port: 4599 persistDir: /tmp/floci-persist services: s3,lambda +namespace: team-probe output: json ``` @@ -667,6 +685,7 @@ have that flag: | `port` | `--port` | `start`, `restart` | | `persistDir` | `--persist` | `start`, `restart` | | `services` | `--services` | `start`, `restart` | +| `namespace` | `--namespace` | `start`, `restart` | Resolution order, highest first: @@ -697,9 +716,14 @@ container recreation. Every command (`status`, `logs`, `env`, `doctor`, `stop`, instance through its container, so passing the same `--profile` is all it takes. Any local state the CLI keeps about an instance lives in `~/.floci///`. +Each instance's emulator also gets its own Docker resource namespace, derived from the container +name unless the profile sets `namespace`. That keeps the containers each instance launches (Lambda functions, +ECS tasks, Cloud Run jobs, Service Bus sidecars, ...) apart, so starting one instance never +cleans up another's. `floci config show --profile ` prints the namespace it will use. + Leave `endpoint` at the product default: the CLI reads the real host port from the running container. `config profile create` warns when a new profile reuses another profile's container, -or its port on the same image. +or its port or resource namespace on the same image. ```sh # AWS diff --git a/src/main/java/io/floci/cli/ProductProfile.java b/src/main/java/io/floci/cli/ProductProfile.java index ec3c06b..9071412 100644 --- a/src/main/java/io/floci/cli/ProductProfile.java +++ b/src/main/java/io/floci/cli/ProductProfile.java @@ -36,6 +36,21 @@ public record ProductProfile( return "aws".equals(name) ? "floci" : "floci " + name; } + /** + * The Docker resource namespace an instance in {@code container} gets when none is set: none + * for the default container, so its child containers keep their names; otherwise the container + * name without the default-container prefix. The emulator already prefixes child names with + * {@code floci--}, so {@code floci-gcp-b} becomes {@code b}, not + * {@code floci-gcp-floci-gcp-b-...}. + */ + public String resourceNamespace(String container) { + if (container == null || container.equals(defaultContainer)) return null; + String prefix = defaultContainer + "-"; + return container.startsWith(prefix) && container.length() > prefix.length() + ? container.substring(prefix.length()) + : container; + } + /** GitHub repository of the product's emulator server, for issue-tracker hints. */ public String serverRepo() { return "https://github.com/floci-io/" + ("aws".equals(name) ? "floci" : "floci-" + name); diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index 2c1606d..77eaca3 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -45,6 +45,11 @@ public class RestartCommand implements Callable { // container stopped, and the values must not be re-read from a file that could change // during the stop plus the one second wait below. StartCommand start = buildStartCommand(); + String invalid = start.validationError(); + if (invalid != null) { + printer.error(invalid); + return 2; + } StopCommand stop = new StopCommand(profile); stop.global = global; diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 03829e0..d1b2078 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -16,6 +16,7 @@ import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import java.util.concurrent.Callable; +import java.util.regex.Pattern; @Command( name = "start", @@ -55,6 +56,12 @@ public class StartCommand implements Callable { @Option(names = {"--image"}, description = "Image reference to use (default: ${DEFAULT-VALUE})", paramLabel = "") String image; + @Option(names = {"--namespace"}, description = "Docker resource namespace for the containers this instance launches (default: derived from --container; none for the default container)", paramLabel = "") + String namespace; + + // Docker's own name rule: the emulators put the namespace inside child container names. + private static final Pattern NAMESPACE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]*"); + @Option(names = {"--pull"}, description = "Image pull policy: always, missing, never", defaultValue = "missing", paramLabel = "always|missing|never") String pull; @@ -96,6 +103,35 @@ public class StartCommand implements Callable { public String services() { return services; } + /** + * The resource namespace this instance passes to the emulator, which scopes the child + * containers and volumes it launches (Lambda, ECS, Cloud Run, Service Bus, ...) and its + * startup orphan sweeps. Without it two instances of one emulator remove each other's + * children. An explicit {@code --namespace} wins; otherwise it is derived from the container + * ({@link ProductProfile#resourceNamespace(String)}). + */ + /** + * Why these settings cannot start, or {@code null}. Checked before anything touches Docker, + * and by {@code restart} before it stops the running container, so a bad profile value never + * leaves an instance stopped. + */ + public String validationError() { + if (namespace != null && !namespace.isBlank() && !NAMESPACE.matcher(namespace).matches()) { + return "Invalid namespace '" + namespace + "'.\nUse letters, digits, '_', '.' and '-', starting with a letter or digit."; + } + return null; + } + + public String resourceNamespace() { + return resourceNamespaceFor(global.container); + } + + /** {@link #resourceNamespace()} for an instance in {@code container}, which a flag may have overridden. */ + public String resourceNamespaceFor(String container) { + if (namespace != null && !namespace.isBlank()) return namespace; + return profile.resourceNamespace(container); + } + /** * The {@code docker run} arguments this invocation would use. Extracted from {@link #call()} * as a test seam so the persistence mount can be pinned without starting a container; @@ -116,6 +152,17 @@ public class StartCommand implements Callable { if (services != null && !services.isBlank()) { args.addAll(List.of("-e", profile.envVar("SERVICES") + "=" + services)); } + // URLs the emulator hands back (SQS QueueUrl, presigned URLs, the OCI invoke endpoint) + // are built from its base URL, which defaults to localhost and the product port. On any + // other host port they would point at whichever instance owns the default one; the host + // comes from the endpoint, so a remote Docker host is named too. + if (port != profile.defaultPort()) { + args.addAll(List.of("-e", profile.envVar("BASE_URL") + "=" + withPort(global.endpoint, port))); + } + String ns = resourceNamespace(); + if (ns != null) { + args.addAll(List.of("-e", profile.envVar("DOCKER_RESOURCE_NAMESPACE") + "=" + ns)); + } new TreeMap<>(profile.startEnv()).forEach((suffix, value) -> args.addAll(List.of("-e", profile.envVar(suffix) + "=" + value))); args.add(image); @@ -138,6 +185,12 @@ public class StartCommand implements Callable { Printer printer = global.printer(); DockerClient docker = new DockerClient(); + String invalid = validationError(); + if (invalid != null) { + printer.error(invalid); + return 2; + } + // Verify docker is available if (!DockerClient.isInstalled()) { printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/"); diff --git a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java index 9f1cfec..a312fcd 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -68,6 +68,9 @@ public class ConfigProfileCommand implements Callable { @Option(names = {"--services"}, description = "create: comma-separated services to enable", paramLabel = "") String services; + @Option(names = {"--namespace"}, description = "create: Docker resource namespace for the containers this instance launches (default: derived from --container)", paramLabel = "") + String namespace; + @Spec CommandSpec spec; @@ -104,6 +107,7 @@ public class ConfigProfileCommand implements Callable { row.put("image", p.image); row.put("persistDir", p.persistDir); row.put("services", p.services); + row.put("namespace", p.namespace); out.add(row); } printer.structured(out); @@ -143,6 +147,7 @@ public class ConfigProfileCommand implements Callable { if (p.port != null) printer.println(" port: " + p.port); if (p.persistDir != null) printer.println(" persistDir: " + p.persistDir); if (p.services != null) printer.println(" services: " + p.services); + if (p.namespace != null) printer.println(" namespace: " + p.namespace); return 0; } catch (IOException e) { printer.error("Could not read profile: " + e.getMessage()); @@ -171,8 +176,9 @@ public class ConfigProfileCommand implements Callable { if (typed("--image")) p.image = image; if (typed("--persist")) p.persistDir = persistDir; if (typed("--services")) p.services = services; + if (typed("--namespace")) p.namespace = namespace; - for (String warning : collisions(store.list(), p)) { + for (String warning : collisions(profile, store.list(), p)) { printer.warn(warning); } store.save(p); @@ -191,25 +197,38 @@ public class ConfigProfileCommand implements Callable { /** * Two profiles that share a container are the same instance, and two that share a port on the - * same image cannot run at once. Both are legitimate (one instance, used at different times), + * same image cannot run at once. Two of one emulator that share a resource namespace remove + * each other's child containers. All are legitimate (one instance, used at different times), * so they are warnings, not errors. */ - static List collisions(List existing, Profile created) { + static List collisions(ProductProfile product, List existing, Profile created) { List warnings = new ArrayList<>(); for (Profile other : existing) { if (other.name == null || other.name.equals(created.name)) continue; if (created.container != null && created.container.equals(other.container)) { warnings.add("Profile '" + other.name + "' already uses container '" + created.container + "'.\n" + "Pick another --container, or start only one of them at a time."); - } else if (created.port != null && created.port.equals(other.port) - && repository(created.image).equals(repository(other.image))) { + continue; // one instance: its port and namespace are the same by definition + } + boolean sameEmulator = repository(created.image).equals(repository(other.image)); + if (sameEmulator && created.port != null && created.port.equals(other.port)) { warnings.add("Profile '" + other.name + "' already uses port " + created.port + ".\n" + "Pick another --port, or start only one of them at a time."); } + // Reported separately: a new port alone does not stop shared child containers. + String ns = sameEmulator ? namespaceOf(product, created) : null; + if (ns != null && ns.equals(namespaceOf(product, other))) { + warnings.add("Profile '" + other.name + "' already uses resource namespace '" + ns + "'.\n" + + "Pass --namespace to give this instance its own."); + } } return warnings; } + private static String namespaceOf(ProductProfile product, Profile p) { + return p.namespace != null && !p.namespace.isBlank() ? p.namespace : product.resourceNamespace(p.container); + } + // floci/floci-az:latest -> floci/floci-az, so two tags of one emulator still collide on a port. private static String repository(String image) { if (image == null) return ""; diff --git a/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java index f1f685e..400c1ed 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java @@ -94,6 +94,10 @@ public class ConfigShowCommand implements Callable { if (p.port != null) data.put("port", resolved.port()); if (p.persistDir != null) data.put("persistDir", resolved.persistDir()); if (p.services != null) data.put("services", resolved.services()); + // Effective, not declared: a profile with its own container gets a namespace unasked, and + // the container in effect (a --container flag beats the profile) is the one it comes from. + String namespace = resolved.resourceNamespaceFor(global.container); + if (namespace != null) data.put("namespace", namespace); } private static String label(String key) { diff --git a/src/main/java/io/floci/cli/config/Profile.java b/src/main/java/io/floci/cli/config/Profile.java index b0ed37b..6628b71 100644 --- a/src/main/java/io/floci/cli/config/Profile.java +++ b/src/main/java/io/floci/cli/config/Profile.java @@ -12,6 +12,7 @@ public class Profile { public Integer port; public String persistDir; public String services; + public String namespace; public String output; public Profile() {} diff --git a/src/main/java/io/floci/cli/config/ProfileDefaults.java b/src/main/java/io/floci/cli/config/ProfileDefaults.java index 8355111..db14452 100644 --- a/src/main/java/io/floci/cli/config/ProfileDefaults.java +++ b/src/main/java/io/floci/cli/config/ProfileDefaults.java @@ -27,6 +27,7 @@ public final class ProfileDefaults { case "--port" -> profile.port == null ? null : String.valueOf(profile.port); case "--persist" -> profile.persistDir; case "--services" -> profile.services; + case "--namespace" -> profile.namespace; case "--output" -> profile.output; default -> null; }; diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java index d505d0d..2170422 100644 --- a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -158,6 +158,38 @@ class ConfigCommandsTest { assertEquals(14578, b.port); assertEquals("floci-az", b.container); assertNull(b.persistDir); + assertNull(b.namespace); + } + + @Test + void createStoresATypedNamespace() throws Exception { + assertEquals(0, profileCmd(ProductProfile.GCP, "create", "ns", + "--container", "floci-gcp-b", "--namespace", "team-b").exit()); + + assertEquals("team-b", store().get("ns").orElseThrow().namespace); + } + + @Test + void showReportsTheNamespaceAProfilesContainerImplies() throws Exception { + writeProfile("b", "container: floci-b\n"); + writeProfile("plain", "port: 4599\n"); + + assertTrue(runShow(ProductProfile.AWS, "--profile", "b", "-o", "json") + .contains("\"namespace\" : \"b\"")); + assertFalse(runShow(ProductProfile.AWS, "--profile", "plain", "-o", "json") + .contains("namespace")); + } + + @Test + void createWarnsWhenTwoInstancesOfOneEmulatorWouldShareANamespace() throws Exception { + writeProfile("a", "container: floci-gcp-b\nport: 14588\nimage: floci/floci-gcp:latest\n"); + + Run same = profileCmd(ProductProfile.GCP, "create", "c", "--container", "b", "--port", "14589"); + assertTrue(same.err().contains("resource namespace 'b'"), same.err()); + + Run own = profileCmd(ProductProfile.GCP, "create", "d", "--container", "b", "--port", "14590", + "--namespace", "team-d"); + assertFalse(own.err().contains("resource namespace"), own.err()); } @Test @@ -184,6 +216,25 @@ class ConfigCommandsTest { assertFalse(otherProduct.err().contains("already uses"), otherProduct.err()); } + @Test + void showDerivesTheNamespaceFromTheContainerInEffect() throws Exception { + writeProfile("b", "container: floci-b\n"); + + String out = runShow(ProductProfile.AWS, "--profile", "b", "--container", "floci-custom", "-o", "json"); + + assertTrue(out.contains("\"namespace\" : \"custom\""), out); + } + + @Test + void aSharedNamespaceIsReportedEvenWhenThePortAlsoCollides() throws Exception { + writeProfile("a", "container: floci-gcp-b\nport: 14588\nimage: floci/floci-gcp:latest\n"); + + Run r = profileCmd(ProductProfile.GCP, "create", "c", "--container", "b", "--port", "14588"); + + assertTrue(r.err().contains("already uses port 14588"), r.err()); + assertTrue(r.err().contains("already uses resource namespace 'b'"), r.err()); + } + @Test void aDigestPinnedImageStillCollidesWithATagOfTheSameRepository() throws Exception { writeProfile("a", "container: floci-az-a\nport: 14577\nimage: floci/floci-az:latest\n"); diff --git a/src/test/java/io/floci/cli/unit/ProductProfileTest.java b/src/test/java/io/floci/cli/unit/ProductProfileTest.java index 08fb08e..55758d1 100644 --- a/src/test/java/io/floci/cli/unit/ProductProfileTest.java +++ b/src/test/java/io/floci/cli/unit/ProductProfileTest.java @@ -64,4 +64,16 @@ class ProductProfileTest { assertEquals("floci oci", ProductProfile.OCI.commandPrefix()); assertEquals(Map.of(), ProductProfile.OCI.startEnv()); } + + @Test + void resourceNamespaceDropsTheDefaultContainerPrefix() { + assertNull(ProductProfile.AWS.resourceNamespace("floci")); + assertNull(ProductProfile.GCP.resourceNamespace("floci-gcp")); + assertEquals("b", ProductProfile.AWS.resourceNamespace("floci-b")); + assertEquals("b", ProductProfile.GCP.resourceNamespace("floci-gcp-b")); + assertEquals("b", ProductProfile.AZ.resourceNamespace("floci-az-b")); + assertEquals("b", ProductProfile.OCI.resourceNamespace("floci-oci-b")); + assertEquals("team-b", ProductProfile.GCP.resourceNamespace("team-b")); + assertEquals("floci-gcp-", ProductProfile.GCP.resourceNamespace("floci-gcp-")); + } } diff --git a/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java b/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java index a735992..1c7e8cf 100644 --- a/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java +++ b/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java @@ -22,6 +22,7 @@ class ProfileDefaultsTest { p.persistDir = "/tmp/floci-persist-test"; p.services = "s3,lambda"; p.output = "json"; + p.namespace = "team-b"; return p; } @@ -34,6 +35,7 @@ class ProfileDefaultsTest { "--persist, /tmp/floci-persist-test", "--services, 's3,lambda'", "--output, json", + "--namespace, team-b", }) void mapsEveryProfileField(String option, String expected) { assertEquals(expected, ProfileDefaults.valueFor(fullProfile(), option), option); @@ -43,6 +45,7 @@ class ProfileDefaultsTest { @ValueSource(strings = { "--service", // wait/logs/env filter — NOT the profile's 'services' "--profile-name", // the OCI CLI profile written by 'floci oci setup' + "--namespace-name", "--global", // 'floci az setup' target, not a profile field "--reset", "--tenant", diff --git a/src/test/java/io/floci/cli/unit/RestartCommandTest.java b/src/test/java/io/floci/cli/unit/RestartCommandTest.java index 1470e05..c1fd1ab 100644 --- a/src/test/java/io/floci/cli/unit/RestartCommandTest.java +++ b/src/test/java/io/floci/cli/unit/RestartCommandTest.java @@ -7,7 +7,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import picocli.CommandLine; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @@ -56,6 +58,7 @@ class RestartCommandTest { "-v", "/tmp/floci-persist-test:/app/data", "-e", "FLOCI_STORAGE_MODE=persistent", "-e", "FLOCI_SERVICES=s3,lambda", + "-e", "FLOCI_BASE_URL=http://localhost:4599", "floci/floci:enforced"), args); } @@ -76,6 +79,16 @@ class RestartCommandTest { assertFalse(args.stream().anyMatch(a -> a.contains("${env:")), args.toString()); } + @Test + void carriesTheProfileNamespaceIntoTheStartItRuns() throws Exception { + writeProfile("ns", "container: floci-oci-b\nnamespace: team-b\n"); + + List args = parse(ProductProfile.OCI, "--profile", "ns") + .buildStartCommand().dockerRunArgs(SOCKET); + + assertTrue(args.contains("FLOCI_OCI_DOCKER_RESOURCE_NAMESPACE=team-b"), args.toString()); + } + @Test void withoutAProfileItStillUsesTheProductDefaults() { List args = parse(ProductProfile.GCP).buildStartCommand().dockerRunArgs(SOCKET); @@ -97,4 +110,19 @@ class RestartCommandTest { "-e", "FLOCI_OCI_STORAGE_MODE=persistent", "floci/floci-oci:latest"), args); } + + /** A namespace start would reject must fail restart before it stops anything. */ + @Test + void anInvalidProfileNamespaceFailsBeforeTheStop() throws Exception { + writeProfile("bad", "container: floci-bad\nnamespace: bad/name\n"); + RestartCommand restart = parse(ProductProfile.AWS, "--profile", "bad"); + + PrintStream err = System.err; + System.setErr(new PrintStream(new ByteArrayOutputStream())); + try { + assertEquals(2, restart.call()); + } finally { + System.setErr(err); + } + } } diff --git a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java index c18dd4b..087df0e 100644 --- a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java +++ b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java @@ -7,7 +7,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import picocli.CommandLine.ParseResult; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @@ -54,6 +56,8 @@ class StartCommandArgsTest { "-v", "/tmp/floci-persist-test:/app/data", "-e", "FLOCI_STORAGE_MODE=persistent", "-e", "FLOCI_SERVICES=s3,lambda", + "-e", "FLOCI_BASE_URL=http://localhost:4599", + "-e", "FLOCI_DOCKER_RESOURCE_NAMESPACE=probe", "floci/floci:enforced"), parse("start", "--profile", "probe").dockerRunArgs(SOCKET)); } @@ -107,6 +111,86 @@ class StartCommandArgsTest { } } + /** + * Two instances of one emulator must not share a resource namespace, or each one's startup + * sweep removes the other's Lambda/ECS/Cloud Run children. The default instance passes none, + * so its child container names stay what they were. + */ + @Test + void theDefaultContainerPassesNoResourceNamespace() { + for (String tree : new String[]{"aws", "gcp", "az", "oci"}) { + assertFalse(parse(tree, "start").dockerRunArgs(SOCKET).stream() + .anyMatch(a -> a.contains("RESOURCE_NAMESPACE")), tree); + } + } + + @Test + void aNonDefaultContainerNamesItsOwnNamespaceInEveryTree() { + // The emulator prefixes child names with floci-- itself, so the default-container + // prefix is dropped: floci-gcp-b -> b, not floci-gcp-floci-gcp-b-... + assertTrue(parse("start", "--container", "floci-b").dockerRunArgs(SOCKET) + .contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=b")); + assertTrue(parse("gcp", "start", "--container", "floci-gcp-b").dockerRunArgs(SOCKET) + .contains("FLOCI_GCP_DOCKER_RESOURCE_NAMESPACE=b")); + assertTrue(parse("az", "start", "--container", "floci-az-b").dockerRunArgs(SOCKET) + .contains("FLOCI_AZ_DOCKER_RESOURCE_NAMESPACE=b")); + assertTrue(parse("oci", "start", "--container", "team-oci").dockerRunArgs(SOCKET) + .contains("FLOCI_OCI_DOCKER_RESOURCE_NAMESPACE=team-oci")); + } + + @Test + void anExplicitNamespaceBeatsTheContainerName() { + assertTrue(parse("start", "--container", "floci-b", "--namespace", "team-b") + .dockerRunArgs(SOCKET).contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=team-b")); + assertTrue(parse("start", "--namespace", "team-a") + .dockerRunArgs(SOCKET).contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=team-a")); + } + + @Test + void theProfileNamespaceAppliesAndTheFlagStillWins() throws Exception { + writeProfile("probe", "container: floci-probe\nnamespace: from-profile\n"); + assertTrue(parse("start", "--container", "floci-probe", "--namespace", "floci-probe") + .dockerRunArgs(SOCKET).contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=floci-probe"), + "an explicit namespace is passed verbatim"); + + assertTrue(parse("start", "--profile", "probe").dockerRunArgs(SOCKET) + .contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=from-profile")); + assertTrue(parse("start", "--profile", "probe", "--namespace", "from-flag").dockerRunArgs(SOCKET) + .contains("FLOCI_DOCKER_RESOURCE_NAMESPACE=from-flag")); + } + + @Test + void anInvalidNamespaceIsRejectedBeforeDockerIsTouched() { + StartCommand start = parse("start", "--namespace", "bad/name"); + PrintStream err = System.err; + System.setErr(new PrintStream(new ByteArrayOutputStream())); + try { + assertEquals(2, start.call()); + } finally { + System.setErr(err); + } + } + + /** Response URLs (SQS QueueUrl, OCI invoke endpoint) must name the port this instance owns. */ + @Test + void aNonDefaultPortMovesTheBaseUrlWithIt() { + assertTrue(parse("start", "--port", "14566").dockerRunArgs(SOCKET) + .contains("FLOCI_BASE_URL=http://localhost:14566")); + assertTrue(parse("oci", "start", "--port", "14599").dockerRunArgs(SOCKET) + .contains("FLOCI_OCI_BASE_URL=http://localhost:14599")); + for (String tree : new String[]{"aws", "gcp", "az", "oci"}) { + assertFalse(parse(tree, "start").dockerRunArgs(SOCKET).stream() + .anyMatch(a -> a.contains("BASE_URL")), tree); + } + } + + /** Returned URLs must reach the emulator, so a remote endpoint's host is kept. */ + @Test + void theBaseUrlKeepsTheEndpointsHost() { + assertTrue(parse("start", "--endpoint", "http://floci.internal:4566", "--port", "14566") + .dockerRunArgs(SOCKET).contains("FLOCI_BASE_URL=http://floci.internal:14566")); + } + @Test void readinessPollKeepsTheHostFromTheEndpointWhenSwappingThePort() { assertEquals("http://floci.internal:4599", StartCommand.withPort("http://floci.internal:4566", 4599));