FileCache.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. #include "LRUCache.h"
  10. #define HTTP_HEADER_MAX_LENGTH 1024 // 1K
  11. #define FILE_CACHE_MAX_NUM 100
  12. #define FILE_CACHE_MAX_SIZE (1 << 22) // 4M
  13. typedef struct file_cache_s {
  14. std::string filepath;
  15. struct stat st;
  16. time_t open_time;
  17. time_t stat_time;
  18. uint32_t stat_cnt;
  19. HBuf buf; // http_header + file_content
  20. hbuf_t filebuf;
  21. hbuf_t httpbuf;
  22. char last_modified[64];
  23. char etag[64];
  24. std::string content_type;
  25. file_cache_s() {
  26. stat_cnt = 0;
  27. }
  28. bool is_modified() {
  29. time_t mtime = st.st_mtime;
  30. stat(filepath.c_str(), &st);
  31. return mtime != st.st_mtime;
  32. }
  33. bool is_complete() {
  34. if(S_ISDIR(st.st_mode)) return filebuf.len > 0;
  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. class FileCache : public hv::LRUCache<std::string, file_cache_ptr> {
  51. public:
  52. int stat_interval;
  53. int expired_time;
  54. FileCache(size_t capacity = FILE_CACHE_MAX_NUM);
  55. struct OpenParam {
  56. bool need_read;
  57. int max_read;
  58. const char* path;
  59. size_t filesize;
  60. int error;
  61. OpenParam() {
  62. need_read = true;
  63. max_read = FILE_CACHE_MAX_SIZE;
  64. path = "/";
  65. filesize = 0;
  66. error = 0;
  67. }
  68. };
  69. file_cache_ptr Open(const char* filepath, OpenParam* param);
  70. bool Exists(const char* filepath) const;
  71. bool Close(const char* filepath);
  72. void RemoveExpiredFileCache();
  73. protected:
  74. file_cache_ptr Get(const char* filepath);
  75. };
  76. #endif // HV_FILE_CACHE_H_