Skip to content

feat(jaci): Jaci-lite photo gallery backend (Fase 3) - #157

Merged
zoedsoupe merged 5 commits into
mainfrom
feat/jaci-lite-fase3
Jun 11, 2026
Merged

zoedsoupe merged 5 commits into
mainfrom
feat/jaci-lite-fase3

Conversation

@zoedsoupe

@zoedsoupe zoedsoupe commented Jun 10, 2026

Copy link
Copy Markdown
Member

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/2 para exibição em grade com paginação por keyset baseada em id, e timeline/2 para 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.54 e biblioteca vips no 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_at do EXIF (em metadata) ou fallback para inserted_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 de Repo.with_tekoa/2 em 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.

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@zoedsoupe, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4426c864-4e74-4b05-b60e-a7d7426c9a29

📥 Commits

Reviewing files that changed from the base of the PR and between def1bc5 and dca8f88.

⛔ Files ignored due to path filters (1)
  • mix.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • config/config.exs
  • lib/taina/jaci.ex
  • lib/taina/ybira/workers/rendition.ex
  • lib/taina_web/router.ex
  • mix.exs
  • test/taina/jaci_test.exs
  • test/taina/ybira/rendition_test.exs
  • test/taina/ybira_test.exs
  • test/taina_web/controllers/file_thumbnail_test.exs

Walkthrough

Este 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

  • taina-labs/taina#27: As mudanças implementam Taina.Jaci (list_photos/2, timeline/2 com agrupamento) que atendem diretamente aos casos de uso de listagem e timeline de fotos.
  • taina-labs/taina#45: O worker Rendition (Taina.Ybira.Workers.Rendition) analisa imagens, gera thumbnails WebP e atualiza metadados — endereçando exatamente essa responsabilidade.
  • taina-labs/taina#47: A migration JaciPhotoIndexes cria índice para fotos Jaci, alinhada com a criação de migrações Jaci-related.

Possibly related PRs

  • taina-labs/taina#151: Os dois PRs integram o domínio Taina.Ybira e workers Oban — #151 cria a base de workers/config, enquanto este PR adiciona o enfileiramento específico do worker de renditions pós-upload.

Poem

🌿 Fotos nascem, metadados desabrocham
Keyset dança pelas datas, EXIF sussurra origens
WebP brota em threads Oban, thumbnails à mão
Soberania das imagens, sem big tech a espreitar 📸

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning A descrição do PR está vazia, deixando de preencher as seções obrigatórias (Problem, Solution, Rationale) definidas no template do repositório. Preencha a descrição seguindo o template: descreva o problema que a Jaci-lite Fase 3 resolve, a solução implementada e a justificativa das escolhas arquiteturais e de implementação.
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed O título descreve claramente a mudança principal: a implementação do backend Jaci-lite photo gallery (Fase 3), sendo específico e diretamente relacionado ao conteúdo do PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/jaci-lite-fase3

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@zoedsoupe

zoedsoupe commented Jun 10, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

@zoedsoupe Claro! Vou iniciar a revisão do PR agora. 🚀

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 88e0446 and def1bc5.

⛔ Files ignored due to path filters (2)
  • flake.lock is excluded by !**/*.lock
  • mix.lock is excluded by !**/*.lock
📒 Files selected for processing (17)
  • flake.nix
  • lib/taina/jaci.ex
  • lib/taina/jaci/behaviour.ex
  • lib/taina/jaci/timeline.ex
  • lib/taina/ybira.ex
  • lib/taina/ybira/media.ex
  • lib/taina/ybira/workers/rendition.ex
  • lib/taina_web/controllers/file_controller.ex
  • lib/taina_web/router.ex
  • mix.exs
  • priv/repo/migrations/20260610132827_jaci_photo_indexes.exs
  • test/support/fixtures.ex
  • test/taina/jaci/timeline_test.exs
  • test/taina/jaci_test.exs
  • test/taina/ybira/purge_trash_test.exs
  • test/taina/ybira/rendition_test.exs
  • test/taina_web/controllers/file_thumbnail_test.exs

Comment thread lib/taina/jaci.ex Outdated
Comment thread lib/taina/ybira.ex
Comment thread lib/taina/ybira/media.ex
Comment thread lib/taina/ybira/workers/rendition.ex
Comment thread lib/taina/ybira/workers/rendition.ex Outdated
Comment thread mix.exs Outdated
Comment thread test/taina_web/controllers/file_thumbnail_test.exs
Comment thread test/taina/jaci_test.exs
Comment thread test/taina/ybira/rendition_test.exs
@zoedsoupe
zoedsoupe merged commit 3a7a753 into main Jun 11, 2026
5 checks passed
@zoedsoupe
zoedsoupe deleted the feat/jaci-lite-fase3 branch June 11, 2026 01:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant