-
Notifications
You must be signed in to change notification settings - Fork 411
/
MigrateToRedis.php
120 lines (102 loc) · 2.83 KB
/
MigrateToRedis.php
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
<?php
namespace App\Console\Commands;
use App\Requests\Request;
use App\Tokens\Token;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Connection;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Redis;
/**
* @property redis
*/
class MigrateToRedis extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'webhook:migrate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Migrate data from SQLite to Redis';
/**
* @var Connection
*/
private $db;
/**
* @var Redis
*/
private $redis;
/**
* Create a new command instance.
*
* @param DatabaseManager $db
*/
public function __construct(DatabaseManager $db)
{
parent::__construct();
$this->db = $db->connection();
$this->redis = Redis::connection(config('database.redis.connection'));
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Set maintenance mode.
$this->call('down');
$count = Token::all()->count();
$this->output->progressStart($count);
Token::chunk(100, function ($tokens) {
foreach ($tokens as $token) {
$this->insertToken($token);
$this->output->progressAdvance();
}
});
$this->output->progressFinish();
$this->call('up');
}
/**
* @param Token $token
*/
private function insertToken(Token $token)
{
$tokenKey = sprintf('%s:%s', 'token', $token->uuid);
$requestsKey = sprintf('%s:%s', $tokenKey, 'requests');
if ($this->redis->exists($tokenKey)) {
$this->redis->expire($tokenKey, config('app.expiry'));
$this->redis->expire($requestsKey, config('app.expiry'));
return;
}
$this->redis->set($tokenKey, $token);
$token->requests()->chunk(500, function ($requests) use ($token, $requestsKey) {
if ($this->redis->hlen($requestsKey) > config('app.max_requests')) {
// Abort request import for token.
return false;
}
foreach ($requests as $request) {
$this->insertRequest($requestsKey, $request);
}
});
$this->redis->expire($tokenKey, config('app.expiry'));
$this->redis->expire($requestsKey, config('app.expiry'));
}
/**
* @param Request $request
*/
private function insertRequest($key, Request $request)
{
try {
$this->redis->hmset($key, $request->uuid, $request);
} catch (\ErrorException $e) {
// Continue on __toString errors.
}
}
}