prettynb 0.13.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. prettynb/__init__.py +7 -0
  2. prettynb/_internal/__init__.py +1 -0
  3. prettynb/_internal/backups.py +327 -0
  4. prettynb/_internal/cli_tools.py +48 -0
  5. prettynb/_internal/containers.py +103 -0
  6. prettynb/_internal/deployment.py +194 -0
  7. prettynb/_internal/diagnostics.py +49 -0
  8. prettynb/_internal/http.py +37 -0
  9. prettynb/_internal/icons.py +51 -0
  10. prettynb/_internal/identities.py +295 -0
  11. prettynb/_internal/journal.py +305 -0
  12. prettynb/_internal/legacy_rendering.py +167 -0
  13. prettynb/_internal/links.py +184 -0
  14. prettynb/_internal/moves.py +168 -0
  15. prettynb/_internal/navigation.py +234 -0
  16. prettynb/_internal/operation_logs.py +97 -0
  17. prettynb/_internal/publication_execute.py +125 -0
  18. prettynb/_internal/publication_plan.py +296 -0
  19. prettynb/_internal/publication_state.py +111 -0
  20. prettynb/_internal/publishing.py +449 -0
  21. prettynb/_internal/rendering.py +49 -0
  22. prettynb/_internal/routes.py +88 -0
  23. prettynb/_internal/search.py +113 -0
  24. prettynb/_internal/storage.py +271 -0
  25. prettynb/_internal/web_state.py +99 -0
  26. prettynb/appearance.py +63 -0
  27. prettynb/cli.py +510 -0
  28. prettynb/commands/__init__.py +0 -0
  29. prettynb/commands/code.py +161 -0
  30. prettynb/commands/collect.py +249 -0
  31. prettynb/commands/commit.py +274 -0
  32. prettynb/commands/correct.py +234 -0
  33. prettynb/commands/deploy.py +111 -0
  34. prettynb/commands/graph.py +189 -0
  35. prettynb/commands/logs.py +17 -0
  36. prettynb/commands/pprint.py +91 -0
  37. prettynb/commands/subl.py +75 -0
  38. prettynb/commands/tasks.py +323 -0
  39. prettynb/helpers/__init__.py +2 -0
  40. prettynb/helpers/_datetime.py +26 -0
  41. prettynb/helpers/wrappers.py +77 -0
  42. prettynb/markdown/__init__.py +31 -0
  43. prettynb/markdown/dialect.py +8 -0
  44. prettynb/markdown/inlines.py +11 -0
  45. prettynb/markdown/nodes.py +49 -0
  46. prettynb/markdown/parser.py +11 -0
  47. prettynb/markdown/renderers.py +200 -0
  48. prettynb/models/__init__.py +4 -0
  49. prettynb/models/components/__init__.py +13 -0
  50. prettynb/models/components/codeblock.py +123 -0
  51. prettynb/models/components/component.py +79 -0
  52. prettynb/models/components/link.py +252 -0
  53. prettynb/models/components/tag.py +72 -0
  54. prettynb/models/components/url.py +104 -0
  55. prettynb/models/note.py +504 -0
  56. prettynb/models/notebook.py +639 -0
  57. prettynb/resources/deploy/checkpoint.py.tmpl +42 -0
  58. prettynb/resources/deploy/common.sh.tmpl +56 -0
  59. prettynb/resources/deploy/environment.example.tmpl +10 -0
  60. prettynb/resources/deploy/init.sh.tmpl +29 -0
  61. prettynb/resources/deploy/nginx.conf.tmpl +33 -0
  62. prettynb/resources/deploy/rollback.sh.tmpl +27 -0
  63. prettynb/resources/deploy/service.tmpl +25 -0
  64. prettynb/resources/deploy/upgrade.sh.tmpl +36 -0
  65. prettynb/settings.py +402 -0
  66. prettynb-0.13.0.dist-info/METADATA +72 -0
  67. prettynb-0.13.0.dist-info/RECORD +71 -0
  68. prettynb-0.13.0.dist-info/WHEEL +5 -0
  69. prettynb-0.13.0.dist-info/entry_points.txt +2 -0
  70. prettynb-0.13.0.dist-info/licenses/LICENSE +22 -0
  71. prettynb-0.13.0.dist-info/top_level.txt +1 -0
