FileCache.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. #define DEFAULT_FILE_STAT_INTERVAL 10 // s
  50. #define DEFAULT_FILE_EXPIRED_TIME 60 // s
  51. class FileCache {
  52. public:
  53. int file_stat_interval;
  54. int file_expired_time;
  55. FileCacheMap cached_files;
  56. std::mutex mutex_;
  57. FileCache() {
  58. file_stat_interval = DEFAULT_FILE_STAT_INTERVAL;
  59. file_expired_time = DEFAULT_FILE_EXPIRED_TIME;
  60. }
  61. struct OpenParam {
  62. bool need_read;
  63. int max_read;
  64. const char* path;
  65. size_t filesize;
  66. int error;
  67. OpenParam() {
  68. need_read = true;
  69. max_read = FILE_CACHE_MAX_SIZE;
  70. path = "/";
  71. filesize = 0;
  72. error = 0;
  73. }
  74. };
  75. file_cache_ptr Open(const char* filepath, OpenParam* param);
  76. bool Close(const char* filepath);
  77. bool Close(const file_cache_ptr& fc);
  78. void RemoveExpiredFileCache();
  79. protected:
  80. file_cache_ptr Get(const char* filepath);
  81. };
  82. #endif // HV_FILE_CACHE_H_