FileCache.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 << 30) // 1G
  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. const char* content_type;
  23. file_cache_s() {
  24. stat_cnt = 0;
  25. content_type = NULL;
  26. }
  27. bool is_modified() {
  28. time_t mtime = st.st_mtime;
  29. stat(filepath.c_str(), &st);
  30. if (mtime == st.st_mtime) {
  31. return false;
  32. }
  33. return true;
  34. }
  35. bool is_complete() {
  36. return filebuf.len == st.st_size;
  37. }
  38. void resize_buf(int filesize) {
  39. buf.resize(HTTP_HEADER_MAX_LENGTH + filesize);
  40. filebuf.base = buf.base + HTTP_HEADER_MAX_LENGTH;
  41. filebuf.len = filesize;
  42. }
  43. void prepend_header(const char* header, int len) {
  44. if (len > HTTP_HEADER_MAX_LENGTH) return;
  45. httpbuf.base = filebuf.base - len;
  46. httpbuf.len = len + filebuf.len;
  47. memcpy(httpbuf.base, header, len);
  48. }
  49. } file_cache_t;
  50. typedef std::shared_ptr<file_cache_t> file_cache_ptr;
  51. // filepath => file_cache_ptr
  52. typedef std::map<std::string, file_cache_ptr> FileCacheMap;
  53. #define DEFAULT_FILE_STAT_INTERVAL 10 // s
  54. #define DEFAULT_FILE_EXPIRED_TIME 60 // s
  55. class FileCache {
  56. public:
  57. int file_stat_interval;
  58. int file_expired_time;
  59. FileCacheMap cached_files;
  60. std::mutex mutex_;
  61. FileCache() {
  62. file_stat_interval = DEFAULT_FILE_STAT_INTERVAL;
  63. file_expired_time = DEFAULT_FILE_EXPIRED_TIME;
  64. }
  65. file_cache_ptr Open(const char* filepath, bool need_read = true, void* ctx = NULL);
  66. bool Close(const char* filepath);
  67. bool Close(const file_cache_ptr& fc);
  68. void RemoveExpiredFileCache();
  69. protected:
  70. file_cache_ptr Get(const char* filepath);
  71. };
  72. #endif // HV_FILE_CACHE_H_