feat(redis-projection): per-dict feature flag (CEO plan E2 tiered perf)

Per-dictionary opt-in для Redis projection materialization. Default false
— projection-writer пропускает event'ы того dict'а, никаких dead writes
в Redis. Включается админ'ом через UI checkbox в Metadata tab.

Migration 0017:
- ALTER TABLE dictionary_definitions ADD COLUMN redis_projection_enabled
  BOOLEAN NOT NULL DEFAULT false.
- Index idx_dict_def_redis_proj для быстрого filtering в list queries.

Backend:
- DictionaryDefinition entity: new field + getter/setter.
- DictionaryResponse DTO: returns flag в response.
- CreateDictionaryRequest DTO: optional Boolean (null/missing = no change).
- DictionaryDefinitionService.create + updateSchema: применяет flag из request.
- ProjectionWriter (projection-writer service):
  * upsert() — early-return + skip counter если flag=false на dict.
  * delete() — symmetric: skip если flag=false (защита от stale keys
    после flag-flip; полный cleanup TODO Phase 2).
  * New metric: ordinis_projection_records_skipped_total.

Admin UI:
- DictionaryEditorDialog Metadata tab: checkbox "Включить Redis-проекцию"
  с описанием. Apply через CreateDictionaryRequest payload.
- DictionaryDefinition + CreateDictionaryRequest types updated.
- i18n RU/EN: schema.redisProjection.{label,hint}.

Что НЕ делается (deferred Phase 2):
- read-api Redis routing — read-api сейчас всегда идёт в PG read replica.
  Когда dict опт-инится в флаг, projection материализуется, но read-api
  ещё не использует. Read routing — отдельная feature с benchmark proof
  (через JMH + k6 SLO test).
- One-shot cleanup job для stale keys после flag-flip from true→false.

Behavior change в production:
- До patch: projection-writer пишет в Redis для ВСЕХ dict events (40
  dictionaries). Default flag=false после migration → projection-writer
  пропускает всё → Redis keys для existing dicts становятся stale.
  Это OK потому что read-api НИКОГДА не читал из Redis (writes были
  dead). Stale keys eventually evicted Redis maxmemory policy.
- После patch: только dicts с redis_projection_enabled=true получают
  материализацию. По default — нет. Admin opt-ins per-dict через UI.

Verify:
- mvn test (full reactor): SUCCESS, all green.
- mvn -P e2e -pl ordinis-app -am test: 20/20 PASS (migration 0017 applied).
- pnpm tsc --noEmit: clean.
- pnpm test (vitest): 89/89 PASS.
- pnpm build: clean.
This commit is contained in:
Zimin A.N.
2026-05-08 12:34:58 +03:00
parent c11044c32e
commit 0a8275ef4c
10 changed files with 117 additions and 1 deletions
@@ -33,6 +33,7 @@ public class ProjectionWriter {
private final ObjectMapper objectMapper;
private final Counter recordsWrittenCounter;
private final Counter recordsDeletedCounter;
private final Counter recordsSkippedCounter;
public ProjectionWriter(
StringRedisTemplate redis,
@@ -48,6 +49,9 @@ public class ProjectionWriter {
this.recordsDeletedCounter = Counter.builder("ordinis_projection_records_deleted_total")
.description("Удалено из Redis projection")
.register(meterRegistry);
this.recordsSkippedCounter = Counter.builder("ordinis_projection_records_skipped_total")
.description("Skipped (dict has redis_projection_enabled=false). CEO E2 tiered perf.")
.register(meterRegistry);
}
@Transactional(readOnly = true)
@@ -58,6 +62,17 @@ public class ProjectionWriter {
return;
}
DictionaryDefinition def = defOpt.get();
// CEO plan E2 (Tiered perf): per-dict opt-in. Default false → projection
// не материализуется в Redis (read-api идёт в PG read replica).
// Admin переключает true когда dict упирается в RPS limit на PG.
if (!def.isRedisProjectionEnabled()) {
recordsSkippedCounter.increment();
log.trace("Projection upsert SKIPPED ({} has redis_projection_enabled=false): {}",
dictionary, businessKey);
return;
}
JsonNode schema = def.getSchemaJson();
String[] locales = def.getSupportedLocales();
@@ -75,7 +90,18 @@ public class ProjectionWriter {
log.debug("Projection upserted: {}:{} ({} locales)", dictionary, businessKey, locales.length);
}
@Transactional(readOnly = true)
public void delete(String bundle, String dictionary, String businessKey) {
Optional<DictionaryDefinition> defOpt = definitionRepository.findByName(dictionary);
if (defOpt.isPresent() && !defOpt.get().isRedisProjectionEnabled()) {
// Symmetric с upsert: nothing to delete если проекция выключена.
// Защита от случая когда раньше flag был true → есть keys → потом стал
// false → keys остаются stale. Этот edge case покрывается через
// отдельную one-shot cleanup job (TODO Phase 2 read-api routing).
recordsSkippedCounter.increment();
return;
}
Set<String> matching = redis.keys(RedisKeys.recordKeyPattern(bundle, dictionary, businessKey));
if (matching != null && !matching.isEmpty()) {
redis.delete(matching);