ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Attach a cache, storage or queue from the app page
Juan Denis6986f497f3b6
diff --git a/backend/app/api/app_attachments.py b/backend/app/api/app_attachments.pyindex ac5929d7..fd0229af 100644--- a/backend/app/api/app_attachments.py+++ b/backend/app/api/app_attachments.py@@ -1,10 +1,11 @@# Bucket: PER-APP (plan 29 #9). Reads gate on can_access_app; attach/detach# gate on can_edit_app for the app AND can_access_app for the service used.-"""Attach services an app uses (plan 86 §C2). Mounted under ``/api/v1/apps``.+"""Attach services an app uses (plan 86 §C2/§C4). Mounted under ``/api/v1/apps``.GET /<app_id>/attachments — this app's attachments- GET /attachments/storage-services — installed storage it can use- POST /<app_id>/attachments/storage — {service_app_id}+ GET /attachments/services?kind=<kind> — installed services for a kind+ POST /<app_id>/attachments/<kind> — {service_app_id}; kind is+ storage, cache or queueDELETE /<app_id>/attachments/<attachment_id> — detach (keeps the bucket)Attach and detach change the app's env; it applies on the next deploy or@@ -14,7 +15,9 @@ from flask import Blueprint, jsonify, requestfrom app.exceptions import NotFoundError, ValidationErrorfrom app.middleware.rbac import developer_required, get_current_user, viewer_required-from app.services.app_attachment_service import AppAttachmentService, AttachmentError+from app.models.app_attachment import AppAttachment+from app.services.app_attachment_service import (+ FAILURE_MODES, AppAttachmentService, AttachmentError)from app.services.resource_grant_service import ResourceGrantServiceapp_attachments_bp = Blueprint('app_attachments', __name__)@@ -29,19 +32,27 @@ def list_attachments(app_id):return jsonify({'attachments': [a.to_dict() for a in AppAttachmentService.list_for_app(app)]})-@app_attachments_bp.route('/attachments/storage-services', methods=['GET'])+def _kind_or_400(kind):+ if kind not in AppAttachment.KINDS:+ raise ValidationError(f"kind must be one of: {', '.join(AppAttachment.KINDS)}")+ return kind+++@app_attachments_bp.route('/attachments/services', methods=['GET'])@viewer_required-def list_storage_services():+def list_services():+ kind = _kind_or_400(request.args.get('kind', ''))user = get_current_user()- services = [s for s in AppAttachmentService.storage_services()+ services = [s for s in AppAttachmentService.services_for(kind)if ResourceGrantService.can_access_app(user, s)]- return jsonify({'services': [{'id': s.id, 'name': s.name, 'status': s.status}+ return jsonify({'kind': kind, 'failure_mode': FAILURE_MODES.get(kind),+ 'services': [{'id': s.id, 'name': s.name, 'status': s.status}for s in services]})-@app_attachments_bp.route('/<int:app_id>/attachments/storage', methods=['POST'])+@app_attachments_bp.route('/<int:app_id>/attachments/<kind>', methods=['POST'])@developer_required-def attach_storage(app_id):+def attach_service(app_id, kind):user = get_current_user()app = AppAttachmentService.live_app(app_id)if app is None or not ResourceGrantService.can_edit_app(user, app):@@ -50,11 +61,12 @@ def attach_storage(app_id):service_app_id = data.get('service_app_id')if not isinstance(service_app_id, int) or isinstance(service_app_id, bool):raise ValidationError("'service_app_id' is required")+ kind = _kind_or_400(kind)service = AppAttachmentService.live_app(service_app_id)if service is None or not ResourceGrantService.can_access_app(user, service):- raise NotFoundError('Storage service not found')+ raise NotFoundError('Service not found')try:- row, created = AppAttachmentService.attach_storage(app, service, user_id=user.id)+ row, created = AppAttachmentService.attach(app, service, kind, user_id=user.id)except AttachmentError as exc:raise ValidationError(str(exc)) from excreturn jsonify({'attachment': row.to_dict(), 'redeploy_required': created}), (201 if created else 200)diff --git a/backend/app/models/app_attachment.py b/backend/app/models/app_attachment.pyindex 69150718..813b66e7 100644--- a/backend/app/models/app_attachment.py+++ b/backend/app/models/app_attachment.py@@ -1,7 +1,7 @@"""An app's attachment to a service it uses (plan 86 §C2/§C4).-One row per (app, kind): the app's storage bucket on a Garage instance today;-cache, queue and tracing attachments reuse the same row. ``details_json``+One row per (app, kind): the app's storage bucket on a Garage instance, or+the cache / queue it uses (env references only). ``details_json``holds what the provisioner created (bucket, key id, the vault secret thatcarries the key), so detaching can remove exactly that and nothing else. Thesecret itself never lands here.@@ -21,7 +21,7 @@ class AppAttachment(JsonColumnMixin, db.Model):db.UniqueConstraint('app_id', 'kind', name='uq_app_attachments_app_kind'),)- KINDS = ('storage',)+ KINDS = ('storage', 'cache', 'queue')id = db.Column(db.Integer, primary_key=True)app_id = db.Column(db.Integer, db.ForeignKey('applications.id', ondelete='CASCADE'),@@ -60,5 +60,6 @@ class AppAttachment(JsonColumnMixin, db.Model):# Never the secret; the key id alone is safe to show.'bucket': details.get('bucket'),'access_key_id': details.get('access_key_id'),+ 'env_keys': details.get('env_keys') or [],'created_at': self.created_at.isoformat() if self.created_at else None,}diff --git a/backend/app/services/app_attachment_service.py b/backend/app/services/app_attachment_service.pyindex 86842511..a1d2348d 100644--- a/backend/app/services/app_attachment_service.py+++ b/backend/app/services/app_attachment_service.py@@ -1,4 +1,9 @@-"""Attach a service an app uses: object storage today (plan 86 §C2).+"""Attach a service an app uses: storage, cache or queue (plan 86 §C2/§C4).++Cache and queue attachments are env references only: the app gets the+service's C1 ``url`` through ``fromService`` under the names its libraries+read (``REDIS_URL``, ``AMQP_URL``/``BROKER_URL``). Storage is the one kind that+provisions something, described below."Attach storage" gives an app its own bucket on an installed Garage and a keythat can read and write that bucket only (never the admin token, never another@@ -52,6 +57,30 @@ def _storage_env(service_name: str, bucket: str, access_key_id: str,}+# kind -> (offers(template, engine) -> bool, env keys for the service's url).+# The env keys depend on what was attached: a Redis used as a queue is still+# only a BROKER_URL, never an AMQP_URL.+def _is_redis(template, engine):+ return engine.get('protocol') == 'redis'+++def _is_amqp(template, engine):+ return template.get('id') == 'rabbitmq'+++CONNECTION_KINDS = {+ 'cache': [(_is_redis, ('REDIS_URL',))],+ 'queue': [(_is_amqp, ('AMQP_URL', 'BROKER_URL')), (_is_redis, ('BROKER_URL',))],+}++# One line per kind, shown where the operator decides (plan 86 §C4).+FAILURE_MODES = {+ 'storage': 'Objects outlive the app: detaching keeps the bucket and its data.',+ 'cache': 'Cached data can be stale; invalidate on write, and never keep the only copy in a cache.',+ 'queue': 'A job can be delivered twice; make jobs safe to run again.',+}++class AppAttachmentService:@staticmethod@@ -83,6 +112,63 @@ class AppAttachmentService:return [a for a in Application.query_active().order_by(Application.name).all()if cls._provisioner(a) == 'garage']+ @staticmethod+ def _connection_env_keys(service_app, kind):+ """The env keys ``service_app`` fills for ``kind``, or None when it+ does not offer that kind."""+ from app.services.service_connection_service import _template_for+ from app.services.template_service import TemplateService+ template = _template_for(service_app) or {}+ engine = TemplateService.engine_metadata(template) or {}+ for offers, keys in CONNECTION_KINDS.get(kind, []):+ if offers(template, engine):+ return keys+ return None++ @classmethod+ def services_for(cls, kind):+ """Installed services an app can attach as ``kind``."""+ if kind == 'storage':+ return cls.storage_services()+ from app.models.application import Application+ return [a for a in Application.query_active().order_by(Application.name).all()+ if cls._connection_env_keys(a, kind)]++ @classmethod+ def attach(cls, app, service_app, kind, user_id=None):+ if kind == 'storage':+ return cls.attach_storage(app, service_app, user_id=user_id)+ if kind not in CONNECTION_KINDS:+ raise AttachmentError(f'Unknown attachment kind: {kind}')+ return cls.attach_connection(app, service_app, kind, user_id=user_id)++ @classmethod+ def attach_connection(cls, app, service_app, kind, user_id=None):+ """Point the app's env at ``service_app``'s URL for ``kind``."""+ from app.models.app_attachment import AppAttachment+ from app.services.env_service import EnvService++ if service_app.id == app.id:+ raise AttachmentError('A service cannot be attached to itself')+ keys = cls._connection_env_keys(service_app, kind)+ if not keys:+ raise AttachmentError(f'{service_app.name} cannot be used as a {kind}')+ existing = AppAttachment.query.filter_by(app_id=app.id, kind=kind).first()+ if existing is not None:+ if existing.service_app_id != service_app.id:+ raise AttachmentError(f'This app already has a {kind} attached; detach it first')+ return existing, False+ ref = {'kind': 'service', 'service': service_app.name, 'property': 'url'}+ for env_key in keys:+ _v, _c, error = EnvService.set_env_reference(app.id, env_key, ref, user_id=user_id)+ if error:+ raise AttachmentError(f'Could not set {env_key}: {error}')+ row = AppAttachment(app_id=app.id, service_app_id=service_app.id, kind=kind)+ row.details = {'env_keys': list(keys)}+ db.session.add(row)+ db.session.commit()+ return row, True+# -- storage ---------------------------------------------------------------@classmethoddiff --git a/backend/tests/test_app_attachments.py b/backend/tests/test_app_attachments.pyindex 61b24ccb..a69a188c 100644--- a/backend/tests/test_app_attachments.py+++ b/backend/tests/test_app_attachments.py@@ -5,6 +5,7 @@ Hermetic: a fake Garage admin records calls. The real-Garage round tripdocker-builds leg in test_real_storage_attach_docker.py."""import json+import osimport pytestimport yaml@@ -150,8 +151,9 @@ def test_api_attach_list_detach(installed, client, auth_headers, monkeypatch):monkeypatch.setattr(svc, 'GarageAdmin', lambda name: fake, raising=False)monkeypatch.setattr('app.services.garage_admin.GarageAdmin', lambda name: fake)- services = client.get('/api/v1/apps/attachments/storage-services', headers=auth_headers)+ services = client.get('/api/v1/apps/attachments/services?kind=storage', headers=auth_headers)assert [s['name'] for s in services.get_json()['services']] == ['store']+ assert 'bucket' in services.get_json()['failure_mode']made = client.post(f'/api/v1/apps/{web.id}/attachments/storage',json={'service_app_id': store.id}, headers=auth_headers)@@ -159,7 +161,7 @@ def test_api_attach_list_detach(installed, client, auth_headers, monkeypatch):body = made.get_json()assert body['redeploy_required'] is Trueassert body['attachment']['bucket'] == 'web'- assert 'secret' not in json.dumps(body).lower().replace('s3_secret', '')+ assert 'topsecret' not in json.dumps(body), 'the secret value never leaves the vault'listed = client.get(f'/api/v1/apps/{web.id}/attachments', headers=auth_headers)assert [a['id'] for a in listed.get_json()['attachments']] == [body['attachment']['id']]@@ -188,3 +190,68 @@ def test_deleting_either_app_takes_the_attachment(installed):db.session.delete(Application.query.get(store.id))db.session.commit()assert AppAttachment.query.count() == 0+++# ── cache and queue (plan 86 §C4) ─────────────────────────────────────────────++def _installed_with_vars(installed, name, template_id, variables):+ row = installed(name, template_id)+ path = os.path.join(row.root_path, '.serverkit-template.json')+ with open(path, 'w') as fh:+ json.dump({'template_id': template_id, 'variables': variables}, fh)+ return row++[email protected]('kind,template_id,keys,scheme', [+ ('cache', 'redis', ['REDIS_URL'], 'redis://'),+ ('cache', 'valkey', ['REDIS_URL'], 'redis://'),+ ('queue', 'rabbitmq', ['AMQP_URL', 'BROKER_URL'], 'amqp://'),+ ('queue', 'redis', ['BROKER_URL'], 'redis://'),+])+def test_connection_kinds_wire_the_services_url(installed, kind, template_id, keys, scheme):+ svc_app = _installed_with_vars(installed, 'svc', template_id,+ {'DB_PASSWORD': 'pw', 'RABBITMQ_USER': 'u',+ 'RABBITMQ_PASSWORD': 'pw'})+ web = installed('web')+ row, created = AppAttachmentService.attach(web, svc_app, kind)+ assert created and row.details['env_keys'] == keys+ env = EnvService.get_effective_env(web.id)+ for key in keys:+ assert env[key].startswith(scheme + ('' if scheme == 'amqp://' else ':')), env[key]+ assert 'AMQP_URL' not in env or template_id == 'rabbitmq'++ AppAttachmentService.detach(row)+ env = EnvService.get_effective_env(web.id)+ assert not any(k in env for k in keys)++[email protected]('kind,template_id', [+ ('cache', 'rabbitmq'), ('cache', 'garage'), ('queue', 'garage'), ('cache', None),+])+def test_a_service_that_does_not_offer_the_kind_is_refused(installed, kind, template_id):+ target, web = installed('target', template_id), installed('web')+ with pytest.raises(AttachmentError, match=f'cannot be used as a {kind}'):+ AppAttachmentService.attach(web, target, kind)+++def test_services_for_lists_only_matching_services(installed):+ installed('cache1', 'redis')+ installed('mq', 'rabbitmq')+ installed('store', 'garage')+ installed('web')+ names = lambda kind: [a.name for a in AppAttachmentService.services_for(kind)]+ assert names('cache') == ['cache1']+ assert names('queue') == ['cache1', 'mq']+ assert names('storage') == ['store']+++def test_api_rejects_an_unknown_kind(installed, client, auth_headers):+ web, cache = installed('web'), installed('cache1', 'redis')+ bad = client.post(f'/api/v1/apps/{web.id}/attachments/tracing',+ json={'service_app_id': cache.id}, headers=auth_headers)+ assert bad.status_code == 400+ assert client.get('/api/v1/apps/attachments/services?kind=nope',+ headers=auth_headers).status_code == 400+ ok = client.post(f'/api/v1/apps/{web.id}/attachments/cache',+ json={'service_app_id': cache.id}, headers=auth_headers)+ assert ok.status_code == 201 and ok.get_json()['attachment']['env_keys'] == ['REDIS_URL']diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.mdindex b0432c9f..64ca589f 100644--- a/docs/API_SURFACE.md+++ b/docs/API_SURFACE.md@@ -158,7 +158,7 @@ Regenerate (backend/):- `GET /api-keys/scopes`- `GET /api-keys/{key_id}`- `GET /apps`-- `GET /apps/attachments/storage-services`+- `GET /apps/attachments/services`- `GET /apps/p/{slug}`- `GET /apps/{app_id}`- `GET /apps/{app_id}/attachments`@@ -773,7 +773,7 @@ Regenerate (backend/):- `POST /apps/scale-sweep`- `POST /apps/sweep-idle`- `POST /apps/upload`-- `POST /apps/{app_id}/attachments/storage`+- `POST /apps/{app_id}/attachments/{kind}`- `POST /apps/{app_id}/backups`- `POST /apps/{app_id}/backups/{run_id}/restore`- `POST /apps/{app_id}/backups/{run_id}/verify`diff --git a/frontend/src/components/service-detail/AttachmentsCard.jsx b/frontend/src/components/service-detail/AttachmentsCard.jsxnew file mode 100644index 00000000..8cb792e7--- /dev/null+++ b/frontend/src/components/service-detail/AttachmentsCard.jsx@@ -0,0 +1,240 @@+import { useCallback, useEffect, useState } from 'react';+import { Plug, Unplug, RotateCw } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import api from '../../services/api';+import Modal from '@/components/Modal';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import { useToast } from '../../contexts/useToast.js';+import { useAuth } from '../../contexts/useAuth.js';+import { useConfirm } from '@/hooks/useConfirm';++// Kind -> the template installed when none exists yet. Must match what the+// backend accepts for that kind (app_attachment_service.CONNECTION_KINDS).+const DEFAULT_TEMPLATES = {+ cache: { id: 'redis', name: 'Redis' },+ storage: { id: 'garage', name: 'Garage' },+ queue: { id: 'rabbitmq', name: 'RabbitMQ' },+};+const KINDS = ['cache', 'storage', 'queue'];++// "Attach → Cache / Storage / Queue" (plan 86 §C4): reuse an installed+// service or install one, write the env references, then offer a redeploy.+export default function AttachmentsCard({ app }) {+ const { t } = useTranslation();+ const toast = useToast();+ const { confirm } = useConfirm();+ const { isAdmin } = useAuth();+ const [attachments, setAttachments] = useState(null);+ const [kind, setKind] = useState(null);+ const [choices, setChoices] = useState(null);+ const [selected, setSelected] = useState('');+ const [busy, setBusy] = useState(false);+ const [needsRedeploy, setNeedsRedeploy] = useState(false);++ // Each component's failure mode, where the operator decides. Mirrors the+ // API's `failure_mode` (app_attachment_service.FAILURE_MODES), translated.+ const failureMode = (k) => ({+ cache: t('app.attachments.failureCache', 'Cached data can be stale; invalidate on write, and never keep the only copy in a cache.'),+ storage: t('app.attachments.failureStorage', 'Objects outlive the app: detaching keeps the bucket and its data.'),+ queue: t('app.attachments.failureQueue', 'A job can be delivered twice; make jobs safe to run again.'),+ }[k]);++ const kindLabel = (k) => ({+ cache: t('app.attachments.kindCache', 'Cache'),+ storage: t('app.attachments.kindStorage', 'Storage'),+ queue: t('app.attachments.kindQueue', 'Queue'),+ }[k]);++ const load = useCallback(() => {+ api.getAppAttachments(app.id)+ .then((data) => setAttachments(data.attachments || []))+ .catch(() => setAttachments([]));+ }, [app.id]);++ useEffect(() => { load(); }, [load]);++ async function openKind(next) {+ setKind(next);+ setChoices(null);+ setSelected('');+ try {+ const data = await api.getAttachableServices(next);+ setChoices(data);+ if (data.services?.length) setSelected(String(data.services[0].id));+ } catch (err) {+ toast.error(err.message);+ setKind(null);+ }+ }++ async function attach(serviceId) {+ setBusy(true);+ try {+ await api.attachService(app.id, kind, serviceId);+ toast.success(t('app.attachments.attached', 'Attached. Redeploy to apply.'));+ setNeedsRedeploy(true);+ setKind(null);+ load();+ } catch (err) {+ toast.error(err.message);+ } finally {+ setBusy(false);+ }+ }++ async function installAndAttach() {+ const templateId = DEFAULT_TEMPLATES[kind].id;+ setBusy(true);+ try {+ const installed = await api.installTemplate(+ templateId, `${app.name}-${kind}`, {}, { wait: true });+ if (installed.job?.status === 'failed') {+ throw new Error(installed.job.error_message || t('app.attachments.installFailed', 'The install failed.'));+ }+ const serviceId = installed.job?.app_id;+ if (!serviceId) throw new Error(t('app.attachments.installNoId', 'Installed, but the new service could not be found. Attach it from the list.'));+ await attach(serviceId);+ } catch (err) {+ toast.error(err.message);+ setBusy(false);+ }+ }++ async function detach(row) {+ if (!await confirm({+ title: t('app.attachments.detachTitle', 'Detach {{name}}?', { name: row.service_name }),+ message: row.kind === 'storage'+ ? t('app.attachments.detachStorage', 'The app loses its key and S3 settings. The bucket and its files are kept.')+ : t('app.attachments.detachConnection', 'The app loses the settings that point at this service.'),+ confirmText: t('app.attachments.detach', 'Detach'),+ })) return;+ try {+ const res = await api.detachService(app.id, row.id);+ if (res.warning) toast.warning(res.warning);+ setNeedsRedeploy(true);+ load();+ } catch (err) {+ toast.error(err.message);+ }+ }++ async function redeploy() {+ setBusy(true);+ try {+ await api.deployApp(app.id);+ toast.success(t('app.attachments.redeploying', 'Redeploy started.'));+ setNeedsRedeploy(false);+ } catch (err) {+ toast.error(err.message);+ } finally {+ setBusy(false);+ }+ }++ const attachedKinds = new Set((attachments || []).map((a) => a.kind));+ const open = KINDS.filter((k) => !attachedKinds.has(k));++ return (+ <div className="overview-tab__card overview-tab__card--full attachments">+ <div className="overview-tab__card-header-row">+ <h3 className="overview-tab__card-title">{t('app.attachments.title', 'Attached services')}</h3>+ {open.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="sm">+ <Plug size={14} />+ {t('app.attachments.attach', 'Attach')}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {open.map((k) => (+ <DropdownMenuItem key={k} onSelect={() => openKind(k)}>+ {kindLabel(k)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>++ {needsRedeploy && (+ <div className="attachments__redeploy">+ <span>{t('app.attachments.redeployHint', 'The app picks up the change on its next deploy.')}</span>+ <Button size="sm" onClick={redeploy} disabled={busy}>+ <RotateCw size={14} />+ {t('app.attachments.redeployNow', 'Redeploy now')}+ </Button>+ </div>+ )}++ {attachments?.length ? (+ <ul className="attachments__list">+ {attachments.map((row) => (+ <li key={row.id} className="attachments__row">+ <span className="attachments__kind">{kindLabel(row.kind)}</span>+ <span className="attachments__service">{row.service_name}</span>+ <code className="attachments__env">+ {row.kind === 'storage' ? `S3_BUCKET=${row.bucket}` : row.env_keys.join(', ')}+ </code>+ <Button variant="ghost" size="sm" onClick={() => detach(row)}+ aria-label={t('app.attachments.detach', 'Detach')}>+ <Unplug size={14} />+ </Button>+ </li>+ ))}+ </ul>+ ) : (+ <p className="attachments__empty">+ {t('app.attachments.empty', 'Nothing attached. Attach a cache, object storage or a queue and the app gets its connection settings as environment variables.')}+ </p>+ )}++ <Modal+ open={kind !== null}+ onClose={() => !busy && setKind(null)}+ title={kind ? t('app.attachments.attachKind', 'Attach {{kind}}', { kind: kindLabel(kind).toLowerCase() }) : ''}+ footer={choices && (choices.services?.length ? (+ <Button onClick={() => attach(Number(selected))} disabled={busy || !selected}>+ {t('app.attachments.attach', 'Attach')}+ </Button>+ ) : isAdmin && (+ <Button onClick={installAndAttach} disabled={busy}>+ {busy+ ? t('app.attachments.installing', 'Installing…')+ : t('app.attachments.installAndAttach', 'Install {{template}} and attach', { template: DEFAULT_TEMPLATES[kind].name })}+ </Button>+ ))}+ >+ {choices === null ? (+ <p>{t('common.loading', 'Loading…')}</p>+ ) : (+ <div className="attachments__dialog">+ {choices.services?.length ? (+ <Select value={selected} onValueChange={setSelected}>+ <SelectTrigger aria-label={t('app.attachments.service', 'Service')}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {choices.services.map((s) => (+ <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <p>+ {isAdmin+ ? t('app.attachments.noneInstalled', 'No {{kind}} service is installed yet. ServerKit can install one now.', { kind: kindLabel(kind).toLowerCase() })+ : t('app.attachments.noneInstalledAskAdmin', 'No {{kind}} service is installed yet. Ask an admin to install one.', { kind: kindLabel(kind).toLowerCase() })}+ </p>+ )}+ <p className="attachments__failure-mode">{failureMode(kind)}</p>+ </div>+ )}+ </Modal>+ </div>+ );+}diff --git a/frontend/src/components/service-detail/OverviewTab.jsx b/frontend/src/components/service-detail/OverviewTab.jsxindex 961055de..d75cb656 100644--- a/frontend/src/components/service-detail/OverviewTab.jsx+++ b/frontend/src/components/service-detail/OverviewTab.jsx@@ -9,6 +9,7 @@ import { formatBytes } from '../../utils/formatBytes';import BandwidthSparkline from '../BandwidthSparkline';import ScheduledTasksCard from '../ScheduledTasksCard';import RequestMetricsCard from './RequestMetricsCard';+import AttachmentsCard from './AttachmentsCard';import { KpiBand, MetricCard, Pill, Gauge, EnvTag, statusKind } from '@/components/ds';import { usePolling } from '@/hooks/usePolling';import { useTranslation } from 'react-i18next';@@ -330,6 +331,9 @@ const OverviewTab = ({ app, deployConfig }) => {{/* Traffic (timed access log; hidden until requests exist) */}<RequestMetricsCard appId={app.id} />+ {/* Cache / storage / queue this app uses (plan 86 §C4) */}+ <AttachmentsCard app={app} />+{/* Recent Deployments */}<div className="overview-tab__card overview-tab__card--full"><div className="overview-tab__card-header-row">diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 18c56086..56edd7eb 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -506,6 +506,33 @@"unavailable": "Unavailable","unknown": "Unsupported attachment"},+ "attachments": {+ "attach": "Attach",+ "attachKind": "Attach {{kind}}",+ "attached": "Attached. Redeploy to apply.",+ "detach": "Detach",+ "detachConnection": "The app loses the settings that point at this service.",+ "detachStorage": "The app loses its key and S3 settings. The bucket and its files are kept.",+ "detachTitle": "Detach {{name}}?",+ "empty": "Nothing attached. Attach a cache, object storage or a queue and the app gets its connection settings as environment variables.",+ "failureCache": "Cached data can be stale; invalidate on write, and never keep the only copy in a cache.",+ "failureQueue": "A job can be delivered twice; make jobs safe to run again.",+ "failureStorage": "Objects outlive the app: detaching keeps the bucket and its data.",+ "installAndAttach": "Install {{template}} and attach",+ "installFailed": "The install failed.",+ "installNoId": "Installed, but the new service could not be found. Attach it from the list.",+ "installing": "Installing…",+ "kindCache": "Cache",+ "kindQueue": "Queue",+ "kindStorage": "Storage",+ "noneInstalled": "No {{kind}} service is installed yet. ServerKit can install one now.",+ "noneInstalledAskAdmin": "No {{kind}} service is installed yet. Ask an admin to install one.",+ "redeployHint": "The app picks up the change on its next deploy.",+ "redeployNow": "Redeploy now",+ "redeploying": "Redeploy started.",+ "service": "Service",+ "title": "Attached services"+ },"auditTab": {"generated": "Generated","recommendations": "Recommendations",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 14e9859a..160af1bc 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -6705,6 +6705,33 @@"p95": "Latencia p95","requests": "Solicitudes","title": "Tráfico"+ },+ "attachments": {+ "attach": "Conectar",+ "attachKind": "Conectar {{kind}}",+ "attached": "Conectado. Vuelve a desplegar para aplicarlo.",+ "detach": "Desconectar",+ "detachConnection": "La app pierde la configuración que apunta a este servicio.",+ "detachStorage": "La app pierde su clave y su configuración S3. El bucket y sus archivos se conservan.",+ "detachTitle": "¿Desconectar {{name}}?",+ "empty": "No hay nada conectado. Conecta una caché, almacenamiento de objetos o una cola y la app recibe su configuración de conexión como variables de entorno.",+ "failureCache": "Los datos en caché pueden quedar obsoletos; invalídalos al escribir y nunca guardes la única copia en una caché.",+ "failureQueue": "Un trabajo puede entregarse dos veces; haz que los trabajos se puedan repetir sin efectos.",+ "failureStorage": "Los objetos sobreviven a la app: al desconectar se conservan el bucket y sus datos.",+ "installAndAttach": "Instalar {{template}} y conectar",+ "installFailed": "La instalación falló.",+ "installNoId": "Instalado, pero no se encontró el nuevo servicio. Conéctalo desde la lista.",+ "installing": "Instalando…",+ "kindCache": "Caché",+ "kindQueue": "Cola",+ "kindStorage": "Almacenamiento",+ "noneInstalled": "Todavía no hay ningún servicio de {{kind}} instalado. ServerKit puede instalar uno ahora.",+ "noneInstalledAskAdmin": "Todavía no hay ningún servicio de {{kind}} instalado. Pide a un administrador que instale uno.",+ "redeployHint": "La app aplica el cambio en su próximo despliegue.",+ "redeployNow": "Volver a desplegar ahora",+ "redeploying": "Despliegue iniciado.",+ "service": "Servicio",+ "title": "Servicios conectados"}},"auth": {diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.jsindex 6506eb92..3d0f9ca8 100644--- a/frontend/src/services/api/apps.js+++ b/frontend/src/services/api/apps.js@@ -534,3 +534,24 @@ export async function rollback(appId, targetVersion = null) {export async function getCurrentDeployment(appId) {return this.request(`/builds/apps/${appId}/current-deployment`);}++// Services an app uses (plan 86 §C4): storage (own bucket + scoped key),+// cache and queue (env references to an installed engine).+export async function getAppAttachments(appId) {+ return this.request(`/apps/${appId}/attachments`);+}++export async function getAttachableServices(kind) {+ return this.request(`/apps/attachments/services?kind=${encodeURIComponent(kind)}`);+}++export async function attachService(appId, kind, serviceAppId) {+ return this.request(`/apps/${appId}/attachments/${encodeURIComponent(kind)}`, {+ method: 'POST',+ body: { service_app_id: serviceAppId },+ });+}++export async function detachService(appId, attachmentId) {+ return this.request(`/apps/${appId}/attachments/${attachmentId}`, { method: 'DELETE' });+}diff --git a/frontend/src/styles/pages/_bandwidth.scss b/frontend/src/styles/pages/_bandwidth.scssindex b0c1d2fa..0d77e4b9 100644--- a/frontend/src/styles/pages/_bandwidth.scss+++ b/frontend/src/styles/pages/_bandwidth.scss@@ -85,3 +85,71 @@max-width: 100%;}}++// Service detail Overview: Attached services card (plan 86 §C4).+// Component: service-detail/AttachmentsCard.+.attachments {+ &__list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }++ &__row {+ display: grid;+ grid-template-columns: 80px minmax(0, 1fr) minmax(0, 2fr) auto;+ align-items: center;+ gap: 12px;+ padding: 6px 0;+ border-top: 1px solid var(--border-soft);++ &:first-child { border-top: 0; }+ }++ &__kind {+ font-size: 11.5px;+ color: var(--text-dim);+ }++ &__service { color: var(--text); }++ &__env {+ font-family: var(--mono);+ font-size: 12px;+ color: var(--text-dim);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__empty {+ margin: 0;+ font-size: 12.5px;+ color: var(--text-dim);+ }++ &__redeploy {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ margin-bottom: 10px;+ font-size: 12.5px;+ color: var(--text-dim);+ }++ &__dialog {+ display: flex;+ flex-direction: column;+ gap: 12px;+ }++ &__failure-mode {+ margin: 0;+ font-size: 12.5px;+ color: var(--text-dim);+ }+}