FileCache.h 2.5 KB

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