mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 06:06:28 +01:00
Compare commits
No commits in common. "d0cfc2ca1faab1359b29a8b073267020c9fe8a50" and "6f4ca6421879232a534d3647fdb83e6e9bcd8869" have entirely different histories.
d0cfc2ca1f
...
6f4ca64218
12
.github/workflows/gatelock-tests.yml
vendored
12
.github/workflows/gatelock-tests.yml
vendored
@ -5,10 +5,10 @@ on:
|
||||
branches: [main]
|
||||
# The workflow's own file counts as gatelock: editing only this file used
|
||||
# to trigger nothing, so a fix to the job itself could never prove itself.
|
||||
paths: ['gatelock/**', 'earned_time/**', 'freedays/**', 'sickdays/**', '.github/workflows/gatelock-tests.yml']
|
||||
paths: ['gatelock/**', '.github/workflows/gatelock-tests.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['gatelock/**', 'earned_time/**', 'freedays/**', 'sickdays/**', '.github/workflows/gatelock-tests.yml']
|
||||
paths: ['gatelock/**', '.github/workflows/gatelock-tests.yml']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@ -26,14 +26,6 @@ jobs:
|
||||
cache: pip
|
||||
cache-dependency-path: gatelock/requirements.txt
|
||||
|
||||
# The evening chain (gatelock.evening_chain) reads earned_time, freedays
|
||||
# and sickdays; they are siblings in this repo, so CI installs the
|
||||
# checkout, not a tag.
|
||||
- name: Install the sibling packages
|
||||
run: >-
|
||||
pip install ../crdt-sync ../earned_time
|
||||
&& pip install --no-deps ../freedays ../sickdays
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements.txt
|
||||
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
/// Shared pieces of the app-errors tests: the RTDB sink fake and a config.
|
||||
library;
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart';
|
||||
|
||||
/// A sink recording every patch; [fail] makes the next ones throw.
|
||||
class FakeSink {
|
||||
final patches = <String, Map<String, Object?>>{};
|
||||
bool fail = false;
|
||||
|
||||
Future<void> call(String path, Map<String, Object?> values) async {
|
||||
if (fail) throw StateError('offline');
|
||||
(patches[path] ??= {}).addAll(values);
|
||||
}
|
||||
|
||||
List<Map<String, Object?>> get entries => [
|
||||
for (final v in patches.values.expand((m) => m.values))
|
||||
v! as Map<String, Object?>,
|
||||
];
|
||||
}
|
||||
|
||||
const config = AppErrorsConfig(
|
||||
app: 'todo',
|
||||
repo: 'kuhyx/todo',
|
||||
build: 42,
|
||||
version: '1.2.3',
|
||||
);
|
||||
|
||||
/// An error whose toString throws.
|
||||
class ThrowingToString {
|
||||
@override
|
||||
String toString() => throw StateError('no');
|
||||
}
|
||||
@ -7,7 +7,28 @@ import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'app_errors_support.dart';
|
||||
/// A sink recording every patch; [fail] makes the next ones throw.
|
||||
class FakeSink {
|
||||
final patches = <String, Map<String, Object?>>{};
|
||||
bool fail = false;
|
||||
|
||||
Future<void> call(String path, Map<String, Object?> values) async {
|
||||
if (fail) throw StateError('offline');
|
||||
(patches[path] ??= {}).addAll(values);
|
||||
}
|
||||
|
||||
List<Map<String, Object?>> get entries => [
|
||||
for (final v in patches.values.expand((m) => m.values))
|
||||
v! as Map<String, Object?>,
|
||||
];
|
||||
}
|
||||
|
||||
const config = AppErrorsConfig(
|
||||
app: 'todo',
|
||||
repo: 'kuhyx/todo',
|
||||
build: 42,
|
||||
version: '1.2.3',
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
@ -69,7 +90,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('never throws on an error whose toString throws', () {
|
||||
reporter().report('k', ThrowingToString());
|
||||
reporter().report('k', _Throws());
|
||||
expect(queue.entries, isEmpty);
|
||||
});
|
||||
|
||||
@ -158,6 +179,221 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('ErrorUploader', () {
|
||||
test('uploads to /<app>/errors/<device>/<id> with the build', () async {
|
||||
final sink = FakeSink();
|
||||
reporter().report('k', 'Bad state: token=abc123 me@x.org');
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => sink.call,
|
||||
deviceId: () async => 'dev-1',
|
||||
);
|
||||
expect(await up.flush(), isTrue);
|
||||
expect(sink.patches.keys.single, 'todo/errors');
|
||||
final key = sink.patches['todo/errors']!.keys.single;
|
||||
expect(key, startsWith('dev-1/'));
|
||||
final e = sink.entries.single;
|
||||
expect(e['build'], 42);
|
||||
expect(e['version'], '1.2.3');
|
||||
expect(e['repo'], 'kuhyx/todo');
|
||||
expect(e['mark'], 'package:todo/');
|
||||
expect(e['error'], 'Bad state: token=<redacted> <email>');
|
||||
expect(queue.entries, isEmpty);
|
||||
});
|
||||
|
||||
test('offline keeps the queue; back online sends it', () async {
|
||||
final sink = FakeSink()..fail = true;
|
||||
reporter().report('k', 'x');
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => sink.call,
|
||||
deviceId: () async => 'd',
|
||||
);
|
||||
expect(await up.flush(), isFalse);
|
||||
expect(queue.entries, hasLength(1));
|
||||
sink.fail = false;
|
||||
expect(await up.flush(), isTrue);
|
||||
expect(sink.entries, hasLength(1));
|
||||
up.dispose();
|
||||
});
|
||||
|
||||
test('signed out (no sink) keeps the queue', () async {
|
||||
reporter().report('k', 'x');
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => null,
|
||||
deviceId: () async => 'd',
|
||||
);
|
||||
expect(await up.flush(), isFalse);
|
||||
expect(queue.entries, hasLength(1));
|
||||
up.dispose();
|
||||
});
|
||||
|
||||
test('nothing pending is a no-op', () async {
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => throw StateError('never called'),
|
||||
deviceId: () async => 'd',
|
||||
);
|
||||
expect(await up.flush(), isTrue);
|
||||
});
|
||||
|
||||
test('an append schedules a debounced flush', () async {
|
||||
final sink = FakeSink();
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => sink.call,
|
||||
deviceId: () async => 'd',
|
||||
debounce: Duration.zero,
|
||||
)..start();
|
||||
reporter().report('k', 'x');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
expect(sink.entries, hasLength(1));
|
||||
up.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
group('installAppErrors', () {
|
||||
late FlutterExceptionHandler? savedFlutter;
|
||||
late ErrorCallback? savedAsync;
|
||||
|
||||
setUp(() {
|
||||
savedFlutter = FlutterError.onError;
|
||||
savedAsync = PlatformDispatcher.instance.onError;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
FlutterError.onError = savedFlutter;
|
||||
PlatformDispatcher.instance.onError = savedAsync;
|
||||
AppErrors.instance = null;
|
||||
});
|
||||
|
||||
test('chains the framework and async hooks', () async {
|
||||
final seen = <Object>[];
|
||||
FlutterError.onError = (d) => seen.add(d.exception);
|
||||
PlatformDispatcher.instance.onError = (e, s) {
|
||||
seen.add(e);
|
||||
return true;
|
||||
};
|
||||
final errors = await installAppErrors(
|
||||
config,
|
||||
preferences: await SharedPreferences.getInstance(),
|
||||
);
|
||||
expect(AppErrors.instance, same(errors));
|
||||
FlutterError.onError!(
|
||||
FlutterErrorDetails(exception: StateError('framework')),
|
||||
);
|
||||
FlutterError.onError!(
|
||||
FlutterErrorDetails(exception: StateError('quiet'), silent: true),
|
||||
);
|
||||
expect(
|
||||
PlatformDispatcher.instance.onError!(
|
||||
StateError('async'),
|
||||
StackTrace.empty,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(seen, hasLength(3));
|
||||
expect(errors.queue.entries.map((e) => e.kind), [
|
||||
'uncaught.flutter',
|
||||
'uncaught.async',
|
||||
]);
|
||||
});
|
||||
|
||||
test('without prior hooks the async error is not handled', () async {
|
||||
FlutterError.onError = null;
|
||||
PlatformDispatcher.instance.onError = null;
|
||||
final errors = await installAppErrors(
|
||||
config,
|
||||
preferences: await SharedPreferences.getInstance(),
|
||||
);
|
||||
FlutterError.onError!(FlutterErrorDetails(exception: StateError('f')));
|
||||
expect(
|
||||
PlatformDispatcher.instance.onError!('a', StackTrace.empty),
|
||||
isFalse,
|
||||
);
|
||||
expect(errors.queue.entries, hasLength(2));
|
||||
});
|
||||
|
||||
test('connect starts uploads; the route observer stamps routes', () async {
|
||||
final errors = await installAppErrors(
|
||||
config,
|
||||
preferences: await SharedPreferences.getInstance(),
|
||||
);
|
||||
final sink = FakeSink();
|
||||
final up = errors.connect(
|
||||
sink: () async => sink.call,
|
||||
deviceId: () async => 'd',
|
||||
startDelay: Duration.zero,
|
||||
);
|
||||
AppErrorsRouteObserver(errors).didPush(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => const SizedBox(),
|
||||
settings: const RouteSettings(name: '/settings'),
|
||||
),
|
||||
null,
|
||||
);
|
||||
errors.reporter.report('k', 'x');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
await up.flush();
|
||||
expect(sink.entries.single['route'], '/settings');
|
||||
up.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
group('WaitWatch', () {
|
||||
tearDown(() => AppErrors.instance = null);
|
||||
|
||||
testWidgets('without AppErrors it only shows the child', (tester) async {
|
||||
await tester.pumpWidget(const WaitWatch.centered('x'));
|
||||
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('a spinner shown 2 s is a perf.slow entry', (tester) async {
|
||||
var now = DateTime.utc(2026);
|
||||
final errors = AppErrors.forTest(config, queue, now: () => now);
|
||||
AppErrors.instance = errors;
|
||||
await tester.pumpWidget(
|
||||
const WaitWatch(operation: 'list.load', child: SizedBox()),
|
||||
);
|
||||
now = now.add(const Duration(seconds: 2));
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(queue.entries.single.operation, 'list.load');
|
||||
});
|
||||
|
||||
testWidgets('backgrounding ends the wait, resuming starts one', (
|
||||
tester,
|
||||
) async {
|
||||
var now = DateTime.utc(2026);
|
||||
final errors = AppErrors.forTest(config, queue, now: () => now);
|
||||
AppErrors.instance = errors;
|
||||
await tester.pumpWidget(
|
||||
const WaitWatch(operation: 'op', child: SizedBox()),
|
||||
);
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
|
||||
now = now.add(const Duration(seconds: 30));
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||
now = now.add(const Duration(milliseconds: 100));
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(queue.entries, isEmpty, reason: 'background time is no wait');
|
||||
});
|
||||
});
|
||||
|
||||
test('install reads the default preferences', () async {
|
||||
final saved = (FlutterError.onError, PlatformDispatcher.instance.onError);
|
||||
final errors = await installAppErrors(config);
|
||||
expect(errors.config.mark, 'package:todo/');
|
||||
FlutterError.onError = saved.$1;
|
||||
PlatformDispatcher.instance.onError = saved.$2;
|
||||
AppErrors.instance = null;
|
||||
});
|
||||
|
||||
test('config mark uses the package name, else the app', () {
|
||||
// ignore: prefer_const_constructors -- a runtime instance for coverage
|
||||
final named = AppErrorsConfig(app: 'a-b', repo: 'o/a', package: 'pkg');
|
||||
@ -166,6 +402,29 @@ void main() {
|
||||
expect(AppErrorsConfig(app: 'a-b', repo: 'o/a').mark, 'package:a_b/');
|
||||
});
|
||||
|
||||
test('route observer follows pop and replace', () {
|
||||
final errors = AppErrors.forTest(config, queue);
|
||||
final observer = AppErrorsRouteObserver(errors);
|
||||
Route<void> named(String name) => MaterialPageRoute<void>(
|
||||
builder: (_) => const SizedBox(),
|
||||
settings: RouteSettings(name: name),
|
||||
);
|
||||
observer.didPop(named('/b'), named('/a'));
|
||||
expect(errors.reporter.route, '/a');
|
||||
observer.didReplace(newRoute: named('/c'));
|
||||
expect(errors.reporter.route, '/c');
|
||||
observer.didPop(named('/c'), null);
|
||||
expect(errors.reporter.route, '/c', reason: 'no name keeps the last');
|
||||
});
|
||||
|
||||
testWidgets('WaitWatch built at runtime', (tester) async {
|
||||
// ignore: prefer_const_constructors
|
||||
await tester.pumpWidget(WaitWatch.centered('x'));
|
||||
// ignore: prefer_const_constructors
|
||||
await tester.pumpWidget(WaitWatch(operation: 'y', child: SizedBox()));
|
||||
expect(find.byType(SizedBox), findsOneWidget);
|
||||
});
|
||||
|
||||
test('redactForReport masks secrets', () {
|
||||
expect(
|
||||
redactForReport(
|
||||
@ -194,3 +453,8 @@ void main() {
|
||||
expect(ErrorEntry.tryFromJson('nope'), isNull);
|
||||
});
|
||||
}
|
||||
|
||||
class _Throws {
|
||||
@override
|
||||
String toString() => throw StateError('no');
|
||||
}
|
||||
|
||||
@ -1,202 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui' show ErrorCallback, PlatformDispatcher;
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'app_errors_support.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late DateTime clock;
|
||||
late ErrorQueue queue;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
clock = DateTime.utc(2026, 11, 17, 10);
|
||||
queue = await ErrorQueue.open(await SharedPreferences.getInstance());
|
||||
});
|
||||
|
||||
ErrorReporter reporter() =>
|
||||
ErrorReporter(queue, config: config, now: () => clock);
|
||||
|
||||
group('ErrorUploader', () {
|
||||
test('uploads to /<app>/errors/<device>/<id> with the build', () async {
|
||||
final sink = FakeSink();
|
||||
reporter().report('k', 'Bad state: token=abc123 me@x.org');
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => sink.call,
|
||||
deviceId: () async => 'dev-1',
|
||||
);
|
||||
expect(await up.flush(), isTrue);
|
||||
expect(sink.patches.keys.single, 'todo/errors');
|
||||
final key = sink.patches['todo/errors']!.keys.single;
|
||||
expect(key, startsWith('dev-1/'));
|
||||
final e = sink.entries.single;
|
||||
expect(e['build'], 42);
|
||||
expect(e['version'], '1.2.3');
|
||||
expect(e['repo'], 'kuhyx/todo');
|
||||
expect(e['mark'], 'package:todo/');
|
||||
expect(e['error'], 'Bad state: token=<redacted> <email>');
|
||||
expect(queue.entries, isEmpty);
|
||||
});
|
||||
|
||||
test('offline keeps the queue; back online sends it', () async {
|
||||
final sink = FakeSink()..fail = true;
|
||||
reporter().report('k', 'x');
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => sink.call,
|
||||
deviceId: () async => 'd',
|
||||
);
|
||||
expect(await up.flush(), isFalse);
|
||||
expect(queue.entries, hasLength(1));
|
||||
sink.fail = false;
|
||||
expect(await up.flush(), isTrue);
|
||||
expect(sink.entries, hasLength(1));
|
||||
up.dispose();
|
||||
});
|
||||
|
||||
test('signed out (no sink) keeps the queue', () async {
|
||||
reporter().report('k', 'x');
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => null,
|
||||
deviceId: () async => 'd',
|
||||
);
|
||||
expect(await up.flush(), isFalse);
|
||||
expect(queue.entries, hasLength(1));
|
||||
up.dispose();
|
||||
});
|
||||
|
||||
test('nothing pending is a no-op', () async {
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => throw StateError('never called'),
|
||||
deviceId: () async => 'd',
|
||||
);
|
||||
expect(await up.flush(), isTrue);
|
||||
});
|
||||
|
||||
test('an append schedules a debounced flush', () async {
|
||||
final sink = FakeSink();
|
||||
final up = ErrorUploader(
|
||||
queue,
|
||||
config: config,
|
||||
sink: () async => sink.call,
|
||||
deviceId: () async => 'd',
|
||||
debounce: Duration.zero,
|
||||
)..start();
|
||||
reporter().report('k', 'x');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
expect(sink.entries, hasLength(1));
|
||||
up.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
group('installAppErrors', () {
|
||||
late FlutterExceptionHandler? savedFlutter;
|
||||
late ErrorCallback? savedAsync;
|
||||
|
||||
setUp(() {
|
||||
savedFlutter = FlutterError.onError;
|
||||
savedAsync = PlatformDispatcher.instance.onError;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
FlutterError.onError = savedFlutter;
|
||||
PlatformDispatcher.instance.onError = savedAsync;
|
||||
AppErrors.instance = null;
|
||||
});
|
||||
|
||||
test('chains the framework and async hooks', () async {
|
||||
final seen = <Object>[];
|
||||
FlutterError.onError = (d) => seen.add(d.exception);
|
||||
PlatformDispatcher.instance.onError = (e, s) {
|
||||
seen.add(e);
|
||||
return true;
|
||||
};
|
||||
final errors = await installAppErrors(
|
||||
config,
|
||||
preferences: await SharedPreferences.getInstance(),
|
||||
);
|
||||
expect(AppErrors.instance, same(errors));
|
||||
FlutterError.onError!(
|
||||
FlutterErrorDetails(exception: StateError('framework')),
|
||||
);
|
||||
FlutterError.onError!(
|
||||
FlutterErrorDetails(exception: StateError('quiet'), silent: true),
|
||||
);
|
||||
expect(
|
||||
PlatformDispatcher.instance.onError!(
|
||||
StateError('async'),
|
||||
StackTrace.empty,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(seen, hasLength(3));
|
||||
expect(errors.queue.entries.map((e) => e.kind), [
|
||||
'uncaught.flutter',
|
||||
'uncaught.async',
|
||||
]);
|
||||
});
|
||||
|
||||
test('without prior hooks the async error is not handled', () async {
|
||||
FlutterError.onError = null;
|
||||
PlatformDispatcher.instance.onError = null;
|
||||
final errors = await installAppErrors(
|
||||
config,
|
||||
preferences: await SharedPreferences.getInstance(),
|
||||
);
|
||||
FlutterError.onError!(FlutterErrorDetails(exception: StateError('f')));
|
||||
expect(
|
||||
PlatformDispatcher.instance.onError!('a', StackTrace.empty),
|
||||
isFalse,
|
||||
);
|
||||
expect(errors.queue.entries, hasLength(2));
|
||||
});
|
||||
|
||||
test('connect starts uploads; the route observer stamps routes', () async {
|
||||
final errors = await installAppErrors(
|
||||
config,
|
||||
preferences: await SharedPreferences.getInstance(),
|
||||
);
|
||||
final sink = FakeSink();
|
||||
final up = errors.connect(
|
||||
sink: () async => sink.call,
|
||||
deviceId: () async => 'd',
|
||||
startDelay: Duration.zero,
|
||||
);
|
||||
AppErrorsRouteObserver(errors).didPush(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => const SizedBox(),
|
||||
settings: const RouteSettings(name: '/settings'),
|
||||
),
|
||||
null,
|
||||
);
|
||||
errors.reporter.report('k', 'x');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
await up.flush();
|
||||
expect(sink.entries.single['route'], '/settings');
|
||||
up.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
test('install reads the default preferences', () async {
|
||||
final saved = (FlutterError.onError, PlatformDispatcher.instance.onError);
|
||||
final errors = await installAppErrors(config);
|
||||
expect(errors.config.mark, 'package:todo/');
|
||||
FlutterError.onError = saved.$1;
|
||||
PlatformDispatcher.instance.onError = saved.$2;
|
||||
AppErrors.instance = null;
|
||||
});
|
||||
}
|
||||
@ -1,88 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui' show ErrorCallback, PlatformDispatcher;
|
||||
|
||||
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'app_errors_support.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late DateTime clock;
|
||||
late ErrorQueue queue;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
clock = DateTime.utc(2026, 11, 17, 10);
|
||||
queue = await ErrorQueue.open(await SharedPreferences.getInstance());
|
||||
});
|
||||
|
||||
ErrorReporter reporter() =>
|
||||
ErrorReporter(queue, config: config, now: () => clock);
|
||||
|
||||
group('WaitWatch', () {
|
||||
tearDown(() => AppErrors.instance = null);
|
||||
|
||||
testWidgets('without AppErrors it only shows the child', (tester) async {
|
||||
await tester.pumpWidget(const WaitWatch.centered('x'));
|
||||
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('a spinner shown 2 s is a perf.slow entry', (tester) async {
|
||||
var now = DateTime.utc(2026);
|
||||
final errors = AppErrors.forTest(config, queue, now: () => now);
|
||||
AppErrors.instance = errors;
|
||||
await tester.pumpWidget(
|
||||
const WaitWatch(operation: 'list.load', child: SizedBox()),
|
||||
);
|
||||
now = now.add(const Duration(seconds: 2));
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(queue.entries.single.operation, 'list.load');
|
||||
});
|
||||
|
||||
testWidgets('backgrounding ends the wait, resuming starts one', (
|
||||
tester,
|
||||
) async {
|
||||
var now = DateTime.utc(2026);
|
||||
final errors = AppErrors.forTest(config, queue, now: () => now);
|
||||
AppErrors.instance = errors;
|
||||
await tester.pumpWidget(
|
||||
const WaitWatch(operation: 'op', child: SizedBox()),
|
||||
);
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
|
||||
now = now.add(const Duration(seconds: 30));
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||
now = now.add(const Duration(milliseconds: 100));
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(queue.entries, isEmpty, reason: 'background time is no wait');
|
||||
});
|
||||
});
|
||||
|
||||
test('route observer follows pop and replace', () {
|
||||
final errors = AppErrors.forTest(config, queue);
|
||||
final observer = AppErrorsRouteObserver(errors);
|
||||
Route<void> named(String name) => MaterialPageRoute<void>(
|
||||
builder: (_) => const SizedBox(),
|
||||
settings: RouteSettings(name: name),
|
||||
);
|
||||
observer.didPop(named('/b'), named('/a'));
|
||||
expect(errors.reporter.route, '/a');
|
||||
observer.didReplace(newRoute: named('/c'));
|
||||
expect(errors.reporter.route, '/c');
|
||||
observer.didPop(named('/c'), null);
|
||||
expect(errors.reporter.route, '/c', reason: 'no name keeps the last');
|
||||
});
|
||||
|
||||
testWidgets('WaitWatch built at runtime', (tester) async {
|
||||
// ignore: prefer_const_constructors
|
||||
await tester.pumpWidget(WaitWatch.centered('x'));
|
||||
// ignore: prefer_const_constructors
|
||||
await tester.pumpWidget(WaitWatch(operation: 'y', child: SizedBox()));
|
||||
expect(find.byType(SizedBox), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@ -5,7 +5,7 @@ description: >-
|
||||
helpers that were each reimplemented in three or more repos. Owns the tokens
|
||||
-- consumers import them rather than transcribing the token table by hand.
|
||||
publish_to: 'none'
|
||||
version: 0.4.1
|
||||
version: 0.4.0
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
||||
@ -143,30 +143,6 @@ Uncaught, thread and Tk callback errors and waits over 1 s go to
|
||||
`~/.local/state/app-errors-spool/<app>.jsonl`. The `app-errors` ingest timer
|
||||
turns them into board tickets. Nothing shows on screen.
|
||||
|
||||
## Evening gate chain
|
||||
|
||||
`python3 -m gatelock.evening_chain pending|run` (0.16.0) runs book, then tutor,
|
||||
then LeetCode in front of night lockdown. Needs the `evening` extra
|
||||
(earned-time, freedays, sickdays); only this CLI imports them.
|
||||
|
||||
- `pending` prints the unpaid rungs. Exit 0 some rung is unpaid; 1 nothing
|
||||
to do (all paid, free day, sick day, or 23:00 and later); 2 could not
|
||||
check (unreadable ledger or key, any exception; stderr says why) -- it
|
||||
fails closed, so root enters lockdown. Reading and LeetCode use
|
||||
`earned_time.done_today`; the tutor is quota-based
|
||||
(`credit_units >= max_units`). The LeetCode rung is pending only while
|
||||
payable: a day settled by any signed `charge:<day>` row (escape hatch,
|
||||
outage) can never earn the bonus, so it is not listed. Cheap: three small reads, root runs it
|
||||
every minute.
|
||||
- `run` runs each unpaid rung's gate (`GATE_COMMANDS`, all `--production
|
||||
--evening`) and re-checks before each. A gate's exit 10
|
||||
(`EXIT_END_EVENING`) stops the chain with 0; 3 (`EXIT_NO_X`) exits 3; a
|
||||
gate killed at 23:00 or nothing left exits 0; a failing gate (or one that
|
||||
exits 0 with its rung still unpaid) is skipped, and two in a row exit 1.
|
||||
- `RANK_EVENING_GATE` = 150 sits between the screen-locker and diet-guard.
|
||||
- `systemd/evening-gates.service` is the user unit root starts;
|
||||
`install_evening_gates.sh` copies it and reloads, and never enables it.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
|
||||
@ -10,7 +10,6 @@ from __future__ import annotations
|
||||
|
||||
from gatelock._arbiter import (
|
||||
RANK_DIET_GUARD,
|
||||
RANK_EVENING_GATE,
|
||||
RANK_SCREEN_LOCKER,
|
||||
RANK_WAKE_ALARM,
|
||||
Arbiter,
|
||||
@ -80,7 +79,6 @@ __all__ = [
|
||||
"QUEUE_HEARTBEAT_SECONDS",
|
||||
"QUEUE_POLL_SECONDS",
|
||||
"RANK_DIET_GUARD",
|
||||
"RANK_EVENING_GATE",
|
||||
"RANK_SCREEN_LOCKER",
|
||||
"RANK_WAKE_ALARM",
|
||||
"Arbiter",
|
||||
|
||||
@ -2,8 +2,9 @@
|
||||
"""Decide which of N locker apps may hold the screen.
|
||||
|
||||
On 2026-07-25 two lockers armed at the same boot. One won the X grab; the
|
||||
other spun forever, logging that "a fullscreen game" held it. No game was
|
||||
running -- the holder was the other locker, and each app only knew itself.
|
||||
other spun forever in a retry loop, logging that "a fullscreen game" held the
|
||||
grab. No game was running -- the holder was the other locker. Nothing
|
||||
coordinated them because nothing could: each app only knew about itself.
|
||||
|
||||
This module is that coordination. Every app publishes a *claim* before it
|
||||
builds any window, and the highest-ranked live claim wins. Ranks, highest
|
||||
@ -11,7 +12,6 @@ first:
|
||||
|
||||
* ``RANK_WAKE_ALARM`` -- you have to wake up before you can do anything else
|
||||
* ``RANK_SCREEN_LOCKER`` -- then you work out
|
||||
* ``RANK_EVENING_GATE`` -- then the evening gate chain
|
||||
* ``RANK_DIET_GUARD`` -- then you eat
|
||||
|
||||
Two properties do the real work.
|
||||
@ -55,8 +55,8 @@ _logger = logging.getLogger(__name__)
|
||||
|
||||
RANK_WAKE_ALARM: Final = 300
|
||||
RANK_SCREEN_LOCKER: Final = 200
|
||||
RANK_EVENING_GATE: Final = 150
|
||||
RANK_DIET_GUARD: Final = 100
|
||||
|
||||
_HOLDER_FILENAME: Final = "holder.lock"
|
||||
|
||||
|
||||
|
||||
@ -1,239 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The spool writer behind ``gatelock.error_report``: reports and timed waits.
|
||||
|
||||
``Reporter`` writes one JSON line per report to
|
||||
``$XDG_STATE_HOME/app-errors-spool/<app>.jsonl`` (utils DOCS-app-errors.md),
|
||||
deduplicating identical errors within ``WINDOW`` seconds and capping each
|
||||
minute, and never raises into the app it watches. ``SlowWait`` is one timed
|
||||
wait: written when it outlasts the threshold, or while it is still going.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Iterator
|
||||
from types import TracebackType
|
||||
|
||||
#: The kind the board files as "bring this wait under 1 s".
|
||||
SLOW_KIND = "perf.slow"
|
||||
#: Seconds in the rate cap's window.
|
||||
_MINUTE = 60.0
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _default_spool() -> Path:
|
||||
base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")
|
||||
return Path(base) / "app-errors-spool"
|
||||
|
||||
|
||||
def _short(path: str, mark: str) -> str:
|
||||
"""Return ``path`` from the package that holds it: no home directory in a report."""
|
||||
for anchor in ("site-packages/", "dist-packages/"):
|
||||
if anchor in path:
|
||||
return path.rsplit(anchor, 1)[1]
|
||||
if mark in path:
|
||||
return mark + path.rsplit(mark, 1)[1]
|
||||
return Path(path).name
|
||||
|
||||
|
||||
#: What a report may fail with (a bad spool path, an error whose str() throws):
|
||||
#: logged and dropped, never raised into the app being watched.
|
||||
_REPORT_FAILURES = (OSError, ValueError, TypeError, RuntimeError, AttributeError)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Guard:
|
||||
"""A reporter's loop guards: recent errors, minute buckets, re-entry."""
|
||||
|
||||
seen: dict[str, float] = field(default_factory=dict)
|
||||
minutes: dict[str, tuple[float, int]] = field(default_factory=dict)
|
||||
busy: bool = False
|
||||
serial: int = 0
|
||||
lock: threading.Lock = field(default_factory=threading.Lock)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Reporter:
|
||||
"""Writes one app's error and slow-wait reports to the spool."""
|
||||
|
||||
#: Seconds an identical error stays suppressed.
|
||||
WINDOW = 30.0
|
||||
#: Most error reports written per minute.
|
||||
MAX_PER_MINUTE = 20
|
||||
#: Most slow-wait reports written per minute.
|
||||
MAX_SLOW_PER_MINUTE = 30
|
||||
|
||||
app: str
|
||||
repo: str
|
||||
mark: str = ""
|
||||
spool: Path = field(default_factory=_default_spool)
|
||||
build: int = 0
|
||||
version: str | None = None
|
||||
threshold: float = 1.0
|
||||
still_after: float = 5.0
|
||||
clock: Callable[[], float] = time.time
|
||||
_guard: _Guard = field(default_factory=_Guard)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Default the frame mark to the app's module directory."""
|
||||
self.mark = self.mark or self.app.replace("-", "_") + "/"
|
||||
|
||||
def _allowed(self, bucket: str, cap: int) -> bool:
|
||||
now = self.clock()
|
||||
start, count = self._guard.minutes.get(bucket, (now, 0))
|
||||
if now - start >= _MINUTE:
|
||||
start, count = now, 0
|
||||
if count >= cap:
|
||||
return False
|
||||
self._guard.minutes[bucket] = (start, count + 1)
|
||||
return True
|
||||
|
||||
def _write(self, entry: dict[str, object]) -> None:
|
||||
at = dt.datetime.fromtimestamp(self.clock(), dt.UTC)
|
||||
entry |= {
|
||||
"at": at.strftime("%Y-%m-%dT%H:%M:%S.") + f"{at.microsecond // 1000:03d}Z",
|
||||
"repo": self.repo,
|
||||
"mark": self.mark,
|
||||
"build": self.build,
|
||||
}
|
||||
if self.version:
|
||||
entry["version"] = self.version
|
||||
line = json.dumps(entry, sort_keys=True) + "\n"
|
||||
with self._guard.lock:
|
||||
self.spool.mkdir(parents=True, exist_ok=True)
|
||||
with (self.spool / f"{self.app}.jsonl").open("a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
|
||||
def report(self, kind: str, error: object, tb: TracebackType | None = None) -> None:
|
||||
"""Record ``error`` (exception or message) as ``kind``, unless suppressed."""
|
||||
if self._guard.busy:
|
||||
return
|
||||
self._guard.busy = True
|
||||
try:
|
||||
text = (
|
||||
f"{type(error).__name__}: {error}"
|
||||
if isinstance(error, BaseException)
|
||||
else str(error)
|
||||
)
|
||||
now = self.clock()
|
||||
key = f"{kind}|{text}"
|
||||
self._guard.seen = {
|
||||
k: t for k, t in self._guard.seen.items() if now - t < self.WINDOW
|
||||
}
|
||||
if key in self._guard.seen or not self._allowed(
|
||||
"error", self.MAX_PER_MINUTE
|
||||
):
|
||||
return
|
||||
self._guard.seen[key] = now
|
||||
frames = traceback.extract_tb(tb) if tb is not None else []
|
||||
stack = [
|
||||
f"{_short(f.filename, self.mark)}:{f.lineno} in {f.name}"
|
||||
for f in reversed(frames)
|
||||
]
|
||||
self._write({"kind": kind, "error": text, "stack": stack})
|
||||
except _REPORT_FAILURES:
|
||||
# Never raise into the app it watches; the log keeps the why.
|
||||
_logger.exception("app-errors: report not written")
|
||||
finally:
|
||||
self._guard.busy = False
|
||||
|
||||
def slow(
|
||||
self,
|
||||
operation: str,
|
||||
ms: int,
|
||||
*,
|
||||
wait_id: str,
|
||||
route: str | None = None,
|
||||
still: bool = False,
|
||||
) -> None:
|
||||
"""Record one wait of ``ms`` milliseconds on ``operation``."""
|
||||
try:
|
||||
if not self._allowed("slow", self.MAX_SLOW_PER_MINUTE):
|
||||
return
|
||||
entry: dict[str, object] = {
|
||||
"kind": SLOW_KIND,
|
||||
"error": f"{operation} waited {ms} ms",
|
||||
"operation": operation,
|
||||
"durationMs": ms,
|
||||
"waitId": wait_id,
|
||||
"still": still,
|
||||
}
|
||||
if route:
|
||||
entry["route"] = route
|
||||
self._write(entry)
|
||||
except _REPORT_FAILURES:
|
||||
_logger.exception("app-errors: slow wait not written")
|
||||
|
||||
def begin(self, operation: str, *, route: str | None = None) -> SlowWait:
|
||||
"""Start timing a wait on ``operation`` (``coach.load``); ``end`` it after."""
|
||||
self._guard.serial += 1
|
||||
return SlowWait(
|
||||
self,
|
||||
operation,
|
||||
route,
|
||||
self.clock(),
|
||||
f"{int(self.clock() * 1000):x}-{self._guard.serial}",
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def wait(self, operation: str, *, route: str | None = None) -> Iterator[SlowWait]:
|
||||
"""Time the ``with`` block as a wait on ``operation``."""
|
||||
handle = self.begin(operation, route=route)
|
||||
try:
|
||||
yield handle
|
||||
finally:
|
||||
handle.end()
|
||||
|
||||
|
||||
@dataclass
|
||||
class SlowWait:
|
||||
"""One timed wait: reported when it ends after the threshold, or is still going."""
|
||||
|
||||
reporter: Reporter
|
||||
operation: str
|
||||
route: str | None
|
||||
started: float
|
||||
id: str
|
||||
_ended: bool = False
|
||||
_reported_still: bool = False
|
||||
_timer: threading.Timer = field(init=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Arm the still-waiting report (a hung load never ends)."""
|
||||
self._timer = threading.Timer(self.reporter.still_after, self._still)
|
||||
self._timer.daemon = True
|
||||
self._timer.start()
|
||||
|
||||
def _ms(self) -> int:
|
||||
return round((self.reporter.clock() - self.started) * 1000)
|
||||
|
||||
def _still(self) -> None:
|
||||
if self._ended:
|
||||
return
|
||||
self._reported_still = True
|
||||
self.reporter.slow(
|
||||
self.operation, self._ms(), wait_id=self.id, route=self.route, still=True
|
||||
)
|
||||
|
||||
def end(self) -> None:
|
||||
"""End the wait; write it if it outlasted the threshold; repeats do nothing."""
|
||||
if self._ended:
|
||||
return
|
||||
self._ended = True
|
||||
self._timer.cancel()
|
||||
ms = self._ms()
|
||||
if self._reported_still or ms > self.reporter.threshold * 1000:
|
||||
self.reporter.slow(self.operation, ms, wait_id=self.id, route=self.route)
|
||||
@ -1,155 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""What the evening chain reads: constants, sources and today's verdict.
|
||||
|
||||
Split from :mod:`gatelock.evening_chain` (the CLI and the run loop) to keep
|
||||
each file readable in one piece. Import the public names from there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import time
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Final, Protocol
|
||||
|
||||
import earned_time
|
||||
import freedays
|
||||
import sickdays
|
||||
|
||||
from gatelock.log_integrity import DEFAULT_HMAC_KEY_FILE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
from datetime import date, datetime
|
||||
|
||||
|
||||
class _Earner(Protocol):
|
||||
"""What this module reads off an ``earned_time.Earner``."""
|
||||
|
||||
ledger: str
|
||||
max_units: int | None
|
||||
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
EXIT_OK: Final = 0
|
||||
EXIT_NOTHING: Final = 1
|
||||
EXIT_UNCHECKABLE: Final = 2
|
||||
EXIT_NO_X: Final = 3
|
||||
EXIT_END_EVENING: Final = 10
|
||||
"""A gate's "end evening" control: stop the chain, lockdown at the next tick."""
|
||||
|
||||
CHAIN: Final = ("reading", "tutor", "leetcode")
|
||||
CUTOFF: Final = time(23, 0)
|
||||
"""The only hard time: from here no gate runs and nothing is pending."""
|
||||
MAX_FAILURES_IN_A_ROW: Final = 2
|
||||
|
||||
_PYTHON: Final = "/usr/bin/python3"
|
||||
GATE_COMMANDS: Final[Mapping[str, tuple[str, ...]]] = {
|
||||
"reading": (_PYTHON, "-m", "book_guard", "lock", "--production", "--evening"),
|
||||
"tutor": (_PYTHON, "-m", "tutor.gate", "--production", "--evening"),
|
||||
"leetcode": (_PYTHON, "-m", "leetcode_guard", "--production", "--evening"),
|
||||
}
|
||||
TUTOR: Final = "tutor"
|
||||
LEETCODE: Final = "leetcode"
|
||||
|
||||
# What a ledger read may raise; anything else is a bug and surfaces in main().
|
||||
_CHECK_ERRORS: Final = (OSError, ValueError, TypeError, LookupError, RuntimeError)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Sources:
|
||||
"""Every file the chain reads. No defaults: callers say where."""
|
||||
|
||||
home: Path
|
||||
key_file: Path
|
||||
free_log: Path | None # None: freedays' own pool
|
||||
sick_log: Path | None # None: sickdays' own pool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Verdict:
|
||||
"""Today's chain: the rungs still to run, in order, and why none."""
|
||||
|
||||
todo: tuple[str, ...] = ()
|
||||
unchecked: tuple[str, ...] = ()
|
||||
stood_down: str = "" # "free", "sick", "late" or ""
|
||||
|
||||
|
||||
def production_sources() -> Sources:
|
||||
"""The real machine's files: ``$HOME`` ledgers, the shared HMAC key."""
|
||||
return Sources(Path.home(), Path(DEFAULT_HMAC_KEY_FILE), None, None)
|
||||
|
||||
|
||||
def _charged_today(ledger: Path, sources: Sources, day: date) -> bool:
|
||||
"""Whether a verified ``charge`` row names ``day``, whatever its source.
|
||||
|
||||
A day settled by the escape hatch or a LeetCode outage carries a
|
||||
non-paying charge, and the gate then writes no ``source=leetcode`` row, so
|
||||
the rung can never be paid. earned_time has no public helper for "any
|
||||
charge" (``done_today`` only sees the paying one), so this reads the rows
|
||||
itself and trusts only signed ones. Raises OSError/ValueError when the
|
||||
ledger or key cannot be read.
|
||||
"""
|
||||
key = sources.key_file.read_bytes().strip()
|
||||
rows = json.loads(ledger.read_text(encoding="utf-8"))["entries"]
|
||||
return any(
|
||||
isinstance(row, dict)
|
||||
and row.get("kind") == "charge"
|
||||
and row.get("day") == day.isoformat()
|
||||
and earned_time.verified(row, key)
|
||||
for row in rows
|
||||
)
|
||||
|
||||
|
||||
def _paid(rung: str, earner: _Earner, sources: Sources, now: datetime) -> bool | None:
|
||||
"""Whether ``rung`` has nothing to run; None when it could not be checked.
|
||||
|
||||
The LeetCode rung also counts as settled on a day an unpaying charge
|
||||
closed (see :func:`_charged_today`): it is not payable, so not pending.
|
||||
"""
|
||||
ledger = sources.home / earner.ledger
|
||||
try:
|
||||
if rung == TUTOR:
|
||||
units = earned_time.credit_units(
|
||||
earner, ledger, sources.key_file, now.date()
|
||||
)
|
||||
cap = earner.max_units
|
||||
return None if units is None or cap is None else units >= cap
|
||||
done = earned_time.done_today(
|
||||
earner, ledger, sources.key_file, now=now, gate_off=False
|
||||
)
|
||||
if done is None:
|
||||
return None
|
||||
if done or rung != LEETCODE:
|
||||
return bool(done)
|
||||
return _charged_today(ledger, sources, now.date())
|
||||
except _CHECK_ERRORS:
|
||||
_logger.exception("Could not check the %s rung", rung)
|
||||
return None
|
||||
|
||||
|
||||
def evaluate(now: datetime, sources: Sources) -> Verdict:
|
||||
"""Which rungs are unpaid at ``now``; free/sick/late days stand down."""
|
||||
now = now.astimezone()
|
||||
if now.time() >= CUTOFF:
|
||||
return Verdict(stood_down="late")
|
||||
day = now.date()
|
||||
if freedays.is_free_day(day, log_path=sources.free_log):
|
||||
return Verdict(stood_down="free")
|
||||
if sickdays.is_sick_day(day, log_path=sources.sick_log):
|
||||
return Verdict(stood_down="sick")
|
||||
earners = {e.name: e for e in earned_time.earners_for(day)}
|
||||
todo: list[str] = []
|
||||
unchecked: list[str] = []
|
||||
for rung in CHAIN:
|
||||
if rung not in earners:
|
||||
continue
|
||||
paid = _paid(rung, earners[rung], sources, now)
|
||||
if paid is None:
|
||||
unchecked.append(rung)
|
||||
if not paid:
|
||||
todo.append(rung)
|
||||
return Verdict(tuple(todo), tuple(unchecked))
|
||||
@ -9,50 +9,229 @@ which every root, ``GateRoot`` included, goes through), each chained to the
|
||||
hook it replaces. ``Reporter.begin``/``wait`` time a user-visible wait, and
|
||||
``watch_stalls`` reports a frozen Tk loop with no call-site work.
|
||||
|
||||
A report is one JSON line in ``$XDG_STATE_HOME/app-errors-spool/<app>.jsonl``
|
||||
(``gatelock._error_spool``). The PC's ``app-errors`` ingest (utils
|
||||
``app_errors/``) groups it by signature and hands it to the board, which files
|
||||
a ticket. Reporting shows nothing on screen and never raises.
|
||||
A report is one JSON line in ``$XDG_STATE_HOME/app-errors-spool/<app>.jsonl``.
|
||||
The PC's ``app-errors`` ingest (utils ``app_errors/``) reads it, groups it by
|
||||
signature and hands it to the board, which files a ticket. Reporting shows
|
||||
nothing on screen, never raises and never reports from inside a report.
|
||||
Identical errors within ``WINDOW`` seconds are dropped and at most
|
||||
``MAX_PER_MINUTE`` are written per minute (an error loop cannot fill the disk).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import tkinter as tk
|
||||
import traceback
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock._error_spool import SLOW_KIND, Reporter, SlowWait
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterator
|
||||
from types import TracebackType
|
||||
|
||||
__all__ = [
|
||||
"SLOW_KIND",
|
||||
"STALL_TICK_MS",
|
||||
"Reporter",
|
||||
"SlowWait",
|
||||
"install",
|
||||
"watch_stalls",
|
||||
]
|
||||
|
||||
#: The kind the board files as "bring this wait under 1 s".
|
||||
SLOW_KIND = "perf.slow"
|
||||
#: How often the stall watch ticks, milliseconds.
|
||||
STALL_TICK_MS = 100
|
||||
|
||||
_TK_DOOR = "_report_exception"
|
||||
|
||||
_installed: Reporter | None = None
|
||||
|
||||
|
||||
def _default_spool() -> Path:
|
||||
base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")
|
||||
return Path(base) / "app-errors-spool"
|
||||
|
||||
|
||||
def _short(path: str, mark: str) -> str:
|
||||
"""Return ``path`` from the package that holds it: no home directory in a report."""
|
||||
for anchor in ("site-packages/", "dist-packages/"):
|
||||
if anchor in path:
|
||||
return path.rsplit(anchor, 1)[1]
|
||||
if mark in path:
|
||||
return mark + path.rsplit(mark, 1)[1]
|
||||
return Path(path).name
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Installed:
|
||||
"""The process's reporter once ``install`` ran (tests put their own here)."""
|
||||
class Reporter:
|
||||
"""Writes one app's error and slow-wait reports to the spool."""
|
||||
|
||||
reporter: Reporter | None = None
|
||||
#: Seconds an identical error stays suppressed.
|
||||
WINDOW = 30.0
|
||||
#: Most error reports written per minute.
|
||||
MAX_PER_MINUTE = 20
|
||||
#: Most slow-wait reports written per minute.
|
||||
MAX_SLOW_PER_MINUTE = 30
|
||||
|
||||
app: str
|
||||
repo: str
|
||||
mark: str = ""
|
||||
spool: Path = field(default_factory=_default_spool)
|
||||
build: int = 0
|
||||
version: str | None = None
|
||||
threshold: float = 1.0
|
||||
still_after: float = 5.0
|
||||
clock: Callable[[], float] = time.time
|
||||
_seen: dict[str, float] = field(default_factory=dict)
|
||||
_minutes: dict[str, tuple[float, int]] = field(default_factory=dict)
|
||||
_busy: bool = False
|
||||
_serial: int = 0
|
||||
_lock: threading.Lock = field(default_factory=threading.Lock)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Default the frame mark to the app's module directory."""
|
||||
self.mark = self.mark or self.app.replace("-", "_") + "/"
|
||||
|
||||
def _allowed(self, bucket: str, cap: int) -> bool:
|
||||
now = self.clock()
|
||||
start, count = self._minutes.get(bucket, (now, 0))
|
||||
if now - start >= 60: # noqa: PLR2004 -- one minute
|
||||
start, count = now, 0
|
||||
if count >= cap:
|
||||
return False
|
||||
self._minutes[bucket] = (start, count + 1)
|
||||
return True
|
||||
|
||||
def _write(self, entry: dict[str, object]) -> None:
|
||||
at = dt.datetime.fromtimestamp(self.clock(), dt.UTC)
|
||||
entry |= {
|
||||
"at": at.strftime("%Y-%m-%dT%H:%M:%S.") + f"{at.microsecond // 1000:03d}Z",
|
||||
"repo": self.repo,
|
||||
"mark": self.mark,
|
||||
"build": self.build,
|
||||
}
|
||||
if self.version:
|
||||
entry["version"] = self.version
|
||||
line = json.dumps(entry, sort_keys=True) + "\n"
|
||||
with self._lock:
|
||||
self.spool.mkdir(parents=True, exist_ok=True)
|
||||
with (self.spool / f"{self.app}.jsonl").open("a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
|
||||
def report(self, kind: str, error: object, tb: TracebackType | None = None) -> None:
|
||||
"""Record ``error`` (exception or message) as ``kind``, unless suppressed."""
|
||||
if self._busy:
|
||||
return
|
||||
self._busy = True
|
||||
try:
|
||||
text = (
|
||||
f"{type(error).__name__}: {error}"
|
||||
if isinstance(error, BaseException)
|
||||
else str(error)
|
||||
)
|
||||
now = self.clock()
|
||||
key = f"{kind}|{text}"
|
||||
self._seen = {k: t for k, t in self._seen.items() if now - t < self.WINDOW}
|
||||
if key in self._seen or not self._allowed("error", self.MAX_PER_MINUTE):
|
||||
return
|
||||
self._seen[key] = now
|
||||
frames = traceback.extract_tb(tb) if tb is not None else []
|
||||
stack = [
|
||||
f"{_short(f.filename, self.mark)}:{f.lineno} in {f.name}"
|
||||
for f in reversed(frames)
|
||||
]
|
||||
self._write({"kind": kind, "error": text, "stack": stack})
|
||||
except Exception: # noqa: BLE001, S110 -- never raise into the app it watches
|
||||
pass
|
||||
finally:
|
||||
self._busy = False
|
||||
|
||||
def slow(
|
||||
self,
|
||||
operation: str,
|
||||
ms: int,
|
||||
*,
|
||||
wait_id: str,
|
||||
route: str | None = None,
|
||||
still: bool = False,
|
||||
) -> None:
|
||||
"""Record one wait of ``ms`` milliseconds on ``operation``."""
|
||||
try:
|
||||
if not self._allowed("slow", self.MAX_SLOW_PER_MINUTE):
|
||||
return
|
||||
entry: dict[str, object] = {
|
||||
"kind": SLOW_KIND,
|
||||
"error": f"{operation} waited {ms} ms",
|
||||
"operation": operation,
|
||||
"durationMs": ms,
|
||||
"waitId": wait_id,
|
||||
"still": still,
|
||||
}
|
||||
if route:
|
||||
entry["route"] = route
|
||||
self._write(entry)
|
||||
except Exception: # noqa: BLE001, S110 -- never raise into the app
|
||||
pass
|
||||
|
||||
def begin(self, operation: str, *, route: str | None = None) -> SlowWait:
|
||||
"""Start timing a wait on ``operation`` (``coach.load``); ``end`` it after."""
|
||||
self._serial += 1
|
||||
return SlowWait(
|
||||
self,
|
||||
operation,
|
||||
route,
|
||||
self.clock(),
|
||||
f"{int(self.clock() * 1000):x}-{self._serial}",
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def wait(self, operation: str, *, route: str | None = None) -> Iterator[SlowWait]:
|
||||
"""Time the ``with`` block as a wait on ``operation``."""
|
||||
handle = self.begin(operation, route=route)
|
||||
try:
|
||||
yield handle
|
||||
finally:
|
||||
handle.end()
|
||||
|
||||
|
||||
INSTALLED = _Installed()
|
||||
@dataclass
|
||||
class SlowWait:
|
||||
"""One timed wait: reported when it ends after the threshold, or is still going."""
|
||||
|
||||
reporter: Reporter
|
||||
operation: str
|
||||
route: str | None
|
||||
started: float
|
||||
id: str
|
||||
_ended: bool = False
|
||||
_reported_still: bool = False
|
||||
_timer: threading.Timer = field(init=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Arm the still-waiting report (a hung load never ends)."""
|
||||
self._timer = threading.Timer(self.reporter.still_after, self._still)
|
||||
self._timer.daemon = True
|
||||
self._timer.start()
|
||||
|
||||
def _ms(self) -> int:
|
||||
return round((self.reporter.clock() - self.started) * 1000)
|
||||
|
||||
def _still(self) -> None:
|
||||
if self._ended:
|
||||
return
|
||||
self._reported_still = True
|
||||
self.reporter.slow(
|
||||
self.operation, self._ms(), wait_id=self.id, route=self.route, still=True
|
||||
)
|
||||
|
||||
def end(self) -> None:
|
||||
"""End the wait; write it if it outlasted the threshold; repeats do nothing."""
|
||||
if self._ended:
|
||||
return
|
||||
self._ended = True
|
||||
self._timer.cancel()
|
||||
ms = self._ms()
|
||||
if self._reported_still or ms > self.reporter.threshold * 1000:
|
||||
self.reporter.slow(self.operation, ms, wait_id=self.id, route=self.route)
|
||||
|
||||
|
||||
def watch_stalls(root: tk.Misc, reporter: Reporter) -> None:
|
||||
@ -68,8 +247,10 @@ def watch_stalls(root: tk.Misc, reporter: Reporter) -> None:
|
||||
last[0] = now
|
||||
if late > reporter.threshold * 1000:
|
||||
reporter.slow("tk.mainloop", late, wait_id=f"stall-{int(now * 1000):x}")
|
||||
with suppress(tk.TclError): # the window is gone: the watch ends
|
||||
try:
|
||||
root.after(STALL_TICK_MS, tick)
|
||||
except tk.TclError:
|
||||
return # the window is gone
|
||||
|
||||
root.after(STALL_TICK_MS, tick)
|
||||
|
||||
@ -87,10 +268,9 @@ def install(
|
||||
The spool is ``$XDG_STATE_HOME/app-errors-spool``; tests build a
|
||||
``Reporter`` with their own ``spool`` instead.
|
||||
"""
|
||||
# One set of process-wide hooks; a test pre-installs its own reporter by
|
||||
# setting INSTALLED.reporter, and no hook is touched.
|
||||
if INSTALLED.reporter is not None:
|
||||
return INSTALLED.reporter
|
||||
global _installed # noqa: PLW0603 -- one set of process-wide hooks
|
||||
if _installed is not None:
|
||||
return _installed
|
||||
rep = Reporter(
|
||||
app=app,
|
||||
repo=repo,
|
||||
@ -128,5 +308,5 @@ def install(
|
||||
sys.excepthook = sys_hook
|
||||
threading.excepthook = thread_hook
|
||||
setattr(tk.Misc, _TK_DOOR, tk_hook)
|
||||
INSTALLED.reporter = rep
|
||||
_installed = rep
|
||||
return rep
|
||||
|
||||
@ -1,197 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The evening gate chain: book, then tutor, then LeetCode, before lockdown.
|
||||
|
||||
When the resolved shutdown time arrives and a rung of the chain is unpaid
|
||||
today, root (digital-wellbeing's day-specific-shutdown-check) asks this module
|
||||
instead of entering night lockdown:
|
||||
|
||||
* ``python3 -m gatelock.evening_chain pending`` -- prints the unpaid rungs.
|
||||
Exit 0 some rung is unpaid; 1 nothing to do (all paid, a free or sick day,
|
||||
or 23:00 or later); 2 could not check. Root calls it every minute, so it
|
||||
reads three small files and nothing else.
|
||||
* ``python3 -m gatelock.evening_chain run`` -- the ``evening-gates.service``
|
||||
body: each unpaid rung's gate in order, until all are paid.
|
||||
|
||||
"Paid today" is read-only from the signed ledgers (``earned_time``): reading
|
||||
and LeetCode by ``done_today``, the tutor by QUOTA (``credit_units`` reaching
|
||||
``max_units``). A rung not in ``earned_time.earners_for(day)`` is not asked.
|
||||
|
||||
Failure modes, chosen out loud. ``pending`` fails CLOSED: an unreadable
|
||||
ledger or key, a missing dependency or any exception is exit 2 on stderr, and
|
||||
root then enters lockdown. ``run`` treats a rung it cannot check as unpaid
|
||||
(its gate stays up and decides itself) but never spins: a gate that fails,
|
||||
or exits 0 with the rung still unpaid, is skipped for the evening, and two
|
||||
such failures in a row stop the chain with exit 1.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from datetime import UTC, datetime
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from gatelock._evening_state import (
|
||||
CHAIN,
|
||||
CUTOFF,
|
||||
EXIT_END_EVENING,
|
||||
EXIT_NO_X,
|
||||
EXIT_NOTHING,
|
||||
EXIT_OK,
|
||||
EXIT_UNCHECKABLE,
|
||||
GATE_COMMANDS,
|
||||
MAX_FAILURES_IN_A_ROW,
|
||||
Sources,
|
||||
Verdict,
|
||||
evaluate,
|
||||
production_sources,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
__all__ = [
|
||||
"CHAIN",
|
||||
"CUTOFF",
|
||||
"EXIT_END_EVENING",
|
||||
"EXIT_NO_X",
|
||||
"GATE_COMMANDS",
|
||||
"Sources",
|
||||
"Verdict",
|
||||
"evaluate",
|
||||
"main",
|
||||
"pending",
|
||||
"run",
|
||||
]
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
# Everything a broken install or ledger can plausibly raise. A tuple, not a
|
||||
# bare ``except Exception``: pylint bans that and per-line suppressions are
|
||||
# banned here. Anything outside it is a traceback and exit 1, which root also
|
||||
# reads as "enter lockdown" (fail closed either way).
|
||||
_ANY_FAILURE: Final = (
|
||||
OSError,
|
||||
ValueError,
|
||||
TypeError,
|
||||
LookupError,
|
||||
RuntimeError,
|
||||
ImportError,
|
||||
AttributeError,
|
||||
ArithmeticError,
|
||||
AssertionError,
|
||||
NameError,
|
||||
)
|
||||
|
||||
type Clock = Callable[[], datetime]
|
||||
type Runner = Callable[[Sequence[str], float], int | None]
|
||||
"""Runs one gate command with a timeout in seconds; None means it timed out."""
|
||||
|
||||
|
||||
def pending(sources: Sources, clock: Clock, emit: Callable[[str], None]) -> int:
|
||||
"""``pending``'s answer: print the unpaid rungs, return its exit code."""
|
||||
verdict = evaluate(clock(), sources)
|
||||
if verdict.stood_down:
|
||||
_logger.info("Evening chain stands down: %s", verdict.stood_down)
|
||||
return EXIT_NOTHING
|
||||
if verdict.unchecked:
|
||||
_logger.error("Could not check: %s", " ".join(verdict.unchecked))
|
||||
return EXIT_UNCHECKABLE
|
||||
if not verdict.todo:
|
||||
return EXIT_NOTHING
|
||||
emit(" ".join(verdict.todo))
|
||||
return EXIT_OK
|
||||
|
||||
|
||||
def subprocess_runner(cmd: Sequence[str], timeout_s: float) -> int | None:
|
||||
"""Run a gate; on timeout kill it and return None."""
|
||||
try:
|
||||
return subprocess.run(cmd, check=False, timeout=timeout_s).returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
return None
|
||||
except OSError:
|
||||
_logger.exception("Cannot start %s", cmd[0])
|
||||
return 127
|
||||
|
||||
|
||||
def _seconds_to_cutoff(now: datetime) -> float:
|
||||
cutoff = datetime.combine(now.date(), CUTOFF, now.tzinfo)
|
||||
return max((cutoff - now).total_seconds(), 1.0)
|
||||
|
||||
|
||||
def _stop_code(rung: str, code: int | None) -> int | None:
|
||||
"""The run's own exit code when ``code`` ends the chain, else None."""
|
||||
if code is None:
|
||||
_logger.warning("%s gate still up at %s; stopping", rung, CUTOFF)
|
||||
return EXIT_OK
|
||||
return {EXIT_END_EVENING: EXIT_OK, EXIT_NO_X: EXIT_NO_X}.get(code)
|
||||
|
||||
|
||||
def run(sources: Sources, clock: Clock, runner: Runner) -> int:
|
||||
"""Run each unpaid rung's gate in order; see the module docstring."""
|
||||
skipped: list[str] = []
|
||||
ran_clean = "" # a rung whose gate exited 0 and must now read as paid
|
||||
failures = 0
|
||||
while True:
|
||||
now = clock().astimezone()
|
||||
verdict = evaluate(now, sources)
|
||||
if ran_clean in verdict.todo:
|
||||
_logger.error("%s gate exited 0 but the rung is unpaid", ran_clean)
|
||||
skipped.append(ran_clean)
|
||||
failures += 1
|
||||
elif ran_clean:
|
||||
failures = 0
|
||||
ran_clean = ""
|
||||
if failures >= MAX_FAILURES_IN_A_ROW:
|
||||
_logger.error("Two gates failed in a row; stopping the chain")
|
||||
return EXIT_NOTHING
|
||||
if verdict.stood_down:
|
||||
return EXIT_OK
|
||||
todo = [r for r in verdict.todo if r not in skipped]
|
||||
if not todo:
|
||||
return EXIT_NOTHING if verdict.todo else EXIT_OK
|
||||
rung = todo[0]
|
||||
code = runner(GATE_COMMANDS[rung], _seconds_to_cutoff(now))
|
||||
stop = _stop_code(rung, code)
|
||||
if stop is not None:
|
||||
return stop
|
||||
if code == 0:
|
||||
ran_clean = rung
|
||||
continue
|
||||
_logger.error("%s gate failed with exit %d; skipping it", rung, code)
|
||||
skipped.append(rung)
|
||||
failures += 1
|
||||
|
||||
|
||||
def main(
|
||||
argv: Sequence[str] | None = None,
|
||||
*,
|
||||
sources: Sources | None = None,
|
||||
clock: Clock | None = None,
|
||||
runner: Runner | None = None,
|
||||
) -> int:
|
||||
"""CLI entry. Collaborators are injectable; defaults are production."""
|
||||
parser = argparse.ArgumentParser(prog="python3 -m gatelock.evening_chain")
|
||||
parser.add_argument("command", choices=("pending", "run"))
|
||||
command = parser.parse_args(argv).command
|
||||
handler = logging.StreamHandler(sys.stderr)
|
||||
root = logging.getLogger()
|
||||
root.addHandler(handler)
|
||||
root.setLevel(logging.INFO)
|
||||
try:
|
||||
where = sources if sources is not None else production_sources()
|
||||
now = clock if clock is not None else (lambda: datetime.now(tz=UTC))
|
||||
if command == "pending":
|
||||
return pending(where, now, print)
|
||||
return run(where, now, runner if runner is not None else subprocess_runner)
|
||||
except _ANY_FAILURE:
|
||||
_logger.exception("Evening chain %s failed", command)
|
||||
return EXIT_UNCHECKABLE if command == "pending" else EXIT_NOTHING
|
||||
finally:
|
||||
root.removeHandler(handler)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@ -12,8 +12,6 @@ display).
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@ -186,14 +184,6 @@ def make_arbiter(
|
||||
return arbiter
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_live_focus_project(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""earned_time reads the real focus projects file; no project is active."""
|
||||
monkeypatch.setitem(
|
||||
sys.modules, "focus_project", SimpleNamespace(active=lambda _day: None)
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _release_arbiters() -> Generator[None]:
|
||||
"""Close every claim file a test opened."""
|
||||
|
||||
@ -1,41 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Shared pieces of the error reporter tests: a settable clock, spool lines."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class Clock:
|
||||
"""A settable wall + monotonic clock."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.t = 1_800_000_000.0
|
||||
|
||||
def __call__(self) -> float:
|
||||
return self.t
|
||||
|
||||
|
||||
def spool_lines(tmp_path: Path, app: str = "leetcode-guard") -> list[dict[str, object]]:
|
||||
path = tmp_path / f"{app}.jsonl"
|
||||
if not path.exists():
|
||||
return []
|
||||
return [json.loads(line) for line in path.read_text().splitlines()]
|
||||
|
||||
|
||||
def _boom() -> None:
|
||||
msg = "bad 12"
|
||||
raise ValueError(msg)
|
||||
|
||||
|
||||
def raised() -> BaseException:
|
||||
"""A ValueError carrying a real traceback."""
|
||||
try:
|
||||
_boom()
|
||||
except ValueError as e:
|
||||
return e
|
||||
raise AssertionError
|
||||
@ -1,8 +1,9 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The error reporter's process hooks: excepthooks, Tk callbacks, stalls."""
|
||||
"""The Tk app error and slow-wait reporter: hooks, dedup, spool lines, stalls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import tkinter as tk
|
||||
@ -12,14 +13,25 @@ from unittest.mock import MagicMock
|
||||
import pytest
|
||||
|
||||
from gatelock import error_report
|
||||
from gatelock._error_spool import Reporter
|
||||
from gatelock.tests.errorkit import Clock, raised, spool_lines
|
||||
from gatelock.error_report import Reporter
|
||||
|
||||
DOOR = "_report_exception"
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class Clock:
|
||||
"""A settable wall + monotonic clock."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.t = 1_800_000_000.0
|
||||
|
||||
def __call__(self) -> float:
|
||||
return self.t
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def clock() -> Clock:
|
||||
return Clock()
|
||||
@ -37,12 +49,118 @@ def reporter(tmp_path: Path, clock: Clock) -> Reporter:
|
||||
)
|
||||
|
||||
|
||||
DOOR = "_report_exception"
|
||||
def _lines(tmp_path: Path, app: str = "leetcode-guard") -> list[dict[str, object]]:
|
||||
path = tmp_path / f"{app}.jsonl"
|
||||
if not path.exists():
|
||||
return []
|
||||
return [json.loads(line) for line in path.read_text().splitlines()]
|
||||
|
||||
|
||||
def _key_error() -> None:
|
||||
key = "cb"
|
||||
raise KeyError(key)
|
||||
def _raise() -> BaseException:
|
||||
try:
|
||||
raise ValueError("bad 12") # noqa: EM101, TRY003, TRY301 -- a real traceback for the test
|
||||
except ValueError as e:
|
||||
return e
|
||||
|
||||
|
||||
def test_report_writes_one_entry(reporter: Reporter, tmp_path: Path) -> None:
|
||||
exc = _raise()
|
||||
reporter.report("uncaught.python", exc, exc.__traceback__)
|
||||
(entry,) = _lines(tmp_path)
|
||||
assert entry["kind"] == "uncaught.python"
|
||||
assert entry["error"] == "ValueError: bad 12"
|
||||
assert entry["repo"] == "kuhyx/leetcode-guard"
|
||||
assert entry["mark"] == "leetcode_guard/"
|
||||
assert entry["build"] == 5
|
||||
assert entry["version"] == "0.3.0"
|
||||
assert entry["at"] == "2027-01-15T08:00:00.000Z"
|
||||
stack = entry["stack"]
|
||||
assert isinstance(stack, list)
|
||||
assert "test_error_report.py" in stack[0]
|
||||
assert " in _raise" in stack[0]
|
||||
|
||||
|
||||
def test_identical_errors_within_window_are_dropped(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
for _ in range(5):
|
||||
reporter.report("k", "same")
|
||||
assert len(_lines(tmp_path)) == 1
|
||||
clock.t += Reporter.WINDOW + 1
|
||||
reporter.report("k", "same")
|
||||
assert len(_lines(tmp_path)) == 2
|
||||
|
||||
|
||||
def test_rate_cap_per_minute(reporter: Reporter, tmp_path: Path, clock: Clock) -> None:
|
||||
for i in range(Reporter.MAX_PER_MINUTE + 5):
|
||||
reporter.report("k", f"e{i}")
|
||||
assert len(_lines(tmp_path)) == Reporter.MAX_PER_MINUTE
|
||||
clock.t += 61
|
||||
reporter.report("k", "later")
|
||||
assert len(_lines(tmp_path)) == Reporter.MAX_PER_MINUTE + 1
|
||||
|
||||
|
||||
def test_report_never_raises(reporter: Reporter, tmp_path: Path) -> None:
|
||||
class Bad:
|
||||
def __str__(self) -> str:
|
||||
raise RuntimeError
|
||||
|
||||
reporter.report("k", Bad())
|
||||
(tmp_path / "leetcode-guard.jsonl").mkdir() # an unwritable spool file
|
||||
reporter.report("k", "other")
|
||||
assert True
|
||||
|
||||
|
||||
def test_report_inside_report_is_ignored(reporter: Reporter, tmp_path: Path) -> None:
|
||||
reporter._busy = True
|
||||
reporter.report("k", "x")
|
||||
assert _lines(tmp_path) == []
|
||||
|
||||
|
||||
def test_slow_wait_over_threshold_is_written(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
wait = reporter.begin("coach.load", route="coach")
|
||||
clock.t += 2.0
|
||||
wait.end()
|
||||
wait.end() # repeat ends do nothing
|
||||
(entry,) = _lines(tmp_path)
|
||||
assert entry["kind"] == "perf.slow"
|
||||
assert entry["operation"] == "coach.load"
|
||||
assert entry["durationMs"] == 2000
|
||||
assert entry["route"] == "coach"
|
||||
assert entry["still"] is False
|
||||
assert entry["error"] == "coach.load waited 2000 ms"
|
||||
|
||||
|
||||
def test_fast_wait_writes_nothing(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
with reporter.wait("quick"):
|
||||
clock.t += 0.5
|
||||
assert _lines(tmp_path) == []
|
||||
|
||||
|
||||
def test_still_waiting_is_written_then_the_end(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
wait = reporter.begin("hung")
|
||||
clock.t += 6
|
||||
wait._still()
|
||||
clock.t += 1
|
||||
wait.end()
|
||||
still, end = _lines(tmp_path)
|
||||
assert still["still"] is True
|
||||
assert end["still"] is False
|
||||
assert still["waitId"] == end["waitId"]
|
||||
|
||||
|
||||
def test_slow_rate_cap(reporter: Reporter, tmp_path: Path, clock: Clock) -> None:
|
||||
for _ in range(Reporter.MAX_SLOW_PER_MINUTE + 3):
|
||||
w = reporter.begin("op")
|
||||
clock.t += 1.5
|
||||
w.end()
|
||||
assert len(_lines(tmp_path)) == Reporter.MAX_SLOW_PER_MINUTE
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@ -51,7 +169,7 @@ def hooks() -> Iterator[None]:
|
||||
yield
|
||||
sys.excepthook, threading.excepthook = saved[:2]
|
||||
setattr(tk.Misc, DOOR, saved[2])
|
||||
error_report.INSTALLED.reporter = None
|
||||
error_report._installed = None
|
||||
|
||||
|
||||
def _install(spool: Path) -> Reporter:
|
||||
@ -67,7 +185,7 @@ def test_install_chains_sys_and_thread_hooks(hooks: None, tmp_path: Path) -> Non
|
||||
threading.excepthook = prior_thread
|
||||
rep = _install(tmp_path)
|
||||
assert _install(tmp_path) is rep # idempotent
|
||||
exc = raised()
|
||||
exc = _raise()
|
||||
sys.excepthook(ValueError, exc, exc.__traceback__)
|
||||
prior.assert_called_once()
|
||||
args = MagicMock(
|
||||
@ -75,7 +193,7 @@ def test_install_chains_sys_and_thread_hooks(hooks: None, tmp_path: Path) -> Non
|
||||
)
|
||||
threading.excepthook(args)
|
||||
prior_thread.assert_called_once_with(args)
|
||||
kinds = [e["kind"] for e in spool_lines(tmp_path, "tk-app")]
|
||||
kinds = [e["kind"] for e in _lines(tmp_path, "tk-app")]
|
||||
assert kinds == ["uncaught.python", "uncaught.thread"]
|
||||
|
||||
|
||||
@ -85,7 +203,7 @@ def test_thread_hook_without_value(hooks: None, tmp_path: Path) -> None:
|
||||
threading.excepthook(
|
||||
MagicMock(exc_type=SystemExit, exc_value=None, exc_traceback=None)
|
||||
)
|
||||
assert spool_lines(tmp_path, "tk-app")[0]["error"] == "SystemExit"
|
||||
assert _lines(tmp_path, "tk-app")[0]["error"] == "SystemExit"
|
||||
|
||||
|
||||
def test_install_reports_tk_callback_errors(hooks: None, tmp_path: Path) -> None:
|
||||
@ -94,11 +212,11 @@ def test_install_reports_tk_callback_errors(hooks: None, tmp_path: Path) -> None
|
||||
_install(tmp_path)
|
||||
widget = MagicMock()
|
||||
try:
|
||||
_key_error()
|
||||
raise KeyError("cb") # noqa: EM101, TRY301
|
||||
except KeyError:
|
||||
getattr(tk.Misc, DOOR)(widget)
|
||||
prior.assert_called_once_with(widget)
|
||||
(entry,) = spool_lines(tmp_path, "tk-app")
|
||||
(entry,) = _lines(tmp_path, "tk-app")
|
||||
assert entry["kind"] == "uncaught.tk"
|
||||
assert entry["error"] == "KeyError: 'cb'"
|
||||
|
||||
@ -107,7 +225,18 @@ def test_tk_hook_without_active_exception(hooks: None, tmp_path: Path) -> None:
|
||||
setattr(tk.Misc, DOOR, MagicMock())
|
||||
_install(tmp_path)
|
||||
getattr(tk.Misc, DOOR)(MagicMock())
|
||||
assert spool_lines(tmp_path, "tk-app") == []
|
||||
assert _lines(tmp_path, "tk-app") == []
|
||||
|
||||
|
||||
def test_default_spool_and_mark(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path))
|
||||
rep = Reporter(app="diet-guard", repo="kuhyx/diet-guard")
|
||||
assert rep.spool == tmp_path / "app-errors-spool"
|
||||
assert rep.mark == "diet_guard/"
|
||||
monkeypatch.delenv("XDG_STATE_HOME")
|
||||
assert Reporter(app="a", repo="kuhyx/a").spool.name == "app-errors-spool"
|
||||
|
||||
|
||||
def test_stall_watch_reports_a_frozen_loop(
|
||||
@ -120,7 +249,7 @@ def test_stall_watch_reports_a_frozen_loop(
|
||||
tick() # on time: nothing
|
||||
clock.t += 2.5 # the loop was blocked 2.5 s
|
||||
tick()
|
||||
(entry,) = spool_lines(tmp_path)
|
||||
(entry,) = _lines(tmp_path)
|
||||
assert entry["operation"] == "tk.mainloop"
|
||||
assert entry["durationMs"] == 2500 - error_report.STALL_TICK_MS
|
||||
|
||||
@ -132,3 +261,30 @@ def test_stall_watch_stops_with_the_window(reporter: Reporter, clock: Clock) ->
|
||||
root.after.side_effect = tk.TclError("destroyed")
|
||||
tick() # must not raise
|
||||
assert root.after.call_count == 2
|
||||
|
||||
|
||||
def test_frame_paths(reporter: Reporter) -> None:
|
||||
assert (
|
||||
error_report._short("/x/lib/python3.15/site-packages/gatelock/a.py", "m/")
|
||||
== "gatelock/a.py"
|
||||
)
|
||||
assert error_report._short(
|
||||
"/home/u/src/leetcode-guard/leetcode_guard/ui.py", "leetcode_guard/"
|
||||
) == ("leetcode_guard/ui.py")
|
||||
assert error_report._short("/somewhere/else.py", "m/") == "else.py"
|
||||
|
||||
|
||||
def test_slow_never_raises(reporter: Reporter, tmp_path: Path) -> None:
|
||||
(tmp_path / "leetcode-guard.jsonl").mkdir()
|
||||
reporter.slow("op", 2000, wait_id="w")
|
||||
assert True
|
||||
|
||||
|
||||
def test_still_after_end_does_nothing(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
wait = reporter.begin("op")
|
||||
wait.end()
|
||||
clock.t += 9
|
||||
wait._still()
|
||||
assert _lines(tmp_path) == []
|
||||
|
||||
@ -1,170 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The error reporter's spool writer: entries, dedup, rate caps, waits."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from gatelock import _error_spool
|
||||
from gatelock._error_spool import Reporter
|
||||
from gatelock.tests.errorkit import Clock, raised, spool_lines
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def clock() -> Clock:
|
||||
return Clock()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reporter(tmp_path: Path, clock: Clock) -> Reporter:
|
||||
return Reporter(
|
||||
app="leetcode-guard",
|
||||
repo="kuhyx/leetcode-guard",
|
||||
spool=tmp_path,
|
||||
build=5,
|
||||
version="0.3.0",
|
||||
clock=clock,
|
||||
)
|
||||
|
||||
|
||||
def test_report_writes_one_entry(reporter: Reporter, tmp_path: Path) -> None:
|
||||
exc = raised()
|
||||
reporter.report("uncaught.python", exc, exc.__traceback__)
|
||||
(entry,) = spool_lines(tmp_path)
|
||||
assert entry["kind"] == "uncaught.python"
|
||||
assert entry["error"] == "ValueError: bad 12"
|
||||
assert entry["repo"] == "kuhyx/leetcode-guard"
|
||||
assert entry["mark"] == "leetcode_guard/"
|
||||
assert entry["build"] == 5
|
||||
assert entry["version"] == "0.3.0"
|
||||
assert entry["at"] == "2027-01-15T08:00:00.000Z"
|
||||
stack = entry["stack"]
|
||||
assert isinstance(stack, list)
|
||||
assert stack[0].startswith("__init__.py:")
|
||||
assert " in _boom" in stack[0]
|
||||
|
||||
|
||||
def test_identical_errors_within_window_are_dropped(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
for _ in range(5):
|
||||
reporter.report("k", "same")
|
||||
assert len(spool_lines(tmp_path)) == 1
|
||||
clock.t += Reporter.WINDOW + 1
|
||||
reporter.report("k", "same")
|
||||
assert len(spool_lines(tmp_path)) == 2
|
||||
|
||||
|
||||
def test_rate_cap_per_minute(reporter: Reporter, tmp_path: Path, clock: Clock) -> None:
|
||||
for i in range(Reporter.MAX_PER_MINUTE + 5):
|
||||
reporter.report("k", f"e{i}")
|
||||
assert len(spool_lines(tmp_path)) == Reporter.MAX_PER_MINUTE
|
||||
clock.t += 61
|
||||
reporter.report("k", "later")
|
||||
assert len(spool_lines(tmp_path)) == Reporter.MAX_PER_MINUTE + 1
|
||||
|
||||
|
||||
def test_report_never_raises(reporter: Reporter, tmp_path: Path) -> None:
|
||||
class Bad:
|
||||
def __str__(self) -> str:
|
||||
raise RuntimeError
|
||||
|
||||
reporter.report("k", Bad())
|
||||
(tmp_path / "leetcode-guard.jsonl").mkdir() # an unwritable spool file
|
||||
reporter.report("k", "other")
|
||||
assert True
|
||||
|
||||
|
||||
def test_report_inside_report_is_ignored(reporter: Reporter, tmp_path: Path) -> None:
|
||||
reporter._guard.busy = True
|
||||
reporter.report("k", "x")
|
||||
assert spool_lines(tmp_path) == []
|
||||
|
||||
|
||||
def test_slow_wait_over_threshold_is_written(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
wait = reporter.begin("coach.load", route="coach")
|
||||
clock.t += 2.0
|
||||
wait.end()
|
||||
wait.end() # repeat ends do nothing
|
||||
(entry,) = spool_lines(tmp_path)
|
||||
assert entry["kind"] == "perf.slow"
|
||||
assert entry["operation"] == "coach.load"
|
||||
assert entry["durationMs"] == 2000
|
||||
assert entry["route"] == "coach"
|
||||
assert entry["still"] is False
|
||||
assert entry["error"] == "coach.load waited 2000 ms"
|
||||
|
||||
|
||||
def test_fast_wait_writes_nothing(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
with reporter.wait("quick"):
|
||||
clock.t += 0.5
|
||||
assert spool_lines(tmp_path) == []
|
||||
|
||||
|
||||
def test_still_waiting_is_written_then_the_end(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
wait = reporter.begin("hung")
|
||||
clock.t += 6
|
||||
wait._still()
|
||||
clock.t += 1
|
||||
wait.end()
|
||||
still, end = spool_lines(tmp_path)
|
||||
assert still["still"] is True
|
||||
assert end["still"] is False
|
||||
assert still["waitId"] == end["waitId"]
|
||||
|
||||
|
||||
def test_slow_rate_cap(reporter: Reporter, tmp_path: Path, clock: Clock) -> None:
|
||||
for _ in range(Reporter.MAX_SLOW_PER_MINUTE + 3):
|
||||
w = reporter.begin("op")
|
||||
clock.t += 1.5
|
||||
w.end()
|
||||
assert len(spool_lines(tmp_path)) == Reporter.MAX_SLOW_PER_MINUTE
|
||||
|
||||
|
||||
def test_default_spool_and_mark(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path))
|
||||
rep = Reporter(app="diet-guard", repo="kuhyx/diet-guard")
|
||||
assert rep.spool == tmp_path / "app-errors-spool"
|
||||
assert rep.mark == "diet_guard/"
|
||||
monkeypatch.delenv("XDG_STATE_HOME")
|
||||
assert Reporter(app="a", repo="kuhyx/a").spool.name == "app-errors-spool"
|
||||
|
||||
|
||||
def test_frame_paths(reporter: Reporter) -> None:
|
||||
assert (
|
||||
_error_spool._short("/x/lib/python3.15/site-packages/gatelock/a.py", "m/")
|
||||
== "gatelock/a.py"
|
||||
)
|
||||
assert _error_spool._short(
|
||||
"/home/u/src/leetcode-guard/leetcode_guard/ui.py", "leetcode_guard/"
|
||||
) == ("leetcode_guard/ui.py")
|
||||
assert _error_spool._short("/somewhere/else.py", "m/") == "else.py"
|
||||
|
||||
|
||||
def test_slow_never_raises(reporter: Reporter, tmp_path: Path) -> None:
|
||||
(tmp_path / "leetcode-guard.jsonl").mkdir()
|
||||
reporter.slow("op", 2000, wait_id="w")
|
||||
assert True
|
||||
|
||||
|
||||
def test_still_after_end_does_nothing(
|
||||
reporter: Reporter, tmp_path: Path, clock: Clock
|
||||
) -> None:
|
||||
wait = reporter.begin("op")
|
||||
wait.end()
|
||||
clock.t += 9
|
||||
wait._still()
|
||||
assert spool_lines(tmp_path) == []
|
||||
@ -1,64 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The chain's process edges: gate subprocesses, production paths, the unit."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from gatelock import evening_chain as chain
|
||||
|
||||
|
||||
def test_subprocess_runner_returns_the_exit_code_with_the_timeout() -> None:
|
||||
done = SimpleNamespace(returncode=7)
|
||||
with mock.patch("gatelock.evening_chain.subprocess.run", return_value=done) as run:
|
||||
assert chain.subprocess_runner(("gate", "--x"), 12.5) == 7
|
||||
run.assert_called_once_with(("gate", "--x"), check=False, timeout=12.5)
|
||||
|
||||
|
||||
def test_subprocess_runner_deadline_is_none() -> None:
|
||||
expired = subprocess.TimeoutExpired(("gate",), 1)
|
||||
with mock.patch("gatelock.evening_chain.subprocess.run", side_effect=expired):
|
||||
assert chain.subprocess_runner(("gate",), 1) is None
|
||||
|
||||
|
||||
def test_subprocess_runner_unstartable_gate_is_a_failure() -> None:
|
||||
with mock.patch("gatelock.evening_chain.subprocess.run", side_effect=OSError):
|
||||
assert chain.subprocess_runner(("gate",), 1) == 127
|
||||
|
||||
|
||||
def test_production_sources_names_the_real_key_and_home() -> None:
|
||||
sources = chain.production_sources()
|
||||
assert str(sources.key_file) == "/etc/workout-locker/hmac.key"
|
||||
assert sources.home == Path.home()
|
||||
assert sources.free_log is None
|
||||
assert sources.sick_log is None
|
||||
|
||||
|
||||
def test_module_entry_point_rejects_an_unknown_command() -> None:
|
||||
with (
|
||||
pytest.warns(RuntimeWarning),
|
||||
pytest.raises(SystemExit) as raised,
|
||||
mock.patch.object(sys, "argv", ["evening_chain", "bogus"]),
|
||||
):
|
||||
runpy.run_module("gatelock.evening_chain", run_name="__main__")
|
||||
assert raised.value.code == 2
|
||||
|
||||
|
||||
UNIT = Path(__file__).parents[2] / "systemd" / "evening-gates.service"
|
||||
|
||||
|
||||
def test_unit_matches_the_contract() -> None:
|
||||
lines = UNIT.read_text(encoding="utf-8").splitlines()
|
||||
assert "Type=simple" in lines
|
||||
assert "Restart=no" in lines
|
||||
assert "Environment=DISPLAY=:0" in lines
|
||||
assert "Environment=XAUTHORITY=%h/.Xauthority" in lines
|
||||
assert "ExecStart=/usr/bin/python3 -m gatelock.evening_chain run" in lines
|
||||
assert "[Install]" not in lines
|
||||
@ -1,222 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""``evening_chain pending``: which rungs are unpaid, and its exit code."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from gatelock import RANK_DIET_GUARD, RANK_SCREEN_LOCKER
|
||||
from gatelock import evening_chain as chain
|
||||
from gatelock._arbiter import RANK_EVENING_GATE
|
||||
from gatelock.tests.test_evening_rows import (
|
||||
DAY,
|
||||
EVENING,
|
||||
LATE,
|
||||
leetcode_row,
|
||||
mark_free,
|
||||
mark_sick,
|
||||
pay_all,
|
||||
seeded,
|
||||
settled_row,
|
||||
tutor_row,
|
||||
write_ledger,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _run(sources: chain.Sources, now: datetime) -> tuple[int, str]:
|
||||
out: list[str] = []
|
||||
code = chain.pending(sources, lambda: now, out.append)
|
||||
return code, " ".join(out)
|
||||
|
||||
|
||||
def test_constants_follow_the_contract() -> None:
|
||||
assert chain.EXIT_END_EVENING == 10
|
||||
assert chain.EXIT_NO_X == 3
|
||||
assert chain.CHAIN == ("reading", "tutor", "leetcode")
|
||||
assert chain.CUTOFF.hour == 23
|
||||
|
||||
|
||||
def test_evening_gate_ranks_between_diet_guard_and_screen_locker() -> None:
|
||||
assert RANK_EVENING_GATE == 150
|
||||
assert RANK_DIET_GUARD < RANK_EVENING_GATE < RANK_SCREEN_LOCKER
|
||||
|
||||
|
||||
def test_nothing_paid_lists_every_rung_exit_0(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
write_ledger(sources, "reading", [])
|
||||
write_ledger(sources, "tutor", [])
|
||||
write_ledger(sources, "leetcode", [])
|
||||
assert _run(sources, EVENING) == (0, "reading tutor leetcode")
|
||||
|
||||
|
||||
def test_everything_paid_is_exit_1(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
assert _run(sources, EVENING) == (1, "")
|
||||
|
||||
|
||||
def test_paid_rungs_are_skipped(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "tutor", [tutor_row(14)]) # 14 min < the 15 quota
|
||||
assert _run(sources, EVENING) == (0, "tutor")
|
||||
|
||||
|
||||
def test_tutor_is_quota_based_not_done_today(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "tutor", [tutor_row(15)])
|
||||
assert _run(sources, EVENING)[0] == 1
|
||||
write_ledger(sources, "tutor", [tutor_row(1)])
|
||||
assert _run(sources, EVENING) == (0, "tutor")
|
||||
|
||||
|
||||
def test_free_day_stands_down(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
mark_free(sources)
|
||||
assert _run(sources, EVENING) == (1, "")
|
||||
|
||||
|
||||
def test_sick_day_stands_down(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
mark_sick(sources)
|
||||
assert _run(sources, EVENING) == (1, "")
|
||||
|
||||
|
||||
def test_from_23_00_nothing_is_pending(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
assert _run(sources, LATE) == (1, "")
|
||||
|
||||
|
||||
def test_unreadable_ledger_fails_closed(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
path = write_ledger(sources, "leetcode", [leetcode_row()])
|
||||
path.write_text("{not json", encoding="utf-8")
|
||||
assert _run(sources, EVENING) == (2, "")
|
||||
|
||||
|
||||
def test_missing_key_fails_closed(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
sources.key_file.unlink()
|
||||
assert _run(sources, EVENING)[0] == 2
|
||||
|
||||
|
||||
def test_unreadable_rung_wins_over_unpaid_one(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
write_ledger(sources, "reading", [])
|
||||
write_ledger(sources, "leetcode", [leetcode_row()]).write_text("x")
|
||||
assert _run(sources, EVENING)[0] == 2
|
||||
|
||||
|
||||
def test_exception_in_the_check_is_exit_2_and_logged(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
def boom(_day: object) -> None:
|
||||
msg = "registry exploded"
|
||||
raise RuntimeError(msg)
|
||||
|
||||
monkeypatch.setattr("earned_time.earners_for", boom)
|
||||
code = chain.main(["pending"], sources=seeded(tmp_path), clock=lambda: EVENING)
|
||||
assert code == 2
|
||||
assert "registry exploded" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_main_pending_prints_rungs_on_stdout(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "reading", [])
|
||||
assert chain.main(["pending"], sources=sources, clock=lambda: EVENING) == 0
|
||||
assert capsys.readouterr().out.strip() == "reading"
|
||||
|
||||
|
||||
def test_a_reader_that_raises_is_unchecked_exit_2(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
|
||||
def boom(*_args: object, **_kwargs: object) -> None:
|
||||
msg = "no shared reader"
|
||||
raise ValueError(msg)
|
||||
|
||||
monkeypatch.setattr("earned_time.done_today", boom)
|
||||
assert _run(sources, EVENING) == (2, "")
|
||||
|
||||
|
||||
def test_a_rung_the_registry_dropped_is_not_asked(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
import earned_time
|
||||
|
||||
sources = seeded(tmp_path)
|
||||
write_ledger(sources, "leetcode", [])
|
||||
kept = tuple(e for e in earned_time.earners_for(DAY) if e.name != "reading")
|
||||
monkeypatch.setattr("earned_time.earners_for", lambda _day: kept)
|
||||
assert _run(sources, EVENING) == (0, "tutor leetcode")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", ["escape", "outage"])
|
||||
def test_a_settled_leetcode_day_is_unpayable_so_not_pending(
|
||||
tmp_path: Path, source: str
|
||||
) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "leetcode", [settled_row(source)])
|
||||
assert _run(sources, EVENING) == (1, "")
|
||||
|
||||
|
||||
def test_a_settled_leetcode_day_leaves_the_other_rungs(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
write_ledger(sources, "reading", [])
|
||||
write_ledger(sources, "tutor", [])
|
||||
write_ledger(sources, "leetcode", [settled_row("escape")])
|
||||
assert _run(sources, EVENING) == (0, "reading tutor")
|
||||
|
||||
|
||||
def test_yesterdays_charge_does_not_settle_today(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
yesterday = DAY - timedelta(days=1)
|
||||
write_ledger(sources, "leetcode", [settled_row("escape", yesterday)])
|
||||
assert _run(sources, EVENING) == (0, "leetcode")
|
||||
|
||||
|
||||
def test_an_unsigned_charge_does_not_settle_the_day(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
forged = {**settled_row("escape"), "hmac": "0" * 64}
|
||||
write_ledger(sources, "leetcode", [forged])
|
||||
assert _run(sources, EVENING) == (0, "leetcode")
|
||||
|
||||
|
||||
def test_a_plain_unpaid_leetcode_day_is_still_pending(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "leetcode", [])
|
||||
assert _run(sources, EVENING) == (0, "leetcode")
|
||||
|
||||
|
||||
def test_a_settled_check_that_cannot_verify_is_exit_2(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "leetcode", [settled_row("escape")])
|
||||
|
||||
def boom(*_args: object) -> bool:
|
||||
msg = "cannot verify"
|
||||
raise ValueError(msg)
|
||||
|
||||
monkeypatch.setattr("earned_time.verified", boom)
|
||||
assert _run(sources, EVENING) == (2, "")
|
||||
@ -1,116 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""Seeded state for the evening-chain tests: tmp ledgers signed with a tmp key.
|
||||
|
||||
Nothing here names a production path. ``seeded`` builds a ``Sources`` whose
|
||||
home, key, free-day pool and sick-day pool all live under ``tmp_path``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import earned_time
|
||||
from earned_time import entry_signature
|
||||
import freedays
|
||||
import sickdays
|
||||
|
||||
from gatelock.evening_chain import Sources
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
|
||||
KEY = b"evening-test-key"
|
||||
DAY = date(2026, 11, 17) # a Tuesday: the tutor's workday quota is 15 minutes
|
||||
EVENING = datetime(2026, 11, 17, 20, 30).astimezone()
|
||||
LATE = datetime(2026, 11, 17, 23, 0).astimezone()
|
||||
LEDGERS = {
|
||||
"reading": earned_time.READING,
|
||||
"tutor": earned_time.TUTOR,
|
||||
"leetcode": earned_time.LEETCODE,
|
||||
}
|
||||
|
||||
|
||||
def stamp(hour: int = 19) -> float:
|
||||
"""A unix time on DAY, local."""
|
||||
return datetime.combine(DAY, time(hour)).astimezone().timestamp()
|
||||
|
||||
|
||||
def _signed(row: Mapping[str, object]) -> dict[str, object]:
|
||||
return {**row, "hmac": entry_signature(row, KEY)}
|
||||
|
||||
|
||||
def reading_row() -> dict[str, object]:
|
||||
"""A reading credit that earned the bonus today."""
|
||||
detail = {"bonus": "1", "ended_at": stamp()}
|
||||
return _signed({"kind": "credit", "entry_id": "r1", "detail": detail})
|
||||
|
||||
|
||||
def leetcode_row() -> dict[str, object]:
|
||||
"""The charge LeetCode writes once today's price is covered by solves."""
|
||||
detail = {"source": "leetcode"}
|
||||
row = {"kind": "charge", "entry_id": "l1", "day": DAY.isoformat(), "detail": detail}
|
||||
return _signed(row)
|
||||
|
||||
|
||||
def settled_row(source: str, day: date = DAY) -> dict[str, object]:
|
||||
"""A non-paying charge: the day settled by escape hatch or outage."""
|
||||
row = {
|
||||
"kind": "charge",
|
||||
"entry_id": f"charge:{day.isoformat()}",
|
||||
"day": day.isoformat(),
|
||||
"detail": {"source": source},
|
||||
}
|
||||
return _signed(row)
|
||||
|
||||
|
||||
def tutor_row(minutes: int) -> dict[str, object]:
|
||||
"""``minutes`` of tutoring ending today."""
|
||||
detail = {"minutes": minutes, "ended_at": stamp()}
|
||||
row = {"kind": "credit", "entry_id": f"s-m{minutes}", "detail": detail}
|
||||
return _signed({**row, "day": DAY.isoformat()})
|
||||
|
||||
|
||||
def write_ledger(sources: Sources, rung: str, rows: list[dict[str, object]]) -> Path:
|
||||
"""Write ``rows`` as ``rung``'s ledger under the tmp home."""
|
||||
path = sources.home / str(LEDGERS[rung].ledger)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps({"entries": rows}), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def seeded(tmp_path: Path) -> Sources:
|
||||
"""Empty sources: key present, no ledgers, no free or sick day."""
|
||||
key = tmp_path / "hmac.key"
|
||||
key.write_bytes(KEY)
|
||||
return Sources(
|
||||
home=tmp_path / "home",
|
||||
key_file=key,
|
||||
free_log=tmp_path / "free" / "free_days.json",
|
||||
sick_log=tmp_path / "sick" / "sick_days.json",
|
||||
)
|
||||
|
||||
|
||||
def pay_all(sources: Sources) -> None:
|
||||
"""Every rung paid today."""
|
||||
write_ledger(sources, "reading", [reading_row()])
|
||||
write_ledger(sources, "tutor", [tutor_row(15)])
|
||||
write_ledger(sources, "leetcode", [leetcode_row()])
|
||||
|
||||
|
||||
def mark_free(sources: Sources) -> None:
|
||||
"""Make DAY a free day in the tmp pool."""
|
||||
assert sources.free_log is not None
|
||||
paths = freedays.Paths.under(sources.free_log.parent)
|
||||
sources.free_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
freedays.mark(DAY, paths=paths, now=DAY)
|
||||
|
||||
|
||||
def mark_sick(sources: Sources) -> None:
|
||||
"""Make DAY a sick day in the tmp pool."""
|
||||
assert sources.sick_log is not None
|
||||
paths = sickdays.Paths.under(sources.sick_log.parent)
|
||||
sources.sick_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
sickdays.add_sick_day(DAY, paths=paths, is_free=lambda _day: False, now=DAY)
|
||||
@ -1,204 +0,0 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""``evening_chain run``: order, skipping, exit codes, no spinning."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import os
|
||||
from pathlib import Path
|
||||
import pwd
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import evening_chain as chain
|
||||
from gatelock.tests.test_evening_rows import (
|
||||
EVENING,
|
||||
leetcode_row,
|
||||
pay_all,
|
||||
reading_row,
|
||||
seeded,
|
||||
settled_row,
|
||||
tutor_row,
|
||||
write_ledger,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
import pytest
|
||||
|
||||
CMD_OF = {tuple(cmd): rung for rung, cmd in chain.GATE_COMMANDS.items()}
|
||||
|
||||
|
||||
class FakeGates:
|
||||
"""Runner stand-in: records the rung run, pays it, returns scripted codes."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sources: chain.Sources,
|
||||
codes: dict[str, list[int | None]] | None = None,
|
||||
) -> None:
|
||||
self.sources = sources
|
||||
self.codes = codes or {}
|
||||
self.ran: list[str] = []
|
||||
self.timeouts: list[float] = []
|
||||
|
||||
def __call__(self, cmd: Sequence[str], timeout_s: float) -> int | None:
|
||||
rung = CMD_OF[tuple(cmd)]
|
||||
self.ran.append(rung)
|
||||
self.timeouts.append(timeout_s)
|
||||
script = self.codes.get(rung)
|
||||
code = script.pop(0) if script else 0
|
||||
if code == 0:
|
||||
pays = {"reading": reading_row, "leetcode": leetcode_row}
|
||||
rows = [tutor_row(15)] if rung == "tutor" else [pays[rung]()]
|
||||
write_ledger(self.sources, rung, rows)
|
||||
return code
|
||||
|
||||
|
||||
def _run(
|
||||
sources: chain.Sources,
|
||||
gates: Callable[[Sequence[str], float], int | None],
|
||||
now: datetime = EVENING,
|
||||
) -> int:
|
||||
return chain.run(sources, lambda: now, gates)
|
||||
|
||||
|
||||
def test_gate_commands_match_the_contract() -> None:
|
||||
py = "/usr/bin/python3"
|
||||
expected = {
|
||||
"reading": (py, "-m", "book_guard", "lock", "--production", "--evening"),
|
||||
"tutor": (py, "-m", "tutor.gate", "--production", "--evening"),
|
||||
"leetcode": (py, "-m", "leetcode_guard", "--production", "--evening"),
|
||||
}
|
||||
assert expected == chain.GATE_COMMANDS
|
||||
|
||||
|
||||
def test_runs_book_then_tutor_then_leetcode(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
gates = FakeGates(sources)
|
||||
assert _run(sources, gates) == 0
|
||||
assert gates.ran == ["reading", "tutor", "leetcode"]
|
||||
|
||||
|
||||
def test_paid_rungs_are_skipped(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "tutor", [])
|
||||
gates = FakeGates(sources)
|
||||
assert _run(sources, gates) == 0
|
||||
assert gates.ran == ["tutor"]
|
||||
|
||||
|
||||
def test_nothing_pending_runs_nothing(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
gates = FakeGates(sources)
|
||||
assert _run(sources, gates) == 0
|
||||
assert gates.ran == []
|
||||
|
||||
|
||||
def test_exit_10_stops_the_chain_with_exit_0(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
gates = FakeGates(sources, {"tutor": [10]})
|
||||
assert _run(sources, gates) == 0
|
||||
assert gates.ran == ["reading", "tutor"]
|
||||
|
||||
|
||||
def test_exit_3_no_x_is_exit_3_at_once(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
gates = FakeGates(sources, {"reading": [3]})
|
||||
assert _run(sources, gates) == 3
|
||||
assert gates.ran == ["reading"]
|
||||
|
||||
|
||||
def test_one_failing_gate_is_skipped_and_the_rest_run(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
gates = FakeGates(sources, {"reading": [7]})
|
||||
assert _run(sources, gates) == 1 # reading stays unpaid
|
||||
assert gates.ran == ["reading", "tutor", "leetcode"]
|
||||
|
||||
|
||||
def test_two_failures_in_a_row_stop_with_exit_1(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
gates = FakeGates(sources, {"reading": [7], "tutor": [9]})
|
||||
assert _run(sources, gates) == 1
|
||||
assert gates.ran == ["reading", "tutor"]
|
||||
|
||||
|
||||
def test_a_gate_that_exits_0_unpaid_never_spins(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
calls: list[str] = []
|
||||
|
||||
def liar(cmd: Sequence[str], timeout_s: float) -> int | None:
|
||||
calls.append(CMD_OF[tuple(cmd)])
|
||||
return 0 if len(calls) < 50 else 99 # pays nothing
|
||||
|
||||
assert _run(sources, liar) == 1
|
||||
assert calls == ["reading", "tutor"]
|
||||
|
||||
|
||||
def test_stops_at_23_00_without_running_a_gate(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
gates = FakeGates(sources)
|
||||
assert _run(sources, gates, EVENING.replace(hour=23, minute=0)) == 0
|
||||
assert gates.ran == []
|
||||
|
||||
|
||||
def test_gate_is_bounded_by_the_23_00_cutoff(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
gates = FakeGates(sources, {"reading": [None]}) # timed out at the deadline
|
||||
assert _run(sources, gates) == 0
|
||||
assert gates.ran == ["reading"]
|
||||
assert gates.timeouts == [timedelta(hours=2, minutes=30).total_seconds()]
|
||||
|
||||
|
||||
def test_unchecked_rung_still_gets_its_gate(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "leetcode", []).write_text("{bad")
|
||||
gates = FakeGates(sources, {"leetcode": [7]})
|
||||
assert _run(sources, gates) == 1
|
||||
assert gates.ran == ["leetcode"]
|
||||
|
||||
|
||||
def test_main_run_uses_the_injected_runner(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
gates = FakeGates(sources)
|
||||
code = chain.main(["run"], sources=sources, clock=lambda: EVENING, runner=gates)
|
||||
assert code == 0
|
||||
assert gates.ran == []
|
||||
|
||||
|
||||
def test_run_failing_to_evaluate_is_exit_1(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
def boom(_day: object) -> None:
|
||||
msg = "registry exploded"
|
||||
raise RuntimeError(msg)
|
||||
|
||||
monkeypatch.setattr("earned_time.earners_for", boom)
|
||||
gates = FakeGates(seeded(tmp_path))
|
||||
code = chain.main(
|
||||
["run"], sources=seeded(tmp_path), clock=lambda: EVENING, runner=gates
|
||||
)
|
||||
assert code == 1
|
||||
assert gates.ran == []
|
||||
|
||||
|
||||
def test_live_ledgers_are_untouched_by_a_run(tmp_path: Path) -> None:
|
||||
home = Path(pwd.getpwuid(os.getuid()).pw_dir)
|
||||
live = sorted((home / ".local" / "share").glob("*/ledger.json"))
|
||||
before = [(p, p.stat().st_mtime_ns) for p in live]
|
||||
sources = seeded(tmp_path)
|
||||
assert _run(sources, FakeGates(sources)) == 0
|
||||
assert [(p, p.stat().st_mtime_ns) for p in live] == before
|
||||
|
||||
|
||||
def test_a_settled_leetcode_day_never_runs_its_gate(tmp_path: Path) -> None:
|
||||
sources = seeded(tmp_path)
|
||||
pay_all(sources)
|
||||
write_ledger(sources, "leetcode", [settled_row("outage")])
|
||||
gates = FakeGates(sources)
|
||||
assert _run(sources, gates) == 0
|
||||
assert gates.ran == []
|
||||
@ -1,28 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Install the evening-gates user unit. Idempotent; never enables or starts it:
|
||||
# root's shutdown check starts it on demand (see evening_chain.py).
|
||||
set -euo pipefail
|
||||
|
||||
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly REPO_DIR
|
||||
readonly UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
|
||||
readonly SYSTEM_PYTHON="/usr/bin/python3"
|
||||
|
||||
fail() {
|
||||
echo "install_evening_gates: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
main() {
|
||||
[[ $EUID -ne 0 ]] || fail "run as kuhy, not root (it is a user unit)"
|
||||
"$SYSTEM_PYTHON" -c "import gatelock.evening_chain, earned_time, freedays, sickdays" \
|
||||
|| fail "the system python cannot import gatelock.evening_chain and its readers"
|
||||
mkdir -p "$UNIT_DIR"
|
||||
install -m 644 "$REPO_DIR/systemd/evening-gates.service" "$UNIT_DIR/"
|
||||
systemctl --user daemon-reload
|
||||
systemd-analyze --user verify "$UNIT_DIR/evening-gates.service" \
|
||||
|| fail "evening-gates.service does not verify"
|
||||
echo "installed $UNIT_DIR/evening-gates.service (not enabled, not started)"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "gatelock"
|
||||
version = "0.16.0"
|
||||
version = "0.15.0"
|
||||
description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [] # pure stdlib — tkinter is bundled with Python
|
||||
@ -16,15 +16,6 @@ dependencies = [] # pure stdlib — tkinter is bundled with Python
|
||||
# because a dependency is missing is itself a way to end up unlocked.
|
||||
# Consumers' install scripts install it unconditionally all the same.
|
||||
randr = ["python-xlib==0.33"]
|
||||
# The evening gate chain (gatelock.evening_chain) reads the signed ledgers and
|
||||
# the free/sick-day pools. Optional for the same reason as randr: a locker
|
||||
# must not refuse to start over a missing dependency, and only the chain's
|
||||
# own CLI imports these (lazily). Pins match book-guard / leetcode-guard.
|
||||
evening = [
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time",
|
||||
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays",
|
||||
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.5#subdirectory=sickdays",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["gatelock*"]
|
||||
@ -123,8 +114,6 @@ ignore = [".venv", "__pycache__"]
|
||||
# paths, so a directory name in `ignore` never fires under the hook.
|
||||
ignore-paths = ["^(.*/)?tests/.*$"]
|
||||
ignore-patterns = [".*\\.pyi$"]
|
||||
# The evening chain reads these siblings; the pre-commit pylint env has none.
|
||||
ignored-modules = ["earned_time", "freedays", "sickdays"]
|
||||
|
||||
[tool.pylint.messages_control]
|
||||
enable = "all"
|
||||
|
||||
@ -1,16 +0,0 @@
|
||||
[Unit]
|
||||
Description=Evening gate chain: book, tutor, LeetCode before night lockdown
|
||||
After=graphical-session.target
|
||||
|
||||
# Started by root's day-specific-shutdown-check (systemctl --user -M kuhy@
|
||||
# start) when `python3 -m gatelock.evening_chain pending` exits 0. There is no
|
||||
# timer and no [Install]: arming it any other way would put a gate up on a day
|
||||
# nobody asked for one.
|
||||
[Service]
|
||||
Type=simple
|
||||
Environment=DISPLAY=:0
|
||||
Environment=XAUTHORITY=%h/.Xauthority
|
||||
ExecStart=/usr/bin/python3 -m gatelock.evening_chain run
|
||||
# A stopped or finished chain stays stopped: root reads "inactive after it was
|
||||
# started tonight" as "kuhy ended the evening" and enters lockdown.
|
||||
Restart=no
|
||||
@ -70,11 +70,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: crdt_sync_flutter
|
||||
ref: "crdt_sync_flutter-v0.9.0"
|
||||
resolved-ref: dfc5d07f5225ed15609f9709748ed2efd6cc4d1d
|
||||
ref: "crdt_sync_flutter-v0.8.2"
|
||||
resolved-ref: "1962d303336dfe260850466b8ee841033b9ad1ce"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.9.0"
|
||||
version: "0.8.2"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -332,10 +332,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: material_ui
|
||||
sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab
|
||||
sha256: "474c135fd46b56ff1d35ca982155e8863d28fbc6464d1192acf4ee53a738680e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.11.1"
|
||||
version: "1.11.0"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@ -18,7 +18,7 @@ dependencies:
|
||||
crdt_sync_flutter:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: crdt_sync_flutter-v0.9.0
|
||||
ref: crdt_sync_flutter-v0.8.2
|
||||
path: crdt_sync_flutter
|
||||
flutter:
|
||||
sdk: flutter
|
||||
|
||||
Loading…
Reference in New Issue
Block a user