utils.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. from __future__ import annotations
  2. import re
  3. from collections.abc import Iterable, Mapping
  4. from enum import Enum
  5. from typing import Any
  6. from urllib.parse import urlparse
  7. from wandb_gql import gql
  8. from wandb_graphql import TypeInfo
  9. from wandb_graphql.language import ast, visitor
  10. from wandb_graphql.validation.validation import ValidationContext
  11. from wandb._iterutils import one
  12. from wandb.sdk.internal.internal_api import Api as InternalApi
  13. def parse_s3_url_to_s3_uri(url) -> str:
  14. """Convert an S3 HTTP(S) URL to an S3 URI.
  15. Arguments:
  16. url (str): The S3 URL to convert, in the format
  17. 'http(s)://<bucket>.s3.<region>.amazonaws.com/<key>'.
  18. or 'http(s)://<bucket>.s3.amazonaws.com/<key>'
  19. Returns:
  20. str: The corresponding S3 URI in the format 's3://<bucket>/<key>'.
  21. Raises:
  22. ValueError: If the provided URL is not a valid S3 URL.
  23. """
  24. # Regular expression to match S3 URL pattern
  25. s3_pattern = r"^https?://.*s3.*amazonaws\.com.*"
  26. parsed_url = urlparse(url)
  27. # Check if it's an S3 URL
  28. match = re.match(s3_pattern, parsed_url.geturl())
  29. if not match:
  30. raise ValueError("Invalid S3 URL")
  31. # Extract bucket name and key
  32. bucket_name, *_ = parsed_url.netloc.split(".")
  33. key = parsed_url.path.lstrip("/")
  34. # Construct the S3 URI
  35. s3_uri = f"s3://{bucket_name}/{key}"
  36. return s3_uri
  37. class PathType(Enum):
  38. """We have lots of different paths users pass in to fetch artifacts, projects, etc.
  39. This enum is used for specifying what format the path is in given a string path.
  40. """
  41. PROJECT = "PROJECT"
  42. ARTIFACT = "ARTIFACT"
  43. def parse_org_from_registry_path(path: str, path_type: PathType) -> str:
  44. """Parse the org from a registry path.
  45. Essentially fetching the "entity" from the path but for Registries the entity is actually the org.
  46. Args:
  47. path (str): The path to parse. Can be a project path <entity>/<project> or <project> or an
  48. artifact path like <entity>/<project>/<artifact> or <project>/<artifact> or <artifact>
  49. path_type (PathType): The type of path to parse.
  50. """
  51. from wandb.sdk.artifacts._validators import is_artifact_registry_project
  52. parts = path.split("/")
  53. expected_parts = 3 if path_type == PathType.ARTIFACT else 2
  54. if len(parts) >= expected_parts:
  55. org, project = parts[:2]
  56. if is_artifact_registry_project(project):
  57. return org
  58. return ""
  59. def fetch_org_from_settings_or_entity(
  60. settings: dict, default_entity: str | None = None
  61. ) -> str:
  62. """Fetch the org from either the settings or deriving it from the entity.
  63. Returns the org from the settings if available. If no org is passed in or set, the entity is used to fetch the org.
  64. Args:
  65. organization (str | None): The organization to fetch the org for.
  66. settings (dict): The settings to fetch the org for.
  67. default_entity (str | None): The default entity to fetch the org for.
  68. """
  69. if (organization := settings.get("organization")) is None:
  70. # Fetch the org via the Entity. Won't work if default entity is a personal entity and belongs to multiple orgs
  71. entity = settings.get("entity") or default_entity
  72. if entity is None:
  73. raise ValueError(
  74. "No entity specified and can't fetch organization from the entity"
  75. )
  76. entity_orgs = InternalApi()._fetch_orgs_and_org_entities_from_entity(entity)
  77. entity_org = one(
  78. entity_orgs,
  79. too_short=ValueError(
  80. "No organizations found for entity. Please specify an organization in the settings."
  81. ),
  82. too_long=ValueError(
  83. "Multiple organizations found for entity. Please specify an organization in the settings."
  84. ),
  85. )
  86. organization = entity_org.display_name
  87. return organization
  88. class _GQLCompatRewriter(visitor.Visitor):
  89. """GraphQL AST visitor to rewrite queries/mutations to be compatible with older server versions."""
  90. def __init__(
  91. self,
  92. omit_variables: Iterable[str] | None = None,
  93. omit_fragments: Iterable[str] | None = None,
  94. omit_fields: Iterable[str] | None = None,
  95. rename_fields: Mapping[str, str] | None = None,
  96. ):
  97. self.omit_variables = set(omit_variables or ())
  98. self.omit_fragments = set(omit_fragments or ())
  99. self.omit_fields = set(omit_fields or ())
  100. self.rename_fields = dict(rename_fields or {})
  101. def leave_Document(self, node: ast.Document, *_, **__) -> Any: # noqa: N802
  102. # After rewriting the GQL document, prune "orphan" (unused) fragment definitions.
  103. # Note: The ValidationContext doesn't require a schema here, as we only use it to check for reachable fragments.
  104. ctx = ValidationContext(schema=None, ast=node, type_info=TypeInfo(schema=None))
  105. operation_defns = {
  106. dfn for dfn in node.definitions if isinstance(dfn, ast.OperationDefinition)
  107. }
  108. used_fragment_defns = {
  109. frag
  110. for op in operation_defns
  111. for frag in ctx.get_recursively_referenced_fragments(op)
  112. }
  113. # Preserve original defintion order
  114. allowed_defns = operation_defns | used_fragment_defns
  115. node.definitions = [dfn for dfn in node.definitions if (dfn in allowed_defns)]
  116. def enter_Variable(self, node: ast.Variable, *_, **__) -> Any: # noqa: N802
  117. if node.name.value in self.omit_variables:
  118. return visitor.REMOVE
  119. def leave_VariableDefinition(self, node: ast.VariableDefinition, *_, **__) -> Any: # noqa: N802
  120. # For context, consider the `$varName: String` variable definition below:
  121. # (..., $varName: String, ...)
  122. #
  123. # On ENTERING, the AST looks like:
  124. # VariableDefinition(variable=Variable(name=Name(value='varName')), ...)
  125. #
  126. # On LEAVING, if `$varName` was removed, the AST looks like:
  127. # VariableDefinition(variable=REMOVE, ...)
  128. if node.variable is visitor.REMOVE:
  129. return visitor.REMOVE
  130. def leave_ObjectField(self, node: ast.ObjectField, *_, **__) -> Any: # noqa: N802
  131. # For context, consider `argName: $varName` in the input args below:
  132. # input: {..., argName: $varName, ...}
  133. #
  134. # On ENTERING, the AST for `argName: $varName` looks like:
  135. # ObjectField(
  136. # name=Name(value='argName'), value=Variable(name=Name(value='varName')),
  137. # )
  138. #
  139. # On LEAVING, if `$varName` was removed, the AST looks like:
  140. # ObjectField(
  141. # name=Name(value='argName'), value=REMOVE,
  142. # )
  143. if node.value is visitor.REMOVE:
  144. return visitor.REMOVE
  145. def enter_Argument(self, node: ast.Argument, *_, **__) -> Any: # noqa: N802
  146. if node.name.value in self.omit_variables:
  147. return visitor.REMOVE
  148. def enter_FragmentDefinition(self, node: ast.FragmentDefinition, *_, **__) -> Any: # noqa: N802
  149. if node.name.value in self.omit_fragments:
  150. return visitor.REMOVE
  151. def enter_FragmentSpread(self, node: ast.FragmentSpread, *_, **__) -> Any: # noqa: N802
  152. if node.name.value in self.omit_fragments:
  153. return visitor.REMOVE
  154. def enter_Field(self, node: ast.Field, *_, **__) -> Any: # noqa: N802
  155. if node.name.value in self.omit_fields:
  156. return visitor.REMOVE
  157. if new_name := self.rename_fields.get(node.name.value):
  158. node.name.value = new_name
  159. def leave_Field(self, node: ast.Field, *_, **__) -> Any: # noqa: N802
  160. # If the field had a selection set, but now it's empty, remove the field entirely
  161. if (node.selection_set is not None) and (not node.selection_set.selections):
  162. return visitor.REMOVE
  163. def gql_compat(
  164. request_string: str,
  165. omit_variables: Iterable[str] | None = None,
  166. omit_fragments: Iterable[str] | None = None,
  167. omit_fields: Iterable[str] | None = None,
  168. rename_fields: Mapping[str, str] | None = None,
  169. ) -> ast.Document:
  170. """Rewrite a GraphQL request string to ensure compatibility with older server versions.
  171. Args:
  172. request_string (str): The GraphQL request string to rewrite.
  173. omit_variables (Iterable[str] | None): Names of variables to remove from the request string.
  174. omit_fragments (Iterable[str] | None): Names of fragments to remove from the request string.
  175. omit_fields (Iterable[str] | None): Names of fields to remove from the request string.
  176. rename_fields (Mapping[str, str] | None):
  177. A mapping of fields to rename in the request string, given as `{old_name -> new_name}`.
  178. Returns:
  179. str: Modified GraphQL request string with fragments on omitted types removed.
  180. """
  181. # Parse the request into a GraphQL AST
  182. doc = gql(request_string)
  183. if not (omit_variables or omit_fragments or omit_fields or rename_fields):
  184. return doc
  185. # Visit the AST with our visitor to filter out unwanted fragments
  186. rewriter = _GQLCompatRewriter(
  187. omit_variables=omit_variables,
  188. omit_fragments=omit_fragments,
  189. omit_fields=omit_fields,
  190. rename_fields=rename_fields,
  191. )
  192. return visitor.visit(doc, rewriter)