penpot/backend/src/app/rpc.clj
Juan de la Cruz ea61730f61
✨ Add review mode, review comments and tasks to design reviews (#12939)
* ✨ Add review mode, review comments and tasks to design reviews

A design review now opens a read-only review mode. The left panel shows
the pages and layers with the View only badge, the toolbar offers the
review tools (move, comment, comment an area, create a task, show the
changes) and the right panel holds the inspect of the selection, the
comments of the review and its tasks. A bar at the bottom names the
review, shows the progress of its tasks and opens its details.

Comments can point at a spot, a layer or an area, and a comment written
in a review says so with its own mark, wherever the file is open. The
layers panel counts the open comments of each layer.

Tasks are new: work on a file, assigned to someone and tied to a layer
or to a spot of the canvas. A comment can become a task and stays
attached to it. A task moves through open, done, verified, reopened and
won't do; anybody may move it, and each move is an event that records
who made it. Deleting a layer with open tasks moves them to its board
and offers to undo the deletion or to mark them done; a task can then
be linked to another layer or get its layer back. Assignees are told by
email. Merging a branch moves its tasks and their threads into main:
the open ones keep going, the closed ones stay as its history, and the
merge dialog lists them and can tell their assignees.

The details of a review show its overview, its tasks and its activity:
what the saves of the branch did to each layer since the review opened,
by person and day, with the values before and after. The changes can be
shown on the canvas one after another.

The backend adds the review fields of a comment thread, the task and
task event tables, the activity of a review (recorded by each save of a
branch under review) and the commands of the tasks.

* ♻️ Bring the design review styles and components up to the DS

Move what the review UI repeated into the design system: layer-chip*,
progress-bar*, comment-card*, link-button* and textarea*, each with its
story and docs. The screens keep the look they had: the same review states
compare equal, pixel by pixel, before and after.

The stylesheets follow the rules of the UI guide: local variables for the
colors that change by state, the right tokens, no unused imports and fewer
element and nested selectors. What has no DS token or typography says so in
a TODO. The aliases left in comments.scss resolve to their tokens.

The components get complete schemas and a single owner for the copyright.
Translations take literal keys and templates instead of dynamic keys and
glued strings, and comments.cljs no longer depends on the review tasks: the
workspace passes it what a thread shows about its task.

Fix three bugs of the review:

- The inspect took the width of a narrower panel and its height from the
  window, so it looked squeezed and cut its last rows. It now fills the
  panel that holds it.
- Enter on the menu of a task opened the task. The row now reacts only to
  keys on itself, and the menu keeps Enter from the workspace shortcuts.
- The resolved and lost marks ignored the pointer: hover now wins over the
  state of a mark.

* ✨ Turn each review message into a task and restore the filter dropdown

Each message of a thread can now become a task, so one thread can hold
several. The new file_task.comment_id column records the message, the
migration fills it with the first message of the thread for existing tasks,
and the backend rejects a message from another thread or one that already
has a task.

Comments and tasks of a review behave like normal ones. The canvas marks
show a short preview on hover and there is one mark per task. A blue label
marks what belongs to a review, in the thread and in the sidebar, and a
selected card takes a blue border there and the primary color elsewhere.
The new review-label* component holds the label.

The sidebar and the review panel go back to a filter dropdown in place of
the chips. Comments offer the views all, yours and mentions, with an option
to hide the resolved ones. Tasks offer all, yours, open and to verify, with
an option to hide the closed ones. Resolved comments now show by default.

"New task" outside a review now arms the task tool: it shows the task cursor
and the next click opens the task form, not a comment. Then the comment tool
returns, and Esc leaves the tool.

The details modal shows changed properties in the format of the compare
dialogs, and showing a task on the canvas syncs the WASM viewport. The sidebar
cards put the layer chip on the line of the replies, and task states lose the
dot and take a color each.

Fix these bugs:

- The hover card of the activity tab crashed on a change with no token.
- The assignee and reviewer dropdowns came out cut. The select now portals
  into the closest dialog, because the modal makes the rest of the page inert.
- The review label cut the header of the thread. It now sits below it.

* ✨ Group overlapping review marks and let tasks change assignee

Comments and tasks of a review that fall on the same spot now show as one
mark with a counter in a white bubble. A click fans them out, as the comment
bubbles do, and the user picks one. They group on the same layer and, by
proximity, at a low zoom. The card of the mark lists up to five items.

Hovering a mark outlines its layer, or its board when the layer is gone. The
WASM viewport draws no outlines under the comments tool, so it now draws the
highlighted ones there. Opening a comment from a mark closes the open task.

A task can change assignee from the selector in its state and from "Assign
to" in its menu, which holds the team in the same popover. The change shows
right away and goes to the history of the task. A closed task keeps its
assignee.

Deleting a task or a comment now asks first, with the usual confirmation. A
task deleted from the details of a review brings the dialog back on its tab.

The state of a task takes two rows, in its panel and in a thread: state and
layer, then assignee and the review it comes from, which a review omits. The
text of tasks and comments sits in a box. The history no longer says that the
task was created.

* ✨ Keep the branch bar and the palettes at one level on a branch

The open branch bar covered the horizontal scroll of the canvas. It now sits
as far from the bottom as the review bar. Folded, it stays flush.

On a branch the palettes no longer lift over the branch bar: both sit at the
same level and work as a toggle. Opening one folds the other, also through
the palette shortcuts, and both can stay folded. The new `:bottom-bar` state
says which one is open. It exists only while the branch bar does, so a file
that is not a branch keeps the palettes on their layout flags and at their
usual place, and what happens on a branch does not reach them.

The branch bar comes open on a branch and centers on the canvas, not on the
window, so that it clears the folded palettes at usual widths. The room it
published for the palettes goes away with the lifting.

* ✨ Give every task a thread and tidy the design review screens

Every task now lives in a message of a comment thread, so anyone can go on
commenting on it. A task made from scratch gets a thread whose first message
is its title, on its layer and in its review, created in the same
transaction. A comment turned into a task keeps its thread, as before. The
panel of a task with no thread is gone: a task always opens as its thread.
Migration 0814 gives a thread to the tasks that had none. Deleting a thread
deletes its tasks, after a confirmation that says so.

The anchor of a task was a plain map, not a point, so a thread on a layer
refused replies. It is now a point.

The details of a review filter the tasks by state with the chips of the
activity, in the colour of each state, and show how many are closed on the
right. The "New task" button leaves the dialog.

Descriptions look the same everywhere: the box of the branch info dialog,
an "Edit" button and a dashed box when empty. Read, they grow up to 400px
and scroll inside; edited, the textarea starts at 400px. The text of a
review in the sidebar does the same once unfolded.

In the review bar, the author gets a "Publish latest changes" button when
the branch moved past the review, with a hint that approvals must be
renewed. The others keep a badge, now "Unpublished changes", with a hint.
The bar refreshes once the publish lands.

Smaller changes: the resolve checkbox lines up with the task button and has
a tooltip, messages sit in a filled box, task events take an outline, and
the change navigator sits right above the review bar.

* 💄 Sort the test runner requires that cljfmt rejects

The Frontend Tests lint step fails on runner.cljs: the requires for
workspace-tasks-test, review-details-test and review-markers-test sat
out of alphabetical order. This is the output of cljfmt fix.

AI-assisted-by: claude-opus-5-5
Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>

* 🐛 Test the design review mode in the pull request spec

The review bar replaced the branch banner, so four tests still drove
the branch bar: a visible Compare button, the rectangle tool and the
Review button. They now drive the design review instead.

* Opening a file with a pr-id enters the review: the bar names the
  review, the header trades the file name for the review title, and
  comparing, merging and cancelling sit in the bar's options menu.
* The compare dialog opens from that menu.
* The review is read-only rather than an editable file: the review
  toolbar offers its five tools, the drawing tools are gone, the
  sidebar says View only, and the right panel is the review's own
  Inspect, Comments and Tasks tabs.
* The verdict comes from the bar's Submit review button and the
  dialog it opens, scoped by role so the bar action and the dialog
  action do not collide.

The tests also reach the review bar by its region label instead of
walking up three parents from the Reviewing the design review text,
which broke as soon as the bar's markup changed.

AI-assisted-by: claude-opus-5-5
Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>

* 🐛 Count only the test thread's acquisitions in the climit test

acquires-the-command-own-limits-before-the-root-limits failed on CI
with an extra "root/global" ahead of the expected order. The test
records metrics through with-redefs, which is global, so a call of
another thread of the test JVM, such as an RPC an earlier test left
running, can take a root limiter inside the window and land in the
same atom.

Record the thread with each metrics call and keep, in
acquired-in-order, only the acquisitions of the calling thread. Both
tests that read it acquire their limiters on the test thread. The
same class of flake was fixed on develop for the waiting-count test
(12d73d0f63); this one is still open there.

AI-assisted-by: claude-opus-5-5
Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>

* 📚 Describe the task moves the server allows in the table comment

The comment on file_task said a task is reopened only from done and
that editors move tasks. files_task.clj::transitions also reopens a
verified or won't-do task, and set-task-status lets anybody who can
read the file move one. Say the same in the schema.

AI-assisted-by: claude-opus-5-5
Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>

---------

Signed-off-by: Álvaro Tejero Cantero <alvorithm@teje.ro>
Co-authored-by: Álvaro Tejero Cantero <alvorithm@teje.ro>
2026-11-17 22:30:22 +01:00

581 lines
23 KiB
Clojure

;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns app.rpc
(:require
[app.auth.ldap :as-alias ldap]
[app.common.data :as d]
[app.common.exceptions :as ex]
[app.common.logging :as l]
[app.common.schema :as sm]
[app.common.spec :as us]
[app.common.time :as ct]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.http :as-alias http]
[app.http.access-token :as actoken]
[app.http.client :as-alias http.client]
[app.http.middleware :as mw]
[app.http.security :as sec]
[app.http.session :as session]
[app.loggers.audit :as audit]
[app.main :as-alias main]
[app.metrics :as mtx]
[app.msgbus :as-alias mbus]
[app.nitrate :as nitrate]
[app.redis :as rds]
[app.rpc.climit :as climit]
[app.rpc.commands.teams :as teams]
[app.rpc.cond :as cond]
[app.rpc.doc :as doc]
[app.rpc.helpers :as rph]
[app.rpc.retry :as retry]
[app.rpc.rlimit :as rlimit]
[app.setup :as-alias setup]
[app.storage :as-alias sto]
[app.util.cache :as cache]
[app.util.inet :as inet]
[app.util.services :as sv]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[cuerdas.core :as str]
[integrant.core :as ig]
[yetti.request :as yreq]
[yetti.response :as yres]))
(s/def ::profile-id ::us/uuid)
(defn- default-handler
[_]
(ex/raise :type :not-found))
(defn- handle-response-transformation
[response request mdata]
(reduce (fn [response transform-fn]
(transform-fn request response))
response
(::response-transform-fns mdata)))
(defn- handle-before-comple-hook
[response mdata]
(doseq [hook-fn (::before-complete-fns mdata)]
(ex/ignoring (hook-fn)))
response)
(defn- handle-response
[request result]
(let [mdata (meta result)
response (if (fn? result)
(result request)
(let [result (rph/unwrap result)
status (or (::http/status mdata)
(if (nil? result)
204
200))
headers (::http/headers mdata {})
headers (cond-> headers
(and (yres/stream-body? result)
(not (contains? headers "content-type")))
(assoc "content-type" "application/octet-stream"))]
{::yres/status status
::yres/headers headers
::yres/body result}))]
(-> response
(handle-response-transformation request mdata)
(handle-before-comple-hook mdata))))
(defn make-rpc-handler
"Ring handler that dispatches cmd requests and convert between
internal async flow into ring async flow."
[methods]
(let [methods (update-vals methods peek)]
(fn [{:keys [path-params method] :as request}]
(let [handler-name (:method-name path-params)
etag (yreq/get-header request "if-none-match")
session-id (yreq/get-header request "x-session-id")
key-id (get request ::http/auth-key-id)
session-pid (::session/profile-id request)
token-pid (::actoken/profile-id request)
profile-id (or session-pid
token-pid
(if key-id uuid/zero nil))
ip-addr (inet/parse-request request)
data (-> {}
(assoc ::handler-name handler-name)
(assoc ::ip-addr ip-addr)
(assoc ::request-at (ct/now))
(assoc ::request-id (uuid/next))
(assoc ::session-id (some-> session-id uuid/parse*))
(assoc ::cond/key etag)
(cond-> (uuid? profile-id)
(assoc ::profile-id profile-id))
(cond-> (uuid? session-pid)
(assoc ::auth-type :session))
(cond-> (and (not (uuid? session-pid))
(uuid? token-pid))
(-> (assoc ::auth-type :token)
(assoc ::token-perms (set (::actoken/perms request #{})))
(assoc ::token-type (::actoken/type request))))
(cond-> key-id
(assoc ::auth-key-id key-id))
;; Server-side only: request bodies cannot forge
;; it (qualified keys are stripped before the
;; merge). Upload maps are only trusted when they
;; arrive over multipart.
(assoc ::is-multipart
(str/starts-with?
(str (yreq/get-header request "content-type"))
"multipart/")))
data (with-meta data
{::http/request request})
handler-fn (get methods (keyword handler-name) default-handler)]
(when (and (or (= method :get)
(= method :head))
(not (str/starts-with? handler-name "get-")))
(ex/raise :type :restriction
:code :method-not-allowed
:hint "method not allowed for this request"))
;; FIXME: why we have this cond enabled here, we need to move it outside this handler
(binding [cond/*enabled* true]
(let [response (handler-fn data)]
(handle-response request response)))))))
(defn- wrap-metrics
"Wrap service method with metrics measurement."
[{:keys [::mtx/metrics ::metrics-id]} f mdata]
(let [labels (into-array String [(::sv/name mdata)])]
(fn [cfg params]
(let [tp (ct/tpoint)]
(try
(f cfg params)
(finally
(mtx/run! metrics
:id metrics-id
:val (inst-ms (tp))
:labels labels)))))))
(defn- wrap-authentication
[_ f mdata]
(let [required-auth? (::auth mdata true)
required-auth-type (::auth-type mdata)
required-token-type (::token-type mdata)
required-perms (into #{} (::perms mdata))]
(fn [cfg params]
(let [profile-id (::profile-id params)
auth-type (::auth-type params)
token-type (::token-type params)
token-perms (set (::token-perms params #{}))]
(cond
(and required-auth? (not (uuid? profile-id)))
(ex/raise :type :authentication
:code :authentication-required
:hint "authentication required for this endpoint")
(or (and (= required-auth-type :token)
(not= auth-type :token))
(and required-token-type
(or (not= auth-type :token)
(not= required-token-type token-type)))
(and (= token-type "mcp")
(not= required-token-type "mcp")))
(ex/raise :type :authorization
:code :token-auth-required
:hint "access token authentication required for this endpoint")
(and (seq required-perms)
(not= auth-type :token))
(ex/raise :type :authorization
:code :token-auth-required
:hint "access token authentication required for this endpoint")
(and (seq required-perms)
(not (set/subset? required-perms token-perms)))
(ex/raise :type :authorization
:code :missing-perms
:hint "missing required permissions"
:required required-perms)
:else
(f cfg params))))))
(defn- wrap-db-transaction
[_ f mdata]
(if (::db/transaction mdata)
(fn [cfg params]
(db/tx-run! cfg f params))
f))
(defn- wrap-audit
[_ f mdata]
(if (or (contains? cf/flags :webhooks)
(contains? cf/flags :audit-log)
(contains? cf/flags :telemetry))
(if-not (::audit/skip mdata)
(fn [cfg params]
(let [result (f cfg params)]
(->> (audit/prepare-rpc-event cfg mdata params result)
(audit/submit cfg))
result))
f)
f))
(defn- wrap-params-validation
[_ f mdata]
(if-let [schema (::sm/params mdata)]
(let [validate (sm/validator schema)
explain (sm/explainer schema)
decode (sm/decoder schema sm/json-transformer)
encode (sm/encoder schema sm/json-transformer)]
(fn [cfg params]
(let [request-params (-> params meta ::http/request :params decode)]
(if (validate request-params)
(let [merged (merge params (d/without-qualified request-params))]
;; Upload temp files are created server-side by the multipart
;; parser, so an upload map smuggled in a transit/JSON body can
;; point :path at any internal server file. Methods declare
;; their upload keys with ::multipart-only-params and they are
;; only accepted when ::is-multipart arrived server-side with
;; the request (request bodies cannot forge qualified keys).
(when (some #(and (contains? merged %)
(not (::is-multipart merged)))
(::multipart-only-params mdata))
(ex/raise :type :validation
:code :params-validation
:hint "upload requires multipart"))
(let [result (f cfg merged)]
(if (instance? clojure.lang.IObj result)
(vary-meta result assoc :encode/json encode)
result)))
(ex/raise :type :validation
:code :params-validation
::sm/explain (explain request-params))))))
f))
(defonce ^:private organization-sso-auth-cache
(cache/create :expire "15m" :max-size 1024))
(defn invalidate-organization-sso-cache-by-organization!
"Invalidates all organization-SSO authorization cache entries for the given organization-id."
[organization-id]
(cache/invalidate-if organization-sso-auth-cache #(= (:organization-id %) organization-id)))
(defn- wrap-nitrate-sso
"Enforce Nitrate organization SSO authentication for RPC handlers.
Resolves the organization/team context from request params:
1. Explicit :organization-id param identifies the organization directly
2. The team comes from the first available of: explicit :team-id, explicit
:project-id -> lookup project.team_id, explicit :file-id -> lookup file's
team via join, or the :id param dispatched by ::rpc/id-type metadata
(:team, :project, or :file)
Once the context is resolved, checks if the user is authorized within that organization's
SSO session using nitrate/sso-session-authorized?, against the organization when it is
known and against the team otherwise. The team is resolved either way, so the raised
error can carry it. Authorized results are cached by [profile-id cache-ref] for 15
minutes to avoid repeated lookups.
Only activates when:
- Nitrate flag is enabled
- Endpoint requires authentication (::auth true by default)
- Endpoint is not marked with ::nitrate/organization-sso false
Raises :nitrate-sso-required error if user is not authorized in the organization.
The error carries the resolved :organization-id and :team-id so the client can
restart the SSO flow (via :check-nitrate-sso) instead of reporting a plain
permission failure."
[_ f mdata]
(if (and (contains? cf/flags :admin-console)
(::auth mdata true) ;; only for endpoints that needs auth
(::nitrate/sso mdata true))
(fn [cfg params]
;; Resolve team/project/file from explicit keys or from :id via metadata
(let [profile-id (::profile-id params)
organization-id (uuid/coerce (:organization-id params))
id-type (::id-type mdata)
id (uuid/coerce (:id params))
team-id (or (uuid/coerce (:team-id params))
(when (= id-type :team) id))
project-id (or (uuid/coerce (:project-id params))
(when (= id-type :project) id))
file-id (or (uuid/coerce (:file-id params))
(when (= id-type :file) id))]
(if (and profile-id
(or organization-id team-id project-id file-id))
(let [cache-ref (or organization-id team-id project-id file-id)
cache-key [profile-id cache-ref]
cached (cache/get organization-sso-auth-cache cache-key)
result (if (some? cached)
cached
;; The team is resolved even when the organization is
;; already known: the client needs it to restart the
;; SSO flow without sending non-members through the
;; organization's identity provider.
(let [team-id (or team-id
(when project-id
(:team-id (db/get-by-id cfg :project project-id {:columns [:id :team-id]})))
(when file-id
(:id (teams/get-team-for-file cfg file-id))))
request (-> (meta params) (get ::http/request))
{:keys [authorized sso]} (if organization-id
(nitrate/sso-session-authorized? cfg organization-id nil request)
(nitrate/sso-session-authorized? cfg nil team-id request))
entry {:authorized authorized
:organization-id (or (:organization-id sso) organization-id)
:team-id team-id}]
(when authorized
(cache/get organization-sso-auth-cache cache-key (constantly entry)))
entry))]
(if (:authorized result)
(f cfg params)
(ex/raise :type :authentication
:code :nitrate-sso-required
:organization-id (:organization-id result)
:team-id (:team-id result)
:hint "organization SSO authentication required")))
(f cfg params))))
f))
(defn- wrap
[cfg f mdata]
(as-> f $
(wrap-db-transaction cfg $ mdata)
(cond/wrap cfg $ mdata)
(retry/wrap-retry cfg $ mdata)
(climit/wrap cfg $ mdata)
(wrap-metrics cfg $ mdata)
(rlimit/wrap cfg $ mdata)
(wrap-audit cfg $ mdata)
(wrap-nitrate-sso cfg $ mdata)
(wrap-params-validation cfg $ mdata)
(wrap-authentication cfg $ mdata)))
(defn- wrap-shared-key-authorization
"Authorizes a shared-key caller against the method's `::allowed-shared-keys`.
A management method declares the shared-key ids allowed to call it with
`::allowed-shared-keys`. When the metadata is absent any configured shared key is
accepted, preserving the previous behavior. When it is present and empty no
key is accepted."
[_ f mdata]
(if (contains? mdata ::allowed-shared-keys)
(let [allowed-keys (::allowed-shared-keys mdata)]
(fn [cfg params]
(if (contains? allowed-keys (::auth-key-id params))
(f cfg params)
(do
(l/wrn :hint "shared key is not allowed for this method"
:handler-name (::handler-name params)
:key-id (::auth-key-id params))
(ex/raise :type :authorization
:code :shared-key-not-allowed
:hint "shared key is not allowed for this method")))))
f))
(defn- wrap-management
[cfg f mdata]
(as-> f $
(wrap-db-transaction cfg $ mdata)
(retry/wrap-retry cfg $ mdata)
(climit/wrap cfg $ mdata)
(wrap-metrics cfg $ mdata)
(wrap-audit cfg $ mdata)
(wrap-nitrate-sso cfg $ mdata)
(wrap-params-validation cfg $ mdata)
(wrap-authentication cfg $ mdata)
;; Outermost on purpose: a denied key never opens a transaction,
;; validates params or runs the method body.
(wrap-shared-key-authorization cfg $ mdata)))
(defn- process-method
[cfg wrap-fn [f mdata]]
(l/trc :hint "add method" :module (::module cfg) :type (::type cfg) :name (::sv/name mdata))
(let [f (wrap-fn cfg f mdata)
k (keyword (::sv/name mdata))]
[k [mdata (partial f cfg)]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; API METHODS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- resolve-methods
[cfg]
(let [cfg (assoc cfg ::module "main" ::type "command" ::metrics-id :rpc-main-timing)]
(->> (sv/scan-ns
'app.rpc.commands.access-token
'app.rpc.commands.audit
'app.rpc.commands.auth
'app.rpc.commands.feedback
'app.rpc.commands.fonts
'app.rpc.commands.binfile
'app.rpc.commands.comments
'app.rpc.commands.demo
'app.rpc.commands.error-reports
'app.rpc.commands.files
'app.rpc.commands.files-create
'app.rpc.commands.files-share
'app.rpc.commands.files-update
'app.rpc.commands.files-snapshot
'app.rpc.commands.files-branch
'app.rpc.commands.files-pull-request
'app.rpc.commands.files-task
'app.rpc.commands.files-thumbnails
'app.rpc.commands.jobs
'app.rpc.commands.ldap
'app.rpc.commands.management
'app.rpc.commands.media
'app.rpc.commands.nitrate
'app.rpc.commands.plugins
'app.rpc.commands.profile
'app.rpc.commands.projects
'app.rpc.commands.search
'app.rpc.commands.teams
'app.rpc.commands.teams-invitations
'app.rpc.commands.verify-token
'app.rpc.commands.viewer
'app.rpc.commands.webhooks)
(map (partial process-method cfg wrap))
(into {}))))
(def ^:private schema:methods-params
[:map {:title "methods-params"}
::session/manager
::http.client/client
::db/pool
::rds/pool
::mbus/msgbus
::sto/storage
::mtx/metrics
[::ldap/provider [:maybe ::ldap/provider]]
[::climit [:maybe ::climit]]
[::rlimit [:maybe ::rlimit]]
::setup/props])
(defmethod ig/assert-key ::methods
[_ params]
(assert (sm/check schema:methods-params params)))
(defmethod ig/init-key ::methods
[_ cfg]
(let [cfg (d/without-nils cfg)]
(resolve-methods cfg)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; MANAGEMENT METHODS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- resolve-management-methods
[cfg]
(let [cfg (assoc cfg ::module "management" ::type "command" ::metrics-id :rpc-management-timing)
mods (cond->> (list 'app.rpc.management.exporter
'app.rpc.management.jobs
'app.rpc.management.files)
(contains? cf/flags :admin-console)
(cons 'app.rpc.management.nitrate))]
(->> (apply sv/scan-ns mods)
(map (partial process-method cfg wrap-management))
(into {}))))
(def ^:private schema:management-methods-params
[:map {:title "management-methods-params"}
::session/manager
::http.client/client
::db/pool
::rds/pool
::mbus/msgbus
::sto/storage
::mtx/metrics
::setup/props])
(defmethod ig/assert-key ::management-methods
[_ params]
(assert (sm/check schema:management-methods-params params)))
(defmethod ig/init-key ::management-methods
[_ cfg]
(let [cfg (d/without-nils cfg)]
(resolve-management-methods cfg)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ROUTES
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- redirect
[href]
(fn [_]
{::yres/status 308
::yres/headers {"location" (str href)}}))
(def ^:private schema:methods
[:map-of :keyword [:tuple :map ::sm/fn]])
(sm/register! ::methods schema:methods)
(def ^:private valid-methods?
(sm/validator schema:methods))
(defmethod ig/assert-key ::routes
[_ params]
(assert (map? (::setup/shared-keys params)))
(assert (db/pool? (::db/pool params)) "expect valid database pool")
(assert (session/manager? (::session/manager params)) "expect valid session manager")
(assert (valid-methods? (::methods params)) "expect valid methods map")
(assert (valid-methods? (::management-methods params)) "expect valid methods map"))
(defmethod ig/init-key ::routes
[_ {:keys [::methods ::management-methods ::setup/shared-keys] :as cfg}]
["/api"
["/management"
["/methods/:method-name"
{:middleware [[mw/shared-key-auth shared-keys]
[session/authz cfg]]
:handler (make-rpc-handler management-methods)}]
(doc/routes :methods management-methods
:label "management"
:base-uri (cf/get-public-uri "api/management")
:description "MANAGEMENT API")]
["/main"
["/methods/:method-name"
{:middleware [[mw/cors]
[sec/client-header-check]
[session/authz cfg]
[actoken/authz (assoc cfg ::actoken/allow-mcp true)]]
:handler (make-rpc-handler methods)}]
(doc/routes :methods methods
:label "main"
:base-uri (cf/get-public-uri "api/main")
:description "MAIN API")]
;; BACKWARD COMPATIBILITY
["/_doc" {:handler (redirect (cf/get-public-uri "api/main/doc"))}]
["/doc" {:handler (redirect (cf/get-public-uri "api/main/doc"))}]
["/openapi" {:handler (redirect (cf/get-public-uri "api/main/doc/openapi"))}]
["/openapi.join" {:handler (redirect (cf/get-public-uri "api/main/doc/openapi.json"))}]
["/rpc/command/:method-name"
{:middleware [[mw/cors]
[sec/client-header-check]
[session/authz cfg]
[actoken/authz (assoc cfg ::actoken/allow-mcp true)]]
:handler (make-rpc-handler methods)}]])