git-annex-mirror-orchestrator/gamo/next_task.py
Michael Hanke 66edb55934
All checks were successful
Ruff / Code linting (push) Successful in 37s
Codespell / Check for spelling errors (push) Successful in 48s
Type annotations / check (push) Successful in 47s
Unit tests (Linux) / check (push) Successful in 2m44s
feat: next-task now queues mirrors with missing keys after minimum interval
2026-11-16 06:45:59 +01:00

115 lines
3.5 KiB
Python

"""
Reads JSON object records from all .json files in a specified directory,
ignoring records whose `enabled` switch is off, computes a `next_due`
timestamp for each record from `last_success` and `last30days_ncommits`
(records that still miss git-annex keys come due after the minimum
interval), sorts the remaining records with missing due dates first, then
by records with missing keys, the computed due timestamp (earliest first)
and `last30days_ncommits` count (highest first), and writes the first
record that is due -- without a due date or with a due date in the past --
to standard output as a single JSON line.
"""
import argparse
import json
from datetime import datetime, timedelta
from pathlib import Path
from datalad_core.config import (
ConfigItem,
get_defaults,
)
from datalad_core.repo import Worktree
from gamo.timestamps import (
now,
parse_timestamp,
)
defaults = get_defaults()
# 8 h
defaults.add('gamo.schedule.minimum-interval', ConfigItem(28800, coercer=int))
# 30 days
defaults.add('gamo.schedule.maximum-interval', ConfigItem(2592000, coercer=int))
def _schedule_value(record: dict, cfg, item: str):
key = f'gamo.schedule.{item}'
val = cfg.get(key).value
return record.get('schedule', {}).get(item, val)
def get_next_due(record: dict, cfg) -> datetime | None:
minint = _schedule_value(record, cfg, 'minimum-interval')
maxint = _schedule_value(record, cfg, 'maximum-interval')
state = record.get('state', {})
if 'last_success' not in state:
return None
last_success = parse_timestamp(state['last_success'])
nchg30 = state.get('last30days_ncommits', 0)
if state.get('keys_missing_n', 0) > 0:
# an incomplete mirror comes due after the minimum interval
latency = minint
elif nchg30:
latency = min(
maxint,
# update latency matches the avg change latency
max(minint, (3600 * 24 * 30) / nchg30),
)
else:
latency = maxint
return last_success + timedelta(seconds=latency)
def _sort_key(record: dict, cfg) -> tuple:
state = record.get('state', {})
incomplete = state.get('keys_missing_n', 0) > 0
next_due = get_next_due(record, cfg)
if next_due is None:
return (
0, # Records without a due date sort first.
0,
0,
0,
)
return (
1,
int(not incomplete), # Incomplete mirrors sort before complete ones.
next_due,
-state.get('last30days_ncommits', 0),
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('--mirror', type=Path, default='mirror')
args = parser.parse_args()
wt = Worktree.from_path(Path.cwd())
cfg = wt.config
records = []
mirror_spec_path = wt.path / args.mirror
for path in sorted(mirror_spec_path.glob('*.json')):
with path.open('r', encoding='utf-8') as file:
record = json.load(file)
# a record whose `enabled` switch is off is ignored completely;
# a missing switch means the record is enabled
if not record.get('enabled', True):
continue
records.append(record)
records.sort(key=lambda record: _sort_key(record, cfg))
for record in records:
next_due = get_next_due(record, cfg)
# only report the first record that is due, i.e. without a due date
# or with a due date in the past
if next_due is None or next_due <= now():
print(json.dumps(record, separators=(',', ':'))) # noqa: T201
return