From 5cf5c3a3caa066c797e49416a01633074a345155 Mon Sep 17 00:00:00 2001 From: "Ganesh, Mohan" Date: Fri, 27 Nov 2026 18:50:18 -0500 Subject: [PATCH] feat(firestore): add builder API to FirestoreDatabaseRunner - Add FirestoreDatabaseRunner.newBuilder() and create(...) factory methods, mirroring the Runner.builder() pattern already established in core ADK - Deprecate legacy constructors (@Deprecated + @SuppressWarnings placed to match how Runner deprecated its own constructors) - Default to InMemoryArtifactService with logger.warn when no GCS bucket is configured, replacing the previous startup RuntimeException - Rename property key firebase->firestore with legacy fallback - Improve branch coverage 83%->89% with 99 tests passing - Update README with Quick Start, builder API reference, and migration guide --- contrib/firestore-session-service/README.md | 333 ++++++--- .../adk/runner/FirestoreDatabaseRunner.java | 336 ++++++++- .../java/com/google/adk/utils/Constants.java | 2 +- .../google/adk/utils/FirestoreProperties.java | 26 +- .../memory/FirestoreMemoryServiceTest.java | 23 + .../runner/FirestoreDatabaseRunnerTest.java | 705 ++++++++++++++---- .../sessions/FirestoreSessionServiceTest.java | 155 ++++ .../com/google/adk/utils/ConstantsTest.java | 3 +- .../adk/utils/FirestorePropertiesTest.java | 56 +- .../resources/adk-firestore-dev.properties | 2 +- .../test/resources/adk-firestore.properties | 2 +- 11 files changed, 1389 insertions(+), 254 deletions(-) diff --git a/contrib/firestore-session-service/README.md b/contrib/firestore-session-service/README.md index 929ee7b16c..d182feab07 100644 --- a/contrib/firestore-session-service/README.md +++ b/contrib/firestore-session-service/README.md @@ -1,14 +1,12 @@ ## Firestore Session Service for ADK -This sub-module contains an implementation of a session service for the ADK (Agent Development Kit) that uses Google Firestore as the backend for storing session data. This allows developers to manage user sessions in a scalable and reliable manner using Firestore's NoSQL database capabilities. +This sub-module contains an implementation of a session service for the ADK (Agent Development Kit) that uses Google Cloud Firestore as the backend for storing session data and conversation memory. This allows ADK Applications to manage user sessions in a scalable, durable manner across distributed servers and restarts. ## Getting Started -To integrate this Firestore session service into your ADK project, add the following dependencies to your project's build configuration: pom.xml for Maven or build.gradle for Gradle. +To integrate Firestore session service into your ADK project, add the following dependencies to your project's build configuration: `pom.xml` for Maven or `build.gradle` for Gradle. -## Basic Setup - -If you're using Maven, add the following to your dependencies: +### Maven Setup @@ -18,16 +16,18 @@ If you're using Maven, add the following to your dependencies: google-adk 1.16.0 - + - com.google.adk - google-adk-dev - 1.16.0 + com.google.adk + google-adk-firestore-session-service + 1.16.0 ``` +### Gradle Setup + ```gradle @@ -41,118 +41,277 @@ dependencies { -## Running the Service +--- -You can customize your ADK application to use the Firestore session service by providing your own Firestore property settings, otherwise library will use the default settings. +## Quick Start -Sample Property Settings: +The minimum to run an agent with Firestore-backed sessions — no Google Cloud Storage bucket or adk-firestore.properties file required: -```properties -# Firestore collection name for storing session data -firebase.root.collection.name=adk-session -# Google Cloud Storage bucket name for artifact storage -gcs.adk.bucket.name=your-gcs-bucket-name -#stop words for keyword extraction -keyword.extraction.stopwords=a,about,above,after,again,against,all,am,an,and,any,are,aren't,as,at,be,because,been,before,being,below,between,both,but,by,can't,cannot,could,couldn't,did,didn't,do,does,doesn't,doing,don't,down,during,each,few,for,from,further,had,hadn't,has,hasn't,have,haven't,having,he,he'd,he'll,he's,her,here,here's,hers,herself,him,himself,his,how,i,i'd,i'll,i'm,i've,if,in,into,is +```java +import com.google.adk.agents.LlmAgent; +import com.google.adk.agents.RunConfig; +import com.google.adk.runner.FirestoreDatabaseRunner; +import com.google.adk.runner.Runner; +import com.google.adk.sessions.Session; +import com.google.cloud.firestore.FirestoreOptions; +import com.google.genai.types.Content; +import com.google.genai.types.Part; + +// 1. Define the agent +Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(LlmAgent.builder() + .name("my-agent") + .model("gemini-3.8-flash") + .instruction("You are a helpful assistant.") + .build()) + .firestore(FirestoreOptions.getDefaultInstance().getService()) + .build(); + +// 2. Create a session +Session session = runner.sessionService().createSession("my-agent", "user-1").blockingGet(); + +// 3. Run +runner.runAsync(session.userId(), session.id(), + Content.fromParts(Part.fromText("Hello!")), RunConfig.builder().build()) + .filter(event -> event.finalResponse()) + .blockingForEach(event -> System.out.println(event.stringifyContent())); ``` -Then, you can use the `FirestoreDatabaseRunner` to start your ADK application with Firestore session management: +Sessions are persisted to Firestore automatically. Artifacts default to in-memory — configure GCS when you need durable file storage (see [Example 2](#example-2-agent-with-google-cloud-storage-gcs-artifacts)). + +--- + +## Example 1: Conversational Agent (Explicit In-Memory Artifacts for local testing) + +For conversational agents that do not use persistent file artifacts, you can explicitly configure `InMemoryArtifactService`: ```java +import static java.nio.charset.StandardCharsets.UTF_8; + import com.google.adk.agents.BaseAgent; import com.google.adk.agents.LlmAgent; import com.google.adk.agents.RunConfig; +import com.google.adk.artifacts.InMemoryArtifactService; +import com.google.adk.events.Event; import com.google.adk.runner.FirestoreDatabaseRunner; -import com.google.cloud.firestore.Firestore; -import com.google.cloud.firestore.FirestoreOptions; -import io.reactivex.rxjava3.core.Flowable; -import java.util.Map; -import com.google.adk.sessions.FirestoreSessionService; +import com.google.adk.runner.Runner; import com.google.adk.sessions.Session; import com.google.adk.tools.Annotations.Schema; import com.google.adk.tools.FunctionTool; +import com.google.cloud.firestore.Firestore; +import com.google.cloud.firestore.FirestoreOptions; import com.google.genai.types.Content; import com.google.genai.types.Part; -import com.google.adk.events.Event; +import io.reactivex.rxjava3.core.Flowable; +import java.util.Map; import java.util.Scanner; -import static java.nio.charset.StandardCharsets.UTF_8; - -/*** - * - */ -public class YourAgentApplication { - public static void main(String[] args) { - System.out.println("Starting YourAgentApplication..."); +public class ChatAgentApplication { + public static void main(String[] args) { + String appName = "hello-time-agent"; + BaseAgent timeAgent = initAgent(); - RunConfig runConfig = RunConfig.builder().build(); - String appName = "hello-time-agent"; + // 1. Initialize Firestore client + Firestore firestore = FirestoreOptions.getDefaultInstance().getService(); - BaseAgent timeAgent = initAgent(); - // Initialize Firestore - FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance(); - Firestore firestore = firestoreOptions.getService(); + // 2. Build the Runner backed by Firestore, explicitly opting into in-memory artifacts + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(timeAgent) + .appName(appName) + .firestore(firestore) + .artifactService(new InMemoryArtifactService()) + .build(); + // 3. Create or resume a session + Session session = + runner.sessionService().createSession(appName, "user1234").blockingGet(); - // Use FirestoreDatabaseRunner to persist session state - FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner( - timeAgent, - appName, - firestore - ); + RunConfig runConfig = RunConfig.builder().build(); + // 4. Run interactive chat loop + try (Scanner scanner = new Scanner(System.in, UTF_8)) { + while (true) { + System.out.print("\nYou > "); + String userInput = scanner.nextLine(); + if ("quit".equalsIgnoreCase(userInput)) { + break; + } + Content userMsg = Content.fromParts(Part.fromText(userInput)); + Flowable events = + runner.runAsync(session.userId(), session.id(), userMsg, runConfig); + + System.out.print("\nAgent > "); + events.blockingForEach( + event -> { + if (event.finalResponse()) { + System.out.println(event.stringifyContent()); + } + }); + } + } + } + + @Schema(description = "Get the current time for a given city") + public static Map getCurrentTime( + @Schema(name = "city", description = "Name of the city") String city) { + return Map.of("city", city, "forecast", "The time is 10:30 AM."); + } + + private static BaseAgent initAgent() { + return LlmAgent.builder() + .name("hello-time-agent") + .description("Tells the current time in a specified city") + .instruction("You are a helpful assistant that tells the current time using the 'getCurrentTime' tool.") + .model("gemini-3.8-flash") + .tools(FunctionTool.create(ChatAgentApplication.class, "getCurrentTime")) + .build(); + } +} +``` - Session session = new FirestoreSessionService(firestore) - .createSession(appName,"user1234",null,"12345") - .blockingGet(); +--- +## Example 2: Agent with Google Cloud Storage (GCS) Artifacts - try (Scanner scanner = new Scanner(System.in, UTF_8)) { - while (true) { - System.out.print("\nYou > "); - String userInput = scanner.nextLine(); - if ("quit".equalsIgnoreCase(userInput)) { - break; - } +When an agent produces or consumes file artifacts (such as images, generated reports, or file downloads), you can configure **Google Cloud Storage** directly through the builder: - Content userMsg = Content.fromParts(Part.fromText(userInput)); - Flowable events = runner.runAsync(session.userId(), session.id(), userMsg, runConfig); +```java +import com.google.adk.agents.BaseAgent; +import com.google.adk.agents.LlmAgent; +import com.google.adk.agents.RunConfig; +import com.google.adk.runner.FirestoreDatabaseRunner; +import com.google.adk.runner.Runner; +import com.google.adk.sessions.Session; +import com.google.cloud.firestore.Firestore; +import com.google.cloud.firestore.FirestoreOptions; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.genai.types.Content; +import com.google.genai.types.Part; - System.out.print("\nAgent > "); - events.blockingForEach(event -> { - if (event.finalResponse()) { - System.out.println(event.stringifyContent()); - } - }); - } - } +public class ArtifactReportingAgentApplication { + public static void main(String[] args) { + String appName = "report-generator-agent"; + BaseAgent reportAgent = initAgent(); - } + // 1. Initialize Firestore & GCS clients + Firestore firestore = FirestoreOptions.getDefaultInstance().getService(); + Storage storage = StorageOptions.getDefaultInstance().getService(); - /** Mock tool implementation */ - @Schema(description = "Get the current time for a given city") - public static Map getCurrentTime( - @Schema(name = "city", description = "Name of the city to get the time for") String city) { - return Map.of( - "city", city, - "forecast", "The time is 10:30am." - ); - } - private static BaseAgent initAgent() { - return LlmAgent.builder() - .name("hello-time-agent") - .description("Tells the current time in a specified city") - .instruction(""" - You are a helpful assistant that tells the current time in a city. - Use the 'getCurrentTime' tool for this purpose. - """) - .model("gemini-3.1-pro-preview") - .tools(FunctionTool.create(YourAgentApplication.class, "getCurrentTime")) + // 2. Build Runner with Firestore for sessions and GCS for persistent artifacts + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(reportAgent) + .appName(appName) + .firestore(firestore) + .withGcsArtifacts("my-agent-artifacts-bucket", storage) .build(); - } + // 3. Create session & run agent + Session session = + runner.sessionService().createSession(appName, "analyst-mg").blockingGet(); + + Content request = Content.fromParts(Part.fromText("Generate the Q3 performance report PDF")); + runner + .runAsync(session.userId(), session.id(), request, RunConfig.builder().build()) + .blockingForEach( + event -> { + if (event.finalResponse()) { + System.out.println("Result: " + event.stringifyContent()); + } + }); + } + + private static BaseAgent initAgent() { + return LlmAgent.builder() + .name("report-generator-agent") + .instruction("Generate and save analysis reports as artifacts.") + .model("gemini-3.8-flash") + .build(); + } } ``` + +--- + +## Optional Configuration (`adk-firestore.properties`) + +Default persistence settings can be configured via `adk-firestore.properties`: + +- **`firestore.root.collection.name`**: Defaults to `"adk-session"`. +- **`keyword.extraction.stopwords`**: Defaults to a built-in set of common English stop words. +- **`gcs.adk.bucket.name`**: Google Cloud Storage bucket for artifact storage (can also be provided in code via `.withGcsArtifacts("bucket-name")`). + +```properties +# Optional: customize root collection name (default: adk-session) +firestore.root.collection.name=custom-adk-session + +# Optional: GCS bucket name for persistent artifacts +gcs.adk.bucket.name=your-gcs-bucket-name + +# Optional: customize stop words for memory search +keyword.extraction.stopwords=a,about,above,after,again,all,and,any,are,at,be,by,for,from,how,if,in,into,is,it,of,on,or,that,the,this,to,was,what,when,where,who,will,with +``` + +--- + +## Builder API Reference + +`FirestoreDatabaseRunner.newBuilder()` supports the following configuration methods: + +| Method | Description | +| --------------------------------------------------- | -------------------------------------------------------------------------------- | +| `.agent(BaseAgent)` | The agent to run. Mutually exclusive with `.app()`. | +| `.app(App)` | An `App` instance. Mutually exclusive with `.agent()`. | +| `.appName(String)` | Override the application name (defaults to agent/app name). | +| `.firestore(Firestore)` | Firestore client for session and memory services. | +| `.withGcsArtifacts(String bucket)` | Configure GCS artifact storage with default credentials. | +| `.withGcsArtifacts(String bucket, Storage storage)` | Configure GCS artifact storage with an explicit `Storage` client. | +| `.artifactService(BaseArtifactService)` | Provide a custom artifact service (e.g., `InMemoryArtifactService` for testing). | +| `.sessionService(BaseSessionService)` | Override the default `FirestoreSessionService`. | +| `.memoryService(BaseMemoryService)` | Override the default `FirestoreMemoryService`. | +| `.plugins(List)` | Add plugins to the runner. | +| `.instantSource(InstantSource)` | Custom timestamp source (useful for testing). | +| `.uuidProvider(UuidProvider)` | Custom ID generator (useful for testing). | +| `.scheduler(Scheduler)` | RxJava scheduler for async hand-offs. | +| `.toRunnerBuilder()` | Returns a `Runner.Builder` for further customization before building. | +| `.build()` | Builds and returns the configured `Runner`. | + +> **Note**: If neither `.withGcsArtifacts()` nor `.artifactService()` is set, and `gcs.adk.bucket.name` is not configured, `.build()` defaults to using `InMemoryArtifactService` for artifacts. This lets text-based agents run without any Google Cloud Storage setup, though any artifacts stored will be ephemeral and lost across restarts or distributed servers. For durable artifact persistence in production, configure `.withGcsArtifacts(...)` or `.artifactService(...)`. +--- + +## Legacy Constructor API (Deprecated) + +> **These constructors are deprecated.** Migrate to `FirestoreDatabaseRunner.newBuilder()`. + +The direct constructor style is retained for backward compatibility but has two important behavior differences from the old API: + +- **Previously**: startup threw `RuntimeException` when `gcs.adk.bucket.name` was not configured. +- **Now**: falls back silently to `InMemoryArtifactService` and **logs a `WARN`** so operators are aware. Artifacts stored in-memory are ephemeral and will be lost on restart. + +```java +// @Deprecated — migrate to newBuilder() +FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(agent, firestore); +FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(agent, appName, firestore); +FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(agent, appName, plugins, firestore); +``` + +**Migration path** — replace any constructor call with the equivalent builder: + +```java +// Before (deprecated) +new FirestoreDatabaseRunner(agent, appName, firestore); + +// After (recommended) +FirestoreDatabaseRunner.newBuilder() + .agent(agent) + .appName(appName) + .firestore(firestore) + .withGcsArtifacts("your-bucket-name") // explicit — no silent fallback + .build(); +``` diff --git a/contrib/firestore-session-service/src/main/java/com/google/adk/runner/FirestoreDatabaseRunner.java b/contrib/firestore-session-service/src/main/java/com/google/adk/runner/FirestoreDatabaseRunner.java index 8e8255a808..64ba9e0f05 100644 --- a/contrib/firestore-session-service/src/main/java/com/google/adk/runner/FirestoreDatabaseRunner.java +++ b/contrib/firestore-session-service/src/main/java/com/google/adk/runner/FirestoreDatabaseRunner.java @@ -17,50 +17,354 @@ package com.google.adk.runner; import com.google.adk.agents.BaseAgent; +import com.google.adk.apps.App; +import com.google.adk.artifacts.BaseArtifactService; +import com.google.adk.artifacts.GcsArtifactService; +import com.google.adk.artifacts.InMemoryArtifactService; +import com.google.adk.memory.BaseMemoryService; import com.google.adk.memory.FirestoreMemoryService; +import com.google.adk.platform.UuidProvider; import com.google.adk.plugins.BasePlugin; +import com.google.adk.plugins.Plugin; +import com.google.adk.sessions.BaseSessionService; import com.google.adk.sessions.FirestoreSessionService; import com.google.adk.utils.FirestoreProperties; import com.google.cloud.firestore.Firestore; +import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import io.reactivex.rxjava3.core.Scheduler; +import java.time.InstantSource; +import java.util.ArrayList; +import java.util.List; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -/** FirestoreDatabaseRunner */ +/** + * Runner subclass pre-configured with Google Cloud Firestore for session and memory management. + * + *

