Repository navigation
Expand file tree
/
Copy pathabsurdctl
More file actions
executable file
·3027 lines (2590 loc) · 93.9 KB
/
Copy pathabsurdctl
File metadata and controls
executable file
·3027 lines (2590 loc) · 93.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import csv
import io
import json
import os
import re
import subprocess
import sys
import shutil
import textwrap
from urllib.request import urlopen
from urllib.error import URLError
from urllib.parse import quote, urlparse
from optparse import OptionParser, IndentedHelpFormatter
# Queue names are interpolated into generated table/index names (t_<queue>,
# r_<queue>_sai, ...). We cap UTF-8 byte length so those identifiers stay
# within PostgreSQL's 63-byte limit; character set is otherwise delegated to
# PostgreSQL quoted identifier rules.
MAX_QUEUE_NAME_LENGTH = 57
GITHUB_OWNER = "earendil-works"
GITHUB_REPO = "absurd"
GITHUB_RAW_BASE = f"https://raw.githubusercontent.com/{GITHUB_OWNER}/{GITHUB_REPO}"
GITHUB_API_BASE = f"https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}"
# BEGIN BUNDLED DATA (autogenerated by scripts/build-absurdctl)
ABSURD_SCHEMA_TARGET_VERSION = "main"
BUNDLED_SCHEMA_SQL = None
BUNDLED_MIGRATIONS = {}
BUNDLED_SKILLS = {}
# END BUNDLED DATA
MIGRATION_FILENAME_RE = re.compile(
r"^(?P<from>[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.]+)?)-(?P<to>main|[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.]+)?)\.sql$"
)
VERSION_RE = re.compile(
r"^(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.(?P<patch>[0-9]+)(?:-(?P<suffix>[A-Za-z0-9.]+))?$"
)
SCHEMA_VERSION_FUNCTION_RE = re.compile(
r"create\s+or\s+replace\s+function\s+absurd\.get_schema_version\s*\(",
re.IGNORECASE,
)
def quote_ident(identifier):
"""Quote a SQL identifier using PostgreSQL double-quote escaping."""
return '"' + identifier.replace('"', '""') + '"'
def queue_relation(prefix, queue_name):
"""Return a fully qualified absurd.<prefix>_<queue> relation reference."""
return f"absurd.{quote_ident(f'{prefix}_{queue_name}')}"
def validate_queue_name(value):
"""Validate queue names used in dynamic table/index names."""
if value is None or value == "":
print("Error: Queue name must be provided.", file=sys.stderr)
sys.exit(1)
if len(value.encode("utf-8")) > MAX_QUEUE_NAME_LENGTH:
print(
f"Error: Queue name '{value}' is too long (max {MAX_QUEUE_NAME_LENGTH} bytes).",
file=sys.stderr,
)
sys.exit(1)
return value
def normalize_partition_table_name(value):
"""Normalize a partition table reference to an absurd-schema table name."""
if value is None:
print("Error: Partition table must be provided.", file=sys.stderr)
sys.exit(1)
partition_table = value.strip()
if not partition_table:
print("Error: Partition table must be provided.", file=sys.stderr)
sys.exit(1)
lower_partition_table = partition_table.lower()
if lower_partition_table.startswith("absurd."):
partition_table = partition_table[len("absurd.") :]
elif lower_partition_table.startswith('"absurd".'):
partition_table = partition_table[len('"absurd".') :]
if partition_table.startswith('"') and partition_table.endswith('"'):
partition_table = partition_table[1:-1].replace('""', '"')
if not partition_table:
print("Error: Partition table must be provided.", file=sys.stderr)
sys.exit(1)
return partition_table
def build_drop_partition_sql(partition_table):
return f"drop table if exists absurd.{quote_ident(partition_table)}"
def build_detach_partition_sql(config, parent_table, partition_table):
has_default = run_psql(
config,
"""
select exists (
select 1
from pg_class parent
join pg_namespace pn on pn.oid = parent.relnamespace
join pg_inherits inh on inh.inhparent = parent.oid
join pg_class child on child.oid = inh.inhrelid
where pn.nspname = 'absurd'
and parent.relname = :'parent_table'
and pg_get_expr(child.relpartbound, child.oid) = 'DEFAULT'
)
""",
tuples_only=True,
no_align=True,
variables={"parent_table": parent_table},
).strip()
sql = (
f"alter table absurd.{quote_ident(parent_table)} "
f"detach partition absurd.{quote_ident(partition_table)}"
)
if has_default != "t":
sql += " concurrently"
return sql
class RemoteMigrationDiscoveryError(Exception):
pass
def get_term_width():
"""Get terminal width for formatting."""
try:
return shutil.get_terminal_size().columns
except Exception:
return 80
class CleanHelpFormatter(IndentedHelpFormatter):
"""Custom formatter with better spacing and formatting."""
def __init__(self):
IndentedHelpFormatter.__init__(
self,
indent_increment=2,
max_help_position=30,
width=get_term_width(),
short_first=1,
)
def format_option(self, option):
result = []
opts = self.option_strings[option]
opt_width = self.help_position - self.current_indent - 2
if len(opts) > opt_width:
opts = "%*s%s\n" % (self.current_indent, "", opts)
indent_first = self.help_position
else:
opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
indent_first = 0
result.append(opts)
if option.help:
help_text = self.expand_default(option)
help_lines = []
help_lines = textwrap.wrap(help_text, self.width - self.help_position)
result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
for line in help_lines[1:]:
result.append("%*s%s\n" % (self.help_position, "", line))
elif opts[-1] != "\n":
result.append("\n")
return "".join(result)
def build_database_config(host, port, user, database):
"""Build a dict with database configuration."""
return {
"host": host,
"port": port,
"user": user,
"database": database,
}
def resolve_database_argument(explicit_database=None):
"""Resolve database/URI using explicit args first, then env vars, then fallback."""
return (
explicit_database
or os.getenv("ABSURD_DATABASE_URL")
or os.getenv("PGDATABASE")
or "postgresql://localhost/absurd"
)
def config_from_options(options):
"""Shortcut to construct a database config from parsed options."""
database = resolve_database_argument(options.database)
parsed = urlparse(database)
if parsed.scheme and "postgres" in parsed.scheme:
return {"uri": database}
return build_database_config(
options.host or os.getenv("PGHOST", "localhost"),
options.port or os.getenv("PGPORT", "5432"),
options.user or os.getenv("PGUSER", os.getenv("USER", "")),
database,
)
def build_psql_command(config, extra_args=None):
"""Construct the base psql command with optional additional arguments."""
cmd = ["psql", "-X"]
if "uri" in config:
cmd.extend(["-d", config["uri"]])
else:
cmd.extend(
[
"-h",
config["host"],
"-p",
config["port"],
"-U",
config["user"],
"-d",
config["database"],
]
)
if extra_args:
cmd.extend(extra_args)
return cmd
def sanitize_uri(uri):
"""Remove password from URI for safe display in verbose output."""
parsed = urlparse(uri)
if parsed.password:
return uri.replace(f"{parsed.password}@", f"****@", 1)
return uri
def get_common_db_details(config):
"""Return standard database connection details for verbose output."""
if "uri" in config:
sanitized_uri = sanitize_uri(config["uri"])
return [("URI", sanitized_uri)]
return [
("Host", config["host"]),
("Port", config["port"]),
("User", config["user"]),
("Database", config["database"]),
]
def print_verbose_configuration(enabled, details):
"""Print a formatted configuration block when verbose output is enabled."""
if not enabled:
return
print("Configuration:")
for label, value in details:
print(f" {label}: {value}")
def run_psql(
config,
query=None,
*,
tuples_only=False,
no_align=False,
extra_args=None,
input_data=None,
error_message=None,
strip_output=True,
variables=None,
fail_on_error=True,
):
"""
Execute a PostgreSQL command. Returns stripped stdout for queries and the
CompletedProcess for other invocations.
Use `variables` dict to pass values safely. In the query, reference them as :'name'
for string values. Example:
run_psql(config, "SELECT * FROM t WHERE id = :'id'", variables={"id": user_input})
Note: psql does not expand :variables for SQL passed via -c, so SQL text is
sent through stdin with -f - whenever query/input_data is provided.
"""
cmd_args = []
stdin_data = input_data
if tuples_only:
cmd_args.append("-t")
if no_align:
cmd_args.append("-A")
if fail_on_error:
cmd_args.extend(["-v", "ON_ERROR_STOP=1"])
if variables:
for name, value in variables.items():
cmd_args.extend(["-v", f"{name}={value}"])
if extra_args:
cmd_args.extend(extra_args)
if query is not None:
if input_data is not None:
raise ValueError("run_psql received both query and input_data")
stdin_data = query
if stdin_data is not None:
cmd_args.extend(["-f", "-"])
message = error_message
if message is None:
message = (
"Error executing query"
if query is not None
else "Error executing psql command"
)
env = os.environ.copy()
env["PGPASSWORD"] = os.getenv("PGPASSWORD", "")
try:
result = subprocess.run(
build_psql_command(config, cmd_args),
input=stdin_data,
capture_output=True,
text=True,
check=True,
env=env,
)
except subprocess.CalledProcessError as e:
if fail_on_error:
print(f"{message}: {e.stderr}", file=sys.stderr)
sys.exit(1)
raise
if query is not None:
return result.stdout.strip() if strip_output else result.stdout
return result
def run_psql_csv(config, query, variables=None):
"""Execute a query and return rows parsed via CSV output."""
output = run_psql(
config,
query,
tuples_only=True,
extra_args=["--csv"],
strip_output=False,
variables=variables,
)
if not output:
return []
reader = csv.reader(io.StringIO(output))
return [row for row in reader if row]
def queue_exists(config, queue_name):
"""Check if a queue exists."""
result = run_psql(
config,
"SELECT COUNT(*) FROM absurd.queues WHERE queue_name = :'queue_name';",
tuples_only=True,
no_align=True,
variables={"queue_name": queue_name},
)
return int(result) > 0
def build_json_params(param_list, base_params=None):
"""
Build JSON parameters from -p flags and optional base --params.
Supports:
-p foo=bar -> {"foo": "bar"}
-p count:=42 -> {"count": 42}
-p enabled:=true -> {"enabled": true}
-p tags:='["a","b"]' -> {"tags": ["a","b"]}
-p user.name=Alice -> {"user": {"name": "Alice"}}
--params '{"x":1}' -> merged with -p flags
"""
result = {}
if base_params:
try:
result = json.loads(base_params)
if not isinstance(result, dict):
raise ValueError("--params must be a JSON object")
except json.JSONDecodeError as e:
print(f"Error parsing --params: {e}", file=sys.stderr)
sys.exit(1)
for param in param_list:
if ":=" in param:
key, value_str = param.split(":=", 1)
try:
value = json.loads(value_str)
except json.JSONDecodeError as e:
print(f"Error parsing JSON value in '{param}': {e}", file=sys.stderr)
sys.exit(1)
elif "=" in param:
key, value = param.split("=", 1)
else:
print(
f"Invalid parameter format: '{param}' (expected key=value or key:=json)",
file=sys.stderr,
)
sys.exit(1)
set_nested_value(result, key, value)
return json.dumps(result)
def set_nested_value(obj, path, value):
"""Set a value in a nested dictionary using dot notation."""
keys = path.split(".")
current = obj
for key in keys[:-1]:
if key not in current:
current[key] = {}
elif not isinstance(current[key], dict):
print(
f"Error: Cannot set nested value, '{key}' is not an object",
file=sys.stderr,
)
sys.exit(1)
current = current[key]
current[keys[-1]] = value
def add_db_options(parser):
"""Add common database connection options to a parser."""
parser.add_option("-h", "--host", dest="host", metavar="HOST", help="Database host")
parser.add_option("-p", "--port", dest="port", metavar="PORT", help="Database port")
parser.add_option("-U", "--user", dest="user", metavar="USER", help="Database user")
parser.add_option(
"-d",
"--database",
dest="database",
metavar="DB",
help="Database name or PostgreSQL connection URI",
)
parser.add_option(
"-v",
"--verbose",
dest="verbose",
action="store_true",
default=False,
help="Verbose output",
)
def build_command_parser(usage):
"""Create an OptionParser with common Absurd defaults."""
parser = OptionParser(
usage=usage,
add_help_option=False,
formatter=CleanHelpFormatter(),
)
add_db_options(parser)
parser.add_option("--help", action="store_true", help="Show this help message")
return parser
def parse_args_with_help(parser, args, examples=None):
"""Parse args and handle --help in a consistent way."""
options, remaining = parser.parse_args(args)
if getattr(options, "help", False):
parser.print_help()
if examples:
print("\nExamples:")
for example in examples:
print(f" {example}")
sys.exit(0)
return options, remaining
def ensure_queue_exists(config, queue_name):
"""Exit with error if queue is missing."""
if not queue_exists(config, queue_name):
print(f"Queue '{queue_name}' does not exist", file=sys.stderr)
sys.exit(1)
def github_absurd_sql_url(ref):
return f"{GITHUB_RAW_BASE}/{quote(ref)}/sql/absurd.sql"
def github_migration_index_url(ref):
return f"{GITHUB_API_BASE}/contents/sql/migrations?ref={quote(ref)}"
def github_migration_sql_url(ref, migration_name):
return f"{GITHUB_RAW_BASE}/{quote(ref)}/sql/migrations/{quote(migration_name)}"
def github_repo_file_url(ref, relative_path):
return f"{GITHUB_RAW_BASE}/{quote(ref)}/{quote(relative_path, safe='/')}"
def fetch_text(url):
with urlopen(url) as response:
return response.read().decode("utf-8")
def parse_migration_filename(filename):
match = MIGRATION_FILENAME_RE.match(filename)
if not match:
return None
return match.group("from"), match.group("to")
def version_sort_key(version):
if version == "main":
return (10**9, 10**9, 10**9, 1, "")
match = VERSION_RE.match(version)
if match is None:
# Keep unknown version strings stable and after regular semver tags.
return (10**8, 0, 0, 0, version)
suffix = match.group("suffix") or ""
# Stable release sorts after pre-release of same x.y.z.
stable_flag = 1 if suffix == "" else 0
return (
int(match.group("major")),
int(match.group("minor")),
int(match.group("patch")),
stable_flag,
suffix,
)
def compare_versions(a, b):
ka = version_sort_key(a)
kb = version_sort_key(b)
if ka < kb:
return -1
if ka > kb:
return 1
return 0
def migration_declares_schema_version(sql_content):
return SCHEMA_VERSION_FUNCTION_RE.search(sql_content) is not None
def get_recorded_schema_version(config):
exists = run_psql(
config,
"SELECT to_regprocedure('absurd.get_schema_version()') IS NOT NULL;",
tuples_only=True,
no_align=True,
error_message="Error checking schema version metadata",
)
if exists.lower() not in ("t", "true", "1"):
return None
version = run_psql(
config,
"SELECT absurd.get_schema_version();",
tuples_only=True,
no_align=True,
error_message="Error loading schema version",
)
return version or None
def load_absurd_sql(script_dir, target_ref, verbose):
local_sql_path = os.path.join(script_dir, "sql", "absurd.sql")
if os.path.exists(local_sql_path) and target_ref == ABSURD_SCHEMA_TARGET_VERSION:
if verbose:
print(f"Using local SQL file: {local_sql_path}")
with open(local_sql_path, "r", encoding="utf-8") as f:
return f.read(), f"local:{local_sql_path}"
if BUNDLED_SCHEMA_SQL and target_ref == ABSURD_SCHEMA_TARGET_VERSION:
if verbose:
print("Using bundled absurd.sql")
return BUNDLED_SCHEMA_SQL, "bundled"
sql_url = github_absurd_sql_url(target_ref)
if verbose:
print(f"Fetching SQL file from: {sql_url}")
try:
return fetch_text(sql_url), f"github:{sql_url}"
except URLError as e:
print(f"Error downloading SQL file from GitHub: {e}", file=sys.stderr)
sys.exit(1)
def discover_local_migrations(script_dir):
migrations = {}
migrations_dir = os.path.join(script_dir, "sql", "migrations")
if not os.path.isdir(migrations_dir):
return migrations
for filename in sorted(os.listdir(migrations_dir)):
parsed = parse_migration_filename(filename)
if parsed is None:
continue
source, target = parsed
path = os.path.join(migrations_dir, filename)
with open(path, "r", encoding="utf-8") as f:
migrations[(source, target)] = {
"name": filename,
"source": "local",
"sql": f.read(),
}
return migrations
def discover_bundled_migrations():
migrations = {}
for filename, sql_content in BUNDLED_MIGRATIONS.items():
parsed = parse_migration_filename(filename)
if parsed is None:
continue
source, target = parsed
migrations[(source, target)] = {
"name": filename,
"source": "bundled",
"sql": sql_content,
}
return migrations
def discover_remote_migrations(target_ref):
migrations = {}
index_url = github_migration_index_url(target_ref)
try:
payload = fetch_text(index_url)
except URLError as e:
raise RemoteMigrationDiscoveryError(
f"failed to download migration index from {index_url}: {e}"
) from e
try:
entries = json.loads(payload)
except json.JSONDecodeError as e:
raise RemoteMigrationDiscoveryError(
f"failed to parse migration index from {index_url}: {e}"
) from e
if not isinstance(entries, list):
raise RemoteMigrationDiscoveryError(
f"unexpected migration index payload from {index_url}: expected JSON list"
)
for entry in entries:
name = entry.get("name", "")
parsed = parse_migration_filename(name)
if parsed is None:
continue
source, target = parsed
migrations[(source, target)] = {
"name": name,
"source": "github",
"url": github_migration_sql_url(target_ref, name),
}
return migrations
def discover_migrations(script_dir, target_ref, include_remote=False):
# Keep source selection simple: use local/bundled assets first and only
# switch to remote discovery when explicitly requested.
if include_remote:
return discover_remote_migrations(target_ref)
local = discover_local_migrations(script_dir)
if local:
return local
bundled = discover_bundled_migrations()
if bundled:
return bundled
return {}
def resolve_migration_path(current_version, target_version, migrations):
direction = compare_versions(current_version, target_version)
if direction == 0:
return []
if direction > 0:
# Downgrades are not supported.
return None
# Migrations are applied in release order by destination version.
# Missing release-to-release files are treated as null migrations.
grouped_by_target = {}
for (src, dst), migration in migrations.items():
if compare_versions(dst, current_version) <= 0:
continue
if compare_versions(dst, target_version) > 0:
continue
grouped_by_target.setdefault(dst, []).append((src, migration))
ordered_targets = sorted(grouped_by_target.keys(), key=version_sort_key)
cursor = current_version
path = []
for dst in ordered_targets:
candidates = grouped_by_target[dst]
exact = [item for item in candidates if compare_versions(item[0], cursor) == 0]
if exact:
chosen = exact[0][1]
else:
le_cursor = [item for item in candidates if compare_versions(item[0], cursor) < 0]
if le_cursor:
# Prefer the newest compatible source version.
chosen = max(le_cursor, key=lambda item: version_sort_key(item[0]))[1]
else:
# No direct predecessor migration is known; assume null migrations
# from cursor up to the first available source.
chosen = min(candidates, key=lambda item: version_sort_key(item[0]))[1]
path.append(chosen)
cursor = dst
return path
def get_migration_sql(migration):
if "sql" in migration:
return migration["sql"]
try:
return fetch_text(migration["url"])
except URLError as e:
print(
f"Error downloading migration {migration['name']} from GitHub: {e}",
file=sys.stderr,
)
sys.exit(1)
def load_skill_file(script_dir, relative_path, verbose):
local_path = os.path.join(script_dir, *relative_path.split("/"))
if os.path.exists(local_path):
if verbose:
print(f"Using local skill file: {local_path}")
with open(local_path, "r", encoding="utf-8") as f:
return f.read(), f"local:{local_path}"
bundled_content = BUNDLED_SKILLS.get(relative_path)
if bundled_content is not None:
if verbose:
print(f"Using bundled skill file: {relative_path}")
return bundled_content, "bundled"
url = github_repo_file_url(ABSURD_SCHEMA_TARGET_VERSION, relative_path)
if verbose:
print(f"Fetching skill file from: {url}")
try:
return fetch_text(url), f"github:{url}"
except URLError as e:
print(f"Error downloading skill file from GitHub: {e}", file=sys.stderr)
sys.exit(1)
def render_combined_migration_sql(current_version, target_version, resolved_steps):
parts = [
"-- Absurd migration SQL bundle",
f"-- Range: {current_version} -> {target_version}",
"",
]
for step in resolved_steps:
migration = step["migration"]
sql_content = step["sql"]
parts.append(
f"-- begin migration: {migration['name']} [{migration['source']}]"
)
if sql_content:
parts.append(sql_content)
parts.append(f"-- end migration: {migration['name']}")
parts.append("")
return "\n".join(parts)
def cmd_cleanup(args):
"""Clean up old completed, failed, or cancelled tasks and events."""
usage = "usage: %prog cleanup [options] QUEUE_NAME TTL_DAYS"
parser = build_command_parser(usage)
parser.add_option(
"-l",
"--limit",
dest="limit",
type="int",
default=1000,
help="Batch size for deletions (default: 1000)",
)
parser.add_option(
"-n",
"--dry-run",
dest="dry_run",
action="store_true",
default=False,
help="Show what would be deleted without actually deleting",
)
examples = [
"absurdctl cleanup myqueue 30",
"absurdctl cleanup --dry-run -v myqueue 30",
]
options, args = parse_args_with_help(parser, args, examples)
if len(args) != 2:
print(
"Error: Missing required arguments QUEUE_NAME and TTL_DAYS", file=sys.stderr
)
parser.print_help()
sys.exit(1)
queue_name = validate_queue_name(args[0])
try:
ttl_days = int(args[1])
except ValueError:
print(
f"Error: TTL_DAYS must be a positive integer, got: {args[1]}",
file=sys.stderr,
)
sys.exit(1)
config = config_from_options(options)
ensure_queue_exists(config, queue_name)
ttl_seconds = ttl_days * 24 * 60 * 60
print_verbose_configuration(
options.verbose,
[
("Queue", queue_name),
("TTL", f"{ttl_days} days ({ttl_seconds} seconds)"),
]
+ get_common_db_details(config)
+ [
("Limit", options.limit),
("Dry run", options.dry_run),
],
)
if options.dry_run:
print("DRY RUN MODE - No data will be deleted")
t_rel = queue_relation("t", queue_name)
r_rel = queue_relation("r", queue_name)
e_rel = queue_relation("e", queue_name)
task_count = run_psql(
config,
f"""SELECT COUNT(*) FROM {t_rel} t
LEFT JOIN {r_rel} r ON r.run_id = t.last_attempt_run
WHERE t.state IN ('completed', 'failed', 'cancelled')
AND ((t.state = 'completed' AND r.completed_at < NOW() - make_interval(secs => :'ttl_seconds'::int))
OR (t.state = 'failed' AND r.failed_at < NOW() - make_interval(secs => :'ttl_seconds'::int))
OR (t.state = 'cancelled' AND t.cancelled_at < NOW() - make_interval(secs => :'ttl_seconds'::int)));""",
tuples_only=True,
no_align=True,
variables={"ttl_seconds": ttl_seconds},
)
event_count = run_psql(
config,
f"SELECT COUNT(*) FROM {e_rel} WHERE emitted_at < NOW() - make_interval(secs => :'ttl_seconds'::int);",
tuples_only=True,
no_align=True,
variables={"ttl_seconds": ttl_seconds},
)
print(f"Would delete {task_count} tasks and {event_count} events")
return
print(f"Starting cleanup for queue '{queue_name}' (TTL: {ttl_days} days)")
total_tasks_deleted = 0
total_events_deleted = 0
iteration = 0
while True:
iteration += 1
if options.verbose:
print(f"Iteration {iteration}...")
tasks_deleted = int(
run_psql(
config,
"SELECT absurd.cleanup_tasks(:'queue_name', :'ttl_seconds'::int, :'limit'::int);",
tuples_only=True,
no_align=True,
variables={
"queue_name": queue_name,
"ttl_seconds": ttl_seconds,
"limit": options.limit,
},
)
)
total_tasks_deleted += tasks_deleted
if options.verbose and tasks_deleted > 0:
print(f" Deleted {tasks_deleted} tasks")
events_deleted = int(
run_psql(
config,
"SELECT absurd.cleanup_events(:'queue_name', :'ttl_seconds'::int, :'limit'::int);",
tuples_only=True,
no_align=True,
variables={
"queue_name": queue_name,
"ttl_seconds": ttl_seconds,
"limit": options.limit,
},
)
)
total_events_deleted += events_deleted
if options.verbose and events_deleted > 0:
print(f" Deleted {events_deleted} events")
if tasks_deleted == 0 and events_deleted == 0:
break
if tasks_deleted > 0 or events_deleted > 0:
print(f"Deleted {tasks_deleted} tasks, {events_deleted} events")
print(
f"Cleanup complete: {total_tasks_deleted} tasks, {total_events_deleted} events deleted in {iteration} iterations"
)
def cmd_create_queue(args):
"""Create a new Absurd queue."""
usage = "usage: %prog create-queue [options] QUEUE_NAME"
parser = build_command_parser(usage)
parser.add_option(
"--storage-mode",
dest="storage_mode",
type="choice",
choices=["unpartitioned", "partitioned"],
default="unpartitioned",
help="Queue storage mode (default: unpartitioned)",
)
options, args = parse_args_with_help(
parser,
args,
[
"absurdctl create-queue myqueue",
"absurdctl create-queue jobs --storage-mode partitioned",
],
)
if len(args) != 1:
print("Error: Missing required argument QUEUE_NAME", file=sys.stderr)
parser.print_help()
sys.exit(1)
queue_name = validate_queue_name(args[0])
config = config_from_options(options)
print_verbose_configuration(
options.verbose,
[("Queue", queue_name), ("Storage mode", options.storage_mode)]
+ get_common_db_details(config),
)
if options.verbose:
print(f"Creating queue '{queue_name}'...")
if options.storage_mode == "unpartitioned":
run_psql(
config,
"SELECT absurd.create_queue(:'queue_name');",
variables={"queue_name": queue_name},
)
else:
run_psql(
config,