FileCache.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #ifndef HV_FILE_CACHE_H_
  2. #define HV_FILE_CACHE_H_
  3. #include <memory>
  4. #include <map>
  5. #include <string>
  6. #include <mutex>
  7. #include "hbuf.h"
  8. #include "hstring.h"
  9. #define HTTP_HEADER_MAX_LENGTH 1024 // 1K
  10. #define FILE_CACHE_MAX_SIZE (1 << 22) // 4M
  11. typedef struct file_cache_s {
  12. std::string filepath;
  13. struct stat st;
  14. time_t open_time;
  15. time_t stat_time;
  16. uint32_t stat_cnt;
  17. HBuf buf; // http_header + file_content
  18. hbuf_t filebuf;
  19. hbuf_t httpbuf;
  20. char last_modified[64];
  21. char etag[64];
  22. std::string content_type;
  23. file_cache_s() {
  24. stat_cnt = 0;
  25. }
  26. bool is_modified() {
  27. time_t mtime = st.st_mtime;
  28. stat(filepath.c_str(), &st);
  29. return mtime != st.st_mtime;
  30. }
  31. bool is_complete() {
  32. if(S_ISDIR(st.st_mode)) return filebuf.len > 0;
  33. return filebuf.len == st.st_size;
  34. }
  35. void resize_buf(int filesize) {
  36. buf.resize(HTTP_HEADER_MAX_LENGTH + filesize);
  37. filebuf.base = buf.base + HTTP_HEADER_MAX_LENGTH;
  38. filebuf.len = filesize;
  39. }
  40. void prepend_header(const char* header, int len) {
  41. if (len > HTTP_HEADER_MAX_LENGTH) return;
  42. httpbuf.base = filebuf.base - len;
  43. httpbuf.len = len + filebuf.len;
  44. memcpy(httpbuf.base, header, len);
  45. }
  46. } file_cache_t;
  47. typedef std::shared_ptr<file_cache_t> file_cache_ptr;
  48. // filepath => file_cache_ptr
  49. typedef std::map<std::string, file_cache_ptr> FileCacheMap;
  50. class FileCache {
  51. public:
  52. FileCacheMap cached_files;
  53. std::mutex mutex_;
  54. int stat_interval;
  55. int expired_time;
  56. FileCache();
  57. struct OpenParam {
  58. bool need_read;
  59. int max_read;
  60. const char* path;
  61. size_t filesize;
  62. int error;
  63. OpenParam() {
  64. need_read = true;
  65. max_read = FILE_CACHE_MAX_SIZE;
  66. path = "/";
  67. filesize = 0;
  68. error = 0;
  69. }
  70. };
  71. file_cache_ptr Open(const char* filepath, OpenParam* param);
  72. bool Close(const char* filepath);
  73. bool Close(const file_cache_ptr& fc);
  74. void RemoveExpiredFileCache();
  75. protected:
  76. file_cache_ptr Get(const char* filepath);
  77. };
  78. #endif // HV_FILE_CACHE_H_