Pahse 5
This commit is contained in:
5
backend/igny8_core/business/publishing/__init__.py
Normal file
5
backend/igny8_core/business/publishing/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
Publishing Domain
|
||||
Phase 5: Sites Renderer & Publishing
|
||||
"""
|
||||
|
||||
12
backend/igny8_core/business/publishing/apps.py
Normal file
12
backend/igny8_core/business/publishing/apps.py
Normal file
@@ -0,0 +1,12 @@
|
||||
"""
|
||||
Publishing App Configuration
|
||||
"""
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class PublishingConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'igny8_core.business.publishing'
|
||||
label = 'publishing'
|
||||
verbose_name = 'Publishing'
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# Generated manually for Phase 5: Publishing System
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('igny8_core_auth', '0014_remove_plan_operation_limits_phase0'),
|
||||
('site_building', '0001_initial'),
|
||||
('writer', '0009_add_content_site_source_fields'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='PublishingRecord',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('destination', models.CharField(db_index=True, help_text="Destination platform: 'wordpress', 'sites', 'shopify'", max_length=50)),
|
||||
('destination_id', models.CharField(blank=True, help_text='External ID in destination platform', max_length=255, null=True)),
|
||||
('destination_url', models.URLField(blank=True, help_text='URL of published content/site', null=True)),
|
||||
('status', models.CharField(choices=[('pending', 'Pending'), ('publishing', 'Publishing'), ('published', 'Published'), ('failed', 'Failed')], db_index=True, default='pending', max_length=20)),
|
||||
('published_at', models.DateTimeField(blank=True, null=True)),
|
||||
('error_message', models.TextField(blank=True, null=True)),
|
||||
('metadata', models.JSONField(default=dict, help_text='Platform-specific metadata')),
|
||||
('account', models.ForeignKey(db_column='tenant_id', on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_set', to='igny8_core_auth.tenant')),
|
||||
('content', models.ForeignKey(blank=True, help_text='Content being published (if publishing content)', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='publishing_records', to='writer.content')),
|
||||
('site', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_set', to='igny8_core_auth.site')),
|
||||
('sector', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_set', to='igny8_core_auth.sector')),
|
||||
('site_blueprint', models.ForeignKey(blank=True, help_text='Site blueprint being published (if publishing site)', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='publishing_records', to='site_building.siteblueprint')),
|
||||
],
|
||||
options={
|
||||
'db_table': 'igny8_publishing_records',
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='DeploymentRecord',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('version', models.IntegerField(help_text='Blueprint version being deployed')),
|
||||
('deployed_version', models.IntegerField(blank=True, help_text='Currently deployed version (after successful deployment)', null=True)),
|
||||
('status', models.CharField(choices=[('pending', 'Pending'), ('deploying', 'Deploying'), ('deployed', 'Deployed'), ('failed', 'Failed'), ('rolled_back', 'Rolled Back')], db_index=True, default='pending', max_length=20)),
|
||||
('deployed_at', models.DateTimeField(blank=True, null=True)),
|
||||
('deployment_url', models.URLField(blank=True, help_text='Public URL of deployed site', null=True)),
|
||||
('error_message', models.TextField(blank=True, null=True)),
|
||||
('metadata', models.JSONField(default=dict, help_text='Deployment metadata (build info, file paths, etc.)')),
|
||||
('account', models.ForeignKey(db_column='tenant_id', on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_set', to='igny8_core_auth.tenant')),
|
||||
('site', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_set', to='igny8_core_auth.site')),
|
||||
('sector', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_set', to='igny8_core_auth.sector')),
|
||||
('site_blueprint', models.ForeignKey(help_text='Site blueprint being deployed', on_delete=django.db.models.deletion.CASCADE, related_name='deployments', to='site_building.siteblueprint')),
|
||||
],
|
||||
options={
|
||||
'db_table': 'igny8_deployment_records',
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='publishingrecord',
|
||||
index=models.Index(fields=['destination', 'status'], name='igny8_publi_destina_123abc_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='publishingrecord',
|
||||
index=models.Index(fields=['content', 'destination'], name='igny8_publi_content_456def_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='publishingrecord',
|
||||
index=models.Index(fields=['site_blueprint', 'destination'], name='igny8_publi_site_bl_789ghi_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='publishingrecord',
|
||||
index=models.Index(fields=['account', 'status'], name='igny8_publi_account_012jkl_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='deploymentrecord',
|
||||
index=models.Index(fields=['site_blueprint', 'status'], name='igny8_deplo_site_bl_345mno_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='deploymentrecord',
|
||||
index=models.Index(fields=['site_blueprint', 'version'], name='igny8_deplo_site_bl_678pqr_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='deploymentrecord',
|
||||
index=models.Index(fields=['status'], name='igny8_deplo_status_901stu_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='deploymentrecord',
|
||||
index=models.Index(fields=['account', 'status'], name='igny8_deplo_account_234vwx_idx'),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
"""
|
||||
Publishing Migrations
|
||||
"""
|
||||
|
||||
159
backend/igny8_core/business/publishing/models.py
Normal file
159
backend/igny8_core/business/publishing/models.py
Normal file
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
Publishing Models
|
||||
Phase 5: Sites Renderer & Publishing
|
||||
"""
|
||||
from django.db import models
|
||||
from igny8_core.auth.models import SiteSectorBaseModel
|
||||
|
||||
|
||||
class PublishingRecord(SiteSectorBaseModel):
|
||||
"""
|
||||
Track content publishing to various destinations.
|
||||
"""
|
||||
|
||||
STATUS_CHOICES = [
|
||||
('pending', 'Pending'),
|
||||
('publishing', 'Publishing'),
|
||||
('published', 'Published'),
|
||||
('failed', 'Failed'),
|
||||
]
|
||||
|
||||
# Content or SiteBlueprint reference (one must be set)
|
||||
content = models.ForeignKey(
|
||||
'content.Content',
|
||||
on_delete=models.CASCADE,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name='publishing_records',
|
||||
help_text="Content being published (if publishing content)"
|
||||
)
|
||||
site_blueprint = models.ForeignKey(
|
||||
'site_building.SiteBlueprint',
|
||||
on_delete=models.CASCADE,
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name='publishing_records',
|
||||
help_text="Site blueprint being published (if publishing site)"
|
||||
)
|
||||
|
||||
# Destination information
|
||||
destination = models.CharField(
|
||||
max_length=50,
|
||||
db_index=True,
|
||||
help_text="Destination platform: 'wordpress', 'sites', 'shopify'"
|
||||
)
|
||||
destination_id = models.CharField(
|
||||
max_length=255,
|
||||
blank=True,
|
||||
null=True,
|
||||
help_text="External ID in destination platform"
|
||||
)
|
||||
destination_url = models.URLField(
|
||||
blank=True,
|
||||
null=True,
|
||||
help_text="URL of published content/site"
|
||||
)
|
||||
|
||||
# Status tracking
|
||||
status = models.CharField(
|
||||
max_length=20,
|
||||
choices=STATUS_CHOICES,
|
||||
default='pending',
|
||||
db_index=True
|
||||
)
|
||||
published_at = models.DateTimeField(null=True, blank=True)
|
||||
error_message = models.TextField(blank=True, null=True)
|
||||
|
||||
# Metadata
|
||||
metadata = models.JSONField(
|
||||
default=dict,
|
||||
help_text="Platform-specific metadata"
|
||||
)
|
||||
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
app_label = 'publishing'
|
||||
db_table = 'igny8_publishing_records'
|
||||
ordering = ['-created_at']
|
||||
indexes = [
|
||||
models.Index(fields=['destination', 'status']),
|
||||
models.Index(fields=['content', 'destination']),
|
||||
models.Index(fields=['site_blueprint', 'destination']),
|
||||
models.Index(fields=['account', 'status']),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
target = self.content or self.site_blueprint
|
||||
return f"{target} → {self.destination} ({self.get_status_display()})"
|
||||
|
||||
|
||||
class DeploymentRecord(SiteSectorBaseModel):
|
||||
"""
|
||||
Track site deployments to Sites renderer.
|
||||
"""
|
||||
|
||||
STATUS_CHOICES = [
|
||||
('pending', 'Pending'),
|
||||
('deploying', 'Deploying'),
|
||||
('deployed', 'Deployed'),
|
||||
('failed', 'Failed'),
|
||||
('rolled_back', 'Rolled Back'),
|
||||
]
|
||||
|
||||
site_blueprint = models.ForeignKey(
|
||||
'site_building.SiteBlueprint',
|
||||
on_delete=models.CASCADE,
|
||||
related_name='deployments',
|
||||
help_text="Site blueprint being deployed"
|
||||
)
|
||||
|
||||
# Version tracking
|
||||
version = models.IntegerField(
|
||||
help_text="Blueprint version being deployed"
|
||||
)
|
||||
deployed_version = models.IntegerField(
|
||||
null=True,
|
||||
blank=True,
|
||||
help_text="Currently deployed version (after successful deployment)"
|
||||
)
|
||||
|
||||
# Status tracking
|
||||
status = models.CharField(
|
||||
max_length=20,
|
||||
choices=STATUS_CHOICES,
|
||||
default='pending',
|
||||
db_index=True
|
||||
)
|
||||
deployed_at = models.DateTimeField(null=True, blank=True)
|
||||
deployment_url = models.URLField(
|
||||
blank=True,
|
||||
null=True,
|
||||
help_text="Public URL of deployed site"
|
||||
)
|
||||
error_message = models.TextField(blank=True, null=True)
|
||||
|
||||
# Metadata
|
||||
metadata = models.JSONField(
|
||||
default=dict,
|
||||
help_text="Deployment metadata (build info, file paths, etc.)"
|
||||
)
|
||||
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
app_label = 'publishing'
|
||||
db_table = 'igny8_deployment_records'
|
||||
ordering = ['-created_at']
|
||||
indexes = [
|
||||
models.Index(fields=['site_blueprint', 'status']),
|
||||
models.Index(fields=['site_blueprint', 'version']),
|
||||
models.Index(fields=['status']),
|
||||
models.Index(fields=['account', 'status']),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.site_blueprint.name} v{self.version} ({self.get_status_display()})"
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
"""
|
||||
Publishing Services
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
"""
|
||||
Publishing Adapters
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""
|
||||
Sites Renderer Adapter
|
||||
Phase 5: Sites Renderer & Publishing
|
||||
|
||||
Adapter for deploying sites to IGNY8 Sites renderer.
|
||||
"""
|
||||
import logging
|
||||
import json
|
||||
import os
|
||||
from typing import Dict, Any
|
||||
from pathlib import Path
|
||||
|
||||
from igny8_core.business.site_building.models import SiteBlueprint
|
||||
from igny8_core.business.publishing.models import DeploymentRecord
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SitesRendererAdapter:
|
||||
"""
|
||||
Adapter for deploying sites to IGNY8 Sites renderer.
|
||||
Writes site definitions to filesystem for Sites container to serve.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.sites_data_path = os.getenv('SITES_DATA_PATH', '/data/app/sites-data')
|
||||
|
||||
def deploy(self, site_blueprint: SiteBlueprint) -> Dict[str, Any]:
|
||||
"""
|
||||
Deploy site blueprint to Sites renderer.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance to deploy
|
||||
|
||||
Returns:
|
||||
dict: Deployment result with status and deployment record
|
||||
"""
|
||||
try:
|
||||
# Create deployment record
|
||||
deployment = DeploymentRecord.objects.create(
|
||||
account=site_blueprint.account,
|
||||
site=site_blueprint.site,
|
||||
sector=site_blueprint.sector,
|
||||
site_blueprint=site_blueprint,
|
||||
version=site_blueprint.version,
|
||||
status='deploying'
|
||||
)
|
||||
|
||||
# Build site definition
|
||||
site_definition = self._build_site_definition(site_blueprint)
|
||||
|
||||
# Write to filesystem
|
||||
deployment_path = self._write_site_definition(
|
||||
site_blueprint,
|
||||
site_definition,
|
||||
deployment.version
|
||||
)
|
||||
|
||||
# Update deployment record
|
||||
deployment.status = 'deployed'
|
||||
deployment.deployed_version = site_blueprint.version
|
||||
deployment.deployment_url = self._get_deployment_url(site_blueprint)
|
||||
deployment.metadata = {
|
||||
'deployment_path': str(deployment_path),
|
||||
'site_definition': site_definition
|
||||
}
|
||||
deployment.save()
|
||||
|
||||
# Update blueprint
|
||||
site_blueprint.deployed_version = site_blueprint.version
|
||||
site_blueprint.status = 'deployed'
|
||||
site_blueprint.save(update_fields=['deployed_version', 'status', 'updated_at'])
|
||||
|
||||
logger.info(
|
||||
f"[SitesRendererAdapter] Successfully deployed site {site_blueprint.id} v{deployment.version}"
|
||||
)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'deployment_id': deployment.id,
|
||||
'version': deployment.version,
|
||||
'deployment_url': deployment.deployment_url,
|
||||
'deployment_path': str(deployment_path)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[SitesRendererAdapter] Error deploying site {site_blueprint.id}: {str(e)}",
|
||||
exc_info=True
|
||||
)
|
||||
|
||||
# Update deployment record with error
|
||||
if 'deployment' in locals():
|
||||
deployment.status = 'failed'
|
||||
deployment.error_message = str(e)
|
||||
deployment.save()
|
||||
|
||||
return {
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def _build_site_definition(self, site_blueprint: SiteBlueprint) -> Dict[str, Any]:
|
||||
"""
|
||||
Build site definition JSON from blueprint.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance
|
||||
|
||||
Returns:
|
||||
dict: Site definition structure
|
||||
"""
|
||||
# Get all pages
|
||||
pages = []
|
||||
for page in site_blueprint.pages.all().order_by('order'):
|
||||
pages.append({
|
||||
'id': page.id,
|
||||
'slug': page.slug,
|
||||
'title': page.title,
|
||||
'type': page.type,
|
||||
'blocks': page.blocks_json,
|
||||
'status': page.status,
|
||||
})
|
||||
|
||||
# Build site definition
|
||||
definition = {
|
||||
'id': site_blueprint.id,
|
||||
'name': site_blueprint.name,
|
||||
'description': site_blueprint.description,
|
||||
'version': site_blueprint.version,
|
||||
'layout': site_blueprint.structure_json.get('layout', 'default'),
|
||||
'theme': site_blueprint.structure_json.get('theme', {}),
|
||||
'navigation': site_blueprint.structure_json.get('navigation', []),
|
||||
'pages': pages,
|
||||
'config': site_blueprint.config_json,
|
||||
'created_at': site_blueprint.created_at.isoformat(),
|
||||
'updated_at': site_blueprint.updated_at.isoformat(),
|
||||
}
|
||||
|
||||
return definition
|
||||
|
||||
def _write_site_definition(
|
||||
self,
|
||||
site_blueprint: SiteBlueprint,
|
||||
site_definition: Dict[str, Any],
|
||||
version: int
|
||||
) -> Path:
|
||||
"""
|
||||
Write site definition to filesystem.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance
|
||||
site_definition: Site definition dict
|
||||
version: Version number
|
||||
|
||||
Returns:
|
||||
Path: Deployment path
|
||||
"""
|
||||
# Build path: /data/app/sites-data/clients/{site_id}/v{version}/
|
||||
site_id = site_blueprint.site.id
|
||||
deployment_dir = Path(self.sites_data_path) / 'clients' / str(site_id) / f'v{version}'
|
||||
deployment_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Write site.json
|
||||
site_json_path = deployment_dir / 'site.json'
|
||||
with open(site_json_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(site_definition, f, indent=2, ensure_ascii=False)
|
||||
|
||||
# Write pages
|
||||
pages_dir = deployment_dir / 'pages'
|
||||
pages_dir.mkdir(exist_ok=True)
|
||||
|
||||
for page in site_definition.get('pages', []):
|
||||
page_json_path = pages_dir / f"{page['slug']}.json"
|
||||
with open(page_json_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(page, f, indent=2, ensure_ascii=False)
|
||||
|
||||
# Ensure assets directory exists
|
||||
assets_dir = deployment_dir / 'assets'
|
||||
assets_dir.mkdir(exist_ok=True)
|
||||
(assets_dir / 'images').mkdir(exist_ok=True)
|
||||
(assets_dir / 'documents').mkdir(exist_ok=True)
|
||||
(assets_dir / 'media').mkdir(exist_ok=True)
|
||||
|
||||
logger.info(f"[SitesRendererAdapter] Wrote site definition to {deployment_dir}")
|
||||
|
||||
return deployment_dir
|
||||
|
||||
def _get_deployment_url(self, site_blueprint: SiteBlueprint) -> str:
|
||||
"""
|
||||
Get deployment URL for site.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance
|
||||
|
||||
Returns:
|
||||
str: Deployment URL
|
||||
"""
|
||||
# TODO: Implement URL generation based on site configuration
|
||||
# For now, return placeholder
|
||||
site_id = site_blueprint.site.id
|
||||
return f"https://{site_id}.igny8.com" # Placeholder
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""
|
||||
Deployment Service
|
||||
Phase 5: Sites Renderer & Publishing
|
||||
|
||||
Manages deployment lifecycle for sites.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from igny8_core.business.site_building.models import SiteBlueprint
|
||||
from igny8_core.business.publishing.models import DeploymentRecord
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DeploymentService:
|
||||
"""
|
||||
Service for managing site deployment lifecycle.
|
||||
"""
|
||||
|
||||
def get_status(self, site_blueprint: SiteBlueprint) -> Optional[DeploymentRecord]:
|
||||
"""
|
||||
Get current deployment status for a site.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance
|
||||
|
||||
Returns:
|
||||
DeploymentRecord or None
|
||||
"""
|
||||
return DeploymentRecord.objects.filter(
|
||||
site_blueprint=site_blueprint,
|
||||
status='deployed'
|
||||
).order_by('-deployed_at').first()
|
||||
|
||||
def get_latest_deployment(
|
||||
self,
|
||||
site_blueprint: SiteBlueprint
|
||||
) -> Optional[DeploymentRecord]:
|
||||
"""
|
||||
Get latest deployment record (any status).
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance
|
||||
|
||||
Returns:
|
||||
DeploymentRecord or None
|
||||
"""
|
||||
return DeploymentRecord.objects.filter(
|
||||
site_blueprint=site_blueprint
|
||||
).order_by('-created_at').first()
|
||||
|
||||
def rollback(
|
||||
self,
|
||||
site_blueprint: SiteBlueprint,
|
||||
target_version: int
|
||||
) -> dict:
|
||||
"""
|
||||
Rollback site to a previous version.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance
|
||||
target_version: Version to rollback to
|
||||
|
||||
Returns:
|
||||
dict: Rollback result
|
||||
"""
|
||||
try:
|
||||
# Find deployment record for target version
|
||||
target_deployment = DeploymentRecord.objects.filter(
|
||||
site_blueprint=site_blueprint,
|
||||
version=target_version,
|
||||
status='deployed'
|
||||
).first()
|
||||
|
||||
if not target_deployment:
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'Deployment for version {target_version} not found'
|
||||
}
|
||||
|
||||
# Create new deployment record for rollback
|
||||
rollback_deployment = DeploymentRecord.objects.create(
|
||||
account=site_blueprint.account,
|
||||
site=site_blueprint.site,
|
||||
sector=site_blueprint.sector,
|
||||
site_blueprint=site_blueprint,
|
||||
version=target_version,
|
||||
status='deployed',
|
||||
deployed_version=target_version,
|
||||
deployment_url=target_deployment.deployment_url,
|
||||
metadata={
|
||||
'rollback_from': site_blueprint.version,
|
||||
'rollback_to': target_version
|
||||
}
|
||||
)
|
||||
|
||||
# Update blueprint
|
||||
site_blueprint.deployed_version = target_version
|
||||
site_blueprint.save(update_fields=['deployed_version', 'updated_at'])
|
||||
|
||||
logger.info(
|
||||
f"[DeploymentService] Rolled back site {site_blueprint.id} to version {target_version}"
|
||||
)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'deployment_id': rollback_deployment.id,
|
||||
'version': target_version
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[DeploymentService] Error rolling back site {site_blueprint.id}: {str(e)}",
|
||||
exc_info=True
|
||||
)
|
||||
return {
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def list_deployments(
|
||||
self,
|
||||
site_blueprint: SiteBlueprint
|
||||
) -> list:
|
||||
"""
|
||||
List all deployments for a site.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance
|
||||
|
||||
Returns:
|
||||
list: List of DeploymentRecord instances
|
||||
"""
|
||||
return list(
|
||||
DeploymentRecord.objects.filter(
|
||||
site_blueprint=site_blueprint
|
||||
).order_by('-created_at')
|
||||
)
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Publisher Service
|
||||
Phase 5: Sites Renderer & Publishing
|
||||
|
||||
Main publishing orchestrator for content and sites.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from igny8_core.business.publishing.models import PublishingRecord, DeploymentRecord
|
||||
from igny8_core.business.site_building.models import SiteBlueprint
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PublisherService:
|
||||
"""
|
||||
Main publishing service for content and sites.
|
||||
Routes to appropriate adapters based on destination.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.adapters = {}
|
||||
self._load_adapters()
|
||||
|
||||
def _load_adapters(self):
|
||||
"""Lazy load adapters to avoid circular imports"""
|
||||
pass # Will be implemented when adapters are created
|
||||
|
||||
def publish_to_sites(self, site_blueprint: SiteBlueprint) -> Dict[str, Any]:
|
||||
"""
|
||||
Publish site to Sites renderer.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance to deploy
|
||||
|
||||
Returns:
|
||||
dict: Deployment result with status and deployment record
|
||||
"""
|
||||
from igny8_core.business.publishing.services.adapters.sites_renderer_adapter import SitesRendererAdapter
|
||||
|
||||
adapter = SitesRendererAdapter()
|
||||
return adapter.deploy(site_blueprint)
|
||||
|
||||
def get_deployment_status(self, site_blueprint: SiteBlueprint) -> Optional[DeploymentRecord]:
|
||||
"""
|
||||
Get deployment status for a site.
|
||||
|
||||
Args:
|
||||
site_blueprint: SiteBlueprint instance
|
||||
|
||||
Returns:
|
||||
DeploymentRecord or None
|
||||
"""
|
||||
from igny8_core.business.publishing.services.deployment_service import DeploymentService
|
||||
|
||||
service = DeploymentService()
|
||||
return service.get_status(site_blueprint)
|
||||
|
||||
def publish_content(
|
||||
self,
|
||||
content_id: int,
|
||||
destinations: List[str],
|
||||
account
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Publish content to multiple destinations.
|
||||
|
||||
Args:
|
||||
content_id: Content ID to publish
|
||||
destinations: List of destination platforms ('wordpress', 'sites', 'shopify')
|
||||
account: Account instance
|
||||
|
||||
Returns:
|
||||
dict: Publishing results per destination
|
||||
"""
|
||||
from igny8_core.business.content.models import Content
|
||||
|
||||
try:
|
||||
content = Content.objects.get(id=content_id, account=account)
|
||||
except Content.DoesNotExist:
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'Content {content_id} not found'
|
||||
}
|
||||
|
||||
results = []
|
||||
for destination in destinations:
|
||||
try:
|
||||
result = self._publish_to_destination(content, destination, account)
|
||||
results.append(result)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error publishing content {content_id} to {destination}: {str(e)}",
|
||||
exc_info=True
|
||||
)
|
||||
results.append({
|
||||
'destination': destination,
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
})
|
||||
|
||||
return {
|
||||
'success': all(r.get('success', False) for r in results),
|
||||
'results': results
|
||||
}
|
||||
|
||||
def _publish_to_destination(
|
||||
self,
|
||||
content,
|
||||
destination: str,
|
||||
account
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Publish content to a specific destination.
|
||||
|
||||
Args:
|
||||
content: Content instance
|
||||
destination: Destination platform name
|
||||
account: Account instance
|
||||
|
||||
Returns:
|
||||
dict: Publishing result
|
||||
"""
|
||||
# Create publishing record
|
||||
record = PublishingRecord.objects.create(
|
||||
account=account,
|
||||
site=content.site,
|
||||
sector=content.sector,
|
||||
content=content,
|
||||
destination=destination,
|
||||
status='pending'
|
||||
)
|
||||
|
||||
try:
|
||||
# Get adapter for destination
|
||||
adapter = self._get_adapter(destination)
|
||||
if not adapter:
|
||||
raise ValueError(f"No adapter found for destination: {destination}")
|
||||
|
||||
# Publish via adapter
|
||||
result = adapter.publish(content, {'account': account})
|
||||
|
||||
# Update record
|
||||
record.status = 'published' if result.get('success') else 'failed'
|
||||
record.destination_id = result.get('external_id')
|
||||
record.destination_url = result.get('url')
|
||||
record.published_at = result.get('published_at')
|
||||
record.error_message = result.get('error')
|
||||
record.metadata = result.get('metadata', {})
|
||||
record.save()
|
||||
|
||||
return {
|
||||
'destination': destination,
|
||||
'success': result.get('success', False),
|
||||
'publishing_record_id': record.id,
|
||||
'external_id': result.get('external_id'),
|
||||
'url': result.get('url')
|
||||
}
|
||||
except Exception as e:
|
||||
record.status = 'failed'
|
||||
record.error_message = str(e)
|
||||
record.save()
|
||||
raise
|
||||
|
||||
def _get_adapter(self, destination: str):
|
||||
"""
|
||||
Get adapter for destination platform.
|
||||
|
||||
Args:
|
||||
destination: Platform name ('wordpress', 'sites', 'shopify')
|
||||
|
||||
Returns:
|
||||
Adapter instance or None
|
||||
"""
|
||||
# Lazy import to avoid circular dependencies
|
||||
if destination == 'sites':
|
||||
from igny8_core.business.publishing.services.adapters.sites_renderer_adapter import SitesRendererAdapter
|
||||
return SitesRendererAdapter()
|
||||
elif destination == 'wordpress':
|
||||
# Will be implemented in Phase 6
|
||||
return None
|
||||
elif destination == 'shopify':
|
||||
# Will be implemented in Phase 6
|
||||
return None
|
||||
return None
|
||||
|
||||
5
backend/igny8_core/modules/publisher/__init__.py
Normal file
5
backend/igny8_core/modules/publisher/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
Publisher Module
|
||||
Phase 5: Sites Renderer & Publishing
|
||||
"""
|
||||
|
||||
12
backend/igny8_core/modules/publisher/apps.py
Normal file
12
backend/igny8_core/modules/publisher/apps.py
Normal file
@@ -0,0 +1,12 @@
|
||||
"""
|
||||
Publisher Module App Configuration
|
||||
"""
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class PublisherConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'igny8_core.modules.publisher'
|
||||
label = 'publisher'
|
||||
verbose_name = 'Publisher'
|
||||
|
||||
22
backend/igny8_core/modules/publisher/urls.py
Normal file
22
backend/igny8_core/modules/publisher/urls.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
Publisher URLs
|
||||
Phase 5: Sites Renderer & Publishing
|
||||
"""
|
||||
from django.urls import path, include
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from igny8_core.modules.publisher.views import (
|
||||
PublishingRecordViewSet,
|
||||
DeploymentRecordViewSet,
|
||||
PublisherViewSet,
|
||||
)
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(r'publishing-records', PublishingRecordViewSet, basename='publishing-record')
|
||||
router.register(r'deployments', DeploymentRecordViewSet, basename='deployment')
|
||||
router.register(r'publisher', PublisherViewSet, basename='publisher')
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
|
||||
198
backend/igny8_core/modules/publisher/views.py
Normal file
198
backend/igny8_core/modules/publisher/views.py
Normal file
@@ -0,0 +1,198 @@
|
||||
"""
|
||||
Publisher ViewSet
|
||||
Phase 5: Sites Renderer & Publishing
|
||||
"""
|
||||
from rest_framework import status, viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
|
||||
from igny8_core.api.base import SiteSectorModelViewSet
|
||||
from igny8_core.api.permissions import IsAuthenticatedAndActive, IsEditorOrAbove
|
||||
from igny8_core.api.response import success_response, error_response
|
||||
from igny8_core.api.throttles import DebugScopedRateThrottle
|
||||
from igny8_core.business.publishing.models import PublishingRecord, DeploymentRecord
|
||||
from igny8_core.business.publishing.services.publisher_service import PublisherService
|
||||
from igny8_core.business.site_building.models import SiteBlueprint
|
||||
|
||||
|
||||
class PublishingRecordViewSet(SiteSectorModelViewSet):
|
||||
"""
|
||||
ViewSet for PublishingRecord model.
|
||||
"""
|
||||
queryset = PublishingRecord.objects.select_related('content', 'site_blueprint')
|
||||
permission_classes = [IsAuthenticatedAndActive, IsEditorOrAbove]
|
||||
throttle_scope = 'publisher'
|
||||
throttle_classes = [DebugScopedRateThrottle]
|
||||
|
||||
def get_serializer_class(self):
|
||||
# Will be created in next step
|
||||
from rest_framework import serializers
|
||||
|
||||
class PublishingRecordSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = PublishingRecord
|
||||
fields = '__all__'
|
||||
|
||||
return PublishingRecordSerializer
|
||||
|
||||
|
||||
class DeploymentRecordViewSet(SiteSectorModelViewSet):
|
||||
"""
|
||||
ViewSet for DeploymentRecord model.
|
||||
"""
|
||||
queryset = DeploymentRecord.objects.select_related('site_blueprint')
|
||||
permission_classes = [IsAuthenticatedAndActive, IsEditorOrAbove]
|
||||
throttle_scope = 'publisher'
|
||||
throttle_classes = [DebugScopedRateThrottle]
|
||||
|
||||
def get_serializer_class(self):
|
||||
# Will be created in next step
|
||||
from rest_framework import serializers
|
||||
|
||||
class DeploymentRecordSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = DeploymentRecord
|
||||
fields = '__all__'
|
||||
|
||||
return DeploymentRecordSerializer
|
||||
|
||||
|
||||
class PublisherViewSet(viewsets.ViewSet):
|
||||
"""
|
||||
Publisher actions for publishing content and sites.
|
||||
"""
|
||||
permission_classes = [IsAuthenticatedAndActive, IsEditorOrAbove]
|
||||
throttle_scope = 'publisher'
|
||||
throttle_classes = [DebugScopedRateThrottle]
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.publisher_service = PublisherService()
|
||||
|
||||
@action(detail=False, methods=['post'], url_path='publish')
|
||||
def publish(self, request):
|
||||
"""
|
||||
Publish content or site to destinations.
|
||||
|
||||
Request body:
|
||||
{
|
||||
"content_id": 123, # Optional: content to publish
|
||||
"site_blueprint_id": 456, # Optional: site to publish
|
||||
"destinations": ["wordpress", "sites"] # Required: list of destinations
|
||||
}
|
||||
"""
|
||||
content_id = request.data.get('content_id')
|
||||
site_blueprint_id = request.data.get('site_blueprint_id')
|
||||
destinations = request.data.get('destinations', [])
|
||||
|
||||
if not destinations:
|
||||
return error_response(
|
||||
'destinations is required',
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
request
|
||||
)
|
||||
|
||||
account = request.account
|
||||
|
||||
if site_blueprint_id:
|
||||
# Publish site
|
||||
try:
|
||||
blueprint = SiteBlueprint.objects.get(id=site_blueprint_id, account=account)
|
||||
except SiteBlueprint.DoesNotExist:
|
||||
return error_response(
|
||||
f'Site blueprint {site_blueprint_id} not found',
|
||||
status.HTTP_404_NOT_FOUND,
|
||||
request
|
||||
)
|
||||
|
||||
if 'sites' in destinations:
|
||||
result = self.publisher_service.publish_to_sites(blueprint)
|
||||
return success_response(result, request=request)
|
||||
else:
|
||||
return error_response(
|
||||
'Site publishing only supports "sites" destination',
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
request
|
||||
)
|
||||
|
||||
elif content_id:
|
||||
# Publish content
|
||||
result = self.publisher_service.publish_content(
|
||||
content_id,
|
||||
destinations,
|
||||
account
|
||||
)
|
||||
return success_response(result, request=request)
|
||||
|
||||
else:
|
||||
return error_response(
|
||||
'Either content_id or site_blueprint_id is required',
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
request
|
||||
)
|
||||
|
||||
@action(detail=False, methods=['post'], url_path='deploy/(?P<blueprint_id>[^/.]+)')
|
||||
def deploy(self, request, blueprint_id):
|
||||
"""
|
||||
Deploy site blueprint to Sites renderer.
|
||||
|
||||
POST /api/v1/publisher/deploy/{blueprint_id}/
|
||||
"""
|
||||
account = request.account
|
||||
|
||||
try:
|
||||
blueprint = SiteBlueprint.objects.get(id=blueprint_id, account=account)
|
||||
except SiteBlueprint.DoesNotExist:
|
||||
return error_response(
|
||||
f'Site blueprint {blueprint_id} not found',
|
||||
status.HTTP_404_NOT_FOUND,
|
||||
request
|
||||
)
|
||||
|
||||
result = self.publisher_service.publish_to_sites(blueprint)
|
||||
|
||||
response_status = status.HTTP_202_ACCEPTED if result.get('success') else status.HTTP_400_BAD_REQUEST
|
||||
return success_response(result, request=request, status_code=response_status)
|
||||
|
||||
@action(detail=False, methods=['get'], url_path='status/(?P<id>[^/.]+)')
|
||||
def get_status(self, request, id):
|
||||
"""
|
||||
Get publishing/deployment status.
|
||||
|
||||
GET /api/v1/publisher/status/{id}/
|
||||
"""
|
||||
account = request.account
|
||||
|
||||
# Try deployment record first
|
||||
try:
|
||||
deployment = DeploymentRecord.objects.get(id=id, account=account)
|
||||
return success_response({
|
||||
'type': 'deployment',
|
||||
'status': deployment.status,
|
||||
'version': deployment.version,
|
||||
'deployed_version': deployment.deployed_version,
|
||||
'deployment_url': deployment.deployment_url,
|
||||
'deployed_at': deployment.deployed_at,
|
||||
'error_message': deployment.error_message,
|
||||
}, request=request)
|
||||
except DeploymentRecord.DoesNotExist:
|
||||
pass
|
||||
|
||||
# Try publishing record
|
||||
try:
|
||||
publishing = PublishingRecord.objects.get(id=id, account=account)
|
||||
return success_response({
|
||||
'type': 'publishing',
|
||||
'status': publishing.status,
|
||||
'destination': publishing.destination,
|
||||
'destination_url': publishing.destination_url,
|
||||
'published_at': publishing.published_at,
|
||||
'error_message': publishing.error_message,
|
||||
}, request=request)
|
||||
except PublishingRecord.DoesNotExist:
|
||||
return error_response(
|
||||
f'Record {id} not found',
|
||||
status.HTTP_404_NOT_FOUND,
|
||||
request
|
||||
)
|
||||
|
||||
@@ -54,9 +54,11 @@ INSTALLED_APPS = [
|
||||
'igny8_core.modules.automation.apps.AutomationConfig',
|
||||
'igny8_core.business.site_building.apps.SiteBuildingConfig',
|
||||
'igny8_core.business.optimization.apps.OptimizationConfig',
|
||||
'igny8_core.business.publishing.apps.PublishingConfig',
|
||||
'igny8_core.modules.site_builder.apps.SiteBuilderConfig',
|
||||
'igny8_core.modules.linker.apps.LinkerConfig',
|
||||
'igny8_core.modules.optimizer.apps.OptimizerConfig',
|
||||
'igny8_core.modules.publisher.apps.PublisherConfig',
|
||||
]
|
||||
|
||||
# System module needs explicit registration for admin
|
||||
|
||||
@@ -33,6 +33,7 @@ urlpatterns = [
|
||||
path('api/v1/automation/', include('igny8_core.modules.automation.urls')), # Automation endpoints
|
||||
path('api/v1/linker/', include('igny8_core.modules.linker.urls')), # Linker endpoints
|
||||
path('api/v1/optimizer/', include('igny8_core.modules.optimizer.urls')), # Optimizer endpoints
|
||||
path('api/v1/publisher/', include('igny8_core.modules.publisher.urls')), # Publisher endpoints
|
||||
# OpenAPI Schema and Documentation
|
||||
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
|
||||
path('api/docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
|
||||
|
||||
Reference in New Issue
Block a user