diff --git a/storage/api/Storage.Samples.Tests/StorageControlRapidCacheTest.cs b/storage/api/Storage.Samples.Tests/StorageControlRapidCacheTest.cs new file mode 100644 index 00000000000..9ee8e902345 --- /dev/null +++ b/storage/api/Storage.Samples.Tests/StorageControlRapidCacheTest.cs @@ -0,0 +1,157 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"). +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Google.Cloud.Storage.Control.V2; +using Google.LongRunning; +using System; +using System.Linq; +using System.Threading; +using Xunit; +using Bucket = Google.Apis.Storage.v1.Data.Bucket; + +namespace Storage.Samples.Tests; + +[Collection(nameof(StorageFixture))] +public class StorageControlRapidCacheTest : IDisposable +{ + private const string RapidCacheType = "rapid-cache-ultra"; + + // The cache moves to the "disabled" state within seconds of the disable request, so the + // test polls for that state for up to 2 minutes. + private const int StatePollAttempts = 12; + private static readonly TimeSpan s_statePollInterval = TimeSpan.FromSeconds(10); + + private readonly StorageFixture _fixture; + private readonly string _zone; + + // The Rapid Cache ID is the same as the zone. + private readonly string _rapidCacheId; + + // Set by the test so that Dispose can clean up whatever was created. + private string _bucketName; + private bool _cacheActive; + + public StorageControlRapidCacheTest(StorageFixture fixture) + { + _fixture = fixture; + _zone = Environment.GetEnvironmentVariable("RAPID_CACHE_ZONE") ?? "us-central1-a"; + _rapidCacheId = _zone; + } + + // Rapid Cache requires an allowlisted project and the bucket can't be deleted until the + // disabled cache has been fully removed (which can take more than an hour), so this + // test is excluded from CI, following the Anywhere Cache samples which have no CI tests. + [Fact(Skip = "b/482946642: Rapid Cache requires an allowlisted project; run manually.")] + public void TestStorageControlRapidCacheLifecycle() + { + _bucketName = _fixture.GenerateBucketName(); + CreateRegionalHnsBucket(_bucketName); + + string rapidCacheName = RapidCacheName.FormatProjectBucketRapidCache("_", _bucketName, _rapidCacheId); + + // Create + var createSample = new StorageControlCreateRapidCacheSample(); + RapidCache created = createSample.StorageControlCreateRapidCache(_bucketName, _zone); + _cacheActive = true; + Assert.Equal(rapidCacheName, created.Name); + Assert.Equal(RapidCacheType, created.CacheType); + + // Get + var getSample = new StorageControlGetRapidCacheSample(); + RapidCache fetched = getSample.StorageControlGetRapidCache(_bucketName, _rapidCacheId); + Assert.Equal(rapidCacheName, fetched.Name); + Assert.Equal(_zone, fetched.Zone); + Assert.Equal("running", fetched.State); + Assert.Equal(RapidCacheType, fetched.CacheType); + + // List + var listSample = new StorageControlListRapidCachesSample(); + var caches = listSample.StorageControlListRapidCaches(_bucketName).ToList(); + Assert.Contains(caches, cache => cache.Name == rapidCacheName); + + // Update + var updateSample = new StorageControlUpdateRapidCacheSample(); + RapidCache updated = updateSample.StorageControlUpdateRapidCache(_bucketName, _rapidCacheId, 172800); + Assert.Equal(rapidCacheName, updated.Name); + Assert.Equal(172800L, updated.Ttl.Seconds); + + // Disable. The operation only completes once the cache has been fully removed, so the + // test checks for the "disabled" state instead of waiting for the operation. + var disableSample = new StorageControlDisableRapidCacheSample(); + Operation operation = + disableSample.StorageControlDisableRapidCache(_bucketName, _rapidCacheId); + _cacheActive = false; + Assert.False(string.IsNullOrEmpty(operation.Name)); + Assert.Equal("disabled", WaitForState(getSample, "disabled")); + } + + // Disables the cache if the test left it active. This is best-effort so that teardown + // never hides the original test failure. The bucket is registered in the fixture, which + // makes a best-effort attempt to delete it when it is disposed. That attempt usually fails + // because the bucket can't be deleted until the disabled cache has been fully removed, so + // the bucket may need to be deleted manually later. + public void Dispose() + { + if (_bucketName is null || !_cacheActive) + { + return; + } + try + { + new StorageControlDisableRapidCacheSample().StorageControlDisableRapidCache(_bucketName, _rapidCacheId); + } + catch (Exception e) + { + Console.WriteLine($"Best-effort disable of Rapid Cache {_rapidCacheId} in bucket {_bucketName}: {e.Message}"); + } + } + + // Polls the cache until it reaches the expected state or the attempts run out, and + // returns the last observed state. + private string WaitForState(StorageControlGetRapidCacheSample getSample, string expectedState) + { + string state = null; + for (int attempt = 1; attempt <= StatePollAttempts; attempt++) + { + state = getSample.StorageControlGetRapidCache(_bucketName, _rapidCacheId).State; + if (state == expectedState || attempt == StatePollAttempts) + { + break; + } + Thread.Sleep(s_statePollInterval); + } + return state; + } + + // Rapid Cache Ultra requires a regional, hierarchical namespace enabled bucket in the + // region of the cache zone. + private void CreateRegionalHnsBucket(string bucketName) + { + int lastHyphen = _zone.LastIndexOf('-'); + string region = lastHyphen > 0 ? _zone.Substring(0, lastHyphen) : _zone; + _fixture.Client.CreateBucket(_fixture.ProjectId, new Bucket + { + Name = bucketName, + Location = region, + IamConfiguration = new Bucket.IamConfigurationData + { + UniformBucketLevelAccess = new Bucket.IamConfigurationData.UniformBucketLevelAccessData { Enabled = true } + }, + HierarchicalNamespace = new Bucket.HierarchicalNamespaceData { Enabled = true } + }); + // Register the bucket right away so the fixture cleans it up even if the test aborts. + _fixture.TempBucketNames.Add(bucketName); + _fixture.SleepAfterBucketCreateUpdateDelete(); + } +} diff --git a/storage/api/Storage.Samples/Storage.Samples.csproj b/storage/api/Storage.Samples/Storage.Samples.csproj index fca943768b8..33fd9b0f522 100644 --- a/storage/api/Storage.Samples/Storage.Samples.csproj +++ b/storage/api/Storage.Samples/Storage.Samples.csproj @@ -5,7 +5,7 @@ - + diff --git a/storage/api/Storage.Samples/StorageControlCreateRapidCache.cs b/storage/api/Storage.Samples/StorageControlCreateRapidCache.cs new file mode 100644 index 00000000000..f10d259a4b4 --- /dev/null +++ b/storage/api/Storage.Samples/StorageControlCreateRapidCache.cs @@ -0,0 +1,65 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"). +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// [START storage_control_create_rapid_cache] + +using Google.Cloud.Storage.Control.V2; +using Google.LongRunning; +using System; + +public class StorageControlCreateRapidCacheSample +{ + /// + /// Creates a Rapid Cache instance for the specified bucket. Only the required fields are + /// set; optional settings such as the time to live (TTL) use the server defaults and can be + /// changed later with an update. + /// + /// The name of the bucket. + /// The zone in which to create the Rapid Cache. The zone must be in the same region as the bucket. + public RapidCache StorageControlCreateRapidCache(string bucketName = "your-unique-bucket-name", + string zone = "us-central1-a") + { + StorageControlClient storageControlClient = StorageControlClient.Create(); + + // Set project to "_" to signify globally scoped bucket. + string parent = $"projects/_/buckets/{bucketName}"; + + // Rapid Cache Ultra requires a regional bucket with hierarchical namespace enabled, + // in the same region as the cache zone. The server derives the cache name from the + // bucket and the zone, so the name doesn't need to be set. + RapidCache rapidCache = new RapidCache + { + Zone = zone, + CacheType = "rapid-cache-ultra" + }; + + CreateRapidCacheRequest request = new CreateRapidCacheRequest + { + Parent = parent, + RapidCache = rapidCache + }; + + // Creating a Rapid Cache is a long-running operation (LRO). + Operation operation = storageControlClient.CreateRapidCache(request); + + // Await the LRO's completion. + RapidCache createdCache = operation.PollUntilCompleted().Result; + + Console.WriteLine($"Created Rapid Cache: {createdCache.Name}"); + Console.WriteLine($"State: {createdCache.State}"); + + return createdCache; + } +} +// [END storage_control_create_rapid_cache] diff --git a/storage/api/Storage.Samples/StorageControlDisableRapidCache.cs b/storage/api/Storage.Samples/StorageControlDisableRapidCache.cs new file mode 100644 index 00000000000..dbc23ddced8 --- /dev/null +++ b/storage/api/Storage.Samples/StorageControlDisableRapidCache.cs @@ -0,0 +1,52 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"). +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// [START storage_control_disable_rapid_cache] + +using Google.Cloud.Storage.Control.V2; +using Google.LongRunning; +using System; + +public class StorageControlDisableRapidCacheSample +{ + /// Disables a Rapid Cache instance for the specified bucket. + /// The name of the bucket that owns the Rapid Cache instance. + /// The unique identifier of the Rapid Cache instance, which is the + /// zone of the cache (for example, "us-central1-a"). + public Operation StorageControlDisableRapidCache( + string bucketName = "your-unique-bucket-name", + string rapidCacheId = "us-central1-a") + { + StorageControlClient storageControlClient = StorageControlClient.Create(); + + // Set project to "_" to signify globally scoped bucket. + string rapidCacheName = RapidCacheName.FormatProjectBucketRapidCache("_", bucketName, rapidCacheId); + + DisableRapidCacheRequest request = new DisableRapidCacheRequest + { + Name = rapidCacheName + }; + + // Disabling a Rapid Cache is a long-running operation (LRO). The cache moves to the + // "disabled" state within seconds, but the operation only completes once the cache has + // been fully removed, which can take more than an hour. Instead of waiting for the + // operation, callers can use StorageControlGetRapidCache to check for the "disabled" state. + Operation operation = storageControlClient.DisableRapidCache(request); + + Console.WriteLine($"Started disabling Rapid Cache {rapidCacheName}. Operation: {operation.Name}"); + + return operation; + } +} +// [END storage_control_disable_rapid_cache] diff --git a/storage/api/Storage.Samples/StorageControlGetRapidCache.cs b/storage/api/Storage.Samples/StorageControlGetRapidCache.cs new file mode 100644 index 00000000000..aa9b1ce55ee --- /dev/null +++ b/storage/api/Storage.Samples/StorageControlGetRapidCache.cs @@ -0,0 +1,49 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"). +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// [START storage_control_get_rapid_cache] + +using Google.Cloud.Storage.Control.V2; +using System; + +public class StorageControlGetRapidCacheSample +{ + /// Gets a Rapid Cache instance for the specified bucket. + /// The name of the bucket that owns the Rapid Cache instance. + /// The unique identifier of the Rapid Cache instance, which is the + /// zone of the cache (for example, "us-central1-a"). + public RapidCache StorageControlGetRapidCache(string bucketName = "your-unique-bucket-name", + string rapidCacheId = "us-central1-a") + { + StorageControlClient storageControlClient = StorageControlClient.Create(); + + // Set project to "_" to signify globally scoped bucket. + string rapidCacheName = RapidCacheName.FormatProjectBucketRapidCache("_", bucketName, rapidCacheId); + + GetRapidCacheRequest request = new GetRapidCacheRequest + { + Name = rapidCacheName + }; + + RapidCache rapidCache = storageControlClient.GetRapidCache(request); + + Console.WriteLine($"Got Rapid Cache: {rapidCache.Name}"); + Console.WriteLine($"Zone: {rapidCache.Zone}"); + Console.WriteLine($"Cache type: {rapidCache.CacheType}"); + Console.WriteLine($"State: {rapidCache.State}"); + + return rapidCache; + } +} +// [END storage_control_get_rapid_cache] diff --git a/storage/api/Storage.Samples/StorageControlListRapidCaches.cs b/storage/api/Storage.Samples/StorageControlListRapidCaches.cs new file mode 100644 index 00000000000..74fe85d0f98 --- /dev/null +++ b/storage/api/Storage.Samples/StorageControlListRapidCaches.cs @@ -0,0 +1,62 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"). +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// [START storage_control_list_rapid_caches] + +using Google.Api.Gax; +using Google.Cloud.Storage.Control.V2; +using System; +using System.Collections.Generic; + +public class StorageControlListRapidCachesSample +{ + /// Lists all Rapid Cache instances for the specified bucket. + /// The name of the bucket that owns the Rapid Cache instances. + /// The maximum number of Rapid Cache instances to return in a single response. + public IEnumerable StorageControlListRapidCaches(string bucketName = "your-unique-bucket-name", + int pageSize = 10) + { + StorageControlClient storageControlClient = StorageControlClient.Create(); + + // Set project to "_" to signify globally scoped bucket. + string parent = $"projects/_/buckets/{bucketName}"; + + ListRapidCachesRequest request = new ListRapidCachesRequest + { + Parent = parent, + PageSize = pageSize + }; + + // The returned sequence fetches additional pages automatically as it is iterated. + PagedEnumerable rapidCaches = storageControlClient.ListRapidCaches(request); + + foreach (RapidCache rapidCache in rapidCaches) + { + Console.WriteLine($"Rapid Cache: {rapidCache.Name}"); + } + + // Alternatively, iterate over the results one page at a time. + foreach (ListRapidCachesResponse page in rapidCaches.AsRawResponses()) + { + Console.WriteLine($"Page with {page.RapidCaches.Count} Rapid Caches:"); + foreach (RapidCache rapidCache in page) + { + Console.WriteLine($"Rapid Cache: {rapidCache.Name}"); + } + } + + return rapidCaches; + } +} +// [END storage_control_list_rapid_caches] diff --git a/storage/api/Storage.Samples/StorageControlUpdateRapidCache.cs b/storage/api/Storage.Samples/StorageControlUpdateRapidCache.cs new file mode 100644 index 00000000000..073db75ab0b --- /dev/null +++ b/storage/api/Storage.Samples/StorageControlUpdateRapidCache.cs @@ -0,0 +1,65 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"). +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// [START storage_control_update_rapid_cache] + +using Google.Cloud.Storage.Control.V2; +using Google.LongRunning; +using Google.Protobuf.WellKnownTypes; +using System; + +public class StorageControlUpdateRapidCacheSample +{ + /// Updates the time to live (TTL) of a Rapid Cache instance. + /// The name of the bucket that owns the Rapid Cache instance. + /// The unique identifier of the Rapid Cache instance, which is the + /// zone of the cache (for example, "us-central1-a"). + /// The new TTL for cache entries, in seconds. The TTL must be between 1 hour and 7 days. + public RapidCache StorageControlUpdateRapidCache(string bucketName = "your-unique-bucket-name", + string rapidCacheId = "us-central1-a", + long ttlSeconds = 172800) + { + StorageControlClient storageControlClient = StorageControlClient.Create(); + + // Set project to "_" to signify globally scoped bucket. + string rapidCacheName = RapidCacheName.FormatProjectBucketRapidCache("_", bucketName, rapidCacheId); + + RapidCache rapidCache = new RapidCache + { + Name = rapidCacheName, + Ttl = new Duration { Seconds = ttlSeconds } + }; + + // Only the fields listed in the update mask are changed. + FieldMask updateMask = new FieldMask { Paths = { "ttl" } }; + + UpdateRapidCacheRequest request = new UpdateRapidCacheRequest + { + RapidCache = rapidCache, + UpdateMask = updateMask + }; + + // Updating a Rapid Cache is a long-running operation (LRO). + Operation operation = storageControlClient.UpdateRapidCache(request); + + // Await the LRO's completion. + RapidCache updatedCache = operation.PollUntilCompleted().Result; + + Console.WriteLine($"Updated Rapid Cache: {updatedCache.Name}"); + Console.WriteLine($"TTL: {updatedCache.Ttl.Seconds} seconds"); + + return updatedCache; + } +} +// [END storage_control_update_rapid_cache]