1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#include "lix/libstore/derivations.hh"
#include "lix/libstore/parsed-derivations.hh"
#include "lix/libstore/globals.hh"
#include "lix/libstore/store-api.hh"
#include "lix/libutil/async-collect.hh"
#include "lix/libutil/async.hh"
#include "lix/libutil/result.hh"
#include "lix/libutil/thread-pool.hh"
#include "lix/libutil/topo-sort.hh"
#include "lix/libutil/closure.hh"
#include "lix/libstore/filetransfer.hh"
#include "lix/libutil/strings.hh"
#include <kj/async.h>
#include <kj/common.h>
#include <kj/vector.h>

namespace nix {

kj::Promise<Result<void>> Store::computeFSClosure(const StorePathSet & startPaths,
    StorePathSet & paths_, bool flipDirection, bool includeOutputs, bool includeDerivers)
try {
    std::function<
        kj::Promise<Result<std::set<StorePath>>>(const StorePath & path, ref<const ValidPathInfo>)>
        queryDeps;
    if (flipDirection) {
        // NOLINTNEXTLINE(cppcoreguidelines-avoid-capturing-lambda-coroutines)
        queryDeps = [&](const StorePath & path,
                        ref<const ValidPathInfo>) -> kj::Promise<Result<std::set<StorePath>>> {
            try {
                StorePathSet res;
                StorePathSet referrers;
                TRY_AWAIT(queryReferrers(path, referrers));
                for (auto& ref : referrers)
                    if (ref != path)
                        res.insert(ref);

                if (includeOutputs)
                    for (auto& i : TRY_AWAIT(queryValidDerivers(path)))
                        res.insert(i);

                if (includeDerivers && path.isDerivation())
                    for (auto& [_, outPath] : TRY_AWAIT(queryDerivationOutputMap(path)))
                        if (TRY_AWAIT(isValidPath(outPath)))
                            res.insert(outPath);
                co_return res;
            } catch (...) {
                co_return result::current_exception();
            }
        };
    } else {
        // NOLINTNEXTLINE(cppcoreguidelines-avoid-capturing-lambda-coroutines)
        queryDeps = [&](const StorePath & path,
                        ref<const ValidPathInfo> info) -> kj::Promise<Result<std::set<StorePath>>> {
            try {
                StorePathSet res;
                for (auto& ref : info->references)
                    if (ref != path)
                        res.insert(ref);

                if (includeOutputs && path.isDerivation())
                    for (auto& [_, outPath] : TRY_AWAIT(queryDerivationOutputMap(path)))
                        if (TRY_AWAIT(isValidPath(outPath)))
                            res.insert(outPath);

                if (includeDerivers && info->deriver && TRY_AWAIT(isValidPath(*info->deriver)))
                    res.insert(*info->deriver);
                co_return res;
            } catch (...) {
                co_return result::current_exception();
            }
        };
    }

    paths_.merge(TRY_AWAIT(computeClosureAsync<StorePath>(
        startPaths,
        // NOLINTNEXTLINE(cppcoreguidelines-avoid-capturing-lambda-coroutines)
        [&](const StorePath& path) -> kj::Promise<Result<StorePathSet>> {
            try {
                co_return TRY_AWAIT(queryDeps(path, TRY_AWAIT(queryPathInfo(path))));
            } catch (...) {
                co_return result::current_exception();
            }
        })));
    co_return result::success();
} catch (...) {
    co_return result::current_exception();
}

kj::Promise<Result<void>> Store::computeFSClosure(const StorePath & startPath,
    StorePathSet & paths_, bool flipDirection, bool includeOutputs, bool includeDerivers)
try {
    StorePathSet paths;
    paths.insert(startPath);
    TRY_AWAIT(computeFSClosure(paths, paths_, flipDirection, includeOutputs, includeDerivers));
    co_return result::success();
} catch (...) {
    co_return result::current_exception();
}


const ContentAddress * getDerivationCA(const BasicDerivation & drv)
{
    auto out = drv.outputs.find("out");
    if (out == drv.outputs.end())
        return nullptr;
    if (auto dof = std::get_if<DerivationOutput::CAFixed>(&out->second.raw)) {
        return &dof->ca;
    }
    return nullptr;
}

namespace {
struct QueryMissingContext
{
    Store & store;

