multi_bucket_s3.py 5.8 KB

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