Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
goal.hh
Go to the documentation of this file.
1#pragma once
3
6
7#include <coroutine>
8#include <queue>
9#include <variant>
10
11namespace nix {
12
13class TimedOut final : public CloneableError<TimedOut, BuildError>
14{
15 void anchor() override;
16
17public:
18 time_t maxDuration;
19
20 TimedOut(time_t maxDuration);
21};
22
26struct Goal;
27class Worker;
28
32typedef std::shared_ptr<Goal> GoalPtr;
33typedef std::weak_ptr<Goal> WeakGoalPtr;
34
36{
37 bool operator()(const GoalPtr & a, const GoalPtr & b) const;
38};
39
43typedef std::set<GoalPtr, CompareGoalPtrs> Goals;
44typedef std::set<WeakGoalPtr, std::owner_less<WeakGoalPtr>> WeakGoals;
45
49typedef std::map<StorePath, WeakGoalPtr> WeakGoalMap;
50
77
78struct Goal : public std::enable_shared_from_this<Goal>
79{
80private:
81 /* VTable anchor to avoid weak linkage of the vtable - it breaks
82 dynamic_cast across shared libraries on Darwin. */
83 virtual void anchor();
84public:
89 {
90 Descriptor fd;
91 std::string data;
92 };
93
94 struct ChildEOF
95 {
96 Descriptor fd;
97 };
98
99 using ChildEvent = std::variant<ChildOutput, ChildEOF, std::unique_ptr<TimedOut>>;
100
101private:
102 class ChildEvents
103 {
110 std::queue<ChildOutput> childOutputs;
111 std::optional<ChildEOF> childEOF;
112 std::unique_ptr<TimedOut> childTimeout;
113
114 public:
115 void pushChildEvent(ChildOutput event);
116 void pushChildEvent(ChildEOF event);
117 void pushChildEvent(TimedOut event);
118 bool hasChildEvent() const;
119 ChildEvent popChildEvent();
120 };
121
125 Goals waitees;
126
130 std::optional<std::string> cachedKey;
131
132 ChildEvents childEvents;
133
134public:
135 typedef enum { ecSuccess, ecFailed, ecNoSubstituters } ExitCode;
136
141
146 WeakGoals waiters;
147
151 size_t nrFailed = 0;
152
158
162 std::string name;
163
169 std::optional<ExitCode> exitCode;
170
175
180 struct Suspend
181 {};
182
188 {};
189
190 template<typename T>
191 class AwaitableFrame;
192 class AwaitableFrameBase;
193
197 template<typename T>
198 using HandleType = std::coroutine_handle<AwaitableFrame<T>>;
199 using HandleTypeBase = std::coroutine_handle<AwaitableFrameBase>;
200
201 template<typename T>
202 struct Co;
203
204 class CoBase
205 {
206 protected:
207 friend struct Goal;
208
212 std::coroutine_handle<> handle;
213
214 explicit CoBase(std::coroutine_handle<> h) noexcept
215 : handle(h)
216 {
217 }
218
219 public:
220 CoBase() noexcept
221 : handle(nullptr)
222 {
223 }
224
225 CoBase(CoBase && rhs) noexcept
226 : handle(std::exchange(rhs.handle, nullptr))
227 {
228 }
229
230 CoBase & operator=(CoBase && rhs) noexcept;
231 CoBase(const CoBase &) = delete;
232 CoBase & operator=(const CoBase &) = delete;
233 ~CoBase();
234 };
235
270 template<typename T>
271 struct [[nodiscard]] Co : CoBase
272 {
273 Co() noexcept = default;
274
275 explicit Co(HandleType<T> h) noexcept
276 : CoBase(h)
277 {
278 }
279
280 AwaitableFrame<T> & frame() const
281 {
282 assert(handle);
283 return HandleType<T>::from_address(handle.address()).promise();
284 }
285 };
286
287 static_assert(sizeof(Co<ExitCode>) == sizeof(CoBase));
288
289 template<typename T>
291 {
292 fun<void(Callback<T>)> fn;
293 };
294
296 {
297 friend struct Goal;
298
299 protected:
303 std::optional<CoBase> continuation;
304
305 void * resultSlot = nullptr;
306 void (*moveResult)(AwaitableFrameBase * from, void * to) noexcept = nullptr;
307
312 Goal * goal = nullptr;
313
318 bool alive = true;
319
320 private:
325 struct InitialSuspend
326 {
331 HandleTypeBase handle;
332
333 bool await_ready()
334 {
335 return false;
336 };
337
338 template<class Promise>
339 void await_suspend(std::coroutine_handle<Promise> h)
340 {
341 handle = HandleTypeBase::from_address(h.address());
342 }
343
344 void await_resume()
345 {
346 assert(handle);
347 assert(handle.promise().goal); // goal must be set
348 assert(handle.promise().goal->top_co); // top_co of goal must be set
349 assert(handle.promise().goal->top_co->handle == handle); // top_co of goal must be us
350 }
351 };
352
353 template<typename T, typename Derived>
354 class CoAwaiterBase
355 {
356 CoAwaiterBase() = default;
357
358 CoAwaiterBase(Co<T> c)
359 : co(std::move(c))
360 {
361 }
362
363 public:
364 Co<T> co;
365
366 bool await_ready() const noexcept
367 {
368 return false;
369 }
370
371 template<class Promise>
372 std::coroutine_handle<> await_suspend(std::coroutine_handle<Promise> caller)
373 {
374 auto & promise = co.frame();
375 auto goal = caller.promise().goal;
376 assert(goal);
377 assert(!promise.continuation); // we must have no continuation
378 assert(!promise.goal); // we must not have a goal yet
379 promise.goal = goal;
380 promise.continuation = std::move(goal->top_co); // we set our continuation to be top_co (i.e. caller)
381 if constexpr (!std::is_void_v<T>) {
382 promise.resultSlot = &static_cast<Derived *>(this)->result;
383 }
384 goal->top_co = std::move(co); // we set top_co to ourselves, don't use this anymore after this!
385 return goal->top_co->handle; // we execute ourselves
386 }
387
388 friend Derived;
389 };
390
391 template<typename T>
392 struct CoAwaiter : CoAwaiterBase<T, CoAwaiter<T>>
393 {
394 CoAwaiter() = default;
395
396 explicit CoAwaiter(Co<T> co)
397 : CoAwaiterBase<T, CoAwaiter<T>>(std::move(co))
398 {
399 }
400
401 std::optional<T> result;
402
403 T await_resume()
404 {
405 assert(result);
406 return std::move(*result);
407 }
408 };
409
414 struct ChildEventAwaiter
415 {
416 HandleTypeBase handle;
417
418 bool await_ready()
419 {
420 return handle && handle.promise().goal->childEvents.hasChildEvent();
421 }
422
423 template<class Promise>
424 void await_suspend(std::coroutine_handle<Promise> h)
425 {
426 handle = HandleTypeBase::from_address(h.address());
427 }
428
429 ChildEvent await_resume()
430 {
431 assert(handle);
432 return handle.promise().goal->childEvents.popChildEvent();
433 }
434 };
435
439 struct FinalAwaiter
440 {
441 bool await_ready() noexcept
442 {
443 return false;
444 };
445
452 template<class Promise>
453 std::coroutine_handle<> await_suspend(std::coroutine_handle<Promise> h) noexcept;
454
455 void await_resume() noexcept
456 {
457 assert(false);
458 };
459 };
460
466 struct SuspendAwaiter
467 {
468 AwaitableFrameBase & promise;
469
470 bool await_ready()
471 {
472 assert(!promise.goal->childEvents.hasChildEvent());
473 return false;
474 }
475
476 template<class Promise>
477 void await_suspend([[maybe_unused]] std::coroutine_handle<Promise> h)
478 {
479 }
480
481 void await_resume() {}
482 };
483
484 public:
490 InitialSuspend initial_suspend()
491 {
492 return {};
493 };
494
499 FinalAwaiter final_suspend() noexcept
500 {
501 return {};
502 };
503
509 {
510 throw;
511 };
512
513 template<typename T>
514 CoAwaiter<T> await_transform(Co<T> && co)
515 {
516 return CoAwaiter<T>{std::move(co)};
517 }
518
519 template<typename T>
520 auto await_transform(AsyncCallback<T> && acb);
521
526 SuspendAwaiter await_transform(Suspend)
527 {
528 return SuspendAwaiter{*this};
529 };
530
535 {
536 return ChildEventAwaiter{HandleTypeBase::from_promise(*this)};
537 };
538 };
539
547 template<typename T>
549 {
553 std::optional<T> result;
554
555 static void doMoveResult(AwaitableFrameBase * from, void * to) noexcept
556 {
557 auto * self = static_cast<AwaitableFrame *>(from);
558 auto * slot = static_cast<std::optional<T> *>(to);
559 slot->emplace(std::move(*self->result));
560 }
561
562 public:
568 {
569 return Co<T>{HandleType<T>::from_promise(*this)};
570 }
571
572 template<typename R>
573 void return_value(R && r)
574 {
575 result.emplace(std::forward<R>(r));
576 moveResult = &doMoveResult;
577 }
578 };
579
580protected:
588 std::optional<CoBase> top_co;
589
594 std::optional<ExitCode> finalExitCode;
595
596public:
597 virtual void cleanup() {}
598
608 bool preserveFailure = false;
609
610 Goal(Worker & worker, Co<ExitCode> init);
611
612 virtual ~Goal()
613 {
614 trace("goal destroyed");
615 }
616
622 void work();
623
628 void handleChildOutput(Descriptor fd, std::string_view data);
629
634 void handleEOF(Descriptor fd);
635
640 void timedOut(TimedOut && ex);
641
642 void trace(std::string_view s);
643
644 std::string getName() const
645 {
646 return name;
647 }
648
661 virtual std::string key() = 0;
662
667 std::string_view keyCached() &
668 {
669 if (cachedKey)
670 return *cachedKey;
671 return *(cachedKey = key());
672 }
673
678 virtual JobCategory jobCategory() const = 0;
679
680protected:
681 Co<void> await(Goals waitees);
682
688
695
696 Co<void> waitForBuildSlot();
697 Co<void> yield();
698};
699
700void addToWeakGoals(WeakGoals & goals, GoalPtr p);
701
702template<typename Promise>
703std::coroutine_handle<> Goal::AwaitableFrameBase::FinalAwaiter::await_suspend(std::coroutine_handle<Promise> h) noexcept
704{
705 auto & p = h.promise();
706 auto goal = p.goal;
707 assert(goal);
708 goal->trace("in FinalAwaiter");
709 auto c = std::move(p.continuation);
710
711 if (p.resultSlot && p.moveResult)
712 p.moveResult(&p, p.resultSlot);
713
714 if (c) {
715 // We still have a continuation, i.e. work to do.
716 // We assert that the goal is still busy.
717 assert(!goal->exitCode);
718 assert(goal->top_co); // Goal must have an active coroutine.
719 assert(goal->top_co->handle == h); // The active coroutine must be us.
720 assert(p.alive); // We must not have been destructed.
721
722 // we move continuation to the top,
723 // note: previous top_co is actually h, so by moving into it,
724 // we're calling the destructor on h, DON'T use h and p after this!
725
726 // We move our continuation into `top_co`, i.e. the marker for the active continuation.
727 // By doing this we destruct the old `top_co`, i.e. us, so `h` can't be used anymore.
728 // Be careful not to access freed memory!
729 goal->top_co = std::move(c);
730
731 // We resume `top_co`.
732 return goal->top_co->handle;
733 } else {
734 // We have no continuation, i.e. we are the top-level coroutine
735 // and just handed our exit code to the goal.
736 assert(p.resultSlot);
737
738 // We reset `top_co` for good measure.
739 p.goal->top_co = {};
740
741 // We jump to the noop coroutine, which doesn't do anything and immediately suspends.
742 // This passes control back to the caller of goal.work().
743 return std::noop_coroutine();
744 }
745}
746
747template<>
748struct Goal::AwaitableFrameBase::CoAwaiter<void> : CoAwaiterBase<void, CoAwaiter<void>>
749{
750 CoAwaiter() = default;
751
752 explicit CoAwaiter(Co<void> co)
753 : CoAwaiterBase<void, CoAwaiter<void>>(std::move(co))
754 {
755 }
756
757 void await_resume() {}
758};
759
760template<>
762{
763 Co<void> get_return_object()
764 {
766 }
767
772 void return_void() {}
773};
774
775} // namespace nix
776
777template<typename T, typename... ArgTypes>
778struct std::coroutine_traits<nix::Goal::Co<T>, ArgTypes...>
779{
780 using promise_type = nix::Goal::AwaitableFrame<T>;
781};
Definition callback.hh:19
Definition goal.hh:296
InitialSuspend initial_suspend()
Definition goal.hh:490
SuspendAwaiter await_transform(Suspend)
Definition goal.hh:526
void unhandled_exception()
Definition goal.hh:508
ChildEventAwaiter await_transform(WaitForChildEvent)
Definition goal.hh:534
std::optional< CoBase > continuation
Definition goal.hh:303
FinalAwaiter final_suspend() noexcept
Definition goal.hh:499
bool alive
Definition goal.hh:318
Goal * goal
Definition goal.hh:312
Definition goal.hh:549
Co< T > get_return_object()
Definition goal.hh:567
Definition goal.hh:205
std::coroutine_handle handle
Definition goal.hh:212
Definition goal.hh:14
Definition worker.hh:110
Definition fun.hh:19
int Descriptor
Definition file-descriptor.hh:36
JobCategory
Definition goal.hh:57
@ Substitution
Definition goal.hh:65
@ Administration
Definition goal.hh:75
@ Build
Definition goal.hh:61
std::shared_ptr< Goal > GoalPtr
Definition goal.hh:32
std::set< GoalPtr, CompareGoalPtrs > Goals
Definition goal.hh:43
std::map< StorePath, WeakGoalPtr > WeakGoalMap
Definition goal.hh:49
Definition build-result.hh:123
Definition goal.hh:36
Definition goal.hh:291
void return_void()
Definition goal.hh:772
Definition goal.hh:95
Definition goal.hh:89
Definition goal.hh:272
Definition goal.hh:181
Definition goal.hh:188
Definition goal.hh:79
std::optional< ExitCode > finalExitCode
Definition goal.hh:594
std::string_view keyCached() &
Definition goal.hh:667
BuildResult buildResult
Definition goal.hh:174
size_t nrFailed
Definition goal.hh:151
void work()
Definition goal.cc:128
std::string name
Definition goal.hh:162
void handleEOF(Descriptor fd)
Definition goal.cc:199
virtual JobCategory jobCategory() const =0
Hint for the scheduler, which concurrency limit applies.
std::coroutine_handle< AwaitableFrame< T > > HandleType
Definition goal.hh:198
void handleChildOutput(Descriptor fd, std::string_view data)
Definition goal.cc:193
std::optional< CoBase > top_co
Definition goal.hh:588
void timedOut(TimedOut &&ex)
Definition goal.cc:205
std::optional< ExitCode > exitCode
Definition goal.hh:169
virtual std::string key()=0
size_t nrNoSubstituters
Definition goal.hh:157
Co< void > waitForAWhile()
Definition goal.cc:217
bool preserveFailure
Definition goal.hh:608
Co< void > waitUntilWoken()
Definition goal.cc:223
Worker & worker
Definition goal.hh:140
WeakGoals waiters
Definition goal.hh:146