Files
shopdb-flask/migrations/versions/7d46_nest_app_packages.py
cproudlock 534f179ee6 Make main the lean product a site receives
main was 16 days and 259 commits behind the line the product is actually built
on, at contract 0.30.0 against 0.35.0, with no per-PC credential code at all. It
was neither current nor curated - just stale. This brings it forward and, at the
same time, makes it mean something: main is what a receiving site installs, and
nothing else.

WHAT IT CARRIES. Twelve plugins - backups, computers, endpoints, guides,
knowledgebase, machines, network, notifications, printers, slides, tools,
warranty - plus applications, which is manifest-less core and always ships. The
only manifest dependency inside that set is endpoints on computers, and both are
in it, so the closure is self-contained.

WHAT IT DOES NOT. employees, geenforce, measuringtools, printedparts and usb
stay on the site line. So do the Windows installer tree, the VM rehearsal
helpers, the agent tooling config, one site's data loader, the internal audit
and findings records, and the planner spreadsheet. 1,135 tracked files against
1,438.

A REMOVAL THAT BREAKS THE APP IS NOT A REMOVAL, and two nearly shipped:

deploy/site-profile-universal.json still named all seventeen plugins. It is the
file docs/DEPLOY.md tells a site to provision from, so a fresh install would
have failed at `flask plugin apply-profile` with PluginError - the first thing a
receiving site does, broken by the branch meant to serve them. It now names the
twelve that exist, and its comment says the two must agree.

agent/ was never refreshed. Whoever populated this branch copied shopdb/,
plugins/, frontend/ and tests/ from the site line and left the agent tree at its
September state: 22 C# and PowerShell sources missing, including AgentCredentials,
EnrollmentService, AgentHttpFactory and the fleet-alert client, plus one file the
site line had deleted still present. The old tree is internally consistent, so it
compiles, and nothing in CI builds it - every gate was green over a server that
speaks enrollment and per-PC credentials to a bundled agent source that cannot.
Resynced whole.

DECISIONS THIS ENCODES, rather than defers:

- The plugin-authoring lab builds printedparts, whose manifest depends on
  employees, so it could not stay. The lab remains on the site line and main
  ships no build-along tutorial. That is a real loss for an adopting developer
  and is recorded here rather than discovered later.
- Recognition, Training and Recertification notifications are no longer seeded.
  Each splits one notification into a card per employee and renders a photo,
  which needs a plugin this branch does not bundle. Seeding them would offer an
  author a type that cannot resolve anybody. A site that installs employees gets
  them from that plugin's own seed.
- Windows/IIS is documented as the legacy path throughout, and the README leads
  with Docker, because that is what a receiving site gets.

The API description is regenerated for THIS branch - 347 paths and 483
operations, down from 415 and 573 - so the published contract describes what is
here rather than what the site line serves. docs/CONFIG.md lost the two
measuring-tool label keys the code no longer declares, which two lanes had
decided opposite ways.

Suite: 3124 passed, 6 skipped. Naming and style gates pass. The docs gates run
rather than skip, and every index line count is derived from the file it names.
2026-09-19 11:24:40 -04:00

137 lines
5.0 KiB
Python

"""Move uploaded installers into per-application directories.
Installers used to be stored flat as "application-<id>.<ext>", which threw away
the name the vendor shipped. That is what made a re-import look like new
software: the operator had no way to see that the file already in the catalogue
was the same one they were about to upload again, so duplicate applications and
versions accumulated. Installers now keep their filename, namespaced by
application id so a generic "setup.exe" from two vendors cannot collide.
That only helps files uploaded from here on. This moves the ones already stored,
so existing download links keep working instead of 404ing against a path the
route no longer serves.
The original filename cannot be recovered - the old scheme discarded it at
upload - so these land as "installer.<ext>". That is no worse than what they
were called before, and re-uploading the installer restores the real name.
Files are MOVED, not copied or deleted: a move is reversible, which is what
lets downgrade() put them back. This is deliberately unlike 7d45, which refused
to touch files because it could only have deleted them.
The database is the part that must not be left inconsistent, so installpath is
rewritten for every affected row whether or not its file was found on disk. A
row pointing at a missing file is a broken download; a row pointing at the old
scheme is a broken download that also cannot be repaired by re-uploading.
Revision ID: 7d46_nest_app_packages
Revises: 7d45_purge_inactive_apps
"""
import os
import re
from alembic import op
import sqlalchemy as sa
revision = '7d46_nest_app_packages'
down_revision = '7d45_purge_inactive_apps'
branch_labels = None
depends_on = None
OLD_PREFIX = '/api/applications/package/'
# application-<id>.<ext>, the only shape the old uploader produced.
OLD_NAME = re.compile(r'^application-(\d+)\.([A-Za-z0-9]+)$')
def _package_dir():
"""The instance-relative directory installers are stored in.
Resolved the same way the API resolves it. If the app context is not
available the migration still rewrites the database and simply leaves the
files alone, rather than failing the whole upgrade over a path lookup.
"""
try:
from flask import current_app
return os.path.join(current_app.instance_path, 'applicationpackages')
except Exception:
return None
def upgrade():
bind = op.get_bind()
rows = bind.execute(sa.text(
"SELECT appid, installpath FROM applications "
"WHERE installpath LIKE :prefix"
), {'prefix': OLD_PREFIX + '%'}).fetchall()
directory = _package_dir()
for appid, installpath in rows:
tail = installpath[len(OLD_PREFIX):]
match = OLD_NAME.match(tail)
if not match:
# Already nested (contains a slash) or otherwise not the old shape.
# Leaving it alone is correct: it is already being served.
continue
ext = match.group(2).lower()
stored = f'installer.{ext}'
if directory:
source = os.path.join(directory, tail)
target_dir = os.path.join(directory, str(appid))
if os.path.isfile(source):
os.makedirs(target_dir, exist_ok=True)
try:
os.replace(source, os.path.join(target_dir, stored))
except OSError:
# Best effort. The row is still repointed below so the
# schema is consistent; a missing file is a re-upload.
pass
bind.execute(sa.text(
"UPDATE applications SET installpath = :path WHERE appid = :appid"
), {'path': f'{OLD_PREFIX}{appid}/{stored}', 'appid': appid})
def downgrade():
bind = op.get_bind()
rows = bind.execute(sa.text(
"SELECT appid, installpath FROM applications "
"WHERE installpath LIKE :prefix"
), {'prefix': OLD_PREFIX + '%'}).fetchall()
directory = _package_dir()
for appid, installpath in rows:
tail = installpath[len(OLD_PREFIX):]
if '/' not in tail:
continue
nested_id, _, stored = tail.partition('/')
if nested_id != str(appid):
continue
ext = os.path.splitext(stored)[1].lstrip('.').lower()
if not ext:
continue
flat = f'application-{appid}.{ext}'
if directory:
source = os.path.join(directory, str(appid), stored)
if os.path.isfile(source):
try:
os.replace(source, os.path.join(directory, flat))
# Remove the now-empty directory so a re-upgrade does not
# find a stale one. Only if empty: a directory with other
# files in it is not ours to remove.
os.rmdir(os.path.join(directory, str(appid)))
except OSError:
pass
bind.execute(sa.text(
"UPDATE applications SET installpath = :path WHERE appid = :appid"
), {'path': OLD_PREFIX + flat, 'appid': appid})