-
Notifications
You must be signed in to change notification settings - Fork 127
/
send.php
executable file
·134 lines (108 loc) · 2.44 KB
/
send.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<?php
declare(strict_types=1);
use Segment\Segment;
/**
* require client
*/
require __DIR__ . '/bootstrap.php';
/**
* Args
*/
$args = parse($argv);
/**
* Make sure both are set
*/
if (!isset($args['secret'])) {
die('--secret must be given');
}
if (!isset($args['file'])) {
die('--file must be given');
}
$file = $args['file'];
if ($file[0] !== '/') {
$file = __DIR__ . '/' . $file;
}
/**
* Rename the file so we don't write the same calls
* multiple times
*/
$dir = dirname($file);
$old = $file;
$file = $dir . '/analytics-' . mt_rand() . '.log';
if (!file_exists($old)) {
print("file: $old does not exist");
exit(0);
}
if (!rename($old, $file)) {
print("error renaming from $old to $file\n");
exit(1);
}
/**
* File contents.
*/
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
/**
* Initialize the client.
*/
Segment::init($args['secret'], [
'debug' => true,
'error_handler' => static function ($code, $msg) {
print("$code: $msg\n");
exit(1);
},
]);
/**
* Payloads
*/
$total = 0;
$successful = 0;
foreach ($lines as $line) {
if (!trim($line)) {
continue;
}
$total++;
$payload = json_decode($line, true);
$dt = new DateTime($payload['timestamp']);
$ts = (float)($dt->getTimestamp() . '.' . $dt->format('u'));
$payload['timestamp'] = date('c', (int)$ts);
$type = $payload['type'];
$currentBatch[] = $payload;
// flush before batch gets too big
if (mb_strlen((json_encode(['batch' => $currentBatch, 'sentAt' => date('c')])), '8bit') >= 512000) {
$libCurlResponse = Segment::flush();
if ($libCurlResponse) {
$successful += count($currentBatch) - 1;
//} else {
// todo: maybe write batch to analytics-error.log for more controlled errorhandling
}
$currentBatch = [];
}
$payload['timestamp'] = $ts;
call_user_func([Segment::class, $type], $payload);
}
$libCurlResponse = Segment::flush();
if ($libCurlResponse) {
$successful += $total - $successful;
}
unlink($file);
/**
* Sent
*/
print("sent $successful from $total requests successfully");
exit(0);
/**
* Parse arguments
*/
function parse($argv): array
{
$ret = [];
foreach ($argv as $i => $iValue) {
$arg = $iValue;
if (strpos($arg, '--') !== 0) {
continue;
}
$ret[substr($arg, 2, strlen($arg))] = trim($argv[++$i]);
}
return $ret;
}