blob: 10a37cdb1689d2a494cf99de1306f156762fc9b3 [file] [log] [blame]
mlumishb892a272014-12-09 16:28:23 -08001<?php
2namespace Grpc;
3
4/**
5 * Represents an active call that allows sending and recieving binary data
6 */
7class ActiveCall {
8 private $completion_queue;
9 private $call;
10 private $flags;
11 private $metadata;
12
13 /**
14 * Create a new active call.
15 * @param Channel $channel The channel to communicate on
16 * @param string $method The method to call on the remote server
17 * @param array $metadata Metadata to send with the call, if applicable
18 * @param long $flags Write flags to use with this call
19 */
20 public function __construct(Channel $channel,
21 $method,
22 $metadata = array(),
23 $flags = 0) {
24 $this->completion_queue = new CompletionQueue();
25 $this->call = new Call($channel, $method, Timeval::inf_future());
26 $this->call->add_metadata($metadata, 0);
27 $this->flags = $flags;
28
29 // Invoke the call.
30 $this->call->start_invoke($this->completion_queue,
31 INVOKE_ACCEPTED,
32 CLIENT_METADATA_READ,
33 FINISHED, 0);
34 $this->completion_queue->pluck(INVOKE_ACCEPTED,
35 Timeval::inf_future());
36 $metadata_event = $this->completion_queue->pluck(CLIENT_METADATA_READ,
37 Timeval::inf_future());
38 $this->metadata = $metadata_event->get_data();
39 }
40
41 /**
42 * @return The metadata sent by the server.
43 */
44 public function getMetadata() {
45 return $this->metadata;
46 }
47
48 /**
49 * Cancels the call
50 */
51 public function cancel() {
52 $this->call->cancel();
53 }
54
55 /**
56 * Read a single message from the server.
57 * @return The next message from the server, or null if there is none.
58 */
59 public function read() {
60 $this->call->start_read(READ);
61 $read_event = $this->completion_queue->pluck(READ, Timeval::inf_future());
62 return $read_event->get_data();
63 }
64
65 /**
66 * Write a single message to the server. This cannot be called after
67 * writesDone is called.
68 * @param ByteBuffer $data The data to write
69 */
70 public function write($data) {
71 if($this->call->start_write($data,
72 WRITE_ACCEPTED,
73 $this->flags) != OP_OK) {
74 // TODO(mlumish): more useful error
75 throw new \Exception("Cannot call write after writesDone");
76 }
77 $this->completion_queue->pluck(WRITE_ACCEPTED, Timeval::inf_future());
78 }
79
80 /**
81 * Indicate that no more writes will be sent.
82 */
83 public function writesDone() {
84 $this->call->writes_done(FINISH_ACCEPTED);
85 $this->completion_queue->pluck(FINISH_ACCEPTED, Timeval::inf_future());
86 }
87
88 /**
89 * Wait for the server to send the status, and return it.
90 * @return object The status object, with integer $code and string $details
91 * members
92 */
93 public function getStatus() {
94 $status_event = $this->completion_queue->pluck(FINISHED,
95 Timeval::inf_future());
96 return $status_event->get_data();
97 }
98}