|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Puzzle\AMQP\Workers\Chunks\ChunkAssemblyTrackers; |
|
4
|
|
|
|
|
5
|
|
|
use Puzzle\AMQP\Workers\Chunks\ChunkAssemblyTracker; |
|
6
|
|
|
use Puzzle\ValueObjects\Uuid; |
|
7
|
|
|
use Puzzle\AMQP\Messages\Chunks\ChunkedMessageMetadata; |
|
8
|
|
|
|
|
9
|
|
|
class SingleTrackingInMemory implements ChunkAssemblyTracker |
|
10
|
|
|
{ |
|
11
|
|
|
private |
|
12
|
|
|
$uuid, |
|
13
|
|
|
$chunks, |
|
14
|
|
|
$nbChunksLeft, |
|
15
|
|
|
$nbChunks; |
|
16
|
|
|
|
|
17
|
|
|
public function __construct() |
|
18
|
|
|
{ |
|
19
|
|
|
$this->uuid = null; |
|
20
|
|
|
$this->chunks = null; |
|
21
|
|
|
$this->nbChunksLeft = 0; |
|
22
|
|
|
$this->nbChunks = 0; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function start(ChunkedMessageMetadata $metadata) |
|
26
|
|
|
{ |
|
27
|
|
|
if($this->uuid instanceof Uuid) |
|
28
|
|
|
{ |
|
29
|
|
|
if($this->isAllHasBeenReceived($this->uuid) === false) |
|
30
|
|
|
{ |
|
31
|
|
|
throw new \LogicException( |
|
32
|
|
|
"Another tracking is in progress (" . $this->uuid . "), cannot start tracking " . $metadata->uuid() |
|
33
|
|
|
); |
|
34
|
|
|
} |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$nbChunks = $metadata->nbChunks(); |
|
38
|
|
|
|
|
39
|
|
|
$this->uuid = $metadata->uuid(); |
|
40
|
|
|
$this->nbChunks = $nbChunks; |
|
41
|
|
|
$this->nbChunksLeft = $nbChunks; |
|
42
|
|
|
$this->chunks = array_fill(0, $nbChunks, false); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function hasBeenStarted(Uuid $uuid) |
|
46
|
|
|
{ |
|
47
|
|
|
return $this->uuid instanceof Uuid |
|
48
|
|
|
&& $this->uuid->equals($uuid) |
|
49
|
|
|
&& is_array($this->chunks); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
private function ensureHasBeenStarted(Uuid $uuid) |
|
53
|
|
|
{ |
|
54
|
|
|
if(! $this->hasBeenStarted($uuid)) |
|
55
|
|
|
{ |
|
56
|
|
|
throw new \LogicException("Chunk assembly tracking has not been initialized ($uuid)"); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
private function convertPlayhead($playhead) |
|
61
|
|
|
{ |
|
62
|
|
|
// 1-based --> 0-based |
|
63
|
|
|
return $playhead - 1; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
public function markAsReceived(Uuid $uuid, $playhead) |
|
67
|
|
|
{ |
|
68
|
|
|
$this->ensureHasBeenStarted($uuid); |
|
69
|
|
|
|
|
70
|
|
|
$playhead = $this->convertPlayhead($playhead); |
|
71
|
|
|
|
|
72
|
|
|
if(! array_key_exists($playhead, $this->chunks)) |
|
73
|
|
|
{ |
|
74
|
|
|
throw new \LogicException("Invalid chunk number : $playhead"); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
if($this->chunks[$playhead] === false) |
|
78
|
|
|
{ |
|
79
|
|
|
$this->nbChunksLeft--; |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
$this->chunks[$playhead] = true; |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
public function isAllHasBeenReceived(Uuid $uuid) |
|
86
|
|
|
{ |
|
87
|
|
|
$this->ensureHasBeenStarted($uuid); |
|
88
|
|
|
|
|
89
|
|
|
return $this->nbChunksLeft === 0; |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|