-
Notifications
You must be signed in to change notification settings - Fork 14
/
HarvestService.cs
529 lines (453 loc) · 20.8 KB
/
HarvestService.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
using FurlandGraph.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Tweetinvi;
using Tweetinvi.Exceptions;
using Tweetinvi.Iterators;
using Tweetinvi.Models;
using Tweetinvi.Parameters;
namespace FurlandGraph.Services
{
public class BasicHarvestUser
{
public string ScreenName { get; set; }
public bool Deleted { get; set; }
public bool Protected { get; set; }
public DateTime? FollowersCollected { get; set; }
public DateTime? FriendsCollected { get; set; }
}
public class WorkItemWithUser
{
public long Id { get; set; }
public BasicHarvestUser User { get; set; }
}
public class HarvestService
{
public HarvestService(
FurlandContext context,
IDbContextFactory<FurlandContext> contextFactory,
IOptions<TwitterConfiguration> twitterConfiguration,
IOptions<HarvesterConfig> harvestConfiguration,
UserService userService)
{
Context = context;
ContextFactory = contextFactory;
TwitterConfiguration = twitterConfiguration;
HarvestConfiguration = harvestConfiguration;
UserService = userService;
}
public FurlandContext Context { get; }
public IDbContextFactory<FurlandContext> ContextFactory { get; }
public IOptions<TwitterConfiguration> TwitterConfiguration { get; }
public IOptions<HarvesterConfig> HarvestConfiguration { get; }
public UserService UserService { get; }
public Queue<long> WorkItems = new Queue<long>();
public Queue<TwitterToken> AvailableTokens = new Queue<TwitterToken>();
public async Task ParallelRun()
{
if (!HarvestConfiguration.Value.Enabled)
{
Console.WriteLine($"!! Harvest service not enabled !!");
return;
}
while (true)
{
try
{
long count = 0;
// int maxWorkers = 100;
var trackers = new Dictionary<Task<bool>, TwitterClientTracker>();
Console.WriteLine($"Max workers: {HarvestConfiguration.Value.MaxWorkers}");
while (true)
{
TwitterClientTracker tracker = null;
var completedTask = trackers.Keys.Where(t => t.IsCompleted).OrderBy(t => t.Id).FirstOrDefault(); // Check if any of the workers is finished
if (completedTask == null)
{
if (trackers.Count >= HarvestConfiguration.Value.MaxWorkers) // If no workers are finished, see if we can create a new one
{
await Task.Delay(TimeSpan.FromSeconds(0.1));
continue;
}
}
else
{
trackers.Remove(completedTask, out tracker); // Remove the worker from the list
try
{
bool result = await completedTask; // If the pagination is finished, remove the work item
if (result)
{
// var workItemToRemove = await Context.WorkItems.FindAsync(tracker.WorkItemId);
// Context.WorkItems.Remove(workItemToRemove);
// await Context.SaveChangesAsync();
}
}
catch (TwitterException ex) when (ex.Message.Contains("Rate limit exceeded (88)"))
{
var a = tracker.TwitterClient.RateLimits.GetEndpointRateLimitAsync(ex.URL);
var waitTime = TimeSpan.FromMinutes(15);
if (ex.TwitterQuery != null && ex.TwitterQuery.QueryRateLimit != null)
{
waitTime = TimeSpan.FromSeconds(ex.TwitterQuery.QueryRateLimit.ResetDateTimeInSeconds + 5);
}
else
{
Console.WriteLine("What error is this?" + ex.ToString());
Console.WriteLine("What error is this? PArt 2" + ex.Message);
Console.WriteLine("What error is this? PArt 3" + ex.TwitterDescription.ToString());
}
// API Key has no calls left
tracker.Token.NextFriendsRequest = DateTime.UtcNow + waitTime;
await Context.SaveChangesAsync();
tracker = null;
}
catch (TwitterException ex) when (ex.Message.Contains("Invalid or expired token"))
{
Context.TwitterTokens.Remove(tracker.Token);
await Context.SaveChangesAsync();
tracker = null;
}
catch (TwitterException ex) when (ex.ToString().Contains("To protect our users from spam and other malicious activity, this account is temporarily locked."))
{
// Oooops
Console.WriteLine("To protect our users from spam and other malicious activity, this account is temporarily locked.");
tracker.Token.NextFriendsRequest = DateTime.UtcNow + TimeSpan.FromDays(1000);
await Context.SaveChangesAsync();
tracker = null;
}
catch (TwitterTimeoutException ex)
{
// .NET is limiting the number of concurrent conncetions....
// Just wait a while
await Task.Delay(TimeSpan.FromSeconds(5));
Console.WriteLine("Twitter timeout...");
}
catch (Exception ex)
{
Console.WriteLine("Unkown error type: " + ex.GetType().FullName);
Console.WriteLine("Error full: " + ex.ToString());
Console.WriteLine("Error inner: " + ex.InnerException?.ToString());
}
}
if (tracker != null && !tracker.CanWork()) // API key has no calls left
{
var nextRequest = TimeSpan.FromMinutes(15);
//var rateLimit = await tracker.TwitterClient.RateLimits.GetEndpointRateLimitAsync("https://api.twitter.com/1.1/followers/ids.json");
//if (rateLimit != null)
//{
// nextRequest = TimeSpan.FromSeconds(rateLimit.ResetDateTimeInSeconds + 5);
//}
tracker.Token.NextFriendsRequest = DateTime.UtcNow + nextRequest;
await Context.SaveChangesAsync();
tracker = null;
}
if (tracker == null) // Finda new API key
{
var token = await GetNextToken(trackers.Values.Select(t => t.Token.Id).ToList());
if (token == null)
{
await Task.Delay(TimeSpan.FromSeconds(1)); // No API Keys found
continue;
}
var client = GetClientFromToken(token);
tracker = new TwitterClientTracker(token, client);
}
var workItemId = await GetNextWorkItem(trackers.Values.Select(t => t.WorkItemId).ToList()); // Find new user to crawl
if (!workItemId.HasValue)
{
await Task.Delay(TimeSpan.FromSeconds(1));
continue;
}
tracker.WorkItemId = workItemId.Value;
var task = Task.Run(() => Harvest(tracker)); // Start async worker
trackers[task] = tracker;
if (count++ % 1000 == 0)
{
Console.WriteLine($"[{DateTime.UtcNow}] Total workers: {trackers.Count} (Completed: {trackers.Where(t => t.Key.IsCompleted).Count()})");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Harvest worker thread died: " + ex.ToString());
}
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
public TwitterClient GetClientFromToken(TwitterToken token)
{
var twitterConfig = TwitterConfiguration.Value;
TwitterClient client;
if (!string.IsNullOrWhiteSpace(token.AccessToken))
{
client = new TwitterClient(twitterConfig.ConsumerKey, twitterConfig.ConsumerSecret, token.AccessToken, token.AccessSecret);
}
else
{
client = new TwitterClient(twitterConfig.ConsumerKey, twitterConfig.ConsumerSecret, token.BearerToken);
}
client.Config.HttpRequestTimeout = TimeSpan.FromSeconds(60);
client.Config.RateLimitTrackerMode = RateLimitTrackerMode.TrackOnly;
return client;
}
public async Task<TwitterToken> GetNextToken(List<long> activeIds)
{
if (AvailableTokens.TryDequeue(out var result))
{
return result;
}
await GetMoreTokens(activeIds);
if (AvailableTokens.TryDequeue(out result))
{
return result;
}
return null;
}
public async Task GetMoreTokens(List<long> activeIds)
{
var tokens = await Context.TwitterTokens
.Where(t => !activeIds.Contains(t.Id) && t.NextFriendsRequest < DateTime.UtcNow)
.OrderBy(t => t.NextFriendsRequest)
.Take(100)
.ToListAsync();
foreach (var token in tokens)
{
AvailableTokens.Enqueue(token);
}
}
public async Task<long?> GetNextWorkItem(List<long> activeIds)
{
if (WorkItems.TryDequeue(out var result))
{
return result;
}
var moreWork = await GetNextWorkItemsToQueue(activeIds);
foreach (var item in moreWork)
{
WorkItems.Enqueue(item);
}
if (WorkItems.TryDequeue(out result))
{
return result;
}
return null;
}
public async Task<List<long>> GetNextWorkItemsToQueue(List<long> activeIds)
{
var workItems = await Context.WorkItems
.Where(t => !activeIds.Contains(t.Id))
.OrderBy(t => t.Id)
.Take(100)
.Select(t => t.Id)
.ToListAsync();
return workItems;
}
public async Task<bool> Harvest(TwitterClientTracker tracker)
{
using var dbContext = await ContextFactory.CreateDbContextAsync();
var workItem = await dbContext.WorkItems.FindAsync(tracker.WorkItemId);
bool result = await HarvestInner(dbContext, workItem, tracker);
if (result)
{
dbContext.WorkItems.Remove(workItem);
await dbContext.SaveChangesAsync();
}
return result;
}
public async Task<bool> HarvestInner(FurlandContext dbContext, WorkItem workItem, TwitterClientTracker tracker)
{
BasicHarvestUser dbUser = await dbContext.Users
.Where(t => t.Id == workItem.UserId)
.Select(t => new BasicHarvestUser()
{
Deleted = t.Deleted,
FollowersCollected = t.FollowersCollected,
FriendsCollected = t.FriendsCollected,
Protected = t.Protected,
ScreenName = t.ScreenName,
})
.FirstOrDefaultAsync();
if (dbUser != null && (dbUser.Deleted || string.IsNullOrEmpty(dbUser.ScreenName)))
{
await dbContext.Database.ExecuteSqlInterpolatedAsync(@$"UPDATE users SET ""lastUpdate""=now(),deleted=true WHERE ""id""={workItem.UserId}");
// dbUser.LastUpdate = DateTime.UtcNow;
// await dbContext.SaveChangesAsync();
return true;
}
if (workItem.Type == "user")
{
IUser friend = null;
try
{
friend = await tracker.TwitterClient.Users.GetUserAsync(workItem.UserId);
// TODO: Do we call the user API too often?
await UserService.CollectUser(dbContext, friend);
}
catch (TwitterException ex) when (ex.StatusCode == 404 && ex.Content.Contains("User not found"))
{
await UserService.AddDeletedUser(dbContext, workItem.UserId);
}
catch (TwitterException ex) when (ex.StatusCode == 403 && ex.Content.Contains("User has been suspended"))
{
await UserService.AddDeletedUser(dbContext, workItem.UserId);
}
catch (TwitterException ex) when (ex.StatusCode == 401 && ex.Content.Contains("Unauthorized"))
{
await UserService.AddDeletedUser(dbContext, workItem.UserId);
}
return true;
}
if (dbUser.Protected)
{
return true;
}
try
{
var iterator = GetIterator(workItem.Type);
if (!iterator.UserCanUpdate(dbUser))
{
return true;
}
return await HarvestFollowers(dbContext, iterator, tracker);
}
catch (TwitterException ex) when (ex.StatusCode == 401 && ex.Content.Contains("Unauthorized"))
{
// User has their account set to private?
await dbContext.Database.ExecuteSqlInterpolatedAsync(@$"UPDATE users SET ""protected""=true WHERE ""id""={workItem.UserId}");
return true;
}
catch (TwitterException ex) when (ex.StatusCode == 401 && ex.Content.Contains("Not authorized"))
{
// User has their account set to private?
await dbContext.Database.ExecuteSqlInterpolatedAsync(@$"UPDATE users SET ""protected""=true WHERE ""id""={workItem.UserId}");
return true;
}
catch (TwitterException ex) when (ex.StatusCode == 404 && ex.Content.Contains("Sorry, that page does not exist"))
{
// User has their account set to private?
await dbContext.Database.ExecuteSqlInterpolatedAsync(@$"UPDATE users SET ""protected""=true WHERE ""id""={workItem.UserId}");
return true;
}
}
public UserRelationIterator GetIterator(string type)
{
if (type == "followers")
{
return new UserFollowersIterator();
}
else if (type == "friends")
{
return new UserFriendIterator();
}
throw new Exception();
}
public async Task<bool> HarvestFollowers(FurlandContext dbContext, UserRelationIterator userRelations, TwitterClientTracker tracker)
{
var workItem = await dbContext.WorkItems.FindAsync(tracker.WorkItemId);
var iterator = userRelations.GetIterator(tracker.TwitterClient, workItem.UserId, workItem.Cursor);
if (workItem.UserIds == null)
{
workItem.UserIds = new List<long>();
}
while (!iterator.Completed && tracker.CanWork())
{
tracker.UseCall();
var page = await iterator.NextPageAsync();
workItem.UserIds.AddRange(page);
}
if (iterator.Completed)
{
using var trans = dbContext.Database.BeginTransaction();
await userRelations.Save(dbContext, workItem.UserId, workItem.UserIds);
await dbContext.SaveChangesAsync();
await trans.CommitAsync();
return true;
}
else
{
workItem.Cursor = iterator.NextCursor;
await dbContext.SaveChangesAsync();
return false;
}
}
}
public abstract class UserRelationIterator
{
public abstract ITwitterIterator<long> GetIterator(TwitterClient twitterClient, long userId, string cursor);
public abstract Task Save(FurlandContext context, long userId, List<long> relationIds);
public abstract bool UserCanUpdate(BasicHarvestUser user);
}
public class UserFriendIterator : UserRelationIterator
{
public override ITwitterIterator<long> GetIterator(TwitterClient twitterClient, long userId, string cursor)
{
var parameter = new GetFriendIdsParameters(userId)
{
Cursor = cursor,
};
return twitterClient.Users.GetFriendIdsIterator(parameter);
}
public override async Task Save(FurlandContext context, long userId, List<long> relationIds)
{
await context.Database.ExecuteSqlInterpolatedAsync(@$"UPDATE users SET ""friendsCollected""=now() WHERE ""id""={userId}");
await context.Database.ExecuteSqlInterpolatedAsync(@$"DELETE FROM ""userRelations"" WHERE ""userId""={userId} and ""type""='friends'");
context.UserRelations.Add(new UserRelations()
{
UserId = userId,
Type = "friends",
List = relationIds.OrderBy(t => t).ToList(),
});
}
public override bool UserCanUpdate(BasicHarvestUser user)
{
return user.FriendsCollected == null || user.FriendsCollected + TimeSpan.FromDays(30) < DateTime.UtcNow;
}
}
public class UserFollowersIterator : UserRelationIterator
{
public override ITwitterIterator<long> GetIterator(TwitterClient twitterClient, long userId, string cursor)
{
var parameter = new GetFollowerIdsParameters(userId)
{
Cursor = cursor,
};
return twitterClient.Users.GetFollowerIdsIterator(parameter);
}
public override async Task Save(FurlandContext context, long userId, List<long> relationIds)
{
await context.Database.ExecuteSqlInterpolatedAsync(@$"UPDATE users SET ""followersCollected""=now() WHERE ""id""={userId}");
await context.Database.ExecuteSqlInterpolatedAsync(@$"DELETE FROM ""userRelations"" WHERE ""userId""={userId} and ""type""='followers'");
context.UserRelations.Add(new UserRelations()
{
UserId = userId,
Type = "followers",
List = relationIds.OrderBy(t => t).ToList(),
});
}
public override bool UserCanUpdate(BasicHarvestUser user)
{
return user.FollowersCollected == null || user.FollowersCollected + TimeSpan.FromDays(30) < DateTime.UtcNow;
}
}
public class TwitterClientTracker
{
public TwitterToken Token { get; }
public TwitterClient TwitterClient { get; }
public long WorkItemId { get; set; }
public int CallsLeft = 15;
public TwitterClientTracker(TwitterToken token, TwitterClient twitterClient)
{
Token = token;
TwitterClient = twitterClient;
}
public void UseCall()
{
Interlocked.Decrement(ref CallsLeft);
}
public bool CanWork()
{
return Thread.VolatileRead(ref CallsLeft) > 0;
}
}
}