prettynb/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ from .models import Notebook, Note
2
+ from .settings import NotebookSettings, SettingsError
3
+ from prettynb._internal.identities import IdentityError
4
+ from prettynb._internal.search import SearchHit
5
+ from prettynb._internal.navigation import NavigationHistory, NavigationIndex
6
+
7
+ __all__ = ["Notebook", "Note", "NotebookSettings", "SettingsError", "IdentityError", "SearchHit", "NavigationIndex", "NavigationHistory"]
@@ -0,0 +1 @@
1
+ """Private implementation helpers; use the public package API."""
@@ -0,0 +1,327 @@
1
+ """Preview-first, stopped-site recovery into new private locations."""
2
+
3
+ from contextlib import closing, contextmanager
4
+ from dataclasses import replace
5
+ from importlib.metadata import version as package_version
6
+ import hashlib
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+ import sqlite3
12
+ import stat
13
+ import time
14
+ import tomllib
15
+
16
+ from .deployment import _run_checked, check_environment
17
+ from .web_state import CURRENT_VERSION, inspect_web_state
18
+
19
+ AUXILIARY = {'db.sqlite3-wal', 'db.sqlite3-shm', 'db.sqlite3-journal'}
20
+
21
+
22
+ def _location(value):
23
+ path = Path(value).expanduser().absolute()
24
+ if path.is_symlink():
25
+ raise ValueError('Recovery locations must not be symlinks.')
26
+ return path.resolve()
27
+
28
+
29
+ def _new_location(value, *sources):
30
+ path = _location(value)
31
+ if path.exists() or not path.parent.is_dir():
32
+ raise ValueError('Choose a new output location with an existing parent directory.')
33
+ for source in sources:
34
+ source = _location(source)
35
+ if path.is_relative_to(source) or source.is_relative_to(path):
36
+ raise ValueError('Recovery output must be separate from existing state and backups.')
37
+ return path
38
+
39
+
40
+ def _scan(root, *, copy_to=None, skip=frozenset()):
41
+ """Read relative to directory descriptors and reject links/special files."""
42
+ files, directories = {}, []
43
+ descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
44
+ def unreadable(error):
45
+ raise error
46
+ try:
47
+ for relative, names, filenames, directory in os.fwalk('.', dir_fd=descriptor, follow_symlinks=False, onerror=unreadable):
48
+ prefix = Path(relative)
49
+ if copy_to is not None:
50
+ (copy_to / prefix).mkdir(mode=0o700, exist_ok=True)
51
+ for name in names:
52
+ if not stat.S_ISDIR(os.stat(name, dir_fd=directory, follow_symlinks=False).st_mode):
53
+ raise ValueError('Recovery trees must not contain symlinks or special files.')
54
+ directories.append((prefix / name).as_posix())
55
+ for name in sorted(filenames):
56
+ if not stat.S_ISREG(os.stat(name, dir_fd=directory, follow_symlinks=False).st_mode):
57
+ raise ValueError('Recovery trees must contain regular files only.')
58
+ relative_name = (prefix / name).as_posix()
59
+ if relative_name in skip:
60
+ continue
61
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
62
+ target = None
63
+ try:
64
+ before = os.fstat(fd)
65
+ if not stat.S_ISREG(before.st_mode):
66
+ raise ValueError('Recovery source is not a regular file.')
67
+ if copy_to is not None:
68
+ target_fd = os.open(copy_to / relative_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
69
+ target = os.fdopen(target_fd, 'wb')
70
+ digest = hashlib.sha256()
71
+ with os.fdopen(fd, 'rb', closefd=False) as stream:
72
+ for chunk in iter(lambda: stream.read(1024 * 1024), b''):
73
+ digest.update(chunk)
74
+ if target is not None:
75
+ target.write(chunk)
76
+ after = os.fstat(fd)
77
+ if (before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns):
78
+ raise ValueError('Recovery source changed while it was read; preserve the incomplete output.')
79
+ if target is not None:
80
+ target.flush()
81
+ os.fsync(target.fileno())
82
+ files[relative_name] = {'sha256': digest.hexdigest(), 'size': before.st_size}
83
+ finally:
84
+ if target is not None:
85
+ target.close()
86
+ os.close(fd)
87
+ finally:
88
+ os.close(descriptor)
89
+ return {'files': files, 'directories': sorted(directories)}
90
+
91
+
92
+ def _write(path, data):
93
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
94
+ with os.fdopen(fd, 'wb') as output:
95
+ output.write(data if isinstance(data, bytes) else data.encode('utf-8'))
96
+ output.flush()
97
+ os.fsync(output.fileno())
98
+
99
+
100
+ def _private_bytes(path):
101
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
102
+ with os.fdopen(fd, 'rb') as source:
103
+ info = os.fstat(source.fileno())
104
+ if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_size > 1024 * 1024:
105
+ raise ValueError('Recovery environment must be a private regular file within the 1 MiB bound.')
106
+ contents = source.read(1024 * 1024 + 1)
107
+ if len(contents) > 1024 * 1024:
108
+ raise ValueError('Recovery environment grew beyond its supported bound.')
109
+ return contents
110
+
111
+
112
+ def _code_identity(spec, profile):
113
+ if profile == 'vps':
114
+ revision = _run_checked(['git', '-C', str(spec.checkout), 'rev-parse', 'HEAD'], label='Backup code revision check')
115
+ if _run_checked(['git', '-C', str(spec.checkout), 'status', '--porcelain', '--untracked-files=all'], label='Backup checkout check'):
116
+ raise ValueError('Use a clean pinned checkout for recovery.')
117
+ try:
118
+ with (spec.checkout / 'pyproject.toml').open('rb') as source:
119
+ version = tomllib.load(source)['project']['version']
120
+ except (OSError, ValueError, KeyError) as error:
121
+ raise ValueError('Matching application metadata is unavailable.') from error
122
+ identity = {'revision': revision, 'version': version}
123
+ elif profile == 'container':
124
+ image = f'prettynb:{spec.revision}'
125
+ revision = _run_checked(['docker', 'image', 'inspect', '--format', '{{index .Config.Labels "org.opencontainers.image.revision"}}', image], label='Backup image revision check')
126
+ image_id = _run_checked(['docker', 'image', 'inspect', '--format', '{{.Id}}', image], label='Backup image identity check')
127
+ version = _run_checked(['docker', 'run', '--rm', '--network', 'none', '--entrypoint', 'python', image,
128
+ '-c', 'from importlib.metadata import version; print(version("prettynb"))'], label='Backup image package check')
129
+ identity = {'revision': revision, 'version': version, 'image_id': image_id}
130
+ else:
131
+ raise ValueError('Unknown recovery profile.')
132
+ if (revision != spec.revision or version != package_version('prettynb')
133
+ or not isinstance(version, str) or not re.fullmatch(r'[A-Za-z0-9.!+_-]{1,64}', version)):
134
+ raise ValueError('Recovery requires the exact matching application revision and version.')
135
+ return identity
136
+
137
+
138
+ def _require_stopped(spec, profile, code, *, match_image=True):
139
+ if profile == 'vps':
140
+ output = _run_checked(['systemctl', 'show', spec.service, '--property=LoadState,ActiveState,MainPID'], label='Stopped service check')
141
+ fields = dict(line.split('=', 1) for line in output.splitlines() if '=' in line)
142
+ if fields.get('LoadState') != 'loaded' or fields.get('ActiveState') not in {'inactive', 'failed'} or fields.get('MainPID') != '0':
143
+ raise ValueError('Stop the managed service completely before applying recovery.')
144
+ else:
145
+ state = json.loads(_run_checked(['docker', 'inspect', '--format', '{{json .State}}', spec.service], label='Stopped container check'))
146
+ image_id = _run_checked(['docker', 'inspect', '--format', '{{.Image}}', spec.service], label='Stopped container image check')
147
+ if not isinstance(state, dict) or state.get('Status') not in {'created', 'exited'} or state.get('Running') or state.get('Restarting') or state.get('Pid') != 0 or (match_image and image_id != code['image_id']):
148
+ raise ValueError('Stop the matching managed container completely before applying recovery.')
149
+
150
+
151
+ @contextmanager
152
+ def _state_lock(root):
153
+ import fcntl
154
+ fd = os.open(root / 'site.lock', os.O_RDONLY | os.O_NOFOLLOW)
155
+ try:
156
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
157
+ raise ValueError('State coordination lock must be a regular file.')
158
+ try:
159
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
160
+ except BlockingIOError as error:
161
+ raise ValueError('A state operation is running; stop the service before backup.') from error
162
+ yield
163
+ finally:
164
+ os.close(fd)
165
+
166
+
167
+ def _environment_check(spec, profile):
168
+ expected = {} if profile == 'vps' else {
169
+ 'PRETTYNB_DATA_DIR': '/var/lib/prettynb',
170
+ 'PRETTYNB_DATABASE_URL': 'sqlite:///var/lib/prettynb/db.sqlite3',
171
+ 'PRETTYNB_PORT': str(spec.port), 'PRETTYNB_WORKERS': str(spec.workers),
172
+ }
173
+ check_environment(spec, expected_values=expected)
174
+
175
+
176
+ def _snapshot_database(source, destination):
177
+ _write(destination, b'')
178
+ deadline = time.monotonic() + 30
179
+ def progress(*args):
180
+ if time.monotonic() > deadline:
181
+ raise ValueError('Database snapshot timed out; preserve the incomplete output.')
182
+ with closing(sqlite3.connect(source.as_uri() + '?mode=ro', uri=True, timeout=5)) as original:
183
+ with closing(sqlite3.connect(destination)) as snapshot:
184
+ original.backup(snapshot, pages=256, progress=progress, sleep=0.05)
185
+ with destination.open('rb') as stream:
186
+ os.fsync(stream.fileno())
187
+
188
+
189
+ def _finish(root, name, payload):
190
+ receipt = json.dumps(payload, indent=2, sort_keys=True) + '\n'
191
+ if len(receipt.encode('utf-8')) > 16 * 1024 * 1024:
192
+ raise ValueError('Recovery receipt exceeds the supported 16 MiB bound; preserve the incomplete output.')
193
+ _write(root / name, receipt)
194
+ # Persist directory entries after all file contents and the receipt are durable.
195
+ for directory in sorted((p for p in root.rglob('*') if p.is_dir()), reverse=True):
196
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
197
+ try:
198
+ os.fsync(fd)
199
+ finally:
200
+ os.close(fd)
201
+ (root / '.incomplete').unlink()
202
+ for directory in (root, root.parent):
203
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
204
+ try:
205
+ os.fsync(fd)
206
+ finally:
207
+ os.close(fd)
208
+
209
+
210
+ def backup_site(spec, output, *, profile='vps', apply=False):
211
+ source = _location(spec.data_dir)
212
+ output = _new_location(output, source, spec.env_file)
213
+ code = _code_identity(spec, profile)
214
+ _environment_check(spec, profile)
215
+ storage = inspect_web_state(source)
216
+ report = {'operation': 'backup', 'apply': apply, 'output': str(output), 'revision': spec.revision,
217
+ 'version': code['version'], 'schema_version': storage['schema_version'], 'profile': profile}
218
+ if not apply:
219
+ return report
220
+ _require_stopped(spec, profile, code)
221
+ with _state_lock(source):
222
+ before = _scan(source, skip={'db.sqlite3-shm'})
223
+ environment = _private_bytes(spec.env_file)
224
+ output.mkdir(mode=0o700)
225
+ _write(output / '.incomplete', 'Backup is incomplete; do not restore.\n')
226
+ (output / 'state').mkdir(mode=0o700)
227
+ _scan(source, copy_to=output / 'state', skip={'db.sqlite3', *AUXILIARY})
228
+ _snapshot_database(source / 'db.sqlite3', output / 'state/db.sqlite3')
229
+ _write(output / 'environment', environment)
230
+ _write(output / 'deployment.json', json.dumps(spec.to_dict(), sort_keys=True))
231
+ inspect_web_state(output / 'state')
232
+ if before != _scan(source, skip={'db.sqlite3-shm'}) or environment != _private_bytes(spec.env_file):
233
+ raise ValueError('Source changed during backup; preserve the incomplete output and retry stopped.')
234
+ if _code_identity(spec, profile) != code:
235
+ raise ValueError('Application identity changed during backup.')
236
+ _require_stopped(spec, profile, code)
237
+ inventory = _scan(output, skip={'.incomplete'})
238
+ _finish(output, 'manifest.json', {'format': 1, 'profile': profile, 'code': code,
239
+ 'schema_version': CURRENT_VERSION, 'inventory': inventory})
240
+ return {**report, 'verified': True}
241
+
242
+
243
+ def verify_backup(path):
244
+ root = _location(path)
245
+ if not root.is_dir() or root.stat().st_mode & 0o077:
246
+ raise ValueError('Backup must be a private directory (mode 0700).')
247
+ if (root / '.incomplete').exists():
248
+ raise ValueError('Backup is incomplete; preserve it and use a verified backup.')
249
+ try:
250
+ manifest_path = root / 'manifest.json'
251
+ if manifest_path.is_symlink() or manifest_path.stat().st_size > 16 * 1024 * 1024:
252
+ raise ValueError('Backup receipt is invalid or exceeds the supported bound.')
253
+ manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
254
+ if (not isinstance(manifest, dict) or manifest.get('format') != 1 or manifest.get('profile') not in {'vps', 'container'}
255
+ or manifest.get('schema_version') != CURRENT_VERSION
256
+ or _scan(root, skip={'manifest.json'}) != manifest.get('inventory')):
257
+ raise ValueError('Backup is incomplete, corrupt or unsupported.')
258
+ if not {'environment', 'deployment.json'} <= set(manifest['inventory']['files']):
259
+ raise ValueError('Backup is missing private configuration.')
260
+ inspect_web_state(root / 'state')
261
+ except (OSError, json.JSONDecodeError, UnicodeError, TypeError, KeyError) as error:
262
+ raise ValueError('Backup could not be verified; preserve it and inspect the private files locally.') from error
263
+ return manifest
264
+
265
+
266
+ def _owner(spec, profile):
267
+ if profile == 'container':
268
+ return 10001, 10001
269
+ import pwd
270
+ try:
271
+ user = pwd.getpwnam(spec.user)
272
+ except KeyError as error:
273
+ raise ValueError('The recovery service account is unavailable.') from error
274
+ if user.pw_uid == 0:
275
+ raise ValueError('Recovery state needs a non-root service account.')
276
+ return user.pw_uid, user.pw_gid
277
+
278
+
279
+ def restore_site(spec, backup, output, *, profile='vps', apply=False):
280
+ backup = _location(backup)
281
+ output = _new_location(output, backup, spec.data_dir, spec.env_file)
282
+ manifest = verify_backup(backup)
283
+ code = _code_identity(spec, profile)
284
+ if manifest['profile'] != profile or manifest['code'] != code:
285
+ raise ValueError('Restore requires the exact backup profile, code version, revision and image identity.')
286
+ deployment = json.loads((backup / 'deployment.json').read_text(encoding='utf-8'))
287
+ if not isinstance(deployment, dict) or any(deployment.get(key) != spec.to_dict()[key] for key in ('domain', 'port', 'workers', 'prefix')):
288
+ raise ValueError('Restore options must retain the backed-up domain, port, workers and prefix.')
289
+ restored_spec = replace(spec, data_dir=output / 'state', env_file=output / 'environment')
290
+ report = {'operation': 'restore', 'apply': apply, 'output': str(output), 'revision': spec.revision,
291
+ 'version': code['version'], 'profile': profile, 'activation_required': True}
292
+ if not apply:
293
+ return report
294
+ _require_stopped(spec, profile, code, match_image=False)
295
+ owner, group = _owner(spec, profile)
296
+ if os.geteuid() != 0 and (owner, group) != (os.geteuid(), os.getegid()):
297
+ raise ValueError('Apply restoration as root or the planned state owner/group.')
298
+ output.mkdir(mode=0o700)
299
+ _write(output / '.incomplete', 'Restoration is incomplete; do not activate.\n')
300
+ (output / 'state').mkdir(mode=0o700)
301
+ _scan(backup / 'state', copy_to=output / 'state')
302
+ expected_state = {
303
+ 'files': {name.removeprefix('state/'): value for name, value in manifest['inventory']['files'].items() if name.startswith('state/')},
304
+ 'directories': [name.removeprefix('state/') for name in manifest['inventory']['directories'] if name.startswith('state/')],
305
+ }
306
+ if _scan(output / 'state') != expected_state:
307
+ raise ValueError('Restored files differ from the verified checkpoint; preserve the incomplete output.')
308
+ original_environment = _private_bytes(backup / 'environment').decode('utf-8')
309
+ environment = original_environment
310
+ if profile == 'vps':
311
+ import shlex
312
+ values = {'PRETTYNB_DATA_DIR': str(output / 'state'), 'PRETTYNB_DATABASE_URL': 'sqlite://' + str(output / 'state/db.sqlite3')}
313
+ environment = '\n'.join(key + '=' + shlex.quote(values[key]) if (key := line.partition('=')[0].strip()) in values else line for line in environment.splitlines()) + '\n'
314
+ _write(output / 'environment.original', original_environment)
315
+ _write(output / 'environment', environment)
316
+ _environment_check(restored_spec, profile)
317
+ inspect_web_state(output / 'state')
318
+ if verify_backup(backup) != manifest:
319
+ raise ValueError('Backup changed during restoration; preserve the incomplete output.')
320
+ _require_stopped(spec, profile, code, match_image=False)
321
+ if _code_identity(spec, profile) != code:
322
+ raise ValueError('Application identity changed during restoration.')
323
+ for path in [output, output / 'state', *(output / 'state').rglob('*')]:
324
+ os.chown(path, owner, group)
325
+ _finish(output, 'restore.json', {'format': 1, 'code': code, 'state': str(output / 'state'),
326
+ 'environment': str(output / 'environment'), 'activation_required': True})
327
+ return {**report, 'verified': True, 'state': str(output / 'state'), 'environment': str(output / 'environment')}
@@ -0,0 +1,48 @@
1
+ """Small application-specific CLI converters and editor support."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ import shlex
6
+ import subprocess
7
+ import tempfile
8
+
9
+ from expose_interface import CommandError
10
+
11
+
12
+ def limit_value(value):
13
+ result = int(value)
14
+ if not 1 <= result <= 200:
15
+ raise ValueError("expected an integer from 1 to 200")
16
+ return result
17
+
18
+
19
+ def offset_value(value):
20
+ result = int(value)
21
+ if result < 0:
22
+ raise ValueError("expected a nonnegative integer")
23
+ return result
24
+
25
+
26
+ def existing_file(value):
27
+ path = Path(value)
28
+ if not path.is_file():
29
+ raise ValueError("expected an existing file")
30
+ return path
31
+
32
+
33
+ def edit_text(text):
34
+ """Edit private temporary Markdown using VISUAL, EDITOR, or the platform editor."""
35
+ editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or ("notepad" if os.name == "nt" else "vi")
36
+ with tempfile.TemporaryDirectory(prefix="prettynb-edit-") as temporary:
37
+ path = Path(temporary) / "note.md"
38
+ path.write_text(text, encoding="utf-8")
39
+ path.chmod(0o600)
40
+ try:
41
+ command = shlex.split(editor)
42
+ if not command:
43
+ raise ValueError("The editor command is empty.")
44
+ subprocess.run([*command, str(path)], check=True)
45
+ except (OSError, ValueError, subprocess.CalledProcessError) as error:
46
+ raise CommandError("The editor could not complete; the note was not changed.") from error
47
+ edited = path.read_text(encoding="utf-8")
48
+ return None if edited == text else edited
@@ -0,0 +1,103 @@
1
+ """Generate the optional single-host Linux container profile without activation."""
2
+
3
+ import hashlib
4
+ import json
5
+ import shlex
6
+ from urllib.request import Request, urlopen
7
+
8
+ from .deployment import bundle, check_environment, _run_checked
9
+
10
+
11
+ def container_bundle(spec, operation='init'):
12
+ if operation not in ('init', 'upgrade'):
13
+ raise ValueError('Unknown deployment operation.')
14
+ if spec.python != 'python3.14':
15
+ raise ValueError('The container profile uses the pinned Python 3.14 image.')
16
+ image = f'prettynb:{spec.revision}'
17
+ service = {
18
+ 'image': image, 'pull_policy': 'never', 'container_name': spec.service,
19
+ 'network_mode': 'host', 'user': '10001:10001', 'read_only': True,
20
+ 'cap_drop': ['ALL'], 'security_opt': ['no-new-privileges:true'],
21
+ 'tmpfs': ['/tmp:rw,noexec,nosuid,size=64m,mode=1777'],
22
+ 'volumes': [{'type': 'bind', 'source': str(spec.data_dir), 'target': '/var/lib/prettynb',
23
+ 'bind': {'create_host_path': False}}],
24
+ 'env_file': [{'path': str(spec.env_file), 'format': 'raw'}],
25
+ 'environment': {'PRETTYNB_PORT': str(spec.port), 'PRETTYNB_WORKERS': str(spec.workers)},
26
+ 'restart': 'unless-stopped', 'stop_grace_period': '45s',
27
+ }
28
+ environment = bundle(spec)['environment.example'].replace(str(spec.data_dir), '/var/lib/prettynb')
29
+ environment += f'PRETTYNB_PORT={spec.port}\nPRETTYNB_WORKERS={spec.workers}\n'
30
+ build = f'''#!/usr/bin/env bash
31
+ set -Eeuo pipefail
32
+ checkout={shlex.quote(str(spec.checkout))}
33
+ revision={shlex.quote(spec.revision)}
34
+ [[ "$(git -C "$checkout" rev-parse HEAD)" == "$revision" ]] || {{ echo 'Checkout does not match the pinned revision.' >&2; exit 1; }}
35
+ [[ -z "$(git -C "$checkout" status --porcelain --untracked-files=all)" ]] || {{ echo 'Preserve checkout changes before building.' >&2; exit 1; }}
36
+ docker build --platform linux/amd64 --build-arg "PRETTYNB_REVISION=$revision" --file "$checkout/apps/web/container/Dockerfile" --tag {shlex.quote(image)} "$checkout"
37
+ '''
38
+ instructions = f'''Linux x86_64, Docker Engine and Compose 2.30+ only. Review all files before use.
39
+ This bundle neither creates secrets nor changes a service, proxy or persistent state.
40
+ Use one Gunicorn instance (1–4 workers), one private local state root and a host TLS nginx proxy.
41
+
42
+ 1. Check out {spec.revision} in {spec.checkout}; preserve any existing checkout changes.
43
+ 2. Run bash build.sh. The build verifies that checkout and uses the reviewed Dockerfile/base digest and hash-locked wheels.
44
+ 3. For initial setup only, create an EMPTY {spec.data_dir} owned by UID/GID 10001, mode 0700.
45
+ Do not chown or overwrite an existing state root. Restore/upgrade it separately after stopping the old service.
46
+ 4. Copy environment.example to {spec.env_file}, mode 0600, with distinct private secrets.
47
+ Never copy the environment into the checkout or image. Check with prettynb deploy check --profile container and the same plan options.
48
+ 5. Validate: docker compose --file compose.json config --quiet
49
+ 6. Stop the existing instance before upgrades. Back up its COMPLETE state and environment plus its image ID/revision before continuing.
50
+ 7. Start: docker compose --file compose.json up --detach --no-build --pull never
51
+ Wait for healthy status and verify the configured loopback /healthz. On failure, stop the container and retain state/logs for diagnosis.
52
+ 8. Install/review nginx.conf on the host with your existing TLS certificate. Test nginx configuration before reloading.
53
+ 9. Claim the owner explicitly, remove PRETTYNB_BOOTSTRAP_TOKEN and recreate the container with the revised environment.
54
+
55
+ Rerunning up reuses the bind-mounted state; no files are replaced by bundle generation.
56
+ Startup runs the established serialized schema migrations. Never run a second VPS/container against the same data root.
57
+ For rollback, stop the new container, restore the verified pre-upgrade state and matching private environment INTO A NEW LOCATION,
58
+ then use the saved old image ID/revision with that restored location. Do not start old code on a migrated database.
59
+ Keep the original and failed state until recovery is verified. Never use compose down --volumes as a backup/restore step.
60
+ Container host networking is deliberate: Gunicorn binds only 127.0.0.1:{spec.port}; host nginx remains the trusted TLS proxy.
61
+ '''
62
+ result = {'compose.json': json.dumps({'name': spec.service, 'services': {'notebook': service}}, indent=2) + '\n',
63
+ 'environment.example': environment, 'nginx.conf': bundle(spec)['nginx.conf'],
64
+ 'build.sh': build, 'README.txt': instructions}
65
+ manifest = {'format': 1, 'profile': 'container', 'operation': operation, 'spec': spec.to_dict(),
66
+ 'image': image, 'files': {name: hashlib.sha256(content.encode()).hexdigest() for name, content in result.items()},
67
+ 'apply': 'Review README.txt; activation is a separate stopped-site operation.',
68
+ 'requirements': ['Linux x86_64, Docker Engine, Compose 2.30+, host nginx and existing TLS',
69
+ 'Private local bind mount owned by UID/GID 10001; one instance only']}
70
+ result['plan.json'] = json.dumps(manifest, indent=2, sort_keys=True) + '\n'
71
+ return result
72
+
73
+
74
+ def check_container(spec, *, health=False, require_bootstrap=False):
75
+ container_bundle(spec)
76
+ if spec.data_dir.is_symlink() or not spec.data_dir.is_dir():
77
+ raise ValueError('Container state must be an existing private directory.')
78
+ metadata = spec.data_dir.stat()
79
+ if metadata.st_mode & 0o077 or metadata.st_uid != 10001 or metadata.st_gid != 10001:
80
+ raise ValueError('Container state must have mode 0700 and UID/GID 10001.')
81
+ result = check_environment(spec, require_bootstrap=require_bootstrap, expected_values={
82
+ 'PRETTYNB_DATA_DIR': '/var/lib/prettynb',
83
+ 'PRETTYNB_DATABASE_URL': 'sqlite:///var/lib/prettynb/db.sqlite3',
84
+ 'PRETTYNB_WORKERS': str(spec.workers), 'PRETTYNB_PORT': str(spec.port),
85
+ })
86
+ image = f'prettynb:{spec.revision}'
87
+ revision = _run_checked(['docker', 'image', 'inspect', '--format',
88
+ '{{index .Config.Labels "org.opencontainers.image.revision"}}', image], label='Container image revision check')
89
+ if revision != spec.revision:
90
+ raise ValueError('Container image does not match the pinned revision.')
91
+ _run_checked(['docker', 'run', '--rm', '--network', 'none', '--entrypoint', 'python', image, '-m', 'pip', 'check'], label='Container dependency check')
92
+ result.update(profile='container', revision=revision, dependencies='ok')
93
+ from .web_state import inspect_web_state
94
+ result['storage'] = inspect_web_state(spec.data_dir, allow_new=True, allow_pending=True)
95
+ if health:
96
+ try:
97
+ with urlopen(Request(f'http://127.0.0.1:{spec.port}/healthz', headers={'Host': spec.domain}), timeout=5) as response:
98
+ if json.loads(response.read(4096)) != {'status': 'ok'}:
99
+ raise ValueError('Invalid health response.')
100
+ except (OSError, ValueError) as error:
101
+ raise ValueError('Loopback health check failed.') from error
102
+ result['health'] = 'ok'
103
+ return result