Azure / azure-functions-host

The host/runtime that powers Azure Functions
https://functions.azure.com
MIT License
1.94k stars 441 forks source link

Analyzer: Suggested DocumentDB Use Pattern #7415

Open kashimiz opened 3 years ago

kashimiz commented 3 years ago

Conditions to Trigger Analyzer Within a [Function]-decorated method, where a new DocumentClient is instantiated..

    public static class CosmosDBWrong
    {
        [FunctionName("CosmosDBWrong")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string endpointUri = "testCosmosDB";
            string primaryKey = 

            var docDBClient = new DocumentClient(new Uri(endpointUri), primaryKey, new ConnectionPolicy()
            {
                MaxConnectionLimit = 100,
                ConnectionMode = ConnectionMode.Gateway,
                ConnectionProtocol = Protocol.Tcp,
                RetryOptions = new RetryOptions() { MaxRetryAttemptsOnThrottledRequests = 3, MaxRetryWaitTimeInSeconds = 60 }
            });

            string responseMessage = "Hello from CosmosDB";

            return new OkObjectResult(responseMessage);
        }
    }

Diagnostic Level Warning

How to Fix Violations

  1. Lazy static instantiation outside of [Function] method:
using Microsoft.Azure.Documents.Client;

private static Lazy<DocumentClient> lazyClient = new Lazy<DocumentClient>(InitializeDocumentClient);
private static DocumentClient documentClient => lazyClient.Value;

private static DocumentClient InitializeDocumentClient()
{
    // Perform any initialization here
    var uri = new Uri("example");
    var authKey = "authKey";

    return new DocumentClient(uri, authKey);
}

public static async Task Run(string input)
{
    Uri collectionUri = UriFactory.CreateDocumentCollectionUri("database", "collection");
    object document = new { Data = "example" };
    await documentClient.UpsertDocumentAsync(collectionUri, document);

    // Rest of function
}
  1. Inject DocumentClient using DI, ex. https://github.com/jeffhollan/functions-csharp-cosmosdb-di

Whether to Supply Codefix Yes for 1, if possible for 2.

Associated Documentation https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections

When to Suppress Analyzer Rule This rule should not be suppressed.

fabiocav commented 3 years ago

Assigning to sprint 105 for initial design/scoping.

fabiocav commented 3 years ago

Moving this to triaged as we should prioritize the IConfiguration analyzer over this.