SessionHandler.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. <?php
  2. namespace Aws\DynamoDb;
  3. /**
  4. * Provides an interface for using Amazon DynamoDB as a session store by hooking
  5. * into PHP's session handler hooks. Once registered, You may use the native
  6. * `$_SESSION` superglobal and session functions, and the sessions will be
  7. * stored automatically in DynamoDB. DynamoDB is a great session storage
  8. * solution due to its speed, scalability, and fault tolerance.
  9. *
  10. * For maximum performance, we recommend that you keep the size of your sessions
  11. * small. Locking is disabled by default, since it can drive up latencies and
  12. * costs under high traffic. Only turn it on if you need it.
  13. *
  14. * By far, the most expensive operation is garbage collection. Therefore, we
  15. * encourage you to carefully consider your session garbage collection strategy.
  16. * Note: the DynamoDB Session Handler does not allow garbage collection to be
  17. * triggered randomly. You must run garbage collection manually or through other
  18. * automated means using a cron job or similar scheduling technique.
  19. */
  20. class SessionHandler implements \SessionHandlerInterface
  21. {
  22. /** @var SessionConnectionInterface Session save logic.*/
  23. private $connection;
  24. /** @var string Session save path. */
  25. private $savePath;
  26. /** @var string Session name. */
  27. private $sessionName;
  28. /** @var string The last known session ID */
  29. private $openSessionId = '';
  30. /** @var string Stores serialized data for tracking changes. */
  31. private $dataRead = '';
  32. /** @var bool Keeps track of whether the session has been written. */
  33. private $sessionWritten = false;
  34. /**
  35. * Creates a new DynamoDB Session Handler.
  36. *
  37. * The configuration array accepts the following array keys and values:
  38. * - table_name: Name of table to store the sessions.
  39. * - hash_key: Name of hash key in table. Default: "id".
  40. * - session_lifetime: Lifetime of inactive sessions expiration.
  41. * - consistent_read: Whether or not to use consistent reads.
  42. * - batch_config: Batch options used for garbage collection.
  43. * - locking: Whether or not to use session locking.
  44. * - max_lock_wait_time: Max time (s) to wait for lock acquisition.
  45. * - min_lock_retry_microtime: Min time (µs) to wait between lock attempts.
  46. * - max_lock_retry_microtime: Max time (µs) to wait between lock attempts.
  47. *
  48. * @param DynamoDbClient $client Client for doing DynamoDB operations
  49. * @param array $config Configuration for the Session Handler
  50. *
  51. * @return SessionHandler
  52. */
  53. public static function fromClient(DynamoDbClient $client, array $config = [])
  54. {
  55. $config += ['locking' => false];
  56. if ($config['locking']) {
  57. $connection = new LockingSessionConnection($client, $config);
  58. } else {
  59. $connection = new StandardSessionConnection($client, $config);
  60. }
  61. return new static($connection);
  62. }
  63. /**
  64. * @param SessionConnectionInterface $connection
  65. */
  66. public function __construct(SessionConnectionInterface $connection)
  67. {
  68. $this->connection = $connection;
  69. }
  70. /**
  71. * Register the DynamoDB session handler.
  72. *
  73. * @return bool Whether or not the handler was registered.
  74. * @codeCoverageIgnore
  75. */
  76. public function register()
  77. {
  78. return session_set_save_handler($this, true);
  79. }
  80. /**
  81. * Open a session for writing. Triggered by session_start().
  82. *
  83. * @param string $savePath Session save path.
  84. * @param string $sessionName Session name.
  85. *
  86. * @return bool Whether or not the operation succeeded.
  87. */
  88. public function open($savePath, $sessionName)
  89. {
  90. $this->savePath = $savePath;
  91. $this->sessionName = $sessionName;
  92. return true;
  93. }
  94. /**
  95. * Close a session from writing.
  96. *
  97. * @return bool Success
  98. */
  99. public function close()
  100. {
  101. $id = session_id();
  102. // Make sure the session is unlocked and the expiration time is updated,
  103. // even if the write did not occur
  104. if ($this->openSessionId !== $id || !$this->sessionWritten) {
  105. $result = $this->connection->write($this->formatId($id), '', false);
  106. $this->sessionWritten = (bool) $result;
  107. }
  108. return $this->sessionWritten;
  109. }
  110. /**
  111. * Read a session stored in DynamoDB.
  112. *
  113. * @param string $id Session ID.
  114. *
  115. * @return string Session data.
  116. */
  117. public function read($id)
  118. {
  119. $this->openSessionId = $id;
  120. // PHP expects an empty string to be returned from this method if no
  121. // data is retrieved
  122. $this->dataRead = '';
  123. // Get session data using the selected locking strategy
  124. $item = $this->connection->read($this->formatId($id));
  125. // Return the data if it is not expired. If it is expired, remove it
  126. if (isset($item['expires']) && isset($item['data'])) {
  127. $this->dataRead = $item['data'];
  128. if ($item['expires'] <= time()) {
  129. $this->dataRead = '';
  130. $this->destroy($id);
  131. }
  132. }
  133. return $this->dataRead;
  134. }
  135. /**
  136. * Write a session to DynamoDB.
  137. *
  138. * @param string $id Session ID.
  139. * @param string $data Serialized session data to write.
  140. *
  141. * @return bool Whether or not the operation succeeded.
  142. */
  143. public function write($id, $data)
  144. {
  145. $changed = $id !== $this->openSessionId
  146. || $data !== $this->dataRead;
  147. $this->openSessionId = $id;
  148. // Write the session data using the selected locking strategy
  149. $this->sessionWritten = $this->connection
  150. ->write($this->formatId($id), $data, $changed);
  151. return $this->sessionWritten;
  152. }
  153. /**
  154. * Delete a session stored in DynamoDB.
  155. *
  156. * @param string $id Session ID.
  157. *
  158. * @return bool Whether or not the operation succeeded.
  159. */
  160. public function destroy($id)
  161. {
  162. $this->openSessionId = $id;
  163. // Delete the session data using the selected locking strategy
  164. $this->sessionWritten
  165. = $this->connection->delete($this->formatId($id));
  166. return $this->sessionWritten;
  167. }
  168. /**
  169. * Satisfies the session handler interface, but does nothing. To do garbage
  170. * collection, you must manually call the garbageCollect() method.
  171. *
  172. * @param int $maxLifetime Ignored.
  173. *
  174. * @return bool Whether or not the operation succeeded.
  175. * @codeCoverageIgnore
  176. */
  177. public function gc($maxLifetime)
  178. {
  179. // Garbage collection for a DynamoDB table must be triggered manually.
  180. return true;
  181. }
  182. /**
  183. * Triggers garbage collection on expired sessions.
  184. * @codeCoverageIgnore
  185. */
  186. public function garbageCollect()
  187. {
  188. $this->connection->deleteExpired();
  189. }
  190. /**
  191. * Prepend the session ID with the session name.
  192. *
  193. * @param string $id The session ID.
  194. *
  195. * @return string Prepared session ID.
  196. */
  197. private function formatId($id)
  198. {
  199. return trim($this->sessionName . '_' . $id, '_');
  200. }
  201. }