FileCache.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. return filebuf.len == st.st_size;
  33. }
  34. void resize_buf(int filesize) {
  35. buf.resize(HTTP_HEADER_MAX_LENGTH + filesize);
  36. filebuf.base = buf.base + HTTP_HEADER_MAX_LENGTH;
  37. filebuf.len = filesize;
  38. }
  39. void prepend_header(const char* header, int len) {
  40. if (len > HTTP_HEADER_MAX_LENGTH) return;
  41. httpbuf.base = filebuf.base - len;
  42. httpbuf.len = len + filebuf.len;
  43. memcpy(httpbuf.base, header, len);
  44. }
  45. } file_cache_t;
  46. typedef std::shared_ptr<file_cache_t> file_cache_ptr;
  47. // filepath => file_cache_ptr
  48. typedef std::map<std::string, file_cache_ptr> FileCacheMap;
  49. class FileCache {
  50. public:
  51. FileCacheMap cached_files;
  52. std::mutex mutex_;
  53. int stat_interval;
  54. int expired_time;
  55. FileCache();
  56. struct OpenParam {
  57. bool need_read;
  58. int max_read;
  59. const char* path;
  60. size_t filesize;
  61. int error;
  62. OpenParam() {
  63. need_read = true;
  64. max_read = FILE_CACHE_MAX_SIZE;
  65. path = "/";
  66. filesize = 0;
  67. error = 0;
  68. }
  69. };
  70. file_cache_ptr Open(const char* filepath, OpenParam* param);
  71. bool Close(const char* filepath);
  72. bool Close(const file_cache_ptr& fc);
  73. void RemoveExpiredFileCache();
  74. protected:
  75. file_cache_ptr Get(const char* filepath);
  76. };
  77. #endif // HV_FILE_CACHE_H_