I'm using Azure Functions for accessing Azure Media Services. I have a HTTP trigger that will get me a streaming link for a video file. When I try to create an on demand streaming locator the server sometimes return the following error:
One or more errors occurred. Microsoft.WindowsAzure.MediaServices.Client: An error occurred while processing this request. Locator's ExpirationDateTime cannot be in the past.
Here is part of the code:
using System.Net;
using Microsoft.WindowsAzure.MediaServices.Client;
...
public static readonly TimeSpan ExpirationTimeThreshold = TimeSpan.FromHours(5);
public static readonly DateTime TimeSkew = DateTime.UtcNow.AddMinutes(-5);
...
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
string assetId = req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "assetId", true) == 0).Value;
IAsset wantedAsset = _context.Assets.Where(a => a.Id.Equals(assetId)).FirstOrDefault();
if (wantedAsset == null)
{
return req.CreateResponse(HttpStatusCode.BadRequest,
"No asset matches the Id");
}
originLocator = wantedAsset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).FirstOrDefault();
if (originLocator == null)
{
IAccessPolicy policy = _context.AccessPolicies.Create("Streaming policy",
ExpirationTimeThreshold,
AccessPermissions.Read);
originLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, wantedAsset,
policy,
TimeSkew); //This is where the exception is returned
}
...
}
This seems to be very inconsistent behaviour, as it will work as expected most of the time. Once when this happened I tried to put in log statements in the Azure Function, and when I saved the changes the function worked as expected.
One thing I realized as I was writing this is that the TimeSkew
variable will not be updated until I save the changes to the Azure Functions.
This means that the first time this is run the TimeSkew
would for example be 5:00PM and after 5 hours the TimeSkew
would still be 5:00PM, meaning the ExpirationTimeThreshold
and the TimeSkew
will negate each other?
Making TimeSkew
a local variable should then fix my problem?
I think you already answered your own question. Every time you recompile (or more specifically, every time a new instance starts running your function), the TimeSkew
static variable is initialized. For all subsequent requests to the same instance, TimeSkew
value stays the same, which probably leads to the mentioned error.
Solution: don't initialize any static variable to DateTime.Now
related things, unless you really want to track the start time of the first run on each instance (which you don't).