    struct State
    {
        std::unordered_set<std::string> done;
        StorePathSet & unknown, & willSubstitute, & willBuild;
        uint64_t & downloadSize;
        uint64_t & narSize;
    };

    struct DrvState
    {
        size_t left;
        bool done = false;
        StorePathSet outPaths;
        DrvState(size_t left) : left(left) { }
    };

    State state;

    explicit QueryMissingContext(
        Store & store,
        StorePathSet & willBuild_,
        StorePathSet & willSubstitute_,
        StorePathSet & unknown_,
        uint64_t & downloadSize_,
        uint64_t & narSize_
    )
        : store(store)
        , state{{}, unknown_, willSubstitute_, willBuild_, downloadSize_, narSize_}
    {
    }

    KJ_DISALLOW_COPY_AND_MOVE(QueryMissingContext);

    kj::Promise<Result<void>> queryMissing(const std::vector<DerivedPath> & targets);

    kj::Promise<Result<void>>
    enqueueDerivedPaths(DerivedPathOpaque inputDrv, const StringSet & inputNode)
    try {
        if (!inputNode.empty()) {
            TRY_AWAIT(doPath(DerivedPath::Built{std::move(inputDrv), inputNode}));
        }
        co_return result::success();
    } catch (...) {
        co_return result::current_exception();
    }

    kj::Promise<Result<void>> mustBuildDrv(const StorePath & drvPath, const Derivation & drv)
    try {
        state.willBuild.insert(drvPath);

        TRY_AWAIT(asyncSpread(drv.inputDrvs, [&](const auto & input) {
            const auto & [inputDrv, inputNode] = input;
            return enqueueDerivedPaths(makeConstantStorePath(inputDrv), inputNode);
        }));
        co_return result::success();
    } catch (...) {
        co_return result::current_exception();
    }

    kj::Promise<Result<void>> checkOutput(
        const StorePath & drvPath,
        ref<Derivation> drv,
        const StorePath & outPath,
        DrvState & drvState
    )
    try {
        SubstitutablePathInfos infos;
        auto * cap = getDerivationCA(*drv);
        TRY_AWAIT(store.querySubstitutablePathInfos(
            {
                {
                    outPath,
                    cap ? std::optional{*cap} : std::nullopt,
                },
            },
            infos
        ));

        if (infos.empty()) {
            drvState.done = true;
            TRY_AWAIT(mustBuildDrv(drvPath, *drv));
        } else {
            {
                if (drvState.done) {
                    co_return result::success();
                }
                assert(drvState.left);
                drvState.left--;
                drvState.outPaths.insert(outPath);
                if (!drvState.left) {
                    TRY_AWAIT(asyncSpread(drvState.outPaths, [&](auto & path) {
                        return doPath(DerivedPath::Opaque{path});
                    }));
                }
            }
        }

        co_return result::success();
    } catch (...) {
        co_return result::current_exception();
    }

    kj::Promise<Result<void>> doPath(DerivedPath req)
    {
        if (!state.done.insert(req.to_string(store)).second) {
            return {result::success()};
        }

        return std::visit(
            overloaded{
                [&](DerivedPath::Built bfd) { return doPathBuilt(std::move(bfd)); },
                [&](DerivedPath::Opaque bo) { return doPathOpaque(std::move(bo)); },
            },
            std::move(req.raw())
        );
    }

    kj::Promise<Result<void>> doPathBuilt(DerivedPath::Built bfd)
    try {
        auto & drvPath = bfd.drvPath.path;

        if (!TRY_AWAIT(store.isValidPath(drvPath))) {
            // FIXME: we could try to substitute the derivation.
            state.unknown.insert(drvPath);
            co_return result::success();
        }

        StorePathSet invalid;
        for (auto & [outputName, path] : TRY_AWAIT(store.queryDerivationOutputMap(drvPath))) {
            if (bfd.outputs.contains(outputName) && !TRY_AWAIT(store.isValidPath(path))) {
                invalid.insert(path);
            }
        }
        if (invalid.empty()) {
            co_return result::success();
        }

        auto drv = make_ref<Derivation>(TRY_AWAIT(store.derivationFromPath(drvPath)));
        ParsedDerivation parsedDrv(StorePath(drvPath), *drv);

        if (settings.useSubstitutes && parsedDrv.substitutesAllowed()) {
            DrvState drvState(invalid.size());
            TRY_AWAIT(asyncSpread(invalid, [&](auto & output) {
                return checkOutput(drvPath, drv, output, drvState);
            }));
        } else {
            TRY_AWAIT(mustBuildDrv(drvPath, *drv));
        }

        co_return result::success();
    } catch (...) {
        co_return result::current_exception();
    }