Supports two usage styles: + * + *

    + *
  • Constructor-based (legacy, deprecated): retained for backward compatibility. + * Logs a warning and falls back to {@link InMemoryArtifactService} when + * {@code gcs.adk.bucket.name} is not configured. Migrate to {@link #newBuilder()}. + *
  • Builder-based (recommended): use {@link #newBuilder()} for explicit control over + * artifact storage, service injection, plugins, and runtime settings. + *
+ * + *

When neither an explicit {@link BaseArtifactService} nor a GCS bucket (via {@link + * Builder#withGcsArtifacts(String)} or {@link Builder#withGcsArtifacts(String, Storage)}) is + * configured, the runner defaults to {@link InMemoryArtifactService}. Artifacts stored in-memory + * are ephemeral and will be lost on restart or across distributed servers. + */ public class FirestoreDatabaseRunner extends Runner { - /** Constructor for FirestoreDatabaseRunner */ + private static final Logger logger = LoggerFactory.getLogger(FirestoreDatabaseRunner.class); + + // ------------------------------------------------------------------------- + // Legacy constructor-based API (deprecated — use newBuilder()) + // ------------------------------------------------------------------------- + + /** + * Creates a runner with Firestore services. + * + * @deprecated Use {@link #newBuilder()} for explicit artifact storage configuration. + */ + @Deprecated + @SuppressWarnings("deprecation") public FirestoreDatabaseRunner(BaseAgent baseAgent, Firestore firestore) { - this(baseAgent, baseAgent.name(), new java.util.ArrayList<>(), firestore); + this(baseAgent, baseAgent.name(), new ArrayList<>(), firestore); } - /** Constructor for FirestoreDatabaseRunner with appName */ + /** + * Creates a runner with Firestore services and a custom app name. + * + * @deprecated Use {@link #newBuilder()} for explicit artifact storage configuration. + */ + @Deprecated + @SuppressWarnings("deprecation") public FirestoreDatabaseRunner(BaseAgent baseAgent, String appName, Firestore firestore) { - this(baseAgent, appName, new java.util.ArrayList<>(), firestore); + this(baseAgent, appName, new ArrayList<>(), firestore); } - /** Constructor for FirestoreDatabaseRunner with parent runners */ + /** + * Creates a runner with Firestore services, a custom app name, and plugins. + * + * @deprecated Use {@link #newBuilder()} for explicit artifact storage configuration. + */ + @Deprecated + @SuppressWarnings("deprecation") // calls deprecated Runner(BaseAgent, String, ..., List) super public FirestoreDatabaseRunner( BaseAgent baseAgent, String appName, - java.util.List plugins, + List plugins, Firestore firestore) { super( baseAgent, appName, - new com.google.adk.artifacts.GcsArtifactService( - getBucketNameFromEnv(), StorageOptions.getDefaultInstance().getService()), + resolveDefaultArtifactService(), new FirestoreSessionService(firestore), new FirestoreMemoryService(firestore), plugins); } - /** Gets the GCS bucket name from the environment variable ADK_GCS_BUCKET_NAME. */ - private static String getBucketNameFromEnv() { + /** + * Resolves the artifact service for legacy constructors. Uses GCS if {@code gcs.adk.bucket.name} + * is set in properties; otherwise falls back to {@link InMemoryArtifactService} and logs a + * warning so operators are aware that artifacts will not be persisted. + */ + private static BaseArtifactService resolveDefaultArtifactService() { + String bucketName = findBucketNameFromProperties(); + if (bucketName != null && !bucketName.trim().isEmpty()) { + return new GcsArtifactService( + bucketName, StorageOptions.getDefaultInstance().getService()); + } + logger.warn( + "No Google Cloud Storage (GCS) bucket configured for artifact storage; falling back to InMemoryArtifactService." + + " Artifacts will be ephemeral and lost on restart." + + " Set 'gcs.adk.bucket.name' in adk-firestore.properties or migrate to" + + " FirestoreDatabaseRunner.newBuilder().withGcsArtifacts(\"bucket-name\")."); + return new InMemoryArtifactService(); + } + + /** Return the GCS bucket name from properties, or null if not set. */ + private static @Nullable String findBucketNameFromProperties() { String bucketName = FirestoreProperties.getInstance().getGcsAdkBucketName(); - if (bucketName == null || bucketName.trim().isEmpty()) { - throw new RuntimeException( - "Required property 'gcs.adk.bucket.name' is not set. This" - + " is needed for the GcsArtifactService."); + return (bucketName == null || bucketName.trim().isEmpty()) ? null : bucketName.trim(); + } + + // ------------------------------------------------------------------------- + // Builder-based API + // ------------------------------------------------------------------------- + + /** Returns a new {@link Builder} to configure and build a {@link Runner}. */ + public static Builder newBuilder() { + return new Builder(); + } + + /** + * Convenience factory: creates a {@link Runner} for the given agent and Firestore instance. Uses + * GCS artifacts if {@code gcs.adk.bucket.name} is set in properties; otherwise defaults to + * {@link InMemoryArtifactService}. + */ + public static Runner create(BaseAgent agent, Firestore firestore) { + return newBuilder().agent(agent).firestore(firestore).build(); + } + + /** + * Convenience factory: creates a {@link Runner} for the given agent, app name, and Firestore + * instance. + */ + public static Runner create(BaseAgent agent, String appName, Firestore firestore) { + return newBuilder().agent(agent).appName(appName).firestore(firestore).build(); + } + + /** Builder for configuring and creating a {@link Runner} backed by Firestore. */ + public static class Builder { + private @Nullable BaseAgent agent; + private @Nullable App app; + private @Nullable String appName; + private final List plugins = new ArrayList<>(); + + private @Nullable Firestore firestore; + private @Nullable BaseSessionService sessionService; + private @Nullable BaseMemoryService memoryService; + private @Nullable BaseArtifactService artifactService; + + private @Nullable String gcsBucketName; + private @Nullable Storage storage; + + private InstantSource instantSource = InstantSource.system(); + private UuidProvider uuidProvider = UuidProvider.SYSTEM; + private @Nullable Scheduler scheduler; + + private Builder() {} + + /** Sets the agent to run. Mutually exclusive with {@link #app(App)}. */ + @CanIgnoreReturnValue + public Builder agent(BaseAgent agent) { + Preconditions.checkState(this.app == null, "Cannot set agent when app is already set."); + this.agent = agent; + return this; + } + + /** Sets the app to run. Mutually exclusive with {@link #agent(BaseAgent)}. */ + @CanIgnoreReturnValue + public Builder app(App app) { + Preconditions.checkState(this.agent == null, "Cannot set app when agent is already set."); + this.app = app; + return this; + } + + /** Sets the application name. Defaults to agent or app name if not provided. */ + @CanIgnoreReturnValue + public Builder appName(String appName) { + this.appName = appName; + return this; + } + + /** Sets the Firestore client instance used for session and memory services. */ + @CanIgnoreReturnValue + public Builder firestore(Firestore firestore) { + this.firestore = firestore; + return this; + } + + /** Explicitly provides a custom {@link BaseSessionService}. */ + @CanIgnoreReturnValue + public Builder sessionService(BaseSessionService sessionService) { + this.sessionService = sessionService; + return this; + } + + /** Explicitly provides a custom {@link BaseMemoryService}. */ + @CanIgnoreReturnValue + public Builder memoryService(BaseMemoryService memoryService) { + this.memoryService = memoryService; + return this; + } + + /** Explicitly provides an artifact service implementation. */ + @CanIgnoreReturnValue + public Builder artifactService(BaseArtifactService artifactService) { + this.artifactService = artifactService; + return this; + } + + /** Configures GCS artifact storage with a bucket name and default storage options. */ + @CanIgnoreReturnValue + public Builder withGcsArtifacts(String bucketName) { + return withGcsArtifacts(bucketName, null); + } + + /** Configures GCS artifact storage with a bucket name and explicit {@link Storage} client. */ + @CanIgnoreReturnValue + public Builder withGcsArtifacts(String bucketName, @Nullable Storage storage) { + this.gcsBucketName = bucketName; + this.storage = storage; + return this; + } + + /** Adds plugins to the runner. */ + @CanIgnoreReturnValue + public Builder plugins(List plugins) { + this.plugins.addAll(plugins); + return this; + } + + /** Adds plugins to the runner. */ + @CanIgnoreReturnValue + public Builder plugins(Plugin... plugins) { + this.plugins.addAll(ImmutableList.copyOf(plugins)); + return this; + } + + /** Sets the {@link InstantSource} for timestamp generation. */ + @CanIgnoreReturnValue + public Builder instantSource(InstantSource instantSource) { + this.instantSource = Preconditions.checkNotNull(instantSource); + return this; + } + + /** Sets the {@link UuidProvider} for ID generation. */ + @CanIgnoreReturnValue + public Builder uuidProvider(UuidProvider uuidProvider) { + this.uuidProvider = Preconditions.checkNotNull(uuidProvider); + return this; + } + + /** Sets the {@link Scheduler} for hand-offs to worker threads. */ + @CanIgnoreReturnValue + public Builder scheduler(@Nullable Scheduler scheduler) { + this.scheduler = scheduler; + return this; + } + + /** + * Converts this builder into a standard {@link Runner.Builder}, pre-configured with Firestore + * services and artifact service. Callers can use this to apply any additional runner settings. + */ + public Runner.Builder toRunnerBuilder() { + if (this.app == null && this.agent == null) { + throw new IllegalStateException("Either agent or app must be set."); + } + + String resolvedAppName = this.appName; + if (resolvedAppName == null) { + resolvedAppName = (this.app != null) ? this.app.name() : this.agent.name(); + } + + BaseSessionService resolvedSessionService = this.sessionService; + BaseMemoryService resolvedMemoryService = this.memoryService; + + if (resolvedSessionService == null || resolvedMemoryService == null) { + if (this.firestore == null) { + throw new IllegalStateException( + "Firestore client must be provided when session or memory service is not explicitly" + + " configured."); + } + if (resolvedSessionService == null) { + resolvedSessionService = + new FirestoreSessionService(this.firestore, this.instantSource, this.uuidProvider); + } + if (resolvedMemoryService == null) { + resolvedMemoryService = new FirestoreMemoryService(this.firestore); + } + } + + BaseArtifactService resolvedArtifactService = this.artifactService; + if (resolvedArtifactService == null) { + String bucket = this.gcsBucketName; + if (bucket == null || bucket.trim().isEmpty()) { + bucket = FirestoreProperties.getInstance().getGcsAdkBucketName(); + } + + if (bucket != null && !bucket.trim().isEmpty()) { + Storage storageClient = + this.storage != null ? this.storage : StorageOptions.getDefaultInstance().getService(); + resolvedArtifactService = new GcsArtifactService(bucket.trim(), storageClient); + } else { + resolvedArtifactService = new InMemoryArtifactService(); + } + } + + Runner.Builder runnerBuilder = Runner.builder(); + if (this.app != null) { + // Runner.Builder.appName() requires app to be unset, so set it before app(). + // Runner.Builder.build() honours appName even when app is set (line: appName == null ? + // app.name() : appName), so an explicit override is correctly propagated. + if (this.appName != null) { + runnerBuilder.appName(this.appName); + } + runnerBuilder.app(this.app); + } else { + runnerBuilder.agent(this.agent).appName(resolvedAppName); + } + + runnerBuilder + .sessionService(resolvedSessionService) + .memoryService(resolvedMemoryService) + .artifactService(resolvedArtifactService) + .instantSource(this.instantSource) + .uuidProvider(this.uuidProvider); + + if (!this.plugins.isEmpty()) { + runnerBuilder.plugins(this.plugins); + } + if (this.scheduler != null) { + runnerBuilder.scheduler(this.scheduler); + } + + return runnerBuilder; + } + + /** Builds the configured {@link Runner}. */ + public Runner build() { + return toRunnerBuilder().build(); } - return bucketName; } } diff --git a/contrib/firestore-session-service/src/main/java/com/google/adk/utils/Constants.java b/contrib/firestore-session-service/src/main/java/com/google/adk/utils/Constants.java index 0cfd6f133c..175f1a0402 100644 --- a/contrib/firestore-session-service/src/main/java/com/google/adk/utils/Constants.java +++ b/contrib/firestore-session-service/src/main/java/com/google/adk/utils/Constants.java @@ -69,7 +69,7 @@ public class Constants { /** root collection name fof firestore */ public static final String ROOT_COLLECTION_NAME = - FirestoreProperties.getInstance().getFirebaseRootCollectionName(); + FirestoreProperties.getInstance().getFirestoreRootCollectionName(); /** private constrctor */ private Constants() { diff --git a/contrib/firestore-session-service/src/main/java/com/google/adk/utils/FirestoreProperties.java b/contrib/firestore-session-service/src/main/java/com/google/adk/utils/FirestoreProperties.java index 7a798a7aca..ebb1c02cb3 100644 --- a/contrib/firestore-session-service/src/main/java/com/google/adk/utils/FirestoreProperties.java +++ b/contrib/firestore-session-service/src/main/java/com/google/adk/utils/FirestoreProperties.java @@ -43,8 +43,9 @@ public class FirestoreProperties { private final Properties properties; - private final String firebaseRootCollectionNameKey = "firebase.root.collection.name"; - private final String firebaseRootCollectionDefaultValue = "adk-session"; + private final String firestoreRootCollectionNameKey = "firestore.root.collection.name"; + private final String legacyFirebaseRootCollectionNameKey = "firebase.root.collection.name"; + private final String firestoreRootCollectionDefaultValue = "adk-session"; private final String gcsAdkBucketNameKey = "gcs.adk.bucket.name"; @@ -120,13 +121,28 @@ public String getProperty(String key) { /** * Get the root collection name from the properties file, or return the default value if not - * found. + * found. Checks 'firestore.root.collection.name' first, falling back to legacy + * 'firebase.root.collection.name'. * * @return the root collection name */ + public String getFirestoreRootCollectionName() { + String name = this.properties.getProperty(firestoreRootCollectionNameKey); + if (name != null && !name.trim().isEmpty()) { + return name; + } + String legacyName = this.properties.getProperty(legacyFirebaseRootCollectionNameKey); + return (legacyName != null && !legacyName.trim().isEmpty()) ? legacyName.trim() : firestoreRootCollectionDefaultValue; + } + + /** + * Legacy method for getting the root collection name. + * + * @deprecated Use {@link #getFirestoreRootCollectionName()} instead. + */ + @Deprecated public String getFirebaseRootCollectionName() { - return this.properties.getProperty( - firebaseRootCollectionNameKey, firebaseRootCollectionDefaultValue); + return getFirestoreRootCollectionName(); } /** diff --git a/contrib/firestore-session-service/src/test/java/com/google/adk/memory/FirestoreMemoryServiceTest.java b/contrib/firestore-session-service/src/test/java/com/google/adk/memory/FirestoreMemoryServiceTest.java index 7526461af9..197515ff34 100644 --- a/contrib/firestore-session-service/src/test/java/com/google/adk/memory/FirestoreMemoryServiceTest.java +++ b/contrib/firestore-session-service/src/test/java/com/google/adk/memory/FirestoreMemoryServiceTest.java @@ -21,8 +21,10 @@ import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.adk.sessions.Session; import com.google.api.core.ApiFutures; import com.google.cloud.firestore.CollectionGroup; import com.google.cloud.firestore.Firestore; @@ -191,6 +193,27 @@ void searchMemory_withDocWithNoParts_returnsMemoryWithEmptyContent() { }); } + /** Tests that addSessionToMemory completes without error (it is a deliberate no-op). */ + @Test + void addSessionToMemory_completesSuccessfully() { + Session session = mock(Session.class); + + memoryService.addSessionToMemory(session).test().assertComplete(); + } + + /** Tests that searchMemory returns empty when every query word is a stop word. */ + @Test + void searchMemory_withAllStopWordsQuery_returnsEmptyWithoutHittingFirestore() { + // "a the is" are all stop words — extractKeywords returns empty set, + // so searchMemory short-circuits without touching Firestore. + TestObserver testObserver = + memoryService.searchMemory("test-app", "test-user", "a the is").test(); + + testObserver.awaitCount(1); + testObserver.assertComplete(); + testObserver.assertValue(response -> response.memories().isEmpty()); + } + /** Tests that searchMemory handles documents with non-text content parts gracefully. */ @Test void searchMemory_withDocWithNonTextPart_returnsMemoryWithEmptyContent() { diff --git a/contrib/firestore-session-service/src/test/java/com/google/adk/runner/FirestoreDatabaseRunnerTest.java b/contrib/firestore-session-service/src/test/java/com/google/adk/runner/FirestoreDatabaseRunnerTest.java index eae6de3b40..61393ae065 100644 --- a/contrib/firestore-session-service/src/test/java/com/google/adk/runner/FirestoreDatabaseRunnerTest.java +++ b/contrib/firestore-session-service/src/test/java/com/google/adk/runner/FirestoreDatabaseRunnerTest.java @@ -17,19 +17,33 @@ package com.google.adk.runner; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.adk.agents.BaseAgent; import com.google.adk.agents.InvocationContext; import com.google.adk.agents.RunConfig; +import com.google.adk.apps.App; +import com.google.adk.artifacts.BaseArtifactService; +import com.google.adk.artifacts.GcsArtifactService; +import com.google.adk.artifacts.InMemoryArtifactService; import com.google.adk.events.Event; +import com.google.adk.memory.BaseMemoryService; +import com.google.adk.memory.FirestoreMemoryService; +import com.google.adk.platform.UuidProvider; import com.google.adk.plugins.BasePlugin; +import com.google.adk.plugins.Plugin; +import com.google.adk.sessions.BaseSessionService; +import com.google.adk.sessions.FirestoreSessionService; import com.google.adk.sessions.Session; import com.google.adk.utils.FirestoreProperties; import com.google.api.core.ApiFutures; @@ -40,16 +54,22 @@ import com.google.cloud.firestore.Query; import com.google.cloud.firestore.QuerySnapshot; import com.google.cloud.firestore.WriteResult; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; import com.google.genai.types.Content; import com.google.genai.types.Part; import io.reactivex.rxjava3.core.Flowable; +import io.reactivex.rxjava3.schedulers.Schedulers; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.time.Instant; +import java.time.InstantSource; import java.util.ArrayList; +import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; @@ -58,194 +78,607 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -/** Test class for {@link FirestoreDatabaseRunner} tests. */ +/** Unit tests for {@link FirestoreDatabaseRunner}. */ @ExtendWith(MockitoExtension.class) public class FirestoreDatabaseRunnerTest { - private static final String ENV_PROPERTY_NAME = "env"; // Renamed for clarity - - @BeforeEach - public void setup() throws Exception { - // Reset properties before each test to ensure isolation - FirestoreProperties.resetForTest(); - } + private static final String ENV_PROPERTY_NAME = "env"; @Mock private BaseAgent mockAgent; @Mock private Firestore mockFirestore; - // Mocks for the FirestoreSessionService that will be created internally + @Mock private Storage mockStorage; + + // Firestore mock chain used by legacy constructor tests @Mock private CollectionReference mockRootCollection; @Mock private DocumentReference mockUserDocRef; @Mock private CollectionReference mockSessionsCollection; @Mock private DocumentReference mockSessionDocRef; @Mock private DocumentSnapshot mockSessionSnapshot; - // Mocks for state updates - @Mock private CollectionReference mockAppStateCollection; - @Mock private DocumentReference mockAppStateDocRef; - @Mock private CollectionReference mockUserStateRootCollection; - @Mock private DocumentReference mockUserStateAppDocRef; - @Mock private CollectionReference mockUserStateUsersCollection; - @Mock private DocumentReference mockUserStateUserDocRef; @Mock private CollectionReference mockEventsCollection; @Mock private DocumentReference mockEventDocRef; @Mock private Query mockQuery; @Mock private QuerySnapshot mockQuerySnapshot; @Mock private WriteResult mockWriteResult; - /** - * Tests that the constructor succeeds when the required properties are set. - * - * @throws Exception - */ - @Test - void constructor_succeeds() throws Exception { - // Ensure the required property is set for the success case - System.setProperty(ENV_PROPERTY_NAME, "default"); // Loads adk-firestore.properties - Mockito.when(mockAgent.name()).thenReturn("test-agent"); + @BeforeEach + void setUp() { + FirestoreProperties.resetForTest(); + } - FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(mockAgent, mockFirestore); - assertNotNull(runner); + @AfterEach + void tearDown() { + FirestoreProperties.resetForTest(); + System.clearProperty(ENV_PROPERTY_NAME); } - /** - * Tests that the constructor throws an exception when the GCS bucket name property is missing. - * - * @throws Exception - */ - @Test - void constructor_withAppName_throwsExceptionWhenBucketNameIsMissing() { - assertThrows( - RuntimeException.class, - () -> { - // Arrange: Use mockito-inline to mock the static method call. - try (MockedStatic mockedProps = - Mockito.mockStatic(FirestoreProperties.class)) { - FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class); - mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance); - when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(" "); // Empty string - - // Act + // ========================================================================= + // Legacy constructor tests + // ========================================================================= + + @Nested + @SuppressWarnings("deprecation") + class LegacyConstructors { + + @Test + void constructor_succeeds() { + System.setProperty(ENV_PROPERTY_NAME, "default"); + when(mockAgent.name()).thenReturn("test-agent"); + + FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(mockAgent, mockFirestore); + assertNotNull(runner); + } + + @Test + void constructor_withAppName_usesInMemoryArtifactServiceWhenBucketNameIsBlank() { + try (MockedStatic mockedProps = + Mockito.mockStatic(FirestoreProperties.class)) { + FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class); + mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance); + when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(" "); + + Runner runner = new FirestoreDatabaseRunner( mockAgent, "test-app", new ArrayList(), mockFirestore); - } - }); + + assertEquals("test-app", runner.appName()); + assertInstanceOf(InMemoryArtifactService.class, runner.artifactService()); + } + } + + @Test + void constructor_usesInMemoryArtifactServiceWhenBucketNameIsNull() { + try (MockedStatic mockedProps = + Mockito.mockStatic(FirestoreProperties.class)) { + FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class); + mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance); + when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(null); + + Runner runner = new FirestoreDatabaseRunner(mockAgent, mockFirestore); + + assertInstanceOf(InMemoryArtifactService.class, runner.artifactService()); + } + } + + @Test + void run_withUserInput_createsSessionAndExecutesAgent() throws Exception { + System.setProperty(ENV_PROPERTY_NAME, "default"); + when(mockAgent.name()).thenReturn("test-agent"); + + String userInput = "hello\nexit\n"; + InputStream originalIn = System.in; + System.setIn(new ByteArrayInputStream(userInput.getBytes())); + + when(mockFirestore.collection("default-adk-session")).thenReturn(mockRootCollection); + when(mockRootCollection.document(anyString())).thenReturn(mockUserDocRef); + when(mockUserDocRef.collection(anyString())).thenReturn(mockSessionsCollection); + when(mockSessionsCollection.document(anyString())).thenReturn(mockSessionDocRef); + when(mockSessionDocRef.create(anyMap())) + .thenReturn(ApiFutures.immediateFuture(mockWriteResult)); + when(mockSessionDocRef.update(anyMap())) + .thenReturn(ApiFutures.immediateFuture(mockWriteResult)); + when(mockSessionDocRef.collection(anyString())).thenReturn(mockEventsCollection); + when(mockEventsCollection.document()).thenReturn(mockEventDocRef); + when(mockEventDocRef.getId()).thenReturn("test-event-id"); + when(mockEventsCollection.document(anyString())).thenReturn(mockEventDocRef); + when(mockEventDocRef.set(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult)); + when(mockSessionDocRef.get()).thenReturn(ApiFutures.immediateFuture(mockSessionSnapshot)); + when(mockSessionSnapshot.exists()).thenReturn(true); + when(mockSessionSnapshot.getData()) + .thenReturn( + Map.of( + "id", "test-session-id", + "appName", "test-app", + "userId", "test-user-id", + "updateTime", Instant.now().toString(), + "state", Map.of())); + when(mockSessionSnapshot.getReference()).thenReturn(mockSessionDocRef); + when(mockEventsCollection.orderBy(anyString())).thenReturn(mockQuery); + when(mockQuery.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot)); + + Event mockAgentEvent = + Event.builder() + .content(Content.builder().parts(Part.fromText("Hi there!")).build()) + .author(mockAgent.name()) + .build(); + when(mockAgent.runAsync(any(InvocationContext.class))) + .thenReturn(Flowable.just(mockAgentEvent)); + + FirestoreDatabaseRunner runner = + new FirestoreDatabaseRunner(mockAgent, "test-app", mockFirestore); + + Session session = + runner.sessionService().createSession("test-app", "test-user-id").blockingGet(); + Content userContent = Content.builder().parts(Part.fromText("hello")).build(); + runner + .runAsync(session.userId(), session.id(), userContent, RunConfig.builder().build()) + .blockingSubscribe(); + + ArgumentCaptor contextCaptor = + ArgumentCaptor.forClass(InvocationContext.class); + verify(mockAgent).runAsync(contextCaptor.capture()); + assertNotNull(contextCaptor.getValue().userContent().get().parts().get().get(0).text()); + + System.setIn(originalIn); + } + } + + // ========================================================================= + // Builder tests + // ========================================================================= + + @Nested + class BuilderTests { + + @Test + void create_withAgentAndFirestore_buildsRunnerWithDefaults() { + when(mockAgent.name()).thenReturn("test-agent"); + + Runner runner = FirestoreDatabaseRunner.create(mockAgent, mockFirestore); + + assertNotNull(runner); + assertEquals("test-agent", runner.appName()); + assertInstanceOf(FirestoreSessionService.class, runner.sessionService()); + assertInstanceOf(FirestoreMemoryService.class, runner.memoryService()); + // adk-firestore.properties in test resources configures test-bucket + assertInstanceOf(GcsArtifactService.class, runner.artifactService()); + } + + @Test + void create_withAgentAppNameAndFirestore_usesCustomAppName() { + Runner runner = FirestoreDatabaseRunner.create(mockAgent, "custom-app", mockFirestore); + + assertNotNull(runner); + assertEquals("custom-app", runner.appName()); + } + + @Test + void builder_withApp_buildsRunnerFromApp() { + App app = App.builder().name("my_app").rootAgent(mockAgent).build(); + + Runner runner = FirestoreDatabaseRunner.newBuilder().app(app).firestore(mockFirestore).build(); + + assertNotNull(runner); + assertEquals("my_app", runner.appName()); + assertEquals(mockAgent, runner.agent()); + } + + @Test + void builder_withAppAndExplicitAppName_usesExplicitAppName() { + App app = App.builder().name("my_app").rootAgent(mockAgent).build(); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .app(app) + .appName("custom_override") + .firestore(mockFirestore) + .build(); + + assertEquals("custom_override", runner.appName()); + } + + @Test + void builder_withAgentAndApp_throwsIllegalStateException() { + App app = App.builder().name("my_app").rootAgent(mockAgent).build(); + + assertThrows( + IllegalStateException.class, + () -> FirestoreDatabaseRunner.newBuilder().agent(mockAgent).app(app)); + + assertThrows( + IllegalStateException.class, + () -> FirestoreDatabaseRunner.newBuilder().app(app).agent(mockAgent)); + } + + @Test + void builder_withGcsArtifacts_configuresGcsArtifactService() { + when(mockAgent.name()).thenReturn("test-agent"); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .firestore(mockFirestore) + .withGcsArtifacts("test-bucket", mockStorage) + .build(); + + assertInstanceOf(GcsArtifactService.class, runner.artifactService()); + } + + @Test + void builder_whenNoGcsBucketConfigured_usesInMemoryArtifactService() { + when(mockAgent.name()).thenReturn("test-agent"); + try (MockedStatic mockedProps = + Mockito.mockStatic(FirestoreProperties.class)) { + FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class); + mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance); + when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(null); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .firestore(mockFirestore) + .build(); + assertInstanceOf(InMemoryArtifactService.class, runner.artifactService()); + + } + } + + @Test + void builder_withExplicitInMemoryArtifactService_succeedsWithoutGcsBucket() { + when(mockAgent.name()).thenReturn("test-agent"); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .firestore(mockFirestore) + .artifactService(new InMemoryArtifactService()) + .build(); + + assertInstanceOf(InMemoryArtifactService.class, runner.artifactService()); + } + + @Test + void builder_withExplicitArtifactService_usesProvidedArtifactService() { + when(mockAgent.name()).thenReturn("test-agent"); + BaseArtifactService mockArtifactService = mock(BaseArtifactService.class); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .firestore(mockFirestore) + .artifactService(mockArtifactService) + .build(); + + assertEquals(mockArtifactService, runner.artifactService()); + } + + @Test + void builder_withCustomSessionAndMemoryServices_doesNotRequireFirestore() { + when(mockAgent.name()).thenReturn("test-agent"); + BaseSessionService customSessionService = mock(BaseSessionService.class); + BaseMemoryService customMemoryService = mock(BaseMemoryService.class); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .sessionService(customSessionService) + .memoryService(customMemoryService) + .build(); + + assertEquals(customSessionService, runner.sessionService()); + assertEquals(customMemoryService, runner.memoryService()); + } + + @Test + void builder_missingAgentAndApp_throwsIllegalStateException() { + assertThrows( + IllegalStateException.class, + () -> FirestoreDatabaseRunner.newBuilder().firestore(mockFirestore).build()); + } + + @Test + void builder_missingFirestoreAndServices_throwsIllegalStateException() { + assertThrows( + IllegalStateException.class, + () -> FirestoreDatabaseRunner.newBuilder().agent(mockAgent).build()); + } + + @Test + void builder_withCustomProvidersAndScheduler_passesThroughToRunner() { + when(mockAgent.name()).thenReturn("test-agent"); + InstantSource fixedSource = InstantSource.fixed(Instant.parse("2025-01-01T00:00:00Z")); + UuidProvider customUuid = () -> "fixed-uuid"; + Plugin mockPlugin = mock(Plugin.class); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .firestore(mockFirestore) + .instantSource(fixedSource) + .uuidProvider(customUuid) + .scheduler(Schedulers.trampoline()) + .plugins(List.of(mockPlugin)) + .build(); + + assertNotNull(runner); + } + + @Test + void builder_withOnlySessionServiceProvided_usesFirestoreForMemoryService() { + when(mockAgent.name()).thenReturn("test-agent"); + BaseSessionService customSessionService = mock(BaseSessionService.class); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .firestore(mockFirestore) + .sessionService(customSessionService) + .build(); + + assertSame(customSessionService, runner.sessionService()); + assertInstanceOf(FirestoreMemoryService.class, runner.memoryService()); + } + + @Test + void toRunnerBuilder_allowsFurtherCustomization() { + when(mockAgent.name()).thenReturn("test-agent"); + + Runner.Builder runnerBuilder = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .firestore(mockFirestore) + .toRunnerBuilder(); + + Runner runner = runnerBuilder.build(); + assertNotNull(runner); + assertEquals("test-agent", runner.appName()); + } + } + + @Test + void builder_withCustomArtifactServiceAndGcsBucket_usesCustomArtifactService() { + when(mockAgent.name()).thenReturn("test-agent"); + BaseArtifactService customArtifactService = mock(BaseArtifactService.class); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .firestore(mockFirestore) + .withGcsArtifacts("test-bucket", mockStorage) + .artifactService(customArtifactService) + .build(); + + assertEquals(customArtifactService, runner.artifactService()); } - /** - * Tests that the constructor throws an exception when the GCS bucket name is null. - * - * @throws Exception - */ @Test - void constructor_throwsExceptionWhenBucketNameIsNull() { - assertThrows( - RuntimeException.class, - () -> { - // Arrange: Use mockito-inline to mock the static method call. - try (MockedStatic mockedProps = - Mockito.mockStatic(FirestoreProperties.class)) { - FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class); - mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance); - when(mockPropsInstance.getGcsAdkBucketName()) - .thenReturn(null); // Explicitly return null for bucketName - // Act - new FirestoreDatabaseRunner(mockAgent, mockFirestore); - } - }); + void builder_withCustomServices_wiresServicesCorrectly() { + System.setProperty(ENV_PROPERTY_NAME, "default"); + try { + Firestore mockFirestore = mock(Firestore.class); + String appName = "test-app"; + GcsArtifactService customArtifactService = + new GcsArtifactService("test-bucket", mockStorage); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .appName(appName) + .firestore(mockFirestore) + .artifactService(customArtifactService) + .build(); + + assertEquals(appName, runner.appName()); + assertInstanceOf(FirestoreSessionService.class, runner.sessionService()); + assertSame(customArtifactService, runner.artifactService()); + } finally { + System.clearProperty(ENV_PROPERTY_NAME); + } } - /** - * Tests that run with user input creates a session and executes the agent. - * - * @throws Exception - */ @Test - void run_withUserInput_createsSessionAndExecutesAgent() throws Exception { - // Arrange - System.setProperty(ENV_PROPERTY_NAME, "default"); // Ensure properties are loaded - when(mockAgent.name()).thenReturn("test-agent"); + void builder_withCustomServices_wiresServicesCorrectlyNoArtifactService() { + System.setProperty(ENV_PROPERTY_NAME, "default"); + try { + Firestore mockFirestore = mock(Firestore.class); + String appName = "test-app"; - // Mock user input - String userInput = "hello\nexit\n"; - InputStream originalIn = System.in; - System.setIn(new ByteArrayInputStream(userInput.getBytes())); + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .appName(appName) + .firestore(mockFirestore) + .build(); - // Mock the Firestore calls that SessionService will make - when(mockFirestore.collection("default-adk-session")).thenReturn(mockRootCollection); + assertEquals(appName, runner.appName()); + assertInstanceOf(FirestoreSessionService.class, runner.sessionService()); + } finally { + System.clearProperty(ENV_PROPERTY_NAME); + } + } + + @Test + void builder_withCustomArtifactService_runsAgentAndProducesEvents() { + System.setProperty(ENV_PROPERTY_NAME, "default"); + + String appName = "test-app"; + GcsArtifactService customArtifactService = new GcsArtifactService("test-bucket", mockStorage); + + when(mockFirestore.collection(anyString())).thenReturn(mockRootCollection); when(mockRootCollection.document(anyString())).thenReturn(mockUserDocRef); when(mockUserDocRef.collection(anyString())).thenReturn(mockSessionsCollection); when(mockSessionsCollection.document(anyString())).thenReturn(mockSessionDocRef); - - when(mockSessionDocRef.create(anyMap())) - .thenReturn(ApiFutures.immediateFuture(mockWriteResult)); - when(mockSessionDocRef.update(anyMap())) - .thenReturn(ApiFutures.immediateFuture(mockWriteResult)); - // Mock the event sub-collection chain + when(mockSessionDocRef.create(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult)); + when(mockSessionDocRef.update(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult)); when(mockSessionDocRef.collection(anyString())).thenReturn(mockEventsCollection); - // THIS IS THE MISSING MOCK: Stub the no-arg document() call for ID generation. when(mockEventsCollection.document()).thenReturn(mockEventDocRef); when(mockEventDocRef.getId()).thenReturn("test-event-id"); when(mockEventsCollection.document(anyString())).thenReturn(mockEventDocRef); when(mockEventDocRef.set(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult)); - // THIS IS THE MISSING MOCK: Stub the get() call on the session document. when(mockSessionDocRef.get()).thenReturn(ApiFutures.immediateFuture(mockSessionSnapshot)); when(mockSessionSnapshot.exists()).thenReturn(true); - // Provide a complete map for the session data when(mockSessionSnapshot.getData()) .thenReturn( Map.of( "id", "test-session-id", - "appName", "test-app", - "userId", "test-user-id", + "appName", appName, + "userId", "user1234", "updateTime", Instant.now().toString(), "state", Map.of())); when(mockSessionSnapshot.getReference()).thenReturn(mockSessionDocRef); - // THIS IS THE MISSING MOCK: Stub the orderBy() call on the events collection. when(mockEventsCollection.orderBy(anyString())).thenReturn(mockQuery); when(mockQuery.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot)); - // Mock Agent behavior - Event mockAgentEvent = - Event.builder() - .content(Content.builder().parts(Part.fromText("Hi there!")).build()) - .author(mockAgent.name()) + BaseAgent testAgent = + new BaseAgent("test-agent", "Test agent", List.of(), List.of(), List.of()) { + @Override + protected Flowable runAsyncImpl(InvocationContext invocationContext) { + return Flowable.just( + Event.builder() + .id(Event.generateEventId()) + .invocationId(invocationContext.invocationId()) + .author(name()) + .content(Content.fromParts(Part.fromText("Hello from test agent!"))) + .build()); + } + + @Override + protected Flowable runLiveImpl(InvocationContext invocationContext) { + return Flowable.error(new UnsupportedOperationException("Live mode not supported")); + } + }; + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(testAgent) + .appName(appName) + .firestore(mockFirestore) + .artifactService(customArtifactService) .build(); - when(mockAgent.runAsync(any(InvocationContext.class))) - .thenReturn(Flowable.just(mockAgentEvent)); - - // Create runner, which will internally create a FirestoreSessionService - // using our mocked Firestore object. - FirestoreDatabaseRunner runner = - new FirestoreDatabaseRunner(mockAgent, "test-app", mockFirestore); - - // Act - // First, create a session to get a valid session ID - Session session = - runner.sessionService().createSession("test-app", "test-user-id").blockingGet(); - // Now, run the agent with the user input - Content userContent = Content.builder().parts(Part.fromText("hello")).build(); - runner - .runAsync(session.userId(), session.id(), userContent, RunConfig.builder().build()) - .blockingSubscribe(); // block until the flow completes - - // Assert - ArgumentCaptor contextCaptor = - ArgumentCaptor.forClass(InvocationContext.class); - verify(mockAgent).runAsync(contextCaptor.capture()); - assertNotNull(contextCaptor.getValue().userContent().get().parts().get().get(0).text()); - - // Restore original System.in - System.setIn(originalIn); + + assertSame(customArtifactService, runner.artifactService()); + + Session session = runner.sessionService().createSession(appName, "user1234").blockingGet(); + assertNotNull(session); + + List events = + runner + .runAsync(session.userId(), session.id(), Content.fromParts(Part.fromText("Hello!")), + RunConfig.builder().build()) + .toList() + .blockingGet(); + + assertEquals(1, events.size()); + assertEquals("test-agent", events.get(0).author()); + assertEquals("Hello from test agent!", events.get(0).stringifyContent()); } - /** - * Cleans up after each test. - * - * @throws Exception - */ - @AfterEach - public void teardown() throws Exception { - // Clean up the environment variable after each test - FirestoreProperties.resetForTest(); // Reset the singleton instance - System.clearProperty(ENV_PROPERTY_NAME); // Clear the system property + @Test + void builder_withMultiplePluginCalls_accumulatesPlugins() { + Firestore mockFirestore = mock(Firestore.class); + Plugin plugin1 = new BasePlugin("plugin-1") {}; + Plugin plugin2 = new BasePlugin("plugin-2") {}; + Plugin plugin3 = new BasePlugin("plugin-3") {}; + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .appName("test-app") + .firestore(mockFirestore) + .plugins(plugin1) + .plugins(plugin2, plugin3) + .build(); + + assertSame(plugin1, runner.pluginManager().getPlugin("plugin-1").orElseThrow()); + assertSame(plugin2, runner.pluginManager().getPlugin("plugin-2").orElseThrow()); + assertSame(plugin3, runner.pluginManager().getPlugin("plugin-3").orElseThrow()); + } + + @Test + void builder_withGcsArtifactsBucketOnly_usesDefaultStorageOptions() { + Firestore mockFirestore = mock(Firestore.class); + StorageOptions mockStorageOptions = mock(StorageOptions.class); + Storage mockDefaultStorage = mock(Storage.class); + when(mockStorageOptions.getService()).thenReturn(mockDefaultStorage); + + try (MockedStatic storageOptionsStatic = mockStatic(StorageOptions.class)) { + storageOptionsStatic.when(StorageOptions::getDefaultInstance).thenReturn(mockStorageOptions); + + Runner runner = + FirestoreDatabaseRunner.newBuilder() + .agent(mockAgent) + .appName("test-app") + .firestore(mockFirestore) + .withGcsArtifacts("test-bucket") + .build(); + + assertInstanceOf(GcsArtifactService.class, runner.artifactService()); + storageOptionsStatic.verify(StorageOptions::getDefaultInstance); + verify(mockStorageOptions).getService(); + } } + + @Test + @SuppressWarnings("deprecation") + void resolveDefaultArtifactService_whenBucketIsNull_returnsInMemoryArtifactService() { + assertInMemoryArtifactServiceForBucket(null); + } + + @Test + @SuppressWarnings("deprecation") + void resolveDefaultArtifactService_whenBucketIsEmpty_returnsInMemoryArtifactService() { + assertInMemoryArtifactServiceForBucket(""); + } + + @Test + @SuppressWarnings("deprecation") + void resolveDefaultArtifactService_whenBucketIsBlank_returnsInMemoryArtifactService() { + assertInMemoryArtifactServiceForBucket(" "); + } + + @SuppressWarnings("deprecation") + private void assertInMemoryArtifactServiceForBucket(String bucketName) { + try (MockedStatic mockedProps = + Mockito.mockStatic(FirestoreProperties.class); + MockedStatic mockedStorageOptions = + Mockito.mockStatic(StorageOptions.class)) { + FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class); + mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance); + when(mockPropsInstance.getGcsAdkBucketName()).thenReturn(bucketName); + + Runner runner = + new FirestoreDatabaseRunner( + mockAgent, "test-app", new ArrayList(), mockFirestore); + + assertInstanceOf(InMemoryArtifactService.class, runner.artifactService()); + mockedStorageOptions.verifyNoInteractions(); + } + } + + @Test + @SuppressWarnings("deprecation") + void resolveDefaultArtifactService_whenBucketConfigured_returnsGcsArtifactService() { + StorageOptions mockStorageOptions = mock(StorageOptions.class); + Storage mockStorage = mock(Storage.class); + when(mockStorageOptions.getService()).thenReturn(mockStorage); + + try (MockedStatic mockedProps = + Mockito.mockStatic(FirestoreProperties.class); + MockedStatic mockedStorageOptions = + Mockito.mockStatic(StorageOptions.class)) { + FirestoreProperties mockPropsInstance = mock(FirestoreProperties.class); + mockedProps.when(FirestoreProperties::getInstance).thenReturn(mockPropsInstance); + when(mockPropsInstance.getGcsAdkBucketName()).thenReturn("my-test-bucket"); + mockedStorageOptions + .when(StorageOptions::getDefaultInstance) + .thenReturn(mockStorageOptions); + + Runner runner = + new FirestoreDatabaseRunner( + mockAgent, "test-app", new ArrayList(), mockFirestore); + + assertInstanceOf(GcsArtifactService.class, runner.artifactService()); + mockedStorageOptions.verify(StorageOptions::getDefaultInstance); + verify(mockStorageOptions).getService(); + } + } } diff --git a/contrib/firestore-session-service/src/test/java/com/google/adk/sessions/FirestoreSessionServiceTest.java b/contrib/firestore-session-service/src/test/java/com/google/adk/sessions/FirestoreSessionServiceTest.java index d4b15b3a52..5dc59e74fc 100644 --- a/contrib/firestore-session-service/src/test/java/com/google/adk/sessions/FirestoreSessionServiceTest.java +++ b/contrib/firestore-session-service/src/test/java/com/google/adk/sessions/FirestoreSessionServiceTest.java @@ -1575,6 +1575,161 @@ void deleteSession_appNameMismatch_doesNotDelete() { verify(mockWriteBatch, never()).commit(); } + /** Tests that appendEvent with a regular (non-prefixed) state key updates session state. */ + @Test + void appendEvent_withRegularStateDeltaKey_updatesSessionState() { + Session session = + Session.builder(SESSION_ID) + .appName(APP_NAME) + .userId(USER_ID) + .state(new ConcurrentHashMap<>()) + .build(); + + EventActions actions = + EventActions.builder() + .stateDelta(new ConcurrentHashMap<>(ImmutableMap.of("myKey", "myValue"))) + .build(); + + Event event = + Event.builder() + .author("model") + .content(Content.builder().parts(List.of(Part.fromText("."))).build()) + .actions(actions) + .build(); + + when(mockSessionsCollection.document(SESSION_ID)).thenReturn(mockSessionDocRef); + when(mockEventsCollection.document()).thenReturn(mockEventDocRef); + when(mockEventDocRef.getId()).thenReturn(EVENT_ID); + when(mockEventsCollection.document(EVENT_ID)).thenReturn(mockEventDocRef); + when(mockSessionDocRef.update(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult)); + + sessionService.appendEvent(session, event).test().assertComplete(); + + assertThat(session.state()).containsEntry("myKey", "myValue"); + } + + /** Tests that deleteSession silently succeeds when the session has no events. */ + @Test + void deleteSession_whenSessionHasNoEvents_deletesSessionDocumentOnly() { + when(mockSessionsCollection.document(SESSION_ID)).thenReturn(mockSessionDocRef); + when(mockSessionDocRef.get()).thenReturn(ApiFutures.immediateFuture(mockSessionSnapshot)); + when(mockSessionSnapshot.exists()).thenReturn(true); + when(mockSessionSnapshot.get(Constants.KEY_APP_NAME)).thenReturn(APP_NAME); + when(mockSessionDocRef.collection(Constants.EVENTS_SUBCOLLECTION_NAME)) + .thenReturn(mockEventsCollection); + when(mockEventsCollection.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot)); + when(mockQuerySnapshot.getDocuments()).thenReturn(Collections.emptyList()); + + sessionService.deleteSession(APP_NAME, USER_ID, SESSION_ID).test().assertComplete(); + + verify(mockWriteBatch, never()).commit(); + verify(mockSessionDocRef).delete(); + } + + /** Tests that listSessions silently skips documents whose data() returns null. */ + @Test + void listSessions_whenDocumentDataIsNull_skipsDocument() { + when(mockSessionsCollection.whereEqualTo(Constants.KEY_APP_NAME, APP_NAME)) + .thenReturn(mockQuery); + when(mockQuery.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot)); + + QueryDocumentSnapshot nullDataDoc = mock(QueryDocumentSnapshot.class); + when(nullDataDoc.getData()).thenReturn(null); + + QueryDocumentSnapshot validDoc = mock(QueryDocumentSnapshot.class); + when(validDoc.getData()) + .thenReturn( + ImmutableMap.of( + "id", SESSION_ID, + "appName", APP_NAME, + "userId", USER_ID, + "updateTime", NOW.toString())); + + when(mockQuerySnapshot.getDocuments()).thenReturn(ImmutableList.of(nullDataDoc, validDoc)); + + TestObserver testObserver = + sessionService.listSessions(APP_NAME, USER_ID).test(); + + testObserver.awaitCount(1); + testObserver.assertComplete(); + testObserver.assertValue(response -> response.sessions().size() == 1); + } + + /** + * Tests that getSession gracefully skips a part whose "functionCall" value is not a Map, + * exercising the safeCast type-mismatch path and functionCallPartFromMap(null). + */ + @Test + void getSession_withNonMapFunctionCallValue_skipsInvalidPart() { + when(mockSessionsCollection.document(SESSION_ID)).thenReturn(mockSessionDocRef); + when(mockSessionDocRef.get()).thenReturn(ApiFutures.immediateFuture(mockSessionSnapshot)); + when(mockSessionSnapshot.exists()).thenReturn(true); + when(mockSessionSnapshot.getReference()).thenReturn(mockSessionDocRef); + when(mockSessionSnapshot.getData()) + .thenReturn( + ImmutableMap.of( + "id", SESSION_ID, + "appName", APP_NAME, + "userId", USER_ID, + "updateTime", NOW.toString(), + "state", Collections.emptyMap())); + + // Event with a "functionCall" value that is a String, not a Map + when(mockEventSnapshot.getData()) + .thenReturn( + ImmutableMap.of( + Constants.KEY_AUTHOR, "agent", + Constants.KEY_TIMESTAMP, NOW.toString(), + "content", + ImmutableMap.of( + "parts", ImmutableList.of(ImmutableMap.of("functionCall", "not-a-map"))))); + when(mockQuery.get()).thenReturn(ApiFutures.immediateFuture(mockQuerySnapshot)); + when(mockQuerySnapshot.getDocuments()).thenReturn(ImmutableList.of(mockEventSnapshot)); + + TestObserver testObserver = + sessionService.getSession(APP_NAME, USER_ID, SESSION_ID, Optional.empty()).test(); + + testObserver.awaitCount(1); + testObserver.assertComplete(); + testObserver.assertValue( + session -> { + // The malformed part is skipped; the event is still returned with empty parts + assertThat(session.events()).hasSize(1); + return true; + }); + } + + /** Tests that appendEvent with an empty-string text part does not add it to keywords. */ + @Test + @SuppressWarnings("unchecked") + void appendEvent_withEmptyStringTextPart_producesNoKeywords() { + Session session = + Session.builder(SESSION_ID) + .appName(APP_NAME) + .userId(USER_ID) + .state(new ConcurrentHashMap<>()) + .build(); + + Event event = + Event.builder() + .author("model") + .content(Content.builder().parts(List.of(Part.fromText(""))).build()) + .build(); + + when(mockSessionsCollection.document(SESSION_ID)).thenReturn(mockSessionDocRef); + when(mockEventsCollection.document()).thenReturn(mockEventDocRef); + when(mockEventDocRef.getId()).thenReturn(EVENT_ID); + when(mockEventsCollection.document(EVENT_ID)).thenReturn(mockEventDocRef); + when(mockSessionDocRef.update(anyMap())).thenReturn(ApiFutures.immediateFuture(mockWriteResult)); + + sessionService.appendEvent(session, event).test().assertComplete(); + + ArgumentCaptor> eventCaptor = ArgumentCaptor.forClass(Map.class); + verify(mockEventDocRef).set(eventCaptor.capture()); + // keywords key is omitted entirely when the extracted set is empty + assertThat(eventCaptor.getValue()).doesNotContainKey("keywords"); + } + private static AlreadyExistsException alreadyExists() { return new AlreadyExistsException( "Document already exists", diff --git a/contrib/firestore-session-service/src/test/java/com/google/adk/utils/ConstantsTest.java b/contrib/firestore-session-service/src/test/java/com/google/adk/utils/ConstantsTest.java index d582e47759..d2f6ee8ff5 100644 --- a/contrib/firestore-session-service/src/test/java/com/google/adk/utils/ConstantsTest.java +++ b/contrib/firestore-session-service/src/test/java/com/google/adk/utils/ConstantsTest.java @@ -26,7 +26,8 @@ public class ConstantsTest { /** Test to verify that the root collection name is as expected. */ @Test void testRootCollectionName() { - String rootCollectionName = FirestoreProperties.getInstance().getFirebaseRootCollectionName(); + String rootCollectionName = + FirestoreProperties.getInstance().getFirestoreRootCollectionName(); assertThat(rootCollectionName).isEqualTo("default-adk-session"); } } diff --git a/contrib/firestore-session-service/src/test/java/com/google/adk/utils/FirestorePropertiesTest.java b/contrib/firestore-session-service/src/test/java/com/google/adk/utils/FirestorePropertiesTest.java index 7f2cfb4382..0361bce2b9 100644 --- a/contrib/firestore-session-service/src/test/java/com/google/adk/utils/FirestorePropertiesTest.java +++ b/contrib/firestore-session-service/src/test/java/com/google/adk/utils/FirestorePropertiesTest.java @@ -17,14 +17,18 @@ package com.google.adk.utils; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashSet; import java.util.Map; +import java.util.Properties; +import java.util.Set; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -96,7 +100,7 @@ public void teardown() { void shouldLoadDefaultPropertiesWhenEnvIsNotSet() { FirestoreProperties props = FirestoreProperties.getInstance(); - assertEquals("default-adk-session", props.getFirebaseRootCollectionName()); + assertEquals("default-adk-session", props.getFirestoreRootCollectionName()); assertEquals("default_value", props.getProperty("another.default.property")); assertEquals("common_default", props.getProperty("common.property")); assertNull(props.getProperty("non.existent.property")); @@ -112,7 +116,7 @@ void shouldLoadDefaultPropertiesWhenEnvIsEmpty() throws Exception { setEnv(ENV_VAR_NAME, ""); FirestoreProperties props = FirestoreProperties.getInstance(); - assertEquals("default-adk-session", props.getFirebaseRootCollectionName()); + assertEquals("default-adk-session", props.getFirestoreRootCollectionName()); assertEquals("default_value", props.getProperty("another.default.property")); } @@ -126,7 +130,7 @@ void shouldLoadDevPropertiesWhenEnvIsSetToDev() throws Exception { setEnv(ENV_VAR_NAME, "dev"); FirestoreProperties props = FirestoreProperties.getInstance(); - assertEquals("dev-adk-session-override", props.getFirebaseRootCollectionName()); + assertEquals("dev-adk-session-override", props.getFirestoreRootCollectionName()); assertEquals("dev_value", props.getProperty("dev.specific.property")); assertEquals("common_dev", props.getProperty("common.property")); // Check overridden property // In JUnit 5, the message is the second argument. @@ -147,7 +151,7 @@ void shouldFallbackToDefaultWhenEnvSpecificFileNotFound() throws Exception { setEnv(ENV_VAR_NAME, "nonexistent"); FirestoreProperties props = FirestoreProperties.getInstance(); - assertEquals("default-adk-session", props.getFirebaseRootCollectionName()); + assertEquals("default-adk-session", props.getFirestoreRootCollectionName()); assertEquals("default_value", props.getProperty("another.default.property")); } @@ -159,12 +163,12 @@ void shouldFallbackToDefaultWhenEnvSpecificFileNotFound() throws Exception { @Test void shouldReturnHardcodedDefaultIfPropertyFileHasNoEntry() throws Exception { // This test requires 'src/test/resources/adk-firestore-empty.properties' - // which contains some properties but NOT 'firebase.root.collection.name' + // which contains some properties but NOT 'firestore.root.collection.name' setEnv(ENV_VAR_NAME, "empty"); FirestoreProperties props = FirestoreProperties.getInstance(); // Should fall back to the hardcoded default value - assertEquals("adk-session", props.getFirebaseRootCollectionName()); + assertEquals("adk-session", props.getFirestoreRootCollectionName()); // Verify that it did load the correct file assertEquals("other_value", props.getProperty("other.key")); } @@ -172,6 +176,9 @@ void shouldReturnHardcodedDefaultIfPropertyFileHasNoEntry() throws Exception { @Test void getInstanceShouldReturnAnInstance() { assertNotNull(FirestoreProperties.getInstance()); + assertEquals( + FirestoreProperties.getInstance().getFirestoreRootCollectionName(), + FirestoreProperties.getInstance().getFirebaseRootCollectionName()); } /** @@ -197,4 +204,41 @@ void shouldReturnDefaultStopWordsWhenPropertyNotSet() throws Exception { assertEquals(expectedStopWords, props.getStopWords()); } + + /** Tests that a blank (whitespace-only) env var is treated the same as unset. */ + @Test + void shouldLoadDefaultPropertiesWhenEnvIsBlankWhitespace() throws Exception { + setEnv(ENV_VAR_NAME, " "); + FirestoreProperties props = FirestoreProperties.getInstance(); + + assertEquals("default-adk-session", props.getFirestoreRootCollectionName()); + } + + /** Tests that a blank firestore.root.collection.name falls back to the hardcoded default. */ + @Test + void getFirestoreRootCollectionName_whenPropertyIsBlank_fallsBackToDefault() throws Exception { + FirestoreProperties props = FirestoreProperties.getInstance(); + Field propsField = FirestoreProperties.class.getDeclaredField("properties"); + propsField.setAccessible(true); + Properties internalProps = (Properties) propsField.get(props); + internalProps.setProperty("firestore.root.collection.name", " "); + internalProps.remove("firebase.root.collection.name"); + + assertEquals("adk-session", props.getFirestoreRootCollectionName()); + } + + /** Tests that a blank keyword.extraction.stopwords falls back to the default stop-word set. */ + @Test + void getStopWords_whenPropertyIsBlank_returnsDefaultStopWords() throws Exception { + FirestoreProperties props = FirestoreProperties.getInstance(); + Field propsField = FirestoreProperties.class.getDeclaredField("properties"); + propsField.setAccessible(true); + Properties internalProps = (Properties) propsField.get(props); + internalProps.setProperty("keyword.extraction.stopwords", " "); + + Set stopWords = props.getStopWords(); + assertNotNull(stopWords); + assertFalse(stopWords.isEmpty()); + assertTrue(stopWords.contains("a")); + } } diff --git a/contrib/firestore-session-service/src/test/resources/adk-firestore-dev.properties b/contrib/firestore-session-service/src/test/resources/adk-firestore-dev.properties index 0fe168f704..07a9d7e819 100644 --- a/contrib/firestore-session-service/src/test/resources/adk-firestore-dev.properties +++ b/contrib/firestore-session-service/src/test/resources/adk-firestore-dev.properties @@ -1,4 +1,4 @@ -firebase.root.collection.name=dev-adk-session-override +firestore.root.collection.name=dev-adk-session-override dev.specific.property=dev_value common.property=common_dev gcs.adk.bucket.name=test-bucket \ No newline at end of file diff --git a/contrib/firestore-session-service/src/test/resources/adk-firestore.properties b/contrib/firestore-session-service/src/test/resources/adk-firestore.properties index dbbd74310b..7f0d1330f1 100644 --- a/contrib/firestore-session-service/src/test/resources/adk-firestore.properties +++ b/contrib/firestore-session-service/src/test/resources/adk-firestore.properties @@ -1,4 +1,4 @@ -firebase.root.collection.name=default-adk-session +firestore.root.collection.name=default-adk-session another.default.property=default_value common.property=common_default gcs.adk.bucket.name=test-bucket