multi_bucket_s3.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import os
  2. from magic_pdf.config.exceptions import InvalidConfig, InvalidParams
  3. from magic_pdf.data.data_reader_writer.base import DataReader, DataWriter
  4. from magic_pdf.data.io.s3 import S3Reader, S3Writer
  5. from magic_pdf.data.schemas import S3Config
  6. from magic_pdf.libs.path_utils import (parse_s3_range_params, parse_s3path,
  7. remove_non_official_s3_args)
  8. class MultiS3Mixin:
  9. def __init__(self, default_prefix: str, s3_configs: list[S3Config]):
  10. """Initialized with multiple s3 configs.
  11. Args:
  12. default_prefix (str): the default prefix of the relative path. for example, {some_bucket}/{some_prefix} or {some_bucket}
  13. s3_configs (list[S3Config]): list of s3 configs, the bucket_name must be unique in the list.
  14. Raises:
  15. InvalidConfig: default bucket config not in s3_configs.
  16. InvalidConfig: bucket name not unique in s3_configs.
  17. InvalidConfig: default bucket must be provided.
  18. """
  19. if len(default_prefix) == 0:
  20. raise InvalidConfig('default_prefix must be provided')
  21. arr = default_prefix.strip("/").split("/")
  22. self.default_bucket = arr[0]
  23. self.default_prefix = "/".join(arr[1:])
  24. found_default_bucket_config = False
  25. for conf in s3_configs:
  26. if conf.bucket_name == self.default_bucket:
  27. found_default_bucket_config = True
  28. break
  29. if not found_default_bucket_config:
  30. raise InvalidConfig(
  31. f'default_bucket: {self.default_bucket} config must be provided in s3_configs: {s3_configs}'
  32. )
  33. uniq_bucket = set([conf.bucket_name for conf in s3_configs])
  34. if len(uniq_bucket) != len(s3_configs):
  35. raise InvalidConfig(
  36. f'the bucket_name in s3_configs: {s3_configs} must be unique'
  37. )
  38. self.s3_configs = s3_configs
  39. self._s3_clients_h: dict = {}
  40. class MultiBucketS3DataReader(DataReader, MultiS3Mixin):
  41. def read(self, path: str) -> bytes:
  42. """Read the path from s3, select diffect bucket client for each request
  43. based on the bucket, also support range read.
  44. Args:
  45. path (str): the s3 path of file, the path must be in the format of s3://bucket_name/path?offset,limit.
  46. for example: s3://bucket_name/path?0,100.
  47. Returns:
  48. bytes: the content of s3 file.
  49. """
  50. may_range_params = parse_s3_range_params(path)
  51. if may_range_params is None or 2 != len(may_range_params):
  52. byte_start, byte_len = 0, -1
  53. else:
  54. byte_start, byte_len = int(may_range_params[0]), int(may_range_params[1])
  55. path = remove_non_official_s3_args(path)
  56. return self.read_at(path, byte_start, byte_len)
  57. def __get_s3_client(self, bucket_name: str):
  58. if bucket_name not in set([conf.bucket_name for conf in self.s3_configs]):
  59. raise InvalidParams(
  60. f'bucket name: {bucket_name} not found in s3_configs: {self.s3_configs}'
  61. )
  62. if bucket_name not in self._s3_clients_h:
  63. conf = next(
  64. filter(lambda conf: conf.bucket_name == bucket_name, self.s3_configs)
  65. )
  66. self._s3_clients_h[bucket_name] = S3Reader(
  67. bucket_name,
  68. conf.access_key,
  69. conf.secret_key,
  70. conf.endpoint_url,
  71. conf.addressing_style,
  72. )
  73. return self._s3_clients_h[bucket_name]
  74. def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
  75. """Read the file with offset and limit, select diffect bucket client
  76. for each request based on the bucket.
  77. Args:
  78. path (str): the file path.
  79. offset (int, optional): the number of bytes skipped. Defaults to 0.
  80. limit (int, optional): the number of bytes want to read. Defaults to -1 which means infinite.
  81. Returns:
  82. bytes: the file content.
  83. """
  84. if path.startswith('s3://'):
  85. bucket_name, path = parse_s3path(path)
  86. s3_reader = self.__get_s3_client(bucket_name)
  87. else:
  88. s3_reader = self.__get_s3_client(self.default_bucket)
  89. path = os.path.join(self.default_prefix, path)
  90. return s3_reader.read_at(path, offset, limit)
  91. class MultiBucketS3DataWriter(DataWriter, MultiS3Mixin):
  92. def __get_s3_client(self, bucket_name: str):
  93. if bucket_name not in set([conf.bucket_name for conf in self.s3_configs]):
  94. raise InvalidParams(
  95. f'bucket name: {bucket_name} not found in s3_configs: {self.s3_configs}'
  96. )
  97. if bucket_name not in self._s3_clients_h:
  98. conf = next(
  99. filter(lambda conf: conf.bucket_name == bucket_name, self.s3_configs)
  100. )
  101. self._s3_clients_h[bucket_name] = S3Writer(
  102. bucket_name,
  103. conf.access_key,
  104. conf.secret_key,
  105. conf.endpoint_url,
  106. conf.addressing_style,
  107. )
  108. return self._s3_clients_h[bucket_name]
  109. def write(self, path: str, data: bytes) -> None:
  110. """Write file with data, also select diffect bucket client for each
  111. request based on the bucket.
  112. Args:
  113. path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
  114. data (bytes): the data want to write.
  115. """
  116. if path.startswith('s3://'):
  117. bucket_name, path = parse_s3path(path)
  118. s3_writer = self.__get_s3_client(bucket_name)
  119. else:
  120. s3_writer = self.__get_s3_client(self.default_bucket)
  121. path = os.path.join(self.default_prefix, path)
  122. return s3_writer.write(path, data)