    kj::Promise<Result<void>> doPathOpaque(DerivedPath::Opaque bo)
    try {
        if (TRY_AWAIT(store.isValidPath(bo.path))) {
            co_return result::success();
        }

        SubstitutablePathInfos infos;
        TRY_AWAIT(store.querySubstitutablePathInfos({{bo.path, std::nullopt}}, infos));

        if (infos.empty()) {
            state.unknown.insert(bo.path);
            co_return result::success();
        }

        auto info = infos.find(bo.path);
        assert(info != infos.end());

        state.willSubstitute.insert(bo.path);
        state.downloadSize += info->second.downloadSize;
        state.narSize += info->second.narSize;

        TRY_AWAIT(asyncSpread(info->second.references, [&](auto & ref) {
            return doPath(DerivedPath::Opaque{ref});
        }));

        co_return result::success();
    } catch (...) {
        co_return result::current_exception();
    }
};
}

kj::Promise<Result<void>> QueryMissingContext::queryMissing(const std::vector<DerivedPath> & targets)
try {
    TRY_AWAIT(asyncSpread(targets, [&](auto & path) { return doPath(path); }));
    co_return result::success();
} catch (...) {
    co_return result::current_exception();
}


kj::Promise<Result<void>> Store::queryMissing(const std::vector<DerivedPath> & targets,
    StorePathSet & willBuild_, StorePathSet & willSubstitute_, StorePathSet & unknown_,
    uint64_t & downloadSize_, uint64_t & narSize_)
try {
    auto act = logger->startActivity(lvlDebug, actUnknown, "querying info about missing paths");

    downloadSize_ = narSize_ = 0;

    TRY_AWAIT(
        QueryMissingContext{*this, willBuild_, willSubstitute_, unknown_, downloadSize_, narSize_}
            .queryMissing(targets)
    );
    co_return result::success();
} catch (...) {
    co_return result::current_exception();
}


kj::Promise<Result<StorePaths>> Store::topoSortPaths(const StorePathSet & paths)
try {
    co_return TRY_AWAIT(topoSortAsync(paths,
        // NOLINTNEXTLINE(cppcoreguidelines-avoid-capturing-lambda-coroutines)
        {[&](const StorePath & path) -> kj::Promise<Result<StorePathSet>> {
            try {
                co_return TRY_AWAIT(queryPathInfo(path))->references;
            } catch (InvalidPath &) {
                co_return StorePathSet();
            } catch (...) {
                co_return result::current_exception();
            }
        }},
        {[&](const StorePath & path, const StorePath & parent) {
            return BuildError(
                "cycle detected in the references of '%s' from '%s'",
                printStorePath(path),
                printStorePath(parent));
        }}));
} catch (...) {
    co_return result::current_exception();
}

kj::Promise<Result<OutputPathMap>>
resolveDerivedPath(Store & store, const DerivedPath::Built & bfd, Store * evalStore_)
try {
    auto drvPath = bfd.drvPath.path;

    auto outputs_ = TRY_AWAIT(store.queryDerivationOutputMap(drvPath, evalStore_));

    co_return std::visit(overloaded {
        [&](const OutputsSpec::All &) {
            // Keep all outputs
            return std::move(outputs_);
        },
        [&](const OutputsSpec::Names & names) {
            // Get just those mentioned by name
            std::map<std::string, StorePath> outputsOpt;
            for (auto & output : names) {
                auto * pOutputPathOpt = get(outputs_, output);
                if (!pOutputPathOpt)
                    throw Error(
                        "the derivation '%s' doesn't have an output named '%s'",
                        bfd.drvPath.to_string(store), output);
                outputsOpt.insert_or_assign(output, std::move(*pOutputPathOpt));
            }
            return outputsOpt;
        },
    }, bfd.outputs.raw);
} catch (...) {
    co_return result::current_exception();
}

}