forked from mtusi2026/mtusi2026lab6
64 lines
2.4 KiB
Java
64 lines
2.4 KiB
Java
package ru.mtusi.messenger.service;
|
|
|
|
import lombok.RequiredArgsConstructor;
|
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.jdbc.core.JdbcTemplate;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.transaction.annotation.Propagation;
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
|
import ru.mtusi.messenger.exception.ServiceUnavailableException;
|
|
import ru.mtusi.messenger.telemetry.Telemetry;
|
|
|
|
import java.util.UUID;
|
|
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class ProcessingJobService {
|
|
private final Telemetry telemetry;
|
|
private final JdbcTemplate jdbc;
|
|
|
|
@Value("${pipeline.max-pending:100}")
|
|
private int maxPending;
|
|
|
|
@Value("${pipeline.max-attempts:5}")
|
|
private int maxAttempts;
|
|
|
|
@Transactional(propagation = Propagation.MANDATORY)
|
|
public void requireCapacity() {
|
|
jdbc.execute("SELECT pg_advisory_xact_lock(741205)");
|
|
Long pending =
|
|
jdbc.queryForObject(
|
|
"SELECT count(*) FROM processing_jobs WHERE status IN"
|
|
+ " ('QUEUED','PROCESSING')",
|
|
Long.class);
|
|
if (pending == null || pending >= maxPending) {
|
|
throw new ServiceUnavailableException("Processing queue capacity exhausted");
|
|
}
|
|
}
|
|
|
|
@Transactional(propagation = Propagation.MANDATORY)
|
|
public void enqueue(UUID attachmentId) {
|
|
var context = telemetry.carrier();
|
|
jdbc.update(
|
|
"""
|
|
WITH job AS (
|
|
INSERT INTO processing_jobs(attachment_id, pipeline_version, attempt_limit)
|
|
VALUES (?, 1, ?) RETURNING *
|
|
)
|
|
INSERT INTO processing_outbox(job_id, payload)
|
|
SELECT job_id, jsonb_strip_nulls(jsonb_build_object('schema_version',1,'job_id',job_id,
|
|
'type','attachment.process.v1','attachment_id',attachment_id,
|
|
'pipeline_version',pipeline_version,'attempt',1,
|
|
'created_at',to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
|
|
'traceparent',CAST(? AS text),'tracestate',CAST(? AS text)))
|
|
FROM job
|
|
""",
|
|
attachmentId,
|
|
maxAttempts,
|
|
context.get("traceparent"),
|
|
context.get("tracestate"));
|
|
}
|
|
}
|