Coverage for app / services / knowledge / source_links.py: 97%

71 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""A source's links — the pages a website source crawls and the documents a 

2file source imports — as a request carries them, and what becomes of them. 

3 

4Three paths take links for a source: knowledge setup's and agent setup's 

5create-from-config (a new source, with the links a search found and the 

6person kept), and applying a source discovery to an existing empty source. 

7Each validates them as a hand-made source's are (``normalise_seed_url``, 

8``web_config``), keeps only what the source's type holds, and — once the 

9row commits — starts the crawl or the downloads. One implementation, so the 

10three cannot drift. 

11""" 

12 

13from __future__ import annotations 

14 

15from collections.abc import Iterable 

16from typing import Any 

17from uuid import UUID 

18 

19from pydantic import BaseModel, Field, field_validator 

20from sqlalchemy.orm import Session 

21 

22from app.db.postgres.models import Knowledge, KnowledgeDocument, User 

23from app.services.knowledge import imports as document_imports 

24from app.services.knowledge import web_config, web_crawl 

25from app.services.knowledge.web_config import normalise_seed_url 

26 

27#: The source types that take links: a website source crawls pages, a file 

28#: source imports documents. 

29WEB = "web" 

30FILE = "file" 

31LINKED_TYPES = frozenset({WEB, FILE}) 

32 

33 

34class DocumentImportInput(BaseModel): 

35 """A document a file source is to import from its link.""" 

36 

37 url: str 

38 title: str = Field(default="", max_length=300) 

39 publisher: str = Field(default="", max_length=200) 

40 

41 @field_validator("url") 

42 @classmethod 

43 def _normalise(cls, v: str) -> str: 

44 return normalise_seed_url(v) 

45 

46 

47class SourceLinks(BaseModel): 

48 """The links a request brings for one source. :meth:`only_for` drops 

49 what its type does not hold.""" 

50 

51 urls: list[str] = Field(default=[], max_length=web_config.MAX_URLS) 

52 scope: str | None = None 

53 refresh: str | None = None 

54 documents: list[DocumentImportInput] = Field( 

55 default=[], max_length=document_imports.MAX_IMPORTS_PER_SOURCE 

56 ) 

57 

58 @field_validator("urls") 

59 @classmethod 

60 def _normalise_urls(cls, urls: list[str]) -> list[str]: 

61 out: list[str] = [] 

62 for raw in urls: 

63 url = normalise_seed_url(raw) 

64 if url not in out: 

65 out.append(url) 

66 return out 

67 

68 def only_for(self, source_type: str) -> SourceLinks: 

69 """Keep what ``source_type`` holds: a website source's URLs, scope 

70 and cadence (an unknown one dropped for the default); a file 

71 source's documents; nothing for any other type.""" 

72 if source_type != WEB: 

73 self.urls, self.scope, self.refresh = [], None, None 

74 else: 

75 self.scope = self.scope if self.scope in web_config.SCOPE_GUIDE else None 

76 self.refresh = ( 

77 self.refresh if self.refresh in web_config.REFRESH_GUIDE else None 

78 ) 

79 if source_type != FILE: 

80 self.documents = [] 

81 return self 

82 

83 @property 

84 def empty(self) -> bool: 

85 return not self.urls and not self.documents 

86 

87 

88def config_for( 

89 source_type: str, links: SourceLinks, *, category: object = None 

90) -> dict: 

91 """A new source's ``source_config``: a website source's validated crawl 

92 settings when it has URLs, else empty. ``category`` is the kind of 

93 knowledge it is made for (``web_config.generated_config``). Raises 

94 ``ValueError``.""" 

95 if source_type == WEB and links.urls: 

96 return web_config.generated_config( 

97 links.urls, links.scope, links.refresh, category=category 

98 ) 

99 return {} 

100 

101 

102def merged_config( 

103 current: dict, links: SourceLinks, *, category: object = None 

104) -> dict: 

105 """An existing website source's config with ``links``' URLs added after 

106 its own — as many as a source takes — and the scope and cadence chosen, 

107 else what it had. An empty source gets a generated one, for the kind of 

108 knowledge it is (``category``). Raises ``ValueError``.""" 

109 if not current: 

110 return web_config.generated_config( 

111 links.urls, links.scope, links.refresh, category=category 

112 ) 

113 urls = list(current.get("urls") or []) 

114 urls += [u for u in links.urls if u not in urls] 

115 merged = {**current, "urls": urls[: web_config.MAX_URLS]} 

116 if links.scope: 

117 merged["scope"] = links.scope 

118 if links.refresh: 

119 merged["refresh"] = links.refresh 

120 return web_config.validate_web_config(merged) 

121 

122 

123def import_placeholders( 

124 db: Session, 

125 knowledge: Knowledge, 

126 links: SourceLinks, 

127 *, 

128 existing: bool, 

129) -> tuple[list[KnowledgeDocument], list[dict]]: 

130 """A file source's documents, as rows ``importing`` from their links — 

131 added, not committed — and the links skipped with why. ``existing`` 

132 False for a source created in the same transaction.""" 

133 if knowledge.source_type != FILE or not links.documents: 

134 return [], [] 

135 return document_imports.placeholders( 

136 db, 

137 knowledge, 

138 [ 

139 document_imports.DocumentRef( 

140 url=d.url, 

141 title=d.title, 

142 publisher=d.publisher, 

143 origin=document_imports.ORIGIN_GENERATION, 

144 ) 

145 for d in links.documents 

146 ], 

147 existing=existing, 

148 ) 

149 

150 

151def documents_snapshot(docs: Iterable[KnowledgeDocument]) -> dict: 

152 """A created source's ``children_snapshot``: the documents it starts 

153 with, stated rather than queried so a create stays one flush.""" 

154 return { 

155 "documents": [{"document_id": str(d.id), "name": d.source_id} for d in docs] 

156 } 

157 

158 

159def start( 

160 db: Session, 

161 sources: Iterable[Knowledge], 

162 imported: Iterable[KnowledgeDocument], 

163 actor: User, 

164 *, 

165 trigger: Any = None, 

166) -> list[UUID]: 

167 """Once committed: each website source's crawl (budget-checked as it 

168 runs) and the downloads (indexed as an upload is). The ids of the 

169 sources whose crawl started.""" 

170 started = [ 

171 kb.id 

172 for kb in sources 

173 if kb.source_type == WEB 

174 and (kb.source_config or {}).get("urls") 

175 and web_crawl.start_quietly( 

176 db, kb, trigger or web_crawl.Trigger.created, actor_user_id=actor.id 

177 ) 

178 ] 

179 document_imports.submit([d.id for d in imported], actor.id) 

180 return started