Optimize ClickHouse projection synchronization
This commit is contained in:
1 parent
d32387bb67
commit
304b8abeb8
4 files changed
+113
-7
No files matched your search
@@ -71,7 +71,20 @@ public sealed class ClickHouseAnalyticsController(
|
||||
sum(studentCount) AS totalStudentCount,
|
||||
sum(averageScore * studentCount) AS totalWeightedScore,
|
||||
sum(passedCount) AS totalPassedCount
|
||||
FROM {options.Database}.gradeStatistics FINAL
|
||||
FROM
|
||||
(
|
||||
SELECT gradeSheetId,
|
||||
latest.1 AS academicTermId, latest.2 AS academicTermName,
|
||||
latest.3 AS collegeId, latest.4 AS studentCount,
|
||||
latest.5 AS averageScore, latest.6 AS passedCount
|
||||
FROM
|
||||
(
|
||||
SELECT gradeSheetId,
|
||||
argMax(tuple(academicTermId, academicTermName, collegeId, studentCount, averageScore, passedCount), projectedAt) AS latest
|
||||
FROM {options.Database}.gradeStatistics
|
||||
GROUP BY gradeSheetId
|
||||
)
|
||||
)
|
||||
WHERE 1 = 1{collegeFilter}
|
||||
GROUP BY academicTermId
|
||||
) AS gradeTotals
|
||||
|
||||
@@ -78,8 +78,36 @@ public sealed class ClickHouseAnalyticsClient(
|
||||
{
|
||||
if (rows.Count == 0) return;
|
||||
var payload = JsonSerializer.Serialize(rows, JsonOptions);
|
||||
// Compare against ClickHouse itself, rather than a process-local cache. A
|
||||
// failed insert, application restart, or a rebuilt analytics database is
|
||||
// therefore retried naturally on the next projection pass.
|
||||
var (schema, columns, keys) = table switch
|
||||
{
|
||||
"auditEvents" => (
|
||||
"id UUID, occurredAt DateTime64(3, 'UTC'), userId Nullable(UUID), method String, path String, statusCode UInt16, ipAddress Nullable(String), projectedAt DateTime64(3, 'UTC')",
|
||||
"id,occurredAt,userId,method,path,statusCode,ipAddress", "id"),
|
||||
"attendanceRecords" => (
|
||||
"attendanceSheetId UUID, studentId UUID, attendanceDate Date, teachingTaskId UUID, academicTermId UUID, collegeId UUID, status UInt8, checkInAt Nullable(DateTime64(3, 'UTC')), checkedInMethod Nullable(UInt8), appealStatus UInt8, projectedAt DateTime64(3, 'UTC')",
|
||||
"attendanceSheetId,studentId,attendanceDate,teachingTaskId,academicTermId,collegeId,status,checkInAt,checkedInMethod,appealStatus", "attendanceSheetId,studentId"),
|
||||
"gradeStatistics" => (
|
||||
"gradeSheetId UUID, teachingTaskId UUID, courseId UUID, academicTermId UUID, collegeId UUID, academicTermName String, studentCount UInt32, passedCount UInt32, excellentCount UInt32, averageScore Decimal(8,2), passRate Decimal(8,4), excellentRate Decimal(8,4), calculatedAt DateTime64(3, 'UTC'), projectedAt DateTime64(3, 'UTC')",
|
||||
"gradeSheetId,teachingTaskId,courseId,academicTermId,collegeId,academicTermName,studentCount,passedCount,excellentCount,averageScore,passRate,excellentRate,calculatedAt", "gradeSheetId"),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(table))
|
||||
};
|
||||
var fields = columns.Split(',');
|
||||
var join = string.Join(" AND ", keys.Split(',').Select(key => $"incoming.{key} = existing.{key}"));
|
||||
var projectedFields = string.Join(",", fields.Select(field => $"incoming.{field}"));
|
||||
await ExecuteAsync(
|
||||
$"INSERT INTO {options.Database}.{table} FORMAT JSONEachRow\n{ToJsonLines(payload)}",
|
||||
$"""
|
||||
INSERT INTO {options.Database}.{table} ({columns},projectedAt)
|
||||
SELECT {projectedFields},incoming.projectedAt
|
||||
FROM (SELECT *, cityHash64(tuple({columns})) AS fingerprint FROM input('{schema.Replace("'", "\\'")}')) AS incoming
|
||||
LEFT ANTI JOIN
|
||||
(SELECT {keys}, cityHash64(argMax(tuple({columns}), projectedAt)) AS fingerprint FROM {options.Database}.{table} GROUP BY {keys}) AS existing
|
||||
ON {join} AND incoming.fingerprint = existing.fingerprint
|
||||
FORMAT JSONEachRow
|
||||
{ToJsonLines(payload)}
|
||||
""",
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
@@ -94,6 +122,20 @@ public sealed class ClickHouseAnalyticsClient(
|
||||
.EnumerateArray().Select(x => x.Clone()).ToArray();
|
||||
}
|
||||
|
||||
public Task DeleteMissingAsync(string table, IReadOnlyCollection<(Guid First, Guid Second)> keys,
|
||||
DateTime cutoff, CancellationToken cancellationToken)
|
||||
{
|
||||
if (keys.Count == 0) return Task.CompletedTask;
|
||||
var predicate = table switch
|
||||
{
|
||||
"auditEvents" => $"id IN ({string.Join(',', keys.Select(x => $"toUUID('{x.First:D}')"))})",
|
||||
"gradeStatistics" => $"gradeSheetId IN ({string.Join(',', keys.Select(x => $"toUUID('{x.First:D}')"))})",
|
||||
"attendanceRecords" => $"(attendanceSheetId, studentId) IN ({string.Join(',', keys.Select(x => $"(toUUID('{x.First:D}'),toUUID('{x.Second:D}'))"))})",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(table))
|
||||
};
|
||||
return ExecuteAsync($"ALTER TABLE {options.Database}.{table} DELETE WHERE ({predicate}) AND projectedAt < toDateTime64('{cutoff:yyyy-MM-dd HH:mm:ss.fff}', 3, 'UTC') SETTINGS mutations_sync = 1", cancellationToken);
|
||||
}
|
||||
|
||||
private async Task ExecuteAsync(string sql, CancellationToken cancellationToken)
|
||||
{
|
||||
using var response = await SendAsync(sql, cancellationToken);
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace Jiaowu.Api.Infrastructure.Analytics;
|
||||
/// <summary>
|
||||
/// Projects MySQL facts to ClickHouse. The projection is deliberately
|
||||
/// best-effort: business writes never depend on an analytics database.
|
||||
/// ReplacingMergeTree plus FINAL reads make repeated lookback batches safe.
|
||||
/// Each batch is compared with the latest stored values before insertion.
|
||||
/// </summary>
|
||||
public sealed class ClickHouseAnalyticsProjectionWorker(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
@@ -52,11 +52,51 @@ public sealed class ClickHouseAnalyticsProjectionWorker(
|
||||
var auditCount = await ProjectAuditsAsync(db, from, projectedAt, cancellationToken);
|
||||
var attendanceCount = await ProjectAttendanceAsync(db, from.Date, projectedAt, cancellationToken);
|
||||
var gradeCount = await ProjectGradesAsync(db, projectedAt, cancellationToken);
|
||||
foreach (var table in new[] { "auditEvents", "attendanceRecords", "gradeStatistics" })
|
||||
await ReconcileDeletesAsync(db, table, projectedAt, cancellationToken);
|
||||
logger.LogInformation(
|
||||
"ClickHouse 分析投影完成:审计 {AuditCount},考勤 {AttendanceCount},成绩 {GradeCount}。",
|
||||
auditCount, attendanceCount, gradeCount);
|
||||
}
|
||||
|
||||
private async Task ReconcileDeletesAsync(AppDbContext db, string table, DateTime cutoff, CancellationToken token)
|
||||
{
|
||||
var firstColumn = table switch { "auditEvents" => "id", "attendanceRecords" => "attendanceSheetId", "gradeStatistics" => "gradeSheetId", _ => throw new ArgumentOutOfRangeException(nameof(table)) };
|
||||
var pair = table == "attendanceRecords";
|
||||
var columns = pair ? $"{firstColumn},studentId" : firstColumn;
|
||||
(Guid First, Guid Second)? cursor = null;
|
||||
while (true)
|
||||
{
|
||||
var where = cursor is null ? "" : pair
|
||||
? $"WHERE ({firstColumn},studentId) > (toUUID('{cursor.Value.First:D}'),toUUID('{cursor.Value.Second:D}'))"
|
||||
: $"WHERE {firstColumn} > toUUID('{cursor.Value.First:D}')";
|
||||
var second = pair ? ", toString(studentId) AS second" : "";
|
||||
var rows = await client.QueryAsync($"SELECT toString({firstColumn}) AS first{second} FROM {options.Database}.{table} {where} GROUP BY {columns} ORDER BY {columns} LIMIT {options.BatchSize}", token);
|
||||
if (rows.Length == 0) return;
|
||||
var keys = rows.Select(row => (First: Guid.Parse(row.GetProperty("first").GetString()!), Second: pair ? Guid.Parse(row.GetProperty("second").GetString()!) : Guid.Empty)).ToArray();
|
||||
var ids = keys.Select(x => x.First).Distinct().ToArray();
|
||||
HashSet<(Guid First, Guid Second)> existing;
|
||||
if (pair)
|
||||
{
|
||||
var students = keys.Select(x => x.Second).Distinct().ToArray();
|
||||
var found = await db.AttendanceRecords.AsNoTracking().Where(x => ids.Contains(x.AttendanceSheetId) && students.Contains(x.StudentId)).Select(x => new { x.AttendanceSheetId, x.StudentId }).ToListAsync(token);
|
||||
existing = found.Select(x => (x.AttendanceSheetId, x.StudentId)).ToHashSet();
|
||||
}
|
||||
else if (table == "auditEvents")
|
||||
{
|
||||
var found = await db.AuditLogs.AsNoTracking().Where(x => ids.Contains(x.Id)).Select(x => x.Id).ToListAsync(token);
|
||||
existing = found.Select(x => (x, Guid.Empty)).ToHashSet();
|
||||
}
|
||||
else
|
||||
{
|
||||
var found = await db.TeachingTaskGradeStatistics.AsNoTracking().Where(x => ids.Contains(x.GradeSheetId)).Select(x => x.GradeSheetId).ToListAsync(token);
|
||||
existing = found.Select(x => (x, Guid.Empty)).ToHashSet();
|
||||
}
|
||||
await client.DeleteMissingAsync(table, keys.Where(key => !existing.Contains(key)).ToArray(), cutoff, token);
|
||||
cursor = keys[^1];
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<int> ProjectAuditsAsync(AppDbContext db, DateTime from, DateTime projectedAt, CancellationToken cancellationToken)
|
||||
{
|
||||
var cursorAt = from;
|
||||
|
||||
Loaded 3 of 4 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user