Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 157 additions & 0 deletions storage/api/Storage.Samples.Tests/StorageControlRapidCacheTest.cs
Comment thread
sahusneha2004 marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -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<RapidCache, DisableRapidCacheMetadata> 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();
}
}
2 changes: 1 addition & 1 deletion storage/api/Storage.Samples/Storage.Samples.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Google.Cloud.Storage.Control.V2" Version="1.8.0" />
<PackageReference Include="Google.Cloud.Storage.Control.V2" Version="1.11.0" />
<PackageReference Include="Google.Cloud.Storage.V1" Version="4.15.0" />
<PackageReference Include="Google.Apis.Storage.v1" Version="*" />
</ItemGroup>
Expand Down
65 changes: 65 additions & 0 deletions storage/api/Storage.Samples/StorageControlCreateRapidCache.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// 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.
/// </summary>
/// <param name="bucketName">The name of the bucket.</param>
/// <param name="zone">The zone in which to create the Rapid Cache. The zone must be in the same region as the bucket.</param>
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<RapidCache, CreateRapidCacheMetadata> 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]
52 changes: 52 additions & 0 deletions storage/api/Storage.Samples/StorageControlDisableRapidCache.cs
Comment thread
sahusneha2004 marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>Disables a Rapid Cache instance for the specified bucket.</summary>
/// <param name="bucketName">The name of the bucket that owns the Rapid Cache instance.</param>
/// <param name="rapidCacheId">The unique identifier of the Rapid Cache instance, which is the
/// zone of the cache (for example, "us-central1-a").</param>
public Operation<RapidCache, DisableRapidCacheMetadata> 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<RapidCache, DisableRapidCacheMetadata> operation = storageControlClient.DisableRapidCache(request);

Console.WriteLine($"Started disabling Rapid Cache {rapidCacheName}. Operation: {operation.Name}");

return operation;
}
}
// [END storage_control_disable_rapid_cache]
49 changes: 49 additions & 0 deletions storage/api/Storage.Samples/StorageControlGetRapidCache.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>Gets a Rapid Cache instance for the specified bucket.</summary>
/// <param name="bucketName">The name of the bucket that owns the Rapid Cache instance.</param>
/// <param name="rapidCacheId">The unique identifier of the Rapid Cache instance, which is the
/// zone of the cache (for example, "us-central1-a").</param>
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]
62 changes: 62 additions & 0 deletions storage/api/Storage.Samples/StorageControlListRapidCaches.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>Lists all Rapid Cache instances for the specified bucket.</summary>
/// <param name="bucketName">The name of the bucket that owns the Rapid Cache instances.</param>
/// <param name="pageSize">The maximum number of Rapid Cache instances to return in a single response.</param>
public IEnumerable<RapidCache> 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<ListRapidCachesResponse, RapidCache> rapidCaches = storageControlClient.ListRapidCaches(request);

foreach (RapidCache rapidCache in rapidCaches)
Comment thread
sahusneha2004 marked this conversation as resolved.
Resolved
{
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]
Loading
Loading