blib/lib/App/karr/Role/TaskMutation.pm

filter: Statementstmt 90.4% 19 / 21 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.8% 26 / 28 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/App/karr/Cmd/Restore.pm ↑ Summary blib/lib/App/karr/Cmd/Context.pm »
1 # ABSTRACT: The one guarded path for changing an existing task
2  
3 package App::karr::Role::TaskMutation;
4 our $VERSION = '0.602';
5 1 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 # No Time::Piece here on purpose: this role never asks for the time itself --
7 # the lifecycle stamps are set by App::karr::Task::update_timestamps, which
8 # loads its own -- and `use Time::Piece;` composed its localtime/gmtime
9 # replacements into move, edit, delete, archive and handoff for nothing (#105).
10 1 ▶use App::karr::Task;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use App::karr::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 # Loaded without importing, for the reason spelled out in
13 # App::karr::Role::Output: a Moo::Role composes every sub in its package into
14 # its consumers, imported ones included, so `use ... qw( user_error )` here
15 # would quietly make user_error a method on move, edit, delete, archive and
16 # handoff.
17 1 ▶use App::karr::Error ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 # Same reason, one module over: `use Scalar::Util qw( refaddr );` here would put
19 # a refaddr method on every command that composes this role.
20 1 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use App::karr::Role::ClaimTimeout;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 0 ▶use App::karr::Role::DependencyCheck;
Subroutine BEGIN: called CC=1 SCAR=2.6
23  
24 with 'App::karr::Role::ClaimTimeout', 'App::karr::Role::DependencyCheck';
25  
26 # What this role calls on its consumer, said out loud (ticket #141; the rule is
27 # ticket #128's). It declared nothing at all until then, and got away with it
28 # only because every command on the mutation path composes the roles that supply
29 # these: git and store from App::karr::Role::BoardDiscovery, save_task and
30 # log_task_write from App::karr::Role::BoardAccess, json from
31 # App::karr::Role::Output. Same accident App::karr::Role::DependencyCheck lived
32 # on before #128, one module over -- and a worse one to leave standing, because
33 # this role is how a command reaches update_task_guarded without ever naming the
34 # collaborators that path needs.
35 #
36 # Two of the calls below are deliberately not on the list: check_claim and
37 # check_dependencies come from the two roles composed above, so they are this
38 # role's own methods and not the consumer's. Requiring one of them would be
39 # worse than redundant -- it could never fail. Role::Tiny installs a role's
40 # methods into the consumer *before* it checks the requires
41 # (role_application_steps), so the check would find the name the composition had
42 # just put there, in every consumer, always, and read as a guarantee that is not
43 # one.
44 #
45 # json is declared here and on App::karr::Role::DependencyCheck both. The
46 # duplication is intended: run_batch reads $self->json for its own per-id
47 # warnings, and a role that lets a role it happens to compose declare a
48 # collaborator on its behalf is the arrangement this ticket is about.
49 requires qw( git store save_task log_task_write json );
50  
51  
52 # One batch loop for every command that takes ID[,ID,...].
53 #
54 # `move`, `edit` and `delete` used to die on the first missing id from inside
55 # the loop, which skipped every id after it: `move 1,999,2` moved 1 and never
56 # looked at 2, while `move 999,1,2` moved nothing. Which ids survived depended
57 # on where the bad one sat in the list. `archive` was the only one that already
58 # warned and carried on, and it is the shape ADR 0002 settled on: "partial
59 # success is committed, the exit code reports the failure (1)" -- the same
60 # contract as kanban-md's runBatch (cmd/root.go), which attempts every id,
61 # prints the per-id failures, and still returns 1 if any of them failed
62 # (ticket #61).
63 #
64 # A usage error is deliberately NOT a per-id failure. `move 1,2,3 bogus-status`
65 # is wrong for every id at once, so it aborts the batch untouched and keeps its
66 # exit code of 2 (ticket #54's rule): collecting it would report the same
67 # message once per id and demote the exit code to 1, which is precisely the
68 # distinction the exit-code contract exists to make. The markers come from
69 # App::karr::Error rather than a second copy of bin/karr's list, so a new marker
70 # on either side cannot silently reclassify a batch.
71 sub run_batch {
72 my ($self, $ids, $per_id) = @_;
73  
74 my @results;
75 my $failed = 0;
76  
77 for my $id (@$ids) {
78 my @out;
79 my $err = do {
80 local $@;
81 eval { @out = $per_id->($id); 1 } ? undef : ( $@ || 'unknown error' );
82 };
83  
84 if ( defined $err ) {
85 die $err if App::karr::Error::is_usage_error($err);
86 $failed++;
87 my $line = App::karr::Error::clean_error($err);
88 # A suggestion block (App::karr::Error/command_hint) belongs to the
89 # STDERR text a person or an agent reads off the terminal, not to
90 # the --json payload: `error` has been exactly one line for as long
91 # as it has existed, and a reader of it is scripting this CLI
92 # already and has no use for a shell line to copy (ticket k263).
93 my ($json_line) = split /\n/, $line, 2;
94 # The colon on the prose line is there to introduce the suggestion.
95 # With the suggestion gone it introduces nothing, so it goes too.
96 $json_line =~ s/:\z// unless $json_line eq $line;
97 # The id is echoed as a number when it is one, so an agent reading
98 # --json gets the same type it passed in -- and a non-numeric id
99 # does not add "Argument isn't numeric" to the diagnosis of what is
100 # already an error.
101 push @results,
102 { id => ( $id =~ /\A[0-9]+\z/ ? $id + 0 : $id ), error => $json_line };
103 warn "$line\n" unless $self->json;
104 next;
105 }
106  
107 push @results, @out;
108 }
109  
110 return ( \@results, $failed );
111 }
112  
113  
114 sub report_batch_failure {
115 my ($self, $failed, $total) = @_;
116 return 0 unless $failed;
117 # After the successful ids are committed and pushed, never instead of them.
118 # A die rather than an exit: bin/karr's handler turns it into the 1 the
119 # contract calls for, and an in-process caller gets an exception instead of
120 # having its interpreter shot out from under it.
121 App::karr::Error::user_error( sprintf '%d of %d ids failed', $failed, $total );
122 }
123  
124  
125 # The canonical location of a task. BoardStore and App::karr::Git build the
126 # same string; this role needs it directly because it reads the OID and the
127 # content together (App::karr::Git::read_ref_with_oid), which is the pair a
128 # compare-and-swap has to guard against, and no BoardStore method hands both
129 # back.
130 sub _task_data_ref {
131 my ($self, $id) = @_;
132 return "refs/karr/tasks/$id/data";
133 }
134  
135 # The one way a callback can say "there is nothing here to write". A
136 # package-lexical scalar ref, compared by address, because the callbacks on
137 # this path return whatever their last statement happened to evaluate to -- a
138 # title, a status, the result of a clearer -- and no value a caller can
139 # construct by accident is this one.
140 #
141 # The address is read with Scalar::Util::refaddr, which is how identity is
142 # asked in this distribution (App::karr::SyncGuard keys its registry of armed
143 # guards the same way). It also settles the overloading question instead of
144 # stepping around it: refaddr returns the address itself and never consults an
145 # overloaded `==`, so a blessed return value cannot be asked a comparison it
146 # would answer with an exception.
147 my $NO_CHANGE = \do { my $sentinel = 'no change' };
148  
149 sub no_change { return $NO_CHANGE }
150  
151  
152 # One spelling of "this id names no card" for every command on the mutation
153 # path (ticket k264). update_task_guarded and delete_task_guarded raise it when
154 # the ref is gone; archive and delete raise the same off the unguarded pre-read
155 # they take before the guard (Cmd::Archive, Cmd::Delete), so move, edit, delete,
156 # archive and handoff can never disagree on the wording -- the drift k263 warned
157 # about when it unified "No karr board found" across five commands. The id is
158 # real and only `karr list --compact` follows it, carrying no placeholder, so
159 # the suggestion is always printed (the shape `karr needs` got in k263). The
160 # trailing newline is here so a `die` honours it and Carp appends no call site.
161 sub task_not_found {
162 my ($self, $id) = @_;
163 return "Task $id not found on this board:\n"
164 . App::karr::Error::command_hint('list', '--compact') . "\n";
165 }
166  
167  
168 sub update_task_guarded {
169 my ($self, $id, $mutate) = @_;
170 my $git = $self->git;
171 my $ref = $self->_task_data_ref($id);
172  
173 return $git->retry_contended( "task $id", sub {
174 my ( $oid, $content ) = $git->read_ref_with_oid($ref);
175 die $self->task_not_found($id) unless defined $oid && length $content;
176  
177 my $task = App::karr::Task->from_string( $content,
178 repair_frontmatter => $git->board_is_legacy_encoded );
179  
180 my $verdict = $mutate->($task);
181  
182 # A callback that found nothing to change gets no write: `updated` is
183 # stamped by the write (App::karr::BoardStore/save_task_cas) and the
184 # activity log hangs off it, so a command that changed nothing and
185 # wrote anyway moved the one field the foundation drain reads to tell a
186 # stuck card from a worked one, and put an entry in the log for an
187 # event that did not happen (#231). Returning the task rather than ()
188 # ends the retry loop: () means "another agent got in first, read again",
189 # and nothing here lost a race.
190 return $task
191 if ref $verdict
192 && Scalar::Util::refaddr($verdict) == Scalar::Util::refaddr($NO_CHANGE);
193  
194 # Through the role's own door rather than straight at write_ref_cas:
195 # BoardAccess::save_task is where the `updated` bump and the activity
196 # log entry live for every command write, guarded or not, and reaching
197 # past it is what dropped move and edit out of `karr log` (#64).
198 return () unless $self->save_task( $task, $oid );
199 return $task;
200 } );
201 }
202  
203  
204 # The same shape as update_task_guarded, and for the same reason: the claim rule
205 # is applied to the revision the delete is guarded against, so the two can never
206 # be about different bytes.
207 #
208 # This used to re-read the task and delete by name, because karr had no guarded
209 # delete to reach for -- App::karr::Git::delete_ref goes through libgit2's
210 # git_reference_remove(repo, name), which takes no expected-old OID. Re-reading
211 # closed the window that can stay open for minutes behind a confirmation prompt
212 # and left the microseconds between the read and the remove, in which a claim
213 # landing on the card was deleted along with it. App::karr::Git::delete_ref_cas
214 # closes that one too (#94).
215 sub delete_task_guarded {
216 my ($self, $id, $claimant) = @_;
217 my $git = $self->git;
218 my $ref = $self->_task_data_ref($id);
219  
220 my $task = $git->retry_contended( "task $id", sub {
221 my ( $oid, $content ) = $git->read_ref_with_oid($ref);
222 die $self->task_not_found($id) unless defined $oid && length $content;
223  
224 my $found = App::karr::Task->from_string( $content,
225 repair_frontmatter => $git->board_is_legacy_encoded );
226 $self->check_claim( $found, $claimant );
227  
228 return () unless $git->delete_ref_cas( $ref, $oid );
229 return $found;
230 } );
231  
232 # L<App::karr::Role::BoardAccess/delete_task> is the activity-log funnel for
233 # the unguarded path; this one writes the ref itself, so it records the same
234 # entry rather than going without one (#64).
235 $self->log_task_write($id);
236 return $task;
237 }
238  
239  
240 # One status-change path, because there used to be two: `karr move` enforced
241 # require_claim and stamped the lifecycle dates, while `karr edit --status` just
242 # assigned the field. So `edit --status in-progress` quietly bought what `move
243 # 1 in-progress` refused to sell, and require_claim -- the guarantee karr's
244 # whole multi-agent coordination rests on -- was one flag away from being
245 # optional (ticket #55).
246 #
247 # The require_claim condition is move's, unchanged: a claim passed on the
248 # command line satisfies it, and so does a claim the task already carries.
249 #
250 # Being the one status-change path, this is also where the status *name* is
251 # checked (ticket #54) and where the lifecycle stamps are maintained (ticket
252 # #68) -- both for `move` and for `edit --status`.
253 sub apply_status_change {
254 my ($self, $task, $new_status, $claimant) = @_;
255  
256 # First, so a batch dies on its first id having written nothing: the check
257 # runs inside update_task_guarded's callback, and a die there means the
258 # compare-and-swap write is never reached. `move 1 ZZZ` and `edit 1
259 # --status ZZZ` used to exit 0 and park the task in a column that does not
260 # exist -- invisible on `karr board`, still in the total, and fatal to the
261 # next `karr move --next`.
262 my $config = App::karr::Config->from_merged( $self->store->effective_config );
263 $config->validate_status($new_status);
264  
265 # A claim handed to a card on its way into backlog is refused (ticket
266 # k306). Ahead of the same-status shortcut below, because `move ID backlog
267 # --claim X` on a card already in backlog is a claim-only move, and that
268 # is exactly the claim the held-back column does not hold.
269 $self->check_held_back_claim( $task, $new_status, $claimant );
270  
271 my $old_status = $task->status;
272  
273 # A status change to the status the card already has changes nothing, so
274 # nothing below it runs and nothing is written. kanban-md answers the same
275 # way (internal/board/mutate.go:101-104), `karr archive` already answers it
276 # one command over for an archived card, and ADR 0002 files that shape --
277 # "no-ops like re-archiving an archived task" -- under exit 0. What made it
278 # worth fixing is what the write cost: `updated` is stamped by every write
279 # (App::karr::BoardStore/save_task_cas) and the activity log hangs off the
280 # same door, so `karr move 5 backlog` on a card already in backlog moved
281 # the field karr-foundation's drain reads to tell a stuck card from a
282 # worked one, and logged a move that never happened (#231).
283 #
284 # In front of the #224 release rather than behind it, and that is free
285 # rather than a compromise: the release fires on terminal -> non-terminal,
286 # and $old_status eq $new_status makes both sides of that pair the same
287 # status, so the condition is unsatisfiable here whatever the card carries.
288 # `move ID done` on a done card holding a claim released nothing before
289 # this line existed either -- done -> done is terminal to terminal, where
290 # #223 keeps the name as provenance.
291 #
292 # What it does skip is require_claim and the dependency check. Deliberately,
293 # and the same order kanban-md uses: a card that is already in a
294 # require_claim column with no owner was not put there by a command that
295 # declines to move it, and what a card waits for is worth saying to whoever
296 # takes it up, not to a command that leaves it exactly where it was. A
297 # caller that brings a claim of its own is not this case at all -- writing
298 # claimed_by/claimed_at is a change -- and App::karr::Cmd::Move decides that
299 # before it ever gets here.
300 return $old_status if $new_status eq $old_status;
301  
302 # Reopening releases the claim. A claim is the lease an agent holds *while
303 # working* a card (CONTEXT.md, Language); reaching a terminal status
304 # releases it and leaves claimed_by behind as provenance, which is why
305 # `karr board` prints no claimant on a finished card and check_claim lets
306 # every command through one (ticket #223). Nothing ever took the field off
307 # again, so the moment the card left that status the same bytes were a live
308 # lease once more, held by whoever had finished the work rather than by
309 # anyone doing it: the card sat in todo, `karr list` called it open work,
310 # `karr board` counted it as claimed, and `karr pick` skipped it without a
311 # word -- on a board whose only card that was, a drain run was told "no
312 # available tasks" while the board showed work waiting (ticket #224).
313 #
314 # Three conditions, none of them decoration:
315 #
316 # * out of a terminal status, into a non-terminal one. `done` ->
317 # `archived` is terminal to terminal and keeps the name, because
318 # archiving does not resume the work -- the provenance #223 kept is
319 # exactly what would be thrown away here.
320 #
321 # * no claimant from the caller. `move ID todo --claim beta-two` and
322 # every `handoff` (where --claim is required) hand the card to a named
323 # agent, and that name wins; only a reopen that names nobody leaves the
324 # card unheld.
325 #
326 # * terminal is this board's word, from App::karr::Config, never the
327 # literal `done` -- the same config object update_timestamps is handed
328 # below, so a board that ends in `shipped` releases there and nowhere
329 # else (tickets #67, #223).
330 #
331 # Before the require_claim check below rather than after it, for the reason
332 # ticket #150 spelled out for `edit --release`: a released claim that still
333 # satisfies require_claim on its way out would land the card in a column
334 # the board says needs an owner with no owner on it. So `move ID
335 # in-progress` off a finished card now asks for --claim instead of quietly
336 # handing the column to the agent that had finished the work.
337 #
338 # claimed_at goes with claimed_by: on its own it is the age of a lease
339 # nobody holds, and it is the timestamp `karr pick` and check_claim measure
340 # expiry against.
341 #
342 # Parking releases it too (ticket k306): a card moved into backlog is
343 # held back, and backlog holds no claim, so whoever was working it lets go
344 # on the way in. The same two fields, cleared at the same point, so the
345 # activity log records it the way it records a reopen -- as the move. A
346 # claimant cannot reach this half: check_held_back_claim above refused it.
347 if ( !( defined $claimant && length $claimant )
348 && ( $config->is_held_back_status($new_status)
349 || ( $config->is_terminal_status($old_status)
350 && !$config->is_terminal_status($new_status) ) ) )
351 {
352 $task->clear_claimed_by;
353 $task->clear_claimed_at;
354 }
355  
356 # "requires a claim", not "requires --claim": naming the option said nothing
357 # about a value following it, and the agent in ticket k263 read it, typed
358 # `--claim` bare, and collected a second error for its trouble. The line
359 # under it is the whole invocation that would have worked, built from the id
360 # and the status this call already has -- see claim_hint_tokens for why the
361 # command name comes from the consumer.
362 App::karr::Error::user_error(
363 App::karr::Error::require_claim_message(
364 $new_status, $self->claim_hint_tokens( $task, $new_status ) ) )
365 if $self->store->status_requires_claim($new_status)
366 && !( defined $claimant && length $claimant )
367 && !$task->has_claimed_by;
368  
369 # Being the one status-change path is also what makes this the one place
370 # `depends_on` has to be consulted: move, edit --status, handoff and archive
371 # all arrive here, so none of them can be the door that forgets to ask
372 # (ticket #123). Recorded, not printed -- this runs inside
373 # update_task_guarded's callback, which re-runs on contention, so the
374 # emitting is left to dependency_report after the write has landed.
375 $self->check_dependencies( $task, $new_status );
376  
377 $task->status($new_status);
378 # The lifecycle rules themselves live on the task, mirroring kanban-md's
379 # internal/task/lifecycle.go: `started` on the first move out of the first
380 # configured status, `completed` on any terminal status, and `completed`
381 # cleared again when a task is reopened.
382 #
383 # The board's own config goes with it, so "terminal" means this board's
384 # last column and not the literal `done`: on a board that ends in
385 # `shipped`, move/edit/archive/handoff recorded no completion at all
386 # (left over from ticket #67).
387 $task->update_timestamps( $old_status, $new_status, ( $config->statuses )[0],
388 $config );
389  
390 return $old_status;
391 }
392  
393  
394 sub check_held_back_claim {
395 my ( $self, $task, $status, $claimant ) = @_;
396 return 1 unless defined $claimant && length $claimant;
397 return 1 unless $self->store->is_held_back_status($status);
398 my $to = App::karr::Config->from_merged( $self->store->effective_config )
399 ->promotion_status;
400 App::karr::Error::user_error(
401 App::karr::Error::held_back_claim_message( $status,
402 'move', $task->id, $to // 'STATUS', '--claim', $claimant ) );
403 }
404  
405  
406 sub claim_hint_tokens {
407 my ( $self, $task, $status ) = @_;
408 return ( 'edit', $task->id, '--status', $status, '--claim', 'NAME' );
409 }
410  
411  
412 1;
413  
414 __END__
« blib/lib/App/karr/Cmd/Restore.pm ↑ Summary blib/lib/App/karr/Cmd/Context.pm »