feat(jaci): Jaci-lite photo gallery backend (Fase 3) - #157
Conversation
|
Warning Review limit reached
More reviews will be available in 34 minutes and 31 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Repository UI Review profile: ASSERTIVE Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (9)
WalkthroughEste PR implementa a galeria Jaci-lite completa: um comportamento de leitura paginado (list_photos com keyset por ID; timeline com keyset composto por data efetiva + ID), análise lightweight de imagens (EXIF com fallback para inserted_at), geração assíncrona de thumbnails WebP pós-upload via worker Oban, e um endpoint autenticado para servir thumbnails com cache privado de 24h. A solução filtra apenas imagens não-deletadas, executa todo o fluxo sob isolamento RLS, e usa cursores opacos base64 para paginação keyset segura. Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai review |
|
✅ Action performedReview finished.
|
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 9
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@lib/taina/jaci.ex`:
- Line 44: A ordenação em order_by atualmente usa [desc: f.inserted_at, desc:
f.id] mas o cursor/filtragem só usa id, o que pode causar paginação
inconsistente; alinhe-os: ou altere order_by para ordenar apenas por id
(substituir por [desc: f.id]) e manter o cursor tal como está, ou expanda o
cursor para carregar inserted_at e id e ajustar a cláusula de paginação para
comparar primeiro inserted_at e depois id (implementando a lógica keyset:
inserted_at < cursor.inserted_at OR (inserted_at == cursor.inserted_at AND id <
cursor.id)) mantendo order_by como [desc: f.inserted_at, desc: f.id]; ajuste
tanto a geração/decodificação do cursor quanto as condições de where/filtragem
correspondentes.
In `@lib/taina/ybira.ex`:
- Around line 113-119: The current maybe_enqueue_rendition/2 calls Oban.insert()
directly which will propagate failures and abort the transaction; change it to
handle insert failures gracefully by pattern-matching the result of
Oban.insert(Rendition.new(%{file_id: file.id, tekoa_public_id:
scope.tekoa.public_id})) (or wrap in a try/rescue if you expect exceptions),
logging any {:error, reason} or caught exception via Logger.error with context
(include file.id and scope.tekoa.public_id) and returning a non-failing value
(e.g., :ok or the original file) so image uploads aren't blocked by transient
Oban failures; if you intend atomic behavior instead, add a clarifying comment
above maybe_enqueue_rendition/2 explaining the choice to let Oban.insert
failures roll back the transaction.
In `@lib/taina/ybira/media.ex`:
- Line 47: O trecho usa File.mkdir_p/1 (não existente) dentro do with; substitua
pela chamada correta File.mkdir_p!/1 e trate a possível exceção no bloco que
envolve essa chamada (ou ajuste o with para lidar com {:ok, _} / {:error, _}
retornos conforme preferir), referenciando a expressão com Path.dirname(dest)
usada para criar o diretório antes de seguir no fluxo; garanta que o pattern
matching no with (atualmente :ok <- ...) corresponda ao comportamento da versão
escolhida (bang levanta exceção que deve ser capturada com rescue, não pattern
matched).
In `@lib/taina/ybira/workers/rendition.ex`:
- Around line 56-57: A chamada a Repo.update/1 em YbiraFile.changeset(file,
%{metadata: metadata}) está descartando o resultado; altere para capturar o
retorno (por exemplo pattern match com {:ok, _updated} | {:error, changeset}) e
propague ou retorne o erro em vez de sempre devolver :ok, para que falhas de
validação/constraint não sejam silenciadas; atualize a função que contém essa
linha (no módulo rendition.ex) para tratar {:error, changeset} — seja retornando
{:error, changeset} para permitir retry/registro ou registrando detalhes de erro
antes de falhar.
- Around line 32-43: The perform/1 currently ignores the result of
Repo.with_tekoa/2 and always returns :ok, so transient render/2 failures won't
be retried; change perform/1 to return the outcome of Repo.with_tekoa/2
(propagate {:ok, _} or {:error, _}) instead of unconditional :ok, and where
render/2 returns definitive errors convert them to {:discard, reason} while
leaving transient errors as {:error, reason} so Oban can retry; update the
perform function to call Repo.with_tekoa(..., fn -> ... end) and directly return
its result (mapping render/2 responses to {:discard, reason} when appropriate).
In `@mix.exs`:
- Line 57: The dependency {:image, "~> 0.54"} is pinned to a line that now
requires Elixir ≥ 1.16; update mix.exs to fix compatibility by either (A)
bumping the :image dependency to a newer compatible release (e.g., "~> 0.68" or
a specific 0.68.0) in the deps list where {:image, "~> 0.54"} appears, or (B)
raising the project Elixir requirement (the :elixir entry in project/def
project) to ">= 1.16.0" so the current :image constraint remains valid—pick one
approach and update the corresponding tuple or :elixir requirement accordingly.
In `@test/taina_web/controllers/file_thumbnail_test.exs`:
- Around line 20-22: Adicionar uma asserção no teste em
test/taina_web/controllers/file_thumbnail_test.exs que verifique o header
"cache-control" na resposta; no bloco onde já checa conn.status e content-type
(usando conn), confirme que get_resp_header(conn, "cache-control") retorna
["private, max-age=86400"] para garantir cache privado por 24h no endpoint de
thumbnail.
In `@test/taina/jaci_test.exs`:
- Around line 37-48: O teste atual pode passar por coincidência de ordem de
upload; ajuste para criar conflito entre ordem de upload e EXIF: ao invés da
ordem atual, faça upload do "other" antes e do "recent" depois (usar
Ybira.upload/tmp_image_fixture como já feito) para que a ordem por upload seja
contrária à ordenação por taken_at, chame set_taken_at(recent.id, ~N[...]) com
uma data antiga e então compare a lista completa de public_id retornada por
Jaci.timeline(scope) com a ordem esperada que reflita a ordenação por EXIF (usar
groups |> Enum.flat_map(& &1.photos) |> Enum.map(& &1.public_id) para obter a
sequência).
In `@test/taina/ybira/rendition_test.exs`:
- Line 22: The test currently only checks that the metadata key "taken_at"
exists but not its value; update the assertion to also validate that the value
is null by using is_nil/1 on the retrieved value (e.g., call
Map.get(photo.metadata, "taken_at") or access photo.metadata["taken_at"] and
assert is_nil/1). Target the test where the variable photo and its metadata map
are used and replace or add to the Map.has_key?(photo.metadata, "taken_at")
check so the contract ensures the value is nil when no EXIF is present.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 546aae3d-1710-4606-bd91-eb70effd4da0
⛔ Files ignored due to path filters (2)
flake.lockis excluded by!**/*.lockmix.lockis excluded by!**/*.lock
📒 Files selected for processing (17)
flake.nixlib/taina/jaci.exlib/taina/jaci/behaviour.exlib/taina/jaci/timeline.exlib/taina/ybira.exlib/taina/ybira/media.exlib/taina/ybira/workers/rendition.exlib/taina_web/controllers/file_controller.exlib/taina_web/router.exmix.exspriv/repo/migrations/20260610132827_jaci_photo_indexes.exstest/support/fixtures.extest/taina/jaci/timeline_test.exstest/taina/jaci_test.exstest/taina/ybira/purge_trash_test.exstest/taina/ybira/rendition_test.exstest/taina_web/controllers/file_thumbnail_test.exs
Signed-off-by: zoey <zoey.spessanha@zeetech.io>
Problema
A aplicação necessita de um backend para galeria de fotos (Jaci-lite Fase 3) que permita listar fotos com paginação eficiente, exibir uma timeline ordenada pela data de captura, gerar miniaturas otimizadas de imagens e servir essas miniaturas aos usuários autenticados.
Solução
O PR implementa uma camada completa de leitura da galeria através do módulo
Taina.Jaci, que fornece dois endpoints principais:list_photos/2para exibição em grade com paginação por keyset baseada emid, etimeline/2para ordenação por data efetiva de captura com paginação composta(taken_at, id). O processamento de imagens é realizado automaticamente após upload através de um worker Oban (Taina.Ybira.Workers.Rendition) que extrai metadados EXIF e gera thumbnails WebP em diferentes tamanhos. Um novo endpoint HTTP (GET /files/:public_id/thumbnail/:size) permite servir esses thumbnails com cache adequado. O suporte a imagem é adicionado via dependência:image ~> 0.54e bibliotecavipsno ambiente de desenvolvimento.Explicação
A implementação utiliza paginação por keyset em vez de offset para maior eficiência em grandes conjuntos de dados. A data de captura é extraída por ordem de preferência:
taken_atdo EXIF (emmetadata) ou fallback parainserted_at. Thumbnails em WebP oferecem melhor compressão que formatos alternativos. O processamento assíncrono via Oban evita bloqueio durante upload. Row-Level Security (RLS) é respeitado através deRepo.with_tekoa/2em todas as operações. Um índice parcial nas imagens não-deletadas otimiza as queries de lista. Testes cobrem paginação, agrupamento por data e geração de renditions com e sem dados EXIF.