in tools/code/publisher/Product.cs [163:216]
private static PutProductInApim GetPutProductInApim(IServiceProvider provider)
{
var serviceUri = provider.GetRequiredService<ManagementServiceUri>();
var pipeline = provider.GetRequiredService<HttpPipeline>();
var logger = provider.GetRequiredService<ILogger>();
return async (name, dto, cancellationToken) =>
{
logger.LogInformation("Putting product {ProductName}...", name);
var productAlreadyExists = await doesProductAlreadyExist(name, cancellationToken);
await ProductUri.From(name, serviceUri)
.PutDto(dto, pipeline, cancellationToken);
// Delete automatically created resources if the product is new. This ensures that APIM is consistent with source control.
if (productAlreadyExists is false)
{
await deleteAutomaticallyCreatedProductGroups(name, cancellationToken);
await deleteAutomaticallyCreatedProductSubscriptions(name, cancellationToken);
}
};
async ValueTask<bool> doesProductAlreadyExist(ProductName name, CancellationToken cancellationToken)
{
var productUri = ProductUri.From(name, serviceUri).ToUri();
var contentOption = await pipeline.GetContentOption(productUri, cancellationToken);
return contentOption.IsSome;
}
async ValueTask deleteAutomaticallyCreatedProductGroups(ProductName productName, CancellationToken cancellationToken) =>
await ProductGroupsUri.From(productName, serviceUri)
.ListNames(pipeline, cancellationToken)
.Do(groupName => logger.LogWarning("Removing automatically added group {GroupName} from product {ProductName}...", groupName, productName))
.IterParallel(async name => await ProductGroupUri.From(name, productName, serviceUri)
.Delete(pipeline, cancellationToken),
cancellationToken);
async ValueTask deleteAutomaticallyCreatedProductSubscriptions(ProductName productName, CancellationToken cancellationToken) =>
await ProductUri.From(productName, serviceUri)
.ListSubscriptionNames(pipeline, cancellationToken)
.WhereAwait(async subscriptionName =>
{
var dto = await SubscriptionUri.From(subscriptionName, serviceUri)
.GetDto(pipeline, cancellationToken);
// Automatically created subscriptions have no display name and end with "/users/1"
return string.IsNullOrWhiteSpace(dto.Properties.DisplayName)
&& (dto.Properties.OwnerId?.EndsWith("/users/1", StringComparison.OrdinalIgnoreCase) ?? false);
})
.Do(subscriptionName => logger.LogWarning("Deleting automatically created subscription {SubscriptionName} from product {ProductName}...", subscriptionName, productName))
.IterParallel(async name => await SubscriptionUri.From(name, serviceUri)
.Delete(pipeline, cancellationToken),
cancellationToken);
}