feat(lineage): Phase 1 backend — dependents endpoints + REGRESSION test
dict-relationships-v2 epic, Phase 1 read-side. Backend готов; admin UI
(card "Used by" + record references) — отдельным commit'ом.
Что добавлено:
- `DependentsQuery` (interface) + `DependentsQueryJdbc` (impl) — native
SQL для record-level dependents lookup (paginated). Interface extracted
чтобы Mockito мог mock'нуть на JDK 25 (concrete-class inline-mock incompat).
- `LineageIndexService` — два режима:
* `findSchemaDependents(name, scopes)` — schema-level reverse FK list
(in-memory traversal definitions, microseconds). Skip self-reference,
scope-hidden sources, malformed x-references (logged warn).
* `findRecordDependents(dict, businessKey, scopes, page, size)` —
record-level paginated, perSource summary + total. Phase 2 переносит
на materialized view; пока живём с прямым JSONB query (acceptable
для <5k SLO).
- `LineageController` — два endpoint'а:
* `GET /api/v1/dictionaries/{name}/dependents`
* `GET /api/v1/records/{dict}/{businessKey}/dependents?page&size`
Errors: 404 dictionary_not_found / record_not_active, 400 invalid_pagination.
Scope hiding делает target invisible (empty list / 404 — без leak existence).
Tests:
- LineageIndexServiceTest (16 unit tests):
* Schema-level: not_found, scope hidden, single ref + count, onClose
propagation (BLOCK default + CASCADE explicit), sorting, source scope
hidden, self-reference skip, malformed skip, target without properties.
* Record-level: invalid pagination (page<0, size<1, size>200),
dict_not_found, record_not_active, no schema refs → empty page,
1 source с dependents → items+perSource+total, pagination через
page=0/1/2 size=2 (3 страницы из 5 records).
- ReferenceCloseRegressionTest (4 mandatory regression tests):
* v1.2.1 schema без x-references-on-close — validate() возвращает
те же error codes (никаких новых on_close/cascade в codes).
* Schema parser default'ит onClose=BLOCK для v1.2.1 schemas.
* Legacy single-arg parseRef(spec) без property schema сохраняет contract.
* Schema без x-references вообще — full no-op (30+ legacy справочников).
mvn -pl ordinis-rest-api -am test: 89/89 PASS (5.686s).
mvn verify -pl '!ordinis-app': все модули SUCCESS (9.031s).
Backward-compat: bundle v1.2.1 → identical поведение к v1.0.7. Cascade engine
не поднимается на closed-side (Phase 3 territory).
This commit is contained in:
+72
@@ -0,0 +1,72 @@
|
||||
package cloud.nstart.terravault.ordinis.domain.record;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Native SQL для record-level dependents lookup: "какие active записи в
|
||||
* source dictionary ссылаются на target record через JSONB
|
||||
* {@code data->>source_field == target_value}".
|
||||
*
|
||||
* <p>Используется {@code LineageIndexService.findRecordDependents} в Phase 1.
|
||||
* Phase 2 переносит этот lookup на materialized view с UNIQUE INDEX(id) для
|
||||
* REFRESH CONCURRENTLY — пока живём с прямым JSONB query (acceptable для
|
||||
* {@code <}5k records SLO).
|
||||
*
|
||||
* <p>Interface вместо concrete класса — JDK 25 + Mockito inline-mock не работает
|
||||
* на concrete classes (см. memo "JDK 25 + Mockito subclass mock-maker incompat").
|
||||
* Default impl {@link DependentsQueryJdbc} автоинджектится через @Component.
|
||||
*/
|
||||
public interface DependentsQuery {
|
||||
|
||||
/**
|
||||
* Active records в source_dict где {@code data->>source_field == value}.
|
||||
* Возвращает paginated slice + total count (один call для UI: count first,
|
||||
* потом page если total > 0).
|
||||
*
|
||||
* <p>NULL-значения в source_field автоматически исключены SQL'ом
|
||||
* (NULL != value никогда не true).
|
||||
*
|
||||
* <p>Order by created_at DESC чтобы newest dependents видны первыми
|
||||
* (admin debug pattern).
|
||||
*
|
||||
* @param sourceDictionaryId source dict (referencing)
|
||||
* @param sourceField JSONB key в source data что хранит ref value
|
||||
* @param targetValue фактическое значение target field в target record
|
||||
* @param at момент времени — обычно now()
|
||||
* @param limit page size (caller должен ограничить ≤ 200)
|
||||
* @param offset page offset (≥ 0)
|
||||
* @return slice records sorted by created_at DESC
|
||||
*/
|
||||
List<DependentRow> findActive(
|
||||
UUID sourceDictionaryId,
|
||||
String sourceField,
|
||||
String targetValue,
|
||||
OffsetDateTime at,
|
||||
int limit,
|
||||
int offset);
|
||||
|
||||
/**
|
||||
* Total count active dependents — отдельный query без LIMIT/OFFSET для
|
||||
* pagination header. Faster чем {@code SELECT COUNT(*)} над основным
|
||||
* results когда LIMIT/OFFSET идёт в отдельном request.
|
||||
*/
|
||||
long countActive(
|
||||
UUID sourceDictionaryId,
|
||||
String sourceField,
|
||||
String targetValue,
|
||||
OffsetDateTime at);
|
||||
|
||||
/**
|
||||
* Lightweight projection — лишний JSONB data в payload не нужен на этом
|
||||
* endpoint, экономим bandwidth.
|
||||
*/
|
||||
record DependentRow(
|
||||
UUID id,
|
||||
UUID dictionaryId,
|
||||
String businessKey,
|
||||
OffsetDateTime validFrom,
|
||||
OffsetDateTime validTo,
|
||||
OffsetDateTime createdAt) {}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package cloud.nstart.terravault.ordinis.domain.record;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* JdbcTemplate-backed default impl {@link DependentsQuery}.
|
||||
*
|
||||
* <p>Поля {@code source_field} приходят из schema parser (валидируются на
|
||||
* bundle import), плюс whitelist regex здесь — SQL injection невозможна.
|
||||
* Native SQL потому что JdbcTemplate не bind'ит JSONB key paths.
|
||||
*/
|
||||
@Component
|
||||
public class DependentsQueryJdbc implements DependentsQuery {
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
@Autowired
|
||||
public DependentsQueryJdbc(JdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DependentRow> findActive(
|
||||
UUID sourceDictionaryId,
|
||||
String sourceField,
|
||||
String targetValue,
|
||||
OffsetDateTime at,
|
||||
int limit,
|
||||
int offset) {
|
||||
validateField(sourceField);
|
||||
if (limit <= 0 || limit > 500) {
|
||||
throw new IllegalArgumentException("limit must be 1..500, got " + limit);
|
||||
}
|
||||
if (offset < 0) {
|
||||
throw new IllegalArgumentException("offset must be >= 0, got " + offset);
|
||||
}
|
||||
|
||||
String sql = """
|
||||
SELECT id, dictionary_id, business_key, valid_from, valid_to, created_at
|
||||
FROM dictionary_records
|
||||
WHERE dictionary_id = ?
|
||||
AND valid_from <= ?
|
||||
AND valid_to > ?
|
||||
AND data ->> '%s' = ?
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""".formatted(sourceField);
|
||||
|
||||
return jdbc.query(
|
||||
sql,
|
||||
(rs, n) -> new DependentRow(
|
||||
(UUID) rs.getObject("id"),
|
||||
(UUID) rs.getObject("dictionary_id"),
|
||||
rs.getString("business_key"),
|
||||
rs.getObject("valid_from", OffsetDateTime.class),
|
||||
rs.getObject("valid_to", OffsetDateTime.class),
|
||||
rs.getObject("created_at", OffsetDateTime.class)),
|
||||
sourceDictionaryId, at, at, targetValue, limit, offset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long countActive(
|
||||
UUID sourceDictionaryId,
|
||||
String sourceField,
|
||||
String targetValue,
|
||||
OffsetDateTime at) {
|
||||
validateField(sourceField);
|
||||
|
||||
String sql = """
|
||||
SELECT COUNT(*) FROM dictionary_records
|
||||
WHERE dictionary_id = ?
|
||||
AND valid_from <= ?
|
||||
AND valid_to > ?
|
||||
AND data ->> '%s' = ?
|
||||
""".formatted(sourceField);
|
||||
|
||||
Long count = jdbc.queryForObject(sql, Long.class, sourceDictionaryId, at, at, targetValue);
|
||||
return count == null ? 0 : count;
|
||||
}
|
||||
|
||||
/** Paranoid SQL injection guard. Mirror'ит {@code OrphanReferenceQuery}. */
|
||||
private static void validateField(String field) {
|
||||
if (field == null || field.isBlank()) {
|
||||
throw new IllegalArgumentException("field name is empty");
|
||||
}
|
||||
if (!field.matches("^[a-zA-Z_][a-zA-Z0-9_]{0,127}$")) {
|
||||
throw new IllegalArgumentException(
|
||||
"field name has unsafe characters: " + field);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user