Skip to content

integrate_review

IntegrateAYONReview

Bases: InstancePlugin

Source code in client/ayon_core/plugins/publish/integrate_review.py
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
class IntegrateAYONReview(pyblish.api.InstancePlugin):
    label = "Integrate AYON Review"
    # Must happen after IntegrateAsset
    order = pyblish.api.IntegratorOrder + 0.15

    def process(self, instance):
        project_name = instance.context.data["projectName"]
        src_version_entity = instance.data.get("versionEntity")
        src_hero_version_entity = instance.data.get("heroVersionEntity")
        for version_entity in (
            src_version_entity,
            src_hero_version_entity,
        ):
            if not version_entity:
                continue

            version_id = version_entity["id"]
            self._upload_reviewable(project_name, version_id, instance)

    def _upload_reviewable(self, project_name, version_id, instance):
        ayon_con = ayon_api.get_server_api_connection()
        major, minor, _, _, _ = ayon_con.get_server_version_tuple()
        if (major, minor) < (1, 3):
            self.log.info(
                "Skipping reviewable upload, supported from server 1.3.x."
                f" Current server version {ayon_con.get_server_version()}"
            )
            return

        uploaded_labels = set()
        for repre in instance.data["representations"]:
            repre_tags = repre.get("tags") or []
            # Ignore representations that are not reviewable
            if "webreview" not in repre_tags:
                continue

            # exclude representations going to be published on farm
            if "publish_on_farm" in repre_tags:
                continue

            # Skip thumbnails
            if repre.get("thumbnail") or "thumbnail" in repre_tags:
                continue

            repre_path = get_publish_repre_path(
                instance, repre, False
            )
            if not repre_path or not os.path.exists(repre_path):
                # TODO log skipper path
                continue

            content_type = get_media_mime_type(repre_path)
            if not content_type:
                self.log.warning(
                    f"Could not determine Content-Type for {repre_path}"
                )
                continue

            label = self._get_review_label(repre, uploaded_labels)
            query = ""
            if label:
                query = f"?label={label}"

            endpoint = (
                f"/projects/{project_name}"
                f"/versions/{version_id}/reviewables{query}"
            )
            self.log.info(f"Uploading reviewable {repre_path}")
            # Upload with retries and clear help if it keeps failing
            self._upload_with_retries(
                ayon_con,
                endpoint,
                repre_path,
                content_type,
            )

    def _get_review_label(self, repre, uploaded_labels):
        # Use output name as label if available
        label = repre.get("outputName")
        if not label:
            return None
        orig_label = label
        idx = 0
        while label in uploaded_labels:
            idx += 1
            label = f"{orig_label}_{idx}"
        return label

    def _upload_with_retries(
        self,
        ayon_con: ayon_api.ServerAPI,
        endpoint: str,
        repre_path: str,
        content_type: str,
    ):
        """Upload file with simple retries."""
        filename = os.path.basename(repre_path)

        headers = ayon_con.get_headers(content_type)
        headers["x-file-name"] = filename
        max_retries = ayon_con.get_default_max_retries()
        # Retries are already implemented in 'ayon_api.upload_file'
        # - added in ayon api 1.2.7
        if hasattr(TransferProgress, "get_attempt"):
            max_retries = 1

        size = os.path.getsize(repre_path)
        self.log.info(
            f"Uploading '{repre_path}' (size: {format_file_size(size)})"
        )

        # How long to sleep before next attempt
        wait_time = 1
        last_error = None
        for attempt in range(max_retries):
            attempt += 1
            start = time.time()
            try:
                output = ayon_con.upload_file(
                    endpoint,
                    repre_path,
                    headers=headers,
                    request_type=RequestTypes.post,
                )
                self.log.debug(f"Uploaded in {time.time() - start}s.")
                return output

            except (
                requests.exceptions.Timeout,
                requests.exceptions.ConnectionError
            ) as exc:
                # Log and retry with backoff if attempts remain
                if attempt >= max_retries:
                    last_error = exc
                    break

                self.log.warning(
                    f"Review upload failed ({attempt}/{max_retries})"
                    f" after {time.time() - start}s."
                    f" Retrying in {wait_time}s...",
                    exc_info=True,
                )
                time.sleep(wait_time)

        # Exhausted retries - raise a user-friendly validation error with help
        raise PublishXmlValidationError(
            self,
            (
                "Upload of reviewable timed out or failed after multiple"
                " attempts. Please try publishing again."
            ),
            formatting_data={
                "upload_type": "Review",
                "file": repre_path,
                "error": str(last_error),
            },
            help_filename="upload_file.xml",
        )