Metadata-Version: 2.4
Name: nez-sdk
Version: 1.0.0
Summary: SDK de Python para la plataforma NEZ (Networking Execution Zone)
License: MIT
Keywords: nez,workflow,orchestration,buildingblock,distributed-computing,containerization
Author: Ricardo Prieto Ortega
Author-email: reyricardo999@hotmail.com
Requires-Python: >=3.10
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Provides-Extra: dev
Provides-Extra: docs
Requires-Dist: black (>=23.7.0) ; extra == "dev"
Requires-Dist: flake8 (>=6.0.0) ; extra == "dev"
Requires-Dist: isort (>=5.12.0) ; extra == "dev"
Requires-Dist: mkdocs (>=1.6.0) ; extra == "docs"
Requires-Dist: mkdocstrings[python] (>=0.30.0) ; extra == "docs"
Requires-Dist: mypy (>=1.4.1) ; extra == "dev"
Requires-Dist: pytest (>=7.4.0) ; extra == "dev"
Requires-Dist: pytest-cov (>=4.1.0) ; extra == "dev"
Requires-Dist: requests (>=2.31.0)
Project-URL: Homepage, https://github.com/jub-ecosystem/nez-sdk
Project-URL: Issues, https://github.com/jub-ecosystem/nez-sdk/issues
Project-URL: Repository, https://github.com/jub-ecosystem/nez-sdk
Description-Content-Type: text/markdown

# NEZ Python SDK

