public async Task <IActionResult> UpdateJudging(
            [FromRoute] string hostname,
            [FromRoute] int judgingId,
            [FromForm] UpdateJudgingModel model)
        {
            var host = await Judgehosts.FindAsync(hostname);

            // Unknown or inactive judgehost requested
            if (host is null)
            {
                return(Empty());
            }
            await Judgehosts.NotifyPollAsync(host);

            var(judging, pid, cid, uid, time) = await Judgings.FindAsync(judgingId);

            if (judging is null)
            {
                return(BadRequest());
            }
            judging.CompileError = model.output_compile ?? "";

            if (model.compile_success != 1)
            {
                judging.Status   = Verdict.CompileError;
                judging.StopTime = DateTimeOffset.Now;
                await FinishJudging(judging, cid, pid, uid, time);
            }
            else
            {
                await Judgings.UpdateAsync(judging);
            }

            return(Ok());
        }
        /// <summary>
        /// Finish the judging pipe, persist into database,
        /// create the events and notify scoreboard.
        /// </summary>
        private async Task FinishJudging(Judging j, int?cid, int pid, int uid, DateTimeOffset subtime)
        {
            if (cid == 0)
            {
                cid = null;
            }
            await Judgings.UpdateAsync(j);

            await HttpContext.AuditAsync(
                AuditlogType.Judging, cid, j.Server,
                "judged", $"{j.JudgingId}", $"{j.Status}");

            if (cid.HasValue && j.Active)
            {
                await HttpContext.RequestServices
                .GetRequiredService <MediatR.IMediator>()
                .JudgingFinished(cid.Value, subtime, pid, uid, j);
            }

            if (j.Active)
            {
                await HttpContext.RequestServices
                .GetRequiredService <ISubmissionStore>()
                .UpdateStatisticsAsync(cid ?? 0, uid, pid, j.Status == Verdict.Accepted);
            }

            Telemetry.TrackDependency(
                dependencyTypeName: "JudgeHost",
                dependencyName: j.Server,
                data: $"j{j.JudgingId} judged " + j.Status,
                startTime: j.StartTime ?? DateTimeOffset.Now,
                duration: (j.StopTime - j.StartTime) ?? TimeSpan.Zero,
                success: j.Status != Verdict.UndefinedError);
        }
        public async Task <ActionResult <NextJudging> > NextJudging([FromRoute] string hostname)
        {
            var host = await Judgehosts.FindAsync(hostname);

            if (host is null)
            {
                return(Empty());              // Unknown or inactive judgehost requested
            }
            await Judgehosts.NotifyPollAsync(host);

            if (!host.Active)
            {
                return(Empty());
            }

            var r = new
            {
                judging = (Judging)null,
                lang    = (Language)null,
                prob    = (Problem)null,
                cid     = 0,
                teamid  = 0,
                rjid    = new int?(),
            };

            using (await Lock.LockAsync())
            {
                r = await Judgings.FindAsync(
                    predicate : j => j.Status == Verdict.Pending &&
                    j.s.l.AllowJudge &&
                    j.s.p.AllowJudge &&
                    !j.s.Ignored,
                    selector : j => new
                {
                    judging = j,
                    lang    = j.s.l,
                    prob    = j.s.p,
                    cid     = j.s.ContestId,
                    teamid  = j.s.Author,
                    rjid    = j.s.RejudgeId
                });

                if (r is null)
                {
                    return(Empty());
                }

                var judging = r.judging;
                judging.Status    = Verdict.Running;
                judging.Server    = host.ServerName;
                judging.StartTime = DateTimeOffset.Now;
                await Judgings.UpdateAsync(judging);

                //if (cid != 0)
                //{
                //    var cts = new Data.Api.ContestJudgement(
                //        judging, next.StartTime ?? DateTimeOffset.Now);
                //    DbContext.Events.Add(cts.ToEvent("create", cid));
                //}
            }

            var toFindMd5 = new[] { r.prob.RunScript, r.prob.CompareScript, r.lang.CompileScript };
            var md5s      = await HttpContext.RequestServices
                            .GetRequiredService <IExecutableStore>()
                            .ListMd5Async(toFindMd5);

            var tcss = await HttpContext.RequestServices
                       .GetRequiredService <ITestcaseStore>()
                       .ListAsync(r.prob.ProblemId);

            return(new NextJudging
            {
                submitid = r.judging.SubmissionId,
                cid = r.cid,
                teamid = r.teamid,
                probid = r.prob.ProblemId,
                langid = r.lang.Id,
                rejudgingid = r.rjid,
                entry_point = null,
                origsubmitid = null,
                maxruntime = r.prob.TimeLimit * r.lang.TimeFactor / 1000.0,         // as seconds
                memlimit = r.prob.MemoryLimit + (r.lang.Id == "java" ? 131072 : 0), // as kb, java more 128M
                outputlimit = r.prob.OutputLimit,                                   // KB
                run = r.prob.RunScript,
                compare = r.prob.CompareScript,
                compare_args = r.prob.ComapreArguments,
                compile_script = r.lang.CompileScript,
                combined_run_compare = r.prob.CombinedRunCompare,
                compare_md5sum = md5s[r.prob.CompareScript],
                run_md5sum = md5s[r.prob.RunScript],
                compile_script_md5sum = md5s[r.lang.CompileScript],
                judgingid = r.judging.JudgingId,
                full_judge = r.judging.FullTest && (r.cid == 0 || r.judging.RejudgeId != null),
                testcases = tcss.ToDictionary(t => $"{t.Rank}", t => new TestcaseToJudge(t))
            });
        }