-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathKeyProvider.cs
85 lines (78 loc) · 2.63 KB
/
KeyProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClassTranscribeDatabase.Services.MSTranscription
{
/// <summary>
/// Each object of this class represents an azure subscription key.
/// </summary>
public class Key
{
public string ApiKey { get; set; }
public string Region { get; set; }
/// <summary>
/// This value indicates the number of tasks that are already using this key currently.
/// </summary>
public int Load { get; set; }
}
/// <summary>
/// This class "provides" azure subscription keys for transcription tasks.
/// It reads its key values from configuration variable "AZURE_SUBSCRIPTION_KEYS"
/// </summary>
public class KeyProvider
{
private readonly AppSettings _appSettings;
private readonly List<Key> Keys;
private readonly HashSet<string> CurrentVideoIds;
public KeyProvider(AppSettings appSettings)
{
_appSettings = appSettings;
string subscriptionKeys = _appSettings.AZURE_SUBSCRIPTION_KEYS ?? "";
Keys = new List<Key>();
CurrentVideoIds = new HashSet<string>();
foreach (string subscriptionKey in subscriptionKeys.Split(';'))
{
if (!subscriptionKeys.Contains(","))
{
continue;
}
string[] keyregion = subscriptionKey.Split(',');
if (keyregion.Length != 2)
{
throw new Exception("AZURE_SUBSCRIPTION_KEYS should be in the form key,region;key,region");
}
Keys.Add(new Key
{
ApiKey = keyregion[0].Trim(),
Region = keyregion[1].Trim(),
Load = 0
});
}
}
/// <summary>
/// To obtain a new key for a task
/// </summary>
public Key GetKey(string videoId)
{
if (!CurrentVideoIds.Contains(videoId))
{
Key key = Keys.OrderBy(k => k.Load).First();
key.Load += 1;
CurrentVideoIds.Add(videoId);
return key;
}
else
{
throw new Exception("Video already being transcribed");
}
}
/// <summary>
/// To release a key that was being used.
/// </summary>
public void ReleaseKey(Key key, string videoId)
{
Keys.Find(k => k.ApiKey == key.ApiKey).Load -= 1;
CurrentVideoIds.Remove(videoId);
}
}
}