summaryrefslogtreecommitdiff
path: root/Postman/Postman-Mail/google-api-php-client-1.1.2/src/Google/Cache/File.php
blob: 000e0db0df14576f67c786004722b2edaefab01b (plain)
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
<?php
/*
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once realpath(dirname(__FILE__) . '/../../../autoload.php');

/*
 * This class implements a basic on disk storage. While that does
 * work quite well it's not the most elegant and scalable solution.
 * It will also get you into a heap of trouble when you try to run
 * this in a clustered environment.
 *
 * @author Chris Chabot <chabotc@google.com>
 */
class Postman_Google_Cache_File extends Postman_Google_Cache_Abstract
{
  const MAX_LOCK_RETRIES = 10;
  private $path;
  private $fh;

  /**
   * @var Postman_Google_Client the current client
   */
  private $client;

  public function __construct(Postman_Google_Client $client)
  {
    $this->client = $client;
    $this->path = $this->client->getClassConfig($this, 'directory');
  }

  public function get($key, $expiration = false)
  {
    $storageFile = $this->getCacheFile($key);
    $data = false;

    if (!file_exists($storageFile)) {
      $this->client->getLogger()->debug(
          'File cache miss',
          array('key' => $key, 'file' => $storageFile)
      );
      return false;
    }

    if ($expiration) {
      $mtime = filemtime($storageFile);
      if ((time() - $mtime) >= $expiration) {
        $this->client->getLogger()->debug(
            'File cache miss (expired)',
            array('key' => $key, 'file' => $storageFile)
        );
        $this->delete($key);
        return false;
      }
    }

    if ($this->acquireReadLock($storageFile)) {
      $data = fread($this->fh, filesize($storageFile));
      $data =  unserialize($data);
      $this->unlock($storageFile);
    }

    $this->client->getLogger()->debug(
        'File cache hit',
        array('key' => $key, 'file' => $storageFile, 'var' => $data)
    );

    return $data;
  }

  public function set($key, $value)
  {
    $storageFile = $this->getWriteableCacheFile($key);
    if ($this->acquireWriteLock($storageFile)) {
      // We serialize the whole request object, since we don't only want the
      // responseContent but also the postBody used, headers, size, etc.
      $data = serialize($value);
      $result = fwrite($this->fh, $data);
      $this->unlock($storageFile);

      $this->client->getLogger()->debug(
          'File cache set',
          array('key' => $key, 'file' => $storageFile, 'var' => $value)
      );
    } else {
      $this->client->getLogger()->notice(
          'File cache set failed',
          array('key' => $key, 'file' => $storageFile)
      );
    }
  }

  public function delete($key)
  {
    $file = $this->getCacheFile($key);
    if (file_exists($file) && !unlink($file)) {
      $this->client->getLogger()->error(
          'File cache delete failed',
          array('key' => $key, 'file' => $file)
      );
      throw new Postman_Google_Cache_Exception("Cache file could not be deleted");
    }

    $this->client->getLogger()->debug(
        'File cache delete',
        array('key' => $key, 'file' => $file)
    );
  }

  private function getWriteableCacheFile($file)
  {
    return $this->getCacheFile($file, true);
  }

  private function getCacheFile($file, $forWrite = false)
  {
    return $this->getCacheDir($file, $forWrite) . '/' . md5($file);
  }

  private function getCacheDir($file, $forWrite)
  {
    // use the first 2 characters of the hash as a directory prefix
    // this should prevent slowdowns due to huge directory listings
    // and thus give some basic amount of scalability
    $storageDir = $this->path . '/' . substr(md5($file), 0, 2);
    if ($forWrite && ! is_dir($storageDir)) {
      if (! mkdir($storageDir, 0755, true)) {
        $this->client->getLogger()->error(
            'File cache creation failed',
            array('dir' => $storageDir)
        );
        throw new Postman_Google_Cache_Exception("Could not create storage directory: $storageDir");
      }
    }
    return $storageDir;
  }

  private function acquireReadLock($storageFile)
  {
    return $this->acquireLock(LOCK_SH, $storageFile);
  }

  private function acquireWriteLock($storageFile)
  {
    $rc = $this->acquireLock(LOCK_EX, $storageFile);
    if (!$rc) {
      $this->client->getLogger()->notice(
          'File cache write lock failed',
          array('file' => $storageFile)
      );
      $this->delete($storageFile);
    }
    return $rc;
  }

  private function acquireLock($type, $storageFile)
  {
    $mode = $type == LOCK_EX ? "w" : "r";
    $this->fh = fopen($storageFile, $mode);
    $count = 0;
    while (!flock($this->fh, $type | LOCK_NB)) {
      // Sleep for 10ms.
      usleep(10000);
      if (++$count < self::MAX_LOCK_RETRIES) {
        return false;
      }
    }
    return true;
  }

  public function unlock($storageFile)
  {
    if ($this->fh) {
      flock($this->fh, LOCK_UN);
    }
  }
}