FileCache.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. 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. file_cache_ptr Open(const char* filepath, bool need_read = true, void* ctx = NULL);
  65. bool Close(const char* filepath);
  66. bool Close(const file_cache_ptr& fc);
  67. void RemoveExpiredFileCache();
  68. protected:
  69. file_cache_ptr Get(const char* filepath);
  70. };
  71. #endif // HV_FILE_CACHE_H_