File size: 7,060 Bytes
6918275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""Centralized document fetching for the document_query plugin."""

from __future__ import annotations

import asyncio
import mimetypes
import os
import tempfile
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Awaitable, Callable
from urllib.parse import urlparse

from helpers import files, tinyfish
from helpers.network import UnsafeUrlError, fetch_public_http_resource


InterventionCallback = Callable[[], Awaitable[None]]


@dataclass(frozen=True)
class FetchedDocument:
    """Fetched document bytes plus metadata needed by parsers."""

    uri: str
    scheme: str
    mimetype: str
    content: bytes
    encoding: str | None = None
    charset: str | None = None
    local_path: str | None = None
    source_uri: str | None = None

    def text(self) -> str:
        charset = self.charset or "utf-8"
        return self.content.decode(charset, errors="replace")

    def suffix(self) -> str:
        path = self.local_path or urlparse(self.uri).path or self.uri
        suffix = Path(path).suffix
        if suffix:
            return suffix
        guessed = mimetypes.guess_extension(self.mimetype)
        return guessed or ".bin"

    @contextmanager
    def local_file(self):
        """Yield a filesystem path for parsers that cannot consume bytes."""
        if self.local_path and os.path.exists(self.local_path):
            yield self.local_path
            return

        tmp = ""
        try:
            with tempfile.NamedTemporaryFile(delete=False, suffix=self.suffix()) as f:
                f.write(self.content)
                tmp = f.name
            yield tmp
        finally:
            if tmp and os.path.exists(tmp):
                os.unlink(tmp)


ProtocolHandler = Callable[
    [str, str, dict, InterventionCallback | None], Awaitable[FetchedDocument]
]

_PROTOCOL_HANDLERS: dict[str, ProtocolHandler] = {}


def register_protocol_handler(scheme: str, handler: ProtocolHandler) -> None:
    """Register or replace a fetch handler for a URI scheme."""
    _PROTOCOL_HANDLERS[scheme.lower()] = handler


async def fetch_public_resource(
    uri: str,
    config: dict | None = None,
    intervention_callback: InterventionCallback | None = None,
) -> FetchedDocument:
    """Fetch local or remote content once, then pass bytes to parsers."""
    config = config or {}
    parsed = urlparse(uri)
    scheme = (parsed.scheme or "file").lower()
    handler = _PROTOCOL_HANDLERS.get(scheme)
    if not handler:
        raise ValueError(f"Unsupported document scheme: {scheme}")
    return await handler(uri, scheme, config, intervention_callback)


async def _fetch_file(
    uri: str,
    scheme: str,
    config: dict,
    intervention_callback: InterventionCallback | None,
) -> FetchedDocument:
    parsed = urlparse(uri)
    raw_path = parsed.path if parsed.scheme == "file" else uri
    if not raw_path:
        raise ValueError(f"Invalid document path: {uri}")

    path = _fix_file_path(raw_path)
    mimetype, encoding = mimetypes.guess_type(path)
    if encoding:
        raise ValueError(f"Compressed documents are unsupported '{encoding}' ({uri})")
    mimetype = mimetype or "application/octet-stream"
    if mimetype == "application/octet-stream":
        raise ValueError(f"Unsupported document mimetype '{mimetype}' ({uri})")

    if intervention_callback:
        await intervention_callback()
    return FetchedDocument(
        uri=path,
        source_uri=uri,
        scheme=scheme,
        mimetype=mimetype,
        encoding=encoding,
        content=files.read_file_bin(path),
        local_path=path,
    )


async def _fetch_http(
    uri: str,
    scheme: str,
    config: dict,
    intervention_callback: InterventionCallback | None,
) -> FetchedDocument:
    timeout = float(config.get("fetch_timeout", 30))
    retries = max(1, int(config.get("fetch_retries", 3)))
    retry_backoff = float(config.get("fetch_retry_backoff", 1.0))
    max_remote_bytes = int(config.get("max_remote_bytes", 50 * 1024 * 1024))
    parsed = urlparse(uri)
    guessed_mimetype, encoding = mimetypes.guess_type(parsed.path or uri)
    if encoding:
        raise ValueError(f"Compressed documents are unsupported '{encoding}' ({uri})")

    last_error = ""
    for attempt in range(retries):
        if intervention_callback:
            await intervention_callback()
        try:
            resource = await asyncio.to_thread(
                fetch_public_http_resource,
                uri,
                max_bytes=max_remote_bytes,
                timeout=(timeout, timeout),
            )
            mimetype = (
                resource.content_type or guessed_mimetype or "application/octet-stream"
            )
            if mimetype == "application/octet-stream":
                raise ValueError(f"Unsupported document mimetype '{mimetype}' ({uri})")

            document = FetchedDocument(
                uri=resource.url,
                source_uri=uri,
                scheme=urlparse(resource.url).scheme or scheme,
                mimetype=mimetype,
                encoding=encoding,
                charset=resource.encoding,
                content=resource.content,
            )
        except UnsafeUrlError:
            # Neither a remote provider nor a retry may bypass SSRF checks.
            raise
        except Exception as e:
            if "exceeds max size" in str(e):
                raise
            if scheme == "https" and tinyfish.configured():
                if intervention_callback:
                    await intervention_callback()
                try:
                    final_url, content = await tinyfish.fetch(
                        uri, timeout=timeout, max_bytes=max_remote_bytes
                    )
                except tinyfish.TinyfishError as error:
                    raise ValueError(
                        f"Document fetch unavailable: local fetch failed; Tinyfish {error}"
                    ) from None
                if intervention_callback:
                    await intervention_callback()
                return FetchedDocument(
                    uri=final_url,
                    source_uri=uri,
                    scheme="https",
                    mimetype="text/markdown",
                    charset="utf-8",
                    content=content,
                )
            last_error = str(e)
            if attempt < retries - 1:
                await asyncio.sleep(retry_backoff)
                if intervention_callback:
                    await intervention_callback()
            continue
        if intervention_callback:
            await intervention_callback()
        return document

    raise ValueError(f"Document fetch error: {uri} ({last_error})")


register_protocol_handler("file", _fetch_file)
register_protocol_handler("http", _fetch_http)
register_protocol_handler("https", _fetch_http)


def _fix_file_path(path: str) -> str:
    if os.path.isabs(path) and os.path.exists(path):
        return path
    return files.fix_dev_path(path)