Spaces:
Sleeping
Sleeping
Download src/modules/artifact_catalog/java_dependencies.py from dellweb3/VibeCoding: direct link, hf CLI and curl.
- Browser
- Download file 9.27 kB
-
https://huggingface.co/spaces/dellweb3/VibeCoding/resolve/main/src/modules/artifact_catalog/java_dependencies.py
- Command line
-
hf download hf://spaces/dellweb3/VibeCoding/src/modules/artifact_catalog/java_dependencies.py
-
curl -L -o java_dependencies.py https://huggingface.co/spaces/dellweb3/VibeCoding/resolve/main/src/modules/artifact_catalog/java_dependencies.py
9.27 kB
| """Server-approved Java dependency closure, verified cache and portable offline pack. | |
| Catalog metadata is server policy. This is not an implementation of Maven's POM/BOM | |
| resolver: a Maven Resolver adapter must approve its complete closure into the catalog. | |
| The same lock is independent of the cloud/internal repository URL and layout. | |
| """ | |
| import hashlib | |
| import io | |
| import json | |
| import re | |
| import uuid | |
| import zipfile | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from urllib.parse import urlsplit | |
| from src.modules.skill.domain.models import SkillError,canonical,digest | |
| class JavaArtifact: | |
| coordinate:str | |
| sha512:str | |
| license:str | |
| max_bytes:int=20_000_000 | |
| dependencies:tuple[str,...]=() | |
| distribution_path:str|None=None | |
| def parts(self): | |
| values=self.coordinate.split(':') | |
| if (len(values)!=3 or any(not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,120}',v) or '..' in v for v in values) | |
| or values[2].upper() in {'LATEST','RELEASE'} or 'SNAPSHOT' in values[2].upper() | |
| or not re.fullmatch(r'[a-f0-9]{128}',self.sha512) or not self.license or not 0<self.max_bytes<=50_000_000): | |
| raise SkillError('DEPENDENCY_DESCRIPTOR_INVALID','依赖必须有固定坐标、摘要、许可证和大小边界。') | |
| return values | |
| class JavaDependencyGateway: | |
| def __init__(self,cache,catalog,repository='https://repo.maven.apache.org/maven2',*,layout='maven',offline=False,fetch=None): | |
| parsed=urlsplit(repository) | |
| if parsed.scheme!='https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: | |
| raise SkillError('DEPENDENCY_REPOSITORY_DENIED','仓库必须是服务端配置的HTTPS地址,凭据不得放在URL。') | |
| if layout not in {'maven','distribution'}:raise ValueError('Unknown repository layout') | |
| self.cache=Path(cache).resolve();self.cache.mkdir(parents=True,exist_ok=True) | |
| self.catalog=dict(catalog);self.repository=repository.rstrip('/');self.layout=layout;self.offline=offline | |
| self.fetch=fetch or self._fetch | |
| def resolve(self,coordinates): | |
| if not isinstance(coordinates,(list,tuple)): | |
| raise SkillError('DEPENDENCY_REQUEST_INVALID','依赖坐标必须是列表。') | |
| roots=list(coordinates) | |
| if not roots or len(roots)>32 or any(not isinstance(c,str) for c in roots): | |
| raise SkillError('DEPENDENCY_REQUEST_INVALID','需要有界的明确依赖坐标。') | |
| ordered=[];seen=set();visiting=set();versions={} | |
| def visit(coordinate): | |
| if coordinate in visiting:raise SkillError('DEPENDENCY_CYCLE','依赖图存在循环。') | |
| if coordinate in seen:return | |
| item=self.catalog.get(coordinate) | |
| if not item or item.coordinate!=coordinate:raise SkillError('DEPENDENCY_NOT_APPROVED','依赖尚未进入服务端批准目录。',409) | |
| group,artifact,version=item.parts();key=(group,artifact) | |
| if key in versions and versions[key]!=version:raise SkillError('DEPENDENCY_VERSION_CONFLICT','依赖版本冲突,不能默默选择版本。',409) | |
| versions[key]=version;visiting.add(coordinate) | |
| if len(versions)>64:raise SkillError('DEPENDENCY_GRAPH_LIMIT','依赖闭包超过限制。') | |
| for child in item.dependencies:visit(child) | |
| visiting.remove(coordinate);seen.add(coordinate) | |
| ordered.append({'coordinate':coordinate,'sha512':item.sha512,'license':item.license,'max_bytes':item.max_bytes}) | |
| for coordinate in roots:visit(coordinate) | |
| body={'schema':'java-dependency-lock-v1','roots':roots,'artifacts':ordered} | |
| return {**body,'digest':digest(body)} | |
| def _checked(self,lock): | |
| if not isinstance(lock,dict) or not isinstance(lock.get('roots'),list) or self.resolve(lock['roots'])!=lock: | |
| raise SkillError('DEPENDENCY_LOCK_INVALID','依赖锁定清单与批准目录不一致。',409) | |
| return lock['artifacts'] | |
| def _path(self,item): | |
| group,artifact,version=item.parts() | |
| if self.layout=='maven':return f'{group.replace(".","/")}/{artifact}/{version}/{artifact}-{version}.jar' | |
| path=item.distribution_path | |
| if not path or path.startswith('/') or any(p in {'','..','.'} for p in path.split('/')) or not re.fullmatch(r'[A-Za-z0-9_./-]+',path): | |
| raise SkillError('DEPENDENCY_SOURCE_NOT_CONFIGURED','此依赖未配置当前仓库来源。',409) | |
| return path | |
| def _verify(data,item): | |
| if len(data)>item.max_bytes or hashlib.sha512(data).hexdigest()!=item.sha512: | |
| raise SkillError('DEPENDENCY_INTEGRITY_FAILED','依赖大小或摘要不符合锁定清单。',409) | |
| def seed(self,coordinate,data): | |
| item=self.catalog.get(coordinate) | |
| if not item:raise SkillError('DEPENDENCY_NOT_APPROVED','依赖未批准。',409) | |
| item.parts();self._verify(data,item) | |
| target=self._cache_path(item) | |
| if target.is_symlink():raise SkillError('DEPENDENCY_CACHE_PATH_DENIED','缓存路径不可为符号链接。') | |
| temporary=self.cache/(uuid.uuid4().hex+'.partial') | |
| try:temporary.write_bytes(data);temporary.replace(target) | |
| finally:temporary.unlink(missing_ok=True) | |
| return target | |
| def _cache_path(self,item): | |
| # Keep Windows cache paths short; the full SHA-512 is still verified on every read. | |
| return self.cache/(hashlib.sha256(bytes.fromhex(item.sha512)).hexdigest()+'.jar') | |
| def materialize(self,lock): | |
| files={} | |
| for entry in self._checked(lock): | |
| item=self.catalog[entry['coordinate']];target=self._cache_path(item) | |
| if target.is_symlink():raise SkillError('DEPENDENCY_CACHE_PATH_DENIED','缓存路径不可为符号链接。') | |
| if target.exists():self._verify(target.read_bytes(),item) | |
| else: | |
| if self.offline:raise SkillError('DEPENDENCY_NOT_CACHED','离线镜像尚未预存完整依赖闭包。',503) | |
| target=self.seed(item.coordinate,self.fetch(self.repository+'/'+self._path(item),item.max_bytes)) | |
| files[item.coordinate]=target | |
| return files | |
| def _fetch(url,limit): | |
| import httpx | |
| try: | |
| with httpx.Client(trust_env=False,follow_redirects=False,timeout=45) as client: | |
| with client.stream('GET',url) as response: | |
| if response.status_code!=200:raise SkillError('DEPENDENCY_DOWNLOAD_FAILED','固定来源未返回依赖文件。',503) | |
| data=bytearray() | |
| for chunk in response.iter_bytes(): | |
| data.extend(chunk) | |
| if len(data)>limit:raise SkillError('DEPENDENCY_SIZE_LIMIT','依赖下载超过大小限制。') | |
| return bytes(data) | |
| except httpx.HTTPError: | |
| raise SkillError('DEPENDENCY_DOWNLOAD_FAILED','依赖仓库连接失败;未向其他来源重试。',503) from None | |
| def export_bundle(self,lock): | |
| files=self.materialize(lock);output=io.BytesIO() | |
| with zipfile.ZipFile(output,'w',zipfile.ZIP_STORED) as archive: | |
| archive.writestr('dependency-lock.json',canonical(lock)) | |
| written=set() | |
| for entry in lock['artifacts']: | |
| if entry['sha512'] not in written: | |
| archive.writestr('artifacts/'+entry['sha512']+'.jar',files[entry['coordinate']].read_bytes()) | |
| written.add(entry['sha512']) | |
| return output.getvalue() | |
| def import_bundle(self,data): | |
| if len(data)>200_000_000:raise SkillError('DEPENDENCY_BUNDLE_LIMIT','依赖包超过上限。') | |
| try:return self._import_bundle(data) | |
| except (zipfile.BadZipFile,KeyError,ValueError,UnicodeError,RuntimeError): | |
| raise SkillError('DEPENDENCY_BUNDLE_INVALID','离线依赖包不可解析或条目不合法。') from None | |
| def _import_bundle(self,data): | |
| with zipfile.ZipFile(io.BytesIO(data)) as archive: | |
| names=archive.namelist() | |
| if (len(names)!=len(set(names)) or len(names)>65 | |
| or sum(e.file_size for e in archive.infolist())>200_000_000 | |
| or archive.getinfo('dependency-lock.json').file_size>65536): | |
| raise SkillError('DEPENDENCY_BUNDLE_INVALID','离线包条目不合法。') | |
| lock=json.loads(archive.read('dependency-lock.json'));entries=self._checked(lock) | |
| if set(names)!={'dependency-lock.json',*('artifacts/'+e['sha512']+'.jar' for e in entries)}: | |
| raise SkillError('DEPENDENCY_BUNDLE_INVALID','离线包包含未批准文件。') | |
| checked=[] | |
| for entry in entries: | |
| item=self.catalog[entry['coordinate']];name='artifacts/'+item.sha512+'.jar' | |
| if archive.getinfo(name).file_size>item.max_bytes:raise SkillError('DEPENDENCY_SIZE_LIMIT','离线文件超过限制。') | |
| payload=archive.read(name);self._verify(payload,item);checked.append((item.coordinate,payload)) | |
| for coordinate,payload in checked:self.seed(coordinate,payload) | |
| return lock | |