[![Python](https://img.shields.io/badge/python-3.10%2B-blue)]()
[![License](https://img.shields.io/badge/license-MIT-green)]()

SDK profesional en Python para interactuar con la plataforma **NEZ**.

Este proyecto no es un wrapper simple. Su objetivo es abstraer un backend legacy e inconsistente, traduciendo errores, estabilizando payloads y ofreciendo una API de uso clara para el desarrollador.

## Que resuelve

- Uso de `access_token` como query param en todos los requests.
- Traduccion de errores del backend a excepciones Python mas claras.
- Soporte para workflows manuales y workflows definidos por DSL.
- Reautenticacion automatica opcional contra el backend NEZ.
- Pruebas unitarias con `pytest` y script integral de validacion.

## Requisitos

- Python 3.10 o superior
- Instancia activa de NEZ
- Token valido o credenciales validas para autoauth

## Instalacion

```bash
pip install -e ".[dev]"
```

## Estructura

```text
nez_sdk/
├── auto_auth.py
├── exceptions.py
├── http_client.py
├── nez.py
├── models/
├── services/
└── utils/
tests/
test_nez_sdk.py
configuration.cfg
```

## Inicio rapido con token

```python
from nez_sdk.nez import Nez

nez = Nez(
    base_url="http://localhost:20510/api/v1",
    token="tu_access_token"
)

nfrs = nez.nfrs.list()
print("NFRs disponibles:", len(nfrs))
```

## Inicio rapido con autoautenticacion

```python
from nez_sdk.nez import Nez

nez = Nez(base_url="http://localhost:20510/api/v1")

token = nez.authenticate(
    user="tu_usuario_o_email",
    password="tu_password",
    use_gateway=False
)

print("Token obtenido:", token)
```

La autoautenticacion usa estos endpoints del backend NEZ:

- `POST /auth/api.php?type=6`
- `POST /APIGateway/API.php?type=20`

## Modelos principales

Los modelos actuales viven en:

- `nez_sdk.models.model_building_block.BuildingBlock`
- `nez_sdk.models.model_stage.Stage`
- `nez_sdk.models.model_workflow.Workflow`
- `nez_sdk.models.model_nfr.NFR`

## Building Blocks

### Crear

```python
from nez_sdk.models.model_building_block import BuildingBlock

bb = BuildingBlock(
    name="thumbnail-service",
    image="registry.example.com/thumbnail:1.0",
    command="python app.py",
    description="Procesa imagenes",
    port=8080
)

response = nez.buildingblocks.create(bb)
print(response)
```

### Listar

```python
buildingblocks = nez.buildingblocks.list()

for item in buildingblocks:
    print(item.id, item.name, item.image)
```

### Actualizar y eliminar

```python
nez.buildingblocks.update("1", bb)
nez.buildingblocks.delete("1")
```

Nota: los endpoints existen y el SDK los ejecuta, pero el backend NEZ puede responder con `405` u otros errores segun la instancia.

## Workflows

### Crear workflow manual

```python
from nez_sdk.models.model_stage import Stage
from nez_sdk.models.model_workflow import Workflow

stage = Stage("stage-procesamiento", [bb])
workflow = Workflow("workflow-demo", [stage])

workflow_id = nez.build(workflow)
print(workflow_id)
```

### Endpoints disponibles

```python
nez.workflows.list()
nez.workflows.get("1")
nez.workflows.update("1", workflow)
nez.workflows.delete("1")
nez.workflows.stages("1")
```

## Workflows usando DSL

Puedes definir workflows en `configuration.cfg` y convertirlos a objetos Python con `DSLParser`.

### Ejemplo

```python
from nez_sdk.utils.dsl_parser import DSLParser

workflow = DSLParser.from_file("configuration.cfg")

print(workflow.name)
print(len(workflow.stages))

workflow_id = nez.build(workflow)
print(workflow_id)
```

## Ejecucion

```python
nez.execution.run("1", platform="docker")
nez.execution.execute("1", puzzle_name="default")
nez.execution.stop("1", puzzle_name="default")
nez.execution.log("1", name="default", folder="/tmp")
```

Tambien existe la fachada:

```python
nez.execute("1")
```

## Manejo de errores

Excepciones principales:

- `NezAPIError`
- `NezAuthError`
- `NezNotFoundError`
- `NezValidationError`
- `NezConnectionError`
- `NezResponseError`

Ejemplo:

```python
from nez_sdk.exceptions import NezAPIError

try:
    nez.workflows.update("1", workflow)
except NezAPIError as exc:
    print(exc)
```

## Testing

### Pruebas unitarias

```bash
pytest -q
```

### Script integral/manual

```bash
python test_nez_sdk.py
```

El script `test_nez_sdk.py` muestra:

- modelos
- DSL
- autoauth
- NFRs
- building blocks
- workflows
- execution
- errores esperados

## Demo

Puedes ejecutar el demo de uso general:

```bash
python demo_nez_sdk.py
```

Variables de entorno soportadas por `demo_nez_sdk.py` y `test_nez_sdk.py`:

- `NEZ_BASE_URL`
- `NEZ_TOKEN`
- `NEZ_AUTH_USER`
- `NEZ_AUTH_PASSWORD`
- `NEZ_AUTH_USE_GATEWAY`

Puedes partir de [`.env.example`](c:\Users\reyri\proyectos\nez_sdk_python\.env.example) para configurar tu entorno local.

## Documentacion

La documentacion del proyecto usa **MkDocs + mkdocstrings**.

Instalacion:

```bash
pip install -e ".[docs]"
```

Vista previa local:

```bash
mkdocs serve
```

Build:

```bash
mkdocs build --strict
```

El proyecto incluye un workflow de GitHub Actions para:

- validar y construir la documentacion en `feature/sdk-refactor`
- desplegar la documentacion en GitHub Pages desde `main` o mediante ejecucion manual

## Releases y publicacion

El proyecto incluye un workflow de GitHub Actions para:

- construir el paquete Python
- crear automaticamente un Release en GitHub
- publicar automaticamente en PyPI cuando se cree un tag de version

Flujo esperado:

```bash
git tag v1.0.1
git push origin v1.0.1
```

La publicacion en PyPI esta preparada para funcionar con **Trusted Publishing** usando la accion oficial `pypa/gh-action-pypi-publish`.

## Estado actual

Este SDK ya cubre:

- endpoints documentados del PDF
- autoautenticacion
- traduccion robusta de errores
- pruebas unitarias con alta cobertura

La principal fuente de inestabilidad sigue siendo el backend NEZ, no la estructura base del SDK.

## Autor

Desarrollado por **Ricardo Prieto Ortega**  
Correo: `prieto.ortega.20035@itsmante.edu.mx`  
GitHub: `https://github.com/RicardoPrietoOrtega`  
LinkedIn: `https://www.linkedin.com/in/ricardo-prieto-ortega/`  
Institucion: `Instituto Tecnologico Superior de El Mante (TEC MANTE)`

