forked from OrleansContrib/Orleankka
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiWorker.cs
More file actions
98 lines (78 loc) · 2.33 KB
/
ApiWorker.cs
File metadata and controls
98 lines (78 loc) · 2.33 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace Demo
{
public interface IApiWorker
{
Task<int> Search(string subject);
}
static class ApiWorkerFactory
{
static readonly IDictionary<string, IApiWorker> registry = new Dictionary<string, IApiWorker>
{
{"facebook", new Faulty(new FacebookApiWorker("facebook.com"))},
{"twitter", new Faulty(new TwitterApiWorker("twitter.com"))},
};
public static Func<IApiWorker> Create(Func<string> api)
{
return () => registry[api()];
}
}
abstract class ApiWorkerBase : IApiWorker
{
public string EndPoint { get; private set; }
protected ApiWorkerBase(string endPoint)
{
EndPoint = endPoint;
}
public abstract Task<int> Search(string subject);
}
class FacebookApiWorker : ApiWorkerBase
{
readonly Random random = new Random();
public FacebookApiWorker(string endPoint)
: base(endPoint)
{}
public override Task<int> Search(string subject)
{
return Task.FromResult(random.Next(0, 50));
}
}
class TwitterApiWorker : ApiWorkerBase
{
readonly Random random = new Random();
public TwitterApiWorker(string endPoint)
: base(endPoint)
{}
public override Task<int> Search(string subject)
{
return Task.FromResult(random.Next(0, 50));
}
}
class Faulty : ApiWorkerBase
{
readonly ApiWorkerBase api;
bool faulted;
long requests;
public Faulty(ApiWorkerBase api) : base(api.EndPoint)
{
this.api = api;
}
public override Task<int> Search(string subject)
{
requests++;
if (faulted)
{
if (requests % 5 == 0)
faulted = false;
throw new HttpException(500, api.EndPoint + " is down");
}
if (requests % 10 == 0)
faulted = true;
return api.Search(subject);
}